Sun, 04 Nov 2012 10:59:42 +0000
7192246: Add type-checking support for default methods
Summary: Add type-checking support for default methods as per Featherweight-Defender document
Reviewed-by: jjg, dlsmith
1 /*
2 * Copyright (c) 2003, 2012, Oracle and/or its affiliates. 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. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
26 package com.sun.tools.javac.code;
28 import java.lang.ref.SoftReference;
29 import java.util.*;
31 import com.sun.tools.javac.code.Attribute.RetentionPolicy;
32 import com.sun.tools.javac.code.Lint.LintCategory;
33 import com.sun.tools.javac.code.Type.UndetVar.InferenceBound;
34 import com.sun.tools.javac.comp.Check;
35 import com.sun.tools.javac.jvm.ClassReader;
36 import com.sun.tools.javac.util.*;
37 import com.sun.tools.javac.util.List;
38 import static com.sun.tools.javac.code.BoundKind.*;
39 import static com.sun.tools.javac.code.Flags.*;
40 import static com.sun.tools.javac.code.Scope.*;
41 import static com.sun.tools.javac.code.Symbol.*;
42 import static com.sun.tools.javac.code.Type.*;
43 import static com.sun.tools.javac.code.TypeTag.*;
44 import static com.sun.tools.javac.util.ListBuffer.lb;
46 /**
47 * Utility class containing various operations on types.
48 *
49 * <p>Unless other names are more illustrative, the following naming
50 * conventions should be observed in this file:
51 *
52 * <dl>
53 * <dt>t</dt>
54 * <dd>If the first argument to an operation is a type, it should be named t.</dd>
55 * <dt>s</dt>
56 * <dd>Similarly, if the second argument to an operation is a type, it should be named s.</dd>
57 * <dt>ts</dt>
58 * <dd>If an operations takes a list of types, the first should be named ts.</dd>
59 * <dt>ss</dt>
60 * <dd>A second list of types should be named ss.</dd>
61 * </dl>
62 *
63 * <p><b>This is NOT part of any supported API.
64 * If you write code that depends on this, you do so at your own risk.
65 * This code and its internal interfaces are subject to change or
66 * deletion without notice.</b>
67 */
68 public class Types {
69 protected static final Context.Key<Types> typesKey =
70 new Context.Key<Types>();
72 final Symtab syms;
73 final JavacMessages messages;
74 final Names names;
75 final boolean allowBoxing;
76 final boolean allowCovariantReturns;
77 final boolean allowObjectToPrimitiveCast;
78 final boolean allowDefaultMethods;
79 final ClassReader reader;
80 final Check chk;
81 JCDiagnostic.Factory diags;
82 List<Warner> warnStack = List.nil();
83 final Name capturedName;
84 private final FunctionDescriptorLookupError functionDescriptorLookupError;
86 // <editor-fold defaultstate="collapsed" desc="Instantiating">
87 public static Types instance(Context context) {
88 Types instance = context.get(typesKey);
89 if (instance == null)
90 instance = new Types(context);
91 return instance;
92 }
94 protected Types(Context context) {
95 context.put(typesKey, this);
96 syms = Symtab.instance(context);
97 names = Names.instance(context);
98 Source source = Source.instance(context);
99 allowBoxing = source.allowBoxing();
100 allowCovariantReturns = source.allowCovariantReturns();
101 allowObjectToPrimitiveCast = source.allowObjectToPrimitiveCast();
102 allowDefaultMethods = source.allowDefaultMethods();
103 reader = ClassReader.instance(context);
104 chk = Check.instance(context);
105 capturedName = names.fromString("<captured wildcard>");
106 messages = JavacMessages.instance(context);
107 diags = JCDiagnostic.Factory.instance(context);
108 functionDescriptorLookupError = new FunctionDescriptorLookupError();
109 }
110 // </editor-fold>
112 // <editor-fold defaultstate="collapsed" desc="upperBound">
113 /**
114 * The "rvalue conversion".<br>
115 * The upper bound of most types is the type
116 * itself. Wildcards, on the other hand have upper
117 * and lower bounds.
118 * @param t a type
119 * @return the upper bound of the given type
120 */
121 public Type upperBound(Type t) {
122 return upperBound.visit(t);
123 }
124 // where
125 private final MapVisitor<Void> upperBound = new MapVisitor<Void>() {
127 @Override
128 public Type visitWildcardType(WildcardType t, Void ignored) {
129 if (t.isSuperBound())
130 return t.bound == null ? syms.objectType : t.bound.bound;
131 else
132 return visit(t.type);
133 }
135 @Override
136 public Type visitCapturedType(CapturedType t, Void ignored) {
137 return visit(t.bound);
138 }
139 };
140 // </editor-fold>
142 // <editor-fold defaultstate="collapsed" desc="lowerBound">
143 /**
144 * The "lvalue conversion".<br>
145 * The lower bound of most types is the type
146 * itself. Wildcards, on the other hand have upper
147 * and lower bounds.
148 * @param t a type
149 * @return the lower bound of the given type
150 */
151 public Type lowerBound(Type t) {
152 return lowerBound.visit(t);
153 }
154 // where
155 private final MapVisitor<Void> lowerBound = new MapVisitor<Void>() {
157 @Override
158 public Type visitWildcardType(WildcardType t, Void ignored) {
159 return t.isExtendsBound() ? syms.botType : visit(t.type);
160 }
162 @Override
163 public Type visitCapturedType(CapturedType t, Void ignored) {
164 return visit(t.getLowerBound());
165 }
166 };
167 // </editor-fold>
169 // <editor-fold defaultstate="collapsed" desc="isUnbounded">
170 /**
171 * Checks that all the arguments to a class are unbounded
172 * wildcards or something else that doesn't make any restrictions
173 * on the arguments. If a class isUnbounded, a raw super- or
174 * subclass can be cast to it without a warning.
175 * @param t a type
176 * @return true iff the given type is unbounded or raw
177 */
178 public boolean isUnbounded(Type t) {
179 return isUnbounded.visit(t);
180 }
181 // where
182 private final UnaryVisitor<Boolean> isUnbounded = new UnaryVisitor<Boolean>() {
184 public Boolean visitType(Type t, Void ignored) {
185 return true;
186 }
188 @Override
189 public Boolean visitClassType(ClassType t, Void ignored) {
190 List<Type> parms = t.tsym.type.allparams();
191 List<Type> args = t.allparams();
192 while (parms.nonEmpty()) {
193 WildcardType unb = new WildcardType(syms.objectType,
194 BoundKind.UNBOUND,
195 syms.boundClass,
196 (TypeVar)parms.head);
197 if (!containsType(args.head, unb))
198 return false;
199 parms = parms.tail;
200 args = args.tail;
201 }
202 return true;
203 }
204 };
205 // </editor-fold>
207 // <editor-fold defaultstate="collapsed" desc="asSub">
208 /**
209 * Return the least specific subtype of t that starts with symbol
210 * sym. If none exists, return null. The least specific subtype
211 * is determined as follows:
212 *
213 * <p>If there is exactly one parameterized instance of sym that is a
214 * subtype of t, that parameterized instance is returned.<br>
215 * Otherwise, if the plain type or raw type `sym' is a subtype of
216 * type t, the type `sym' itself is returned. Otherwise, null is
217 * returned.
218 */
219 public Type asSub(Type t, Symbol sym) {
220 return asSub.visit(t, sym);
221 }
222 // where
223 private final SimpleVisitor<Type,Symbol> asSub = new SimpleVisitor<Type,Symbol>() {
225 public Type visitType(Type t, Symbol sym) {
226 return null;
227 }
229 @Override
230 public Type visitClassType(ClassType t, Symbol sym) {
231 if (t.tsym == sym)
232 return t;
233 Type base = asSuper(sym.type, t.tsym);
234 if (base == null)
235 return null;
236 ListBuffer<Type> from = new ListBuffer<Type>();
237 ListBuffer<Type> to = new ListBuffer<Type>();
238 try {
239 adapt(base, t, from, to);
240 } catch (AdaptFailure ex) {
241 return null;
242 }
243 Type res = subst(sym.type, from.toList(), to.toList());
244 if (!isSubtype(res, t))
245 return null;
246 ListBuffer<Type> openVars = new ListBuffer<Type>();
247 for (List<Type> l = sym.type.allparams();
248 l.nonEmpty(); l = l.tail)
249 if (res.contains(l.head) && !t.contains(l.head))
250 openVars.append(l.head);
251 if (openVars.nonEmpty()) {
252 if (t.isRaw()) {
253 // The subtype of a raw type is raw
254 res = erasure(res);
255 } else {
256 // Unbound type arguments default to ?
257 List<Type> opens = openVars.toList();
258 ListBuffer<Type> qs = new ListBuffer<Type>();
259 for (List<Type> iter = opens; iter.nonEmpty(); iter = iter.tail) {
260 qs.append(new WildcardType(syms.objectType, BoundKind.UNBOUND, syms.boundClass, (TypeVar) iter.head));
261 }
262 res = subst(res, opens, qs.toList());
263 }
264 }
265 return res;
266 }
268 @Override
269 public Type visitErrorType(ErrorType t, Symbol sym) {
270 return t;
271 }
272 };
273 // </editor-fold>
275 // <editor-fold defaultstate="collapsed" desc="isConvertible">
276 /**
277 * Is t a subtype of or convertible via boxing/unboxing
278 * conversion to s?
279 */
280 public boolean isConvertible(Type t, Type s, Warner warn) {
281 if (t.tag == ERROR)
282 return true;
283 boolean tPrimitive = t.isPrimitive();
284 boolean sPrimitive = s.isPrimitive();
285 if (tPrimitive == sPrimitive) {
286 return isSubtypeUnchecked(t, s, warn);
287 }
288 if (!allowBoxing) return false;
289 return tPrimitive
290 ? isSubtype(boxedClass(t).type, s)
291 : isSubtype(unboxedType(t), s);
292 }
294 /**
295 * Is t a subtype of or convertiable via boxing/unboxing
296 * convertions to s?
297 */
298 public boolean isConvertible(Type t, Type s) {
299 return isConvertible(t, s, Warner.noWarnings);
300 }
301 // </editor-fold>
303 // <editor-fold defaultstate="collapsed" desc="findSam">
305 /**
306 * Exception used to report a function descriptor lookup failure. The exception
307 * wraps a diagnostic that can be used to generate more details error
308 * messages.
309 */
310 public static class FunctionDescriptorLookupError extends RuntimeException {
311 private static final long serialVersionUID = 0;
313 JCDiagnostic diagnostic;
315 FunctionDescriptorLookupError() {
316 this.diagnostic = null;
317 }
319 FunctionDescriptorLookupError setMessage(JCDiagnostic diag) {
320 this.diagnostic = diag;
321 return this;
322 }
324 public JCDiagnostic getDiagnostic() {
325 return diagnostic;
326 }
327 }
329 /**
330 * A cache that keeps track of function descriptors associated with given
331 * functional interfaces.
332 */
333 class DescriptorCache {
335 private WeakHashMap<TypeSymbol, Entry> _map = new WeakHashMap<TypeSymbol, Entry>();
337 class FunctionDescriptor {
338 Symbol descSym;
340 FunctionDescriptor(Symbol descSym) {
341 this.descSym = descSym;
342 }
344 public Symbol getSymbol() {
345 return descSym;
346 }
348 public Type getType(Type origin) {
349 return memberType(origin, descSym);
350 }
351 }
353 class Entry {
354 final FunctionDescriptor cachedDescRes;
355 final int prevMark;
357 public Entry(FunctionDescriptor cachedDescRes,
358 int prevMark) {
359 this.cachedDescRes = cachedDescRes;
360 this.prevMark = prevMark;
361 }
363 boolean matches(int mark) {
364 return this.prevMark == mark;
365 }
366 }
368 FunctionDescriptor get(TypeSymbol origin) throws FunctionDescriptorLookupError {
369 Entry e = _map.get(origin);
370 CompoundScope members = membersClosure(origin.type, false);
371 if (e == null ||
372 !e.matches(members.getMark())) {
373 FunctionDescriptor descRes = findDescriptorInternal(origin, members);
374 _map.put(origin, new Entry(descRes, members.getMark()));
375 return descRes;
376 }
377 else {
378 return e.cachedDescRes;
379 }
380 }
382 /**
383 * Scope filter used to skip methods that should be ignored during
384 * function interface conversion (such as methods overridden by
385 * j.l.Object)
386 */
387 class DescriptorFilter implements Filter<Symbol> {
389 TypeSymbol origin;
391 DescriptorFilter(TypeSymbol origin) {
392 this.origin = origin;
393 }
395 @Override
396 public boolean accepts(Symbol sym) {
397 return sym.kind == Kinds.MTH &&
398 (sym.flags() & ABSTRACT) != 0 &&
399 !overridesObjectMethod(origin, sym) &&
400 notOverridden(sym);
401 }
403 private boolean notOverridden(Symbol msym) {
404 Symbol impl = ((MethodSymbol)msym).implementation(origin, Types.this, false);
405 return impl == null || (impl.flags() & ABSTRACT) != 0;
406 }
407 };
409 /**
410 * Compute the function descriptor associated with a given functional interface
411 */
412 public FunctionDescriptor findDescriptorInternal(TypeSymbol origin, CompoundScope membersCache) throws FunctionDescriptorLookupError {
413 if (!origin.isInterface()) {
414 //t must be an interface
415 throw failure("not.a.functional.intf");
416 }
418 final ListBuffer<Symbol> abstracts = ListBuffer.lb();
419 for (Symbol sym : membersCache.getElements(new DescriptorFilter(origin))) {
420 Type mtype = memberType(origin.type, sym);
421 if (abstracts.isEmpty() ||
422 (sym.name == abstracts.first().name &&
423 overrideEquivalent(mtype, memberType(origin.type, abstracts.first())))) {
424 abstracts.append(sym);
425 } else {
426 //the target method(s) should be the only abstract members of t
427 throw failure("not.a.functional.intf.1",
428 diags.fragment("incompatible.abstracts", Kinds.kindName(origin), origin));
429 }
430 }
431 if (abstracts.isEmpty()) {
432 //t must define a suitable non-generic method
433 throw failure("not.a.functional.intf.1",
434 diags.fragment("no.abstracts", Kinds.kindName(origin), origin));
435 } else if (abstracts.size() == 1) {
436 if (abstracts.first().type.tag == FORALL) {
437 throw failure("invalid.generic.desc.in.functional.intf",
438 abstracts.first(),
439 Kinds.kindName(origin),
440 origin);
441 } else {
442 return new FunctionDescriptor(abstracts.first());
443 }
444 } else { // size > 1
445 for (Symbol msym : abstracts) {
446 if (msym.type.tag == FORALL) {
447 throw failure("invalid.generic.desc.in.functional.intf",
448 abstracts.first(),
449 Kinds.kindName(origin),
450 origin);
451 }
452 }
453 FunctionDescriptor descRes = mergeDescriptors(origin, abstracts.toList());
454 if (descRes == null) {
455 //we can get here if the functional interface is ill-formed
456 ListBuffer<JCDiagnostic> descriptors = ListBuffer.lb();
457 for (Symbol desc : abstracts) {
458 String key = desc.type.getThrownTypes().nonEmpty() ?
459 "descriptor.throws" : "descriptor";
460 descriptors.append(diags.fragment(key, desc.name,
461 desc.type.getParameterTypes(),
462 desc.type.getReturnType(),
463 desc.type.getThrownTypes()));
464 }
465 JCDiagnostic.MultilineDiagnostic incompatibleDescriptors =
466 new JCDiagnostic.MultilineDiagnostic(diags.fragment("incompatible.descs.in.functional.intf",
467 Kinds.kindName(origin), origin), descriptors.toList());
468 throw failure(incompatibleDescriptors);
469 }
470 return descRes;
471 }
472 }
474 /**
475 * Compute a synthetic type for the target descriptor given a list
476 * of override-equivalent methods in the functional interface type.
477 * The resulting method type is a method type that is override-equivalent
478 * and return-type substitutable with each method in the original list.
479 */
480 private FunctionDescriptor mergeDescriptors(TypeSymbol origin, List<Symbol> methodSyms) {
481 //pick argument types - simply take the signature that is a
482 //subsignature of all other signatures in the list (as per JLS 8.4.2)
483 List<Symbol> mostSpecific = List.nil();
484 outer: for (Symbol msym1 : methodSyms) {
485 Type mt1 = memberType(origin.type, msym1);
486 for (Symbol msym2 : methodSyms) {
487 Type mt2 = memberType(origin.type, msym2);
488 if (!isSubSignature(mt1, mt2)) {
489 continue outer;
490 }
491 }
492 mostSpecific = mostSpecific.prepend(msym1);
493 }
494 if (mostSpecific.isEmpty()) {
495 return null;
496 }
499 //pick return types - this is done in two phases: (i) first, the most
500 //specific return type is chosen using strict subtyping; if this fails,
501 //a second attempt is made using return type substitutability (see JLS 8.4.5)
502 boolean phase2 = false;
503 Symbol bestSoFar = null;
504 while (bestSoFar == null) {
505 outer: for (Symbol msym1 : mostSpecific) {
506 Type mt1 = memberType(origin.type, msym1);
507 for (Symbol msym2 : methodSyms) {
508 Type mt2 = memberType(origin.type, msym2);
509 if (phase2 ?
510 !returnTypeSubstitutable(mt1, mt2) :
511 !isSubtypeInternal(mt1.getReturnType(), mt2.getReturnType())) {
512 continue outer;
513 }
514 }
515 bestSoFar = msym1;
516 }
517 if (phase2) {
518 break;
519 } else {
520 phase2 = true;
521 }
522 }
523 if (bestSoFar == null) return null;
525 //merge thrown types - form the intersection of all the thrown types in
526 //all the signatures in the list
527 List<Type> thrown = null;
528 for (Symbol msym1 : methodSyms) {
529 Type mt1 = memberType(origin.type, msym1);
530 thrown = (thrown == null) ?
531 mt1.getThrownTypes() :
532 chk.intersect(mt1.getThrownTypes(), thrown);
533 }
535 final List<Type> thrown1 = thrown;
536 return new FunctionDescriptor(bestSoFar) {
537 @Override
538 public Type getType(Type origin) {
539 Type mt = memberType(origin, getSymbol());
540 return new MethodType(mt.getParameterTypes(), mt.getReturnType(), thrown1, syms.methodClass);
541 }
542 };
543 }
545 boolean isSubtypeInternal(Type s, Type t) {
546 return (s.isPrimitive() && t.isPrimitive()) ?
547 isSameType(t, s) :
548 isSubtype(s, t);
549 }
551 FunctionDescriptorLookupError failure(String msg, Object... args) {
552 return failure(diags.fragment(msg, args));
553 }
555 FunctionDescriptorLookupError failure(JCDiagnostic diag) {
556 return functionDescriptorLookupError.setMessage(diag);
557 }
558 }
560 private DescriptorCache descCache = new DescriptorCache();
562 /**
563 * Find the method descriptor associated to this class symbol - if the
564 * symbol 'origin' is not a functional interface, an exception is thrown.
565 */
566 public Symbol findDescriptorSymbol(TypeSymbol origin) throws FunctionDescriptorLookupError {
567 return descCache.get(origin).getSymbol();
568 }
570 /**
571 * Find the type of the method descriptor associated to this class symbol -
572 * if the symbol 'origin' is not a functional interface, an exception is thrown.
573 */
574 public Type findDescriptorType(Type origin) throws FunctionDescriptorLookupError {
575 return descCache.get(origin.tsym).getType(origin);
576 }
578 /**
579 * Is given type a functional interface?
580 */
581 public boolean isFunctionalInterface(TypeSymbol tsym) {
582 try {
583 findDescriptorSymbol(tsym);
584 return true;
585 } catch (FunctionDescriptorLookupError ex) {
586 return false;
587 }
588 }
589 // </editor-fold>
591 // <editor-fold defaultstate="collapsed" desc="isSubtype">
592 /**
593 * Is t an unchecked subtype of s?
594 */
595 public boolean isSubtypeUnchecked(Type t, Type s) {
596 return isSubtypeUnchecked(t, s, Warner.noWarnings);
597 }
598 /**
599 * Is t an unchecked subtype of s?
600 */
601 public boolean isSubtypeUnchecked(Type t, Type s, Warner warn) {
602 boolean result = isSubtypeUncheckedInternal(t, s, warn);
603 if (result) {
604 checkUnsafeVarargsConversion(t, s, warn);
605 }
606 return result;
607 }
608 //where
609 private boolean isSubtypeUncheckedInternal(Type t, Type s, Warner warn) {
610 if (t.hasTag(ARRAY) && s.hasTag(ARRAY)) {
611 if (((ArrayType)t).elemtype.isPrimitive()) {
612 return isSameType(elemtype(t), elemtype(s));
613 } else {
614 return isSubtypeUnchecked(elemtype(t), elemtype(s), warn);
615 }
616 } else if (isSubtype(t, s)) {
617 return true;
618 }
619 else if (t.tag == TYPEVAR) {
620 return isSubtypeUnchecked(t.getUpperBound(), s, warn);
621 }
622 else if (!s.isRaw()) {
623 Type t2 = asSuper(t, s.tsym);
624 if (t2 != null && t2.isRaw()) {
625 if (isReifiable(s))
626 warn.silentWarn(LintCategory.UNCHECKED);
627 else
628 warn.warn(LintCategory.UNCHECKED);
629 return true;
630 }
631 }
632 return false;
633 }
635 private void checkUnsafeVarargsConversion(Type t, Type s, Warner warn) {
636 if (t.tag != ARRAY || isReifiable(t)) return;
637 ArrayType from = (ArrayType)t;
638 boolean shouldWarn = false;
639 switch (s.tag) {
640 case ARRAY:
641 ArrayType to = (ArrayType)s;
642 shouldWarn = from.isVarargs() &&
643 !to.isVarargs() &&
644 !isReifiable(from);
645 break;
646 case CLASS:
647 shouldWarn = from.isVarargs();
648 break;
649 }
650 if (shouldWarn) {
651 warn.warn(LintCategory.VARARGS);
652 }
653 }
655 /**
656 * Is t a subtype of s?<br>
657 * (not defined for Method and ForAll types)
658 */
659 final public boolean isSubtype(Type t, Type s) {
660 return isSubtype(t, s, true);
661 }
662 final public boolean isSubtypeNoCapture(Type t, Type s) {
663 return isSubtype(t, s, false);
664 }
665 public boolean isSubtype(Type t, Type s, boolean capture) {
666 if (t == s)
667 return true;
669 if (s.isPartial())
670 return isSuperType(s, t);
672 if (s.isCompound()) {
673 for (Type s2 : interfaces(s).prepend(supertype(s))) {
674 if (!isSubtype(t, s2, capture))
675 return false;
676 }
677 return true;
678 }
680 Type lower = lowerBound(s);
681 if (s != lower)
682 return isSubtype(capture ? capture(t) : t, lower, false);
684 return isSubtype.visit(capture ? capture(t) : t, s);
685 }
686 // where
687 private TypeRelation isSubtype = new TypeRelation()
688 {
689 public Boolean visitType(Type t, Type s) {
690 switch (t.tag) {
691 case BYTE:
692 return (!s.hasTag(CHAR) && t.getTag().isSubRangeOf(s.getTag()));
693 case CHAR:
694 return (!s.hasTag(SHORT) && t.getTag().isSubRangeOf(s.getTag()));
695 case SHORT: case INT: case LONG:
696 case FLOAT: case DOUBLE:
697 return t.getTag().isSubRangeOf(s.getTag());
698 case BOOLEAN: case VOID:
699 return t.hasTag(s.getTag());
700 case TYPEVAR:
701 return isSubtypeNoCapture(t.getUpperBound(), s);
702 case BOT:
703 return
704 s.hasTag(BOT) || s.hasTag(CLASS) ||
705 s.hasTag(ARRAY) || s.hasTag(TYPEVAR);
706 case WILDCARD: //we shouldn't be here - avoids crash (see 7034495)
707 case NONE:
708 return false;
709 default:
710 throw new AssertionError("isSubtype " + t.tag);
711 }
712 }
714 private Set<TypePair> cache = new HashSet<TypePair>();
716 private boolean containsTypeRecursive(Type t, Type s) {
717 TypePair pair = new TypePair(t, s);
718 if (cache.add(pair)) {
719 try {
720 return containsType(t.getTypeArguments(),
721 s.getTypeArguments());
722 } finally {
723 cache.remove(pair);
724 }
725 } else {
726 return containsType(t.getTypeArguments(),
727 rewriteSupers(s).getTypeArguments());
728 }
729 }
731 private Type rewriteSupers(Type t) {
732 if (!t.isParameterized())
733 return t;
734 ListBuffer<Type> from = lb();
735 ListBuffer<Type> to = lb();
736 adaptSelf(t, from, to);
737 if (from.isEmpty())
738 return t;
739 ListBuffer<Type> rewrite = lb();
740 boolean changed = false;
741 for (Type orig : to.toList()) {
742 Type s = rewriteSupers(orig);
743 if (s.isSuperBound() && !s.isExtendsBound()) {
744 s = new WildcardType(syms.objectType,
745 BoundKind.UNBOUND,
746 syms.boundClass);
747 changed = true;
748 } else if (s != orig) {
749 s = new WildcardType(upperBound(s),
750 BoundKind.EXTENDS,
751 syms.boundClass);
752 changed = true;
753 }
754 rewrite.append(s);
755 }
756 if (changed)
757 return subst(t.tsym.type, from.toList(), rewrite.toList());
758 else
759 return t;
760 }
762 @Override
763 public Boolean visitClassType(ClassType t, Type s) {
764 Type sup = asSuper(t, s.tsym);
765 return sup != null
766 && sup.tsym == s.tsym
767 // You're not allowed to write
768 // Vector<Object> vec = new Vector<String>();
769 // But with wildcards you can write
770 // Vector<? extends Object> vec = new Vector<String>();
771 // which means that subtype checking must be done
772 // here instead of same-type checking (via containsType).
773 && (!s.isParameterized() || containsTypeRecursive(s, sup))
774 && isSubtypeNoCapture(sup.getEnclosingType(),
775 s.getEnclosingType());
776 }
778 @Override
779 public Boolean visitArrayType(ArrayType t, Type s) {
780 if (s.tag == ARRAY) {
781 if (t.elemtype.isPrimitive())
782 return isSameType(t.elemtype, elemtype(s));
783 else
784 return isSubtypeNoCapture(t.elemtype, elemtype(s));
785 }
787 if (s.tag == CLASS) {
788 Name sname = s.tsym.getQualifiedName();
789 return sname == names.java_lang_Object
790 || sname == names.java_lang_Cloneable
791 || sname == names.java_io_Serializable;
792 }
794 return false;
795 }
797 @Override
798 public Boolean visitUndetVar(UndetVar t, Type s) {
799 //todo: test against origin needed? or replace with substitution?
800 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN) {
801 return true;
802 } else if (s.tag == BOT) {
803 //if 's' is 'null' there's no instantiated type U for which
804 //U <: s (but 'null' itself, which is not a valid type)
805 return false;
806 }
808 t.addBound(InferenceBound.UPPER, s, Types.this);
809 return true;
810 }
812 @Override
813 public Boolean visitErrorType(ErrorType t, Type s) {
814 return true;
815 }
816 };
818 /**
819 * Is t a subtype of every type in given list `ts'?<br>
820 * (not defined for Method and ForAll types)<br>
821 * Allows unchecked conversions.
822 */
823 public boolean isSubtypeUnchecked(Type t, List<Type> ts, Warner warn) {
824 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
825 if (!isSubtypeUnchecked(t, l.head, warn))
826 return false;
827 return true;
828 }
830 /**
831 * Are corresponding elements of ts subtypes of ss? If lists are
832 * of different length, return false.
833 */
834 public boolean isSubtypes(List<Type> ts, List<Type> ss) {
835 while (ts.tail != null && ss.tail != null
836 /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
837 isSubtype(ts.head, ss.head)) {
838 ts = ts.tail;
839 ss = ss.tail;
840 }
841 return ts.tail == null && ss.tail == null;
842 /*inlined: ts.isEmpty() && ss.isEmpty();*/
843 }
845 /**
846 * Are corresponding elements of ts subtypes of ss, allowing
847 * unchecked conversions? If lists are of different length,
848 * return false.
849 **/
850 public boolean isSubtypesUnchecked(List<Type> ts, List<Type> ss, Warner warn) {
851 while (ts.tail != null && ss.tail != null
852 /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
853 isSubtypeUnchecked(ts.head, ss.head, warn)) {
854 ts = ts.tail;
855 ss = ss.tail;
856 }
857 return ts.tail == null && ss.tail == null;
858 /*inlined: ts.isEmpty() && ss.isEmpty();*/
859 }
860 // </editor-fold>
862 // <editor-fold defaultstate="collapsed" desc="isSuperType">
863 /**
864 * Is t a supertype of s?
865 */
866 public boolean isSuperType(Type t, Type s) {
867 switch (t.tag) {
868 case ERROR:
869 return true;
870 case UNDETVAR: {
871 UndetVar undet = (UndetVar)t;
872 if (t == s ||
873 undet.qtype == s ||
874 s.tag == ERROR ||
875 s.tag == BOT) return true;
876 undet.addBound(InferenceBound.LOWER, s, this);
877 return true;
878 }
879 default:
880 return isSubtype(s, t);
881 }
882 }
883 // </editor-fold>
885 // <editor-fold defaultstate="collapsed" desc="isSameType">
886 /**
887 * Are corresponding elements of the lists the same type? If
888 * lists are of different length, return false.
889 */
890 public boolean isSameTypes(List<Type> ts, List<Type> ss) {
891 while (ts.tail != null && ss.tail != null
892 /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
893 isSameType(ts.head, ss.head)) {
894 ts = ts.tail;
895 ss = ss.tail;
896 }
897 return ts.tail == null && ss.tail == null;
898 /*inlined: ts.isEmpty() && ss.isEmpty();*/
899 }
901 /**
902 * Is t the same type as s?
903 */
904 public boolean isSameType(Type t, Type s) {
905 return isSameType.visit(t, s);
906 }
907 // where
908 private TypeRelation isSameType = new TypeRelation() {
910 public Boolean visitType(Type t, Type s) {
911 if (t == s)
912 return true;
914 if (s.isPartial())
915 return visit(s, t);
917 switch (t.tag) {
918 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
919 case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
920 return t.tag == s.tag;
921 case TYPEVAR: {
922 if (s.tag == TYPEVAR) {
923 //type-substitution does not preserve type-var types
924 //check that type var symbols and bounds are indeed the same
925 return t.tsym == s.tsym &&
926 visit(t.getUpperBound(), s.getUpperBound());
927 }
928 else {
929 //special case for s == ? super X, where upper(s) = u
930 //check that u == t, where u has been set by Type.withTypeVar
931 return s.isSuperBound() &&
932 !s.isExtendsBound() &&
933 visit(t, upperBound(s));
934 }
935 }
936 default:
937 throw new AssertionError("isSameType " + t.tag);
938 }
939 }
941 @Override
942 public Boolean visitWildcardType(WildcardType t, Type s) {
943 if (s.isPartial())
944 return visit(s, t);
945 else
946 return false;
947 }
949 @Override
950 public Boolean visitClassType(ClassType t, Type s) {
951 if (t == s)
952 return true;
954 if (s.isPartial())
955 return visit(s, t);
957 if (s.isSuperBound() && !s.isExtendsBound())
958 return visit(t, upperBound(s)) && visit(t, lowerBound(s));
960 if (t.isCompound() && s.isCompound()) {
961 if (!visit(supertype(t), supertype(s)))
962 return false;
964 HashSet<SingletonType> set = new HashSet<SingletonType>();
965 for (Type x : interfaces(t))
966 set.add(new SingletonType(x));
967 for (Type x : interfaces(s)) {
968 if (!set.remove(new SingletonType(x)))
969 return false;
970 }
971 return (set.isEmpty());
972 }
973 return t.tsym == s.tsym
974 && visit(t.getEnclosingType(), s.getEnclosingType())
975 && containsTypeEquivalent(t.getTypeArguments(), s.getTypeArguments());
976 }
978 @Override
979 public Boolean visitArrayType(ArrayType t, Type s) {
980 if (t == s)
981 return true;
983 if (s.isPartial())
984 return visit(s, t);
986 return s.hasTag(ARRAY)
987 && containsTypeEquivalent(t.elemtype, elemtype(s));
988 }
990 @Override
991 public Boolean visitMethodType(MethodType t, Type s) {
992 // isSameType for methods does not take thrown
993 // exceptions into account!
994 return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType());
995 }
997 @Override
998 public Boolean visitPackageType(PackageType t, Type s) {
999 return t == s;
1000 }
1002 @Override
1003 public Boolean visitForAll(ForAll t, Type s) {
1004 if (s.tag != FORALL)
1005 return false;
1007 ForAll forAll = (ForAll)s;
1008 return hasSameBounds(t, forAll)
1009 && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
1010 }
1012 @Override
1013 public Boolean visitUndetVar(UndetVar t, Type s) {
1014 if (s.tag == WILDCARD)
1015 // FIXME, this might be leftovers from before capture conversion
1016 return false;
1018 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
1019 return true;
1021 t.addBound(InferenceBound.EQ, s, Types.this);
1023 return true;
1024 }
1026 @Override
1027 public Boolean visitErrorType(ErrorType t, Type s) {
1028 return true;
1029 }
1030 };
1031 // </editor-fold>
1033 // <editor-fold defaultstate="collapsed" desc="Contains Type">
1034 public boolean containedBy(Type t, Type s) {
1035 switch (t.tag) {
1036 case UNDETVAR:
1037 if (s.tag == WILDCARD) {
1038 UndetVar undetvar = (UndetVar)t;
1039 WildcardType wt = (WildcardType)s;
1040 switch(wt.kind) {
1041 case UNBOUND: //similar to ? extends Object
1042 case EXTENDS: {
1043 Type bound = upperBound(s);
1044 undetvar.addBound(InferenceBound.UPPER, bound, this);
1045 break;
1046 }
1047 case SUPER: {
1048 Type bound = lowerBound(s);
1049 undetvar.addBound(InferenceBound.LOWER, bound, this);
1050 break;
1051 }
1052 }
1053 return true;
1054 } else {
1055 return isSameType(t, s);
1056 }
1057 case ERROR:
1058 return true;
1059 default:
1060 return containsType(s, t);
1061 }
1062 }
1064 boolean containsType(List<Type> ts, List<Type> ss) {
1065 while (ts.nonEmpty() && ss.nonEmpty()
1066 && containsType(ts.head, ss.head)) {
1067 ts = ts.tail;
1068 ss = ss.tail;
1069 }
1070 return ts.isEmpty() && ss.isEmpty();
1071 }
1073 /**
1074 * Check if t contains s.
1075 *
1076 * <p>T contains S if:
1077 *
1078 * <p>{@code L(T) <: L(S) && U(S) <: U(T)}
1079 *
1080 * <p>This relation is only used by ClassType.isSubtype(), that
1081 * is,
1082 *
1083 * <p>{@code C<S> <: C<T> if T contains S.}
1084 *
1085 * <p>Because of F-bounds, this relation can lead to infinite
1086 * recursion. Thus we must somehow break that recursion. Notice
1087 * that containsType() is only called from ClassType.isSubtype().
1088 * Since the arguments have already been checked against their
1089 * bounds, we know:
1090 *
1091 * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)}
1092 *
1093 * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)}
1094 *
1095 * @param t a type
1096 * @param s a type
1097 */
1098 public boolean containsType(Type t, Type s) {
1099 return containsType.visit(t, s);
1100 }
1101 // where
1102 private TypeRelation containsType = new TypeRelation() {
1104 private Type U(Type t) {
1105 while (t.tag == WILDCARD) {
1106 WildcardType w = (WildcardType)t;
1107 if (w.isSuperBound())
1108 return w.bound == null ? syms.objectType : w.bound.bound;
1109 else
1110 t = w.type;
1111 }
1112 return t;
1113 }
1115 private Type L(Type t) {
1116 while (t.tag == WILDCARD) {
1117 WildcardType w = (WildcardType)t;
1118 if (w.isExtendsBound())
1119 return syms.botType;
1120 else
1121 t = w.type;
1122 }
1123 return t;
1124 }
1126 public Boolean visitType(Type t, Type s) {
1127 if (s.isPartial())
1128 return containedBy(s, t);
1129 else
1130 return isSameType(t, s);
1131 }
1133 // void debugContainsType(WildcardType t, Type s) {
1134 // System.err.println();
1135 // System.err.format(" does %s contain %s?%n", t, s);
1136 // System.err.format(" %s U(%s) <: U(%s) %s = %s%n",
1137 // upperBound(s), s, t, U(t),
1138 // t.isSuperBound()
1139 // || isSubtypeNoCapture(upperBound(s), U(t)));
1140 // System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
1141 // L(t), t, s, lowerBound(s),
1142 // t.isExtendsBound()
1143 // || isSubtypeNoCapture(L(t), lowerBound(s)));
1144 // System.err.println();
1145 // }
1147 @Override
1148 public Boolean visitWildcardType(WildcardType t, Type s) {
1149 if (s.isPartial())
1150 return containedBy(s, t);
1151 else {
1152 // debugContainsType(t, s);
1153 return isSameWildcard(t, s)
1154 || isCaptureOf(s, t)
1155 || ((t.isExtendsBound() || isSubtypeNoCapture(L(t), lowerBound(s))) &&
1156 (t.isSuperBound() || isSubtypeNoCapture(upperBound(s), U(t))));
1157 }
1158 }
1160 @Override
1161 public Boolean visitUndetVar(UndetVar t, Type s) {
1162 if (s.tag != WILDCARD)
1163 return isSameType(t, s);
1164 else
1165 return false;
1166 }
1168 @Override
1169 public Boolean visitErrorType(ErrorType t, Type s) {
1170 return true;
1171 }
1172 };
1174 public boolean isCaptureOf(Type s, WildcardType t) {
1175 if (s.tag != TYPEVAR || !((TypeVar)s).isCaptured())
1176 return false;
1177 return isSameWildcard(t, ((CapturedType)s).wildcard);
1178 }
1180 public boolean isSameWildcard(WildcardType t, Type s) {
1181 if (s.tag != WILDCARD)
1182 return false;
1183 WildcardType w = (WildcardType)s;
1184 return w.kind == t.kind && w.type == t.type;
1185 }
1187 public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) {
1188 while (ts.nonEmpty() && ss.nonEmpty()
1189 && containsTypeEquivalent(ts.head, ss.head)) {
1190 ts = ts.tail;
1191 ss = ss.tail;
1192 }
1193 return ts.isEmpty() && ss.isEmpty();
1194 }
1195 // </editor-fold>
1197 // <editor-fold defaultstate="collapsed" desc="isCastable">
1198 public boolean isCastable(Type t, Type s) {
1199 return isCastable(t, s, Warner.noWarnings);
1200 }
1202 /**
1203 * Is t is castable to s?<br>
1204 * s is assumed to be an erased type.<br>
1205 * (not defined for Method and ForAll types).
1206 */
1207 public boolean isCastable(Type t, Type s, Warner warn) {
1208 if (t == s)
1209 return true;
1211 if (t.isPrimitive() != s.isPrimitive())
1212 return allowBoxing && (
1213 isConvertible(t, s, warn)
1214 || (allowObjectToPrimitiveCast &&
1215 s.isPrimitive() &&
1216 isSubtype(boxedClass(s).type, t)));
1217 if (warn != warnStack.head) {
1218 try {
1219 warnStack = warnStack.prepend(warn);
1220 checkUnsafeVarargsConversion(t, s, warn);
1221 return isCastable.visit(t,s);
1222 } finally {
1223 warnStack = warnStack.tail;
1224 }
1225 } else {
1226 return isCastable.visit(t,s);
1227 }
1228 }
1229 // where
1230 private TypeRelation isCastable = new TypeRelation() {
1232 public Boolean visitType(Type t, Type s) {
1233 if (s.tag == ERROR)
1234 return true;
1236 switch (t.tag) {
1237 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
1238 case DOUBLE:
1239 return s.isNumeric();
1240 case BOOLEAN:
1241 return s.tag == BOOLEAN;
1242 case VOID:
1243 return false;
1244 case BOT:
1245 return isSubtype(t, s);
1246 default:
1247 throw new AssertionError();
1248 }
1249 }
1251 @Override
1252 public Boolean visitWildcardType(WildcardType t, Type s) {
1253 return isCastable(upperBound(t), s, warnStack.head);
1254 }
1256 @Override
1257 public Boolean visitClassType(ClassType t, Type s) {
1258 if (s.tag == ERROR || s.tag == BOT)
1259 return true;
1261 if (s.tag == TYPEVAR) {
1262 if (isCastable(t, s.getUpperBound(), Warner.noWarnings)) {
1263 warnStack.head.warn(LintCategory.UNCHECKED);
1264 return true;
1265 } else {
1266 return false;
1267 }
1268 }
1270 if (t.isCompound()) {
1271 Warner oldWarner = warnStack.head;
1272 warnStack.head = Warner.noWarnings;
1273 if (!visit(supertype(t), s))
1274 return false;
1275 for (Type intf : interfaces(t)) {
1276 if (!visit(intf, s))
1277 return false;
1278 }
1279 if (warnStack.head.hasLint(LintCategory.UNCHECKED))
1280 oldWarner.warn(LintCategory.UNCHECKED);
1281 return true;
1282 }
1284 if (s.isCompound()) {
1285 // call recursively to reuse the above code
1286 return visitClassType((ClassType)s, t);
1287 }
1289 if (s.tag == CLASS || s.tag == ARRAY) {
1290 boolean upcast;
1291 if ((upcast = isSubtype(erasure(t), erasure(s)))
1292 || isSubtype(erasure(s), erasure(t))) {
1293 if (!upcast && s.tag == ARRAY) {
1294 if (!isReifiable(s))
1295 warnStack.head.warn(LintCategory.UNCHECKED);
1296 return true;
1297 } else if (s.isRaw()) {
1298 return true;
1299 } else if (t.isRaw()) {
1300 if (!isUnbounded(s))
1301 warnStack.head.warn(LintCategory.UNCHECKED);
1302 return true;
1303 }
1304 // Assume |a| <: |b|
1305 final Type a = upcast ? t : s;
1306 final Type b = upcast ? s : t;
1307 final boolean HIGH = true;
1308 final boolean LOW = false;
1309 final boolean DONT_REWRITE_TYPEVARS = false;
1310 Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS);
1311 Type aLow = rewriteQuantifiers(a, LOW, DONT_REWRITE_TYPEVARS);
1312 Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS);
1313 Type bLow = rewriteQuantifiers(b, LOW, DONT_REWRITE_TYPEVARS);
1314 Type lowSub = asSub(bLow, aLow.tsym);
1315 Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
1316 if (highSub == null) {
1317 final boolean REWRITE_TYPEVARS = true;
1318 aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS);
1319 aLow = rewriteQuantifiers(a, LOW, REWRITE_TYPEVARS);
1320 bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS);
1321 bLow = rewriteQuantifiers(b, LOW, REWRITE_TYPEVARS);
1322 lowSub = asSub(bLow, aLow.tsym);
1323 highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
1324 }
1325 if (highSub != null) {
1326 if (!(a.tsym == highSub.tsym && a.tsym == lowSub.tsym)) {
1327 Assert.error(a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym);
1328 }
1329 if (!disjointTypes(aHigh.allparams(), highSub.allparams())
1330 && !disjointTypes(aHigh.allparams(), lowSub.allparams())
1331 && !disjointTypes(aLow.allparams(), highSub.allparams())
1332 && !disjointTypes(aLow.allparams(), lowSub.allparams())) {
1333 if (upcast ? giveWarning(a, b) :
1334 giveWarning(b, a))
1335 warnStack.head.warn(LintCategory.UNCHECKED);
1336 return true;
1337 }
1338 }
1339 if (isReifiable(s))
1340 return isSubtypeUnchecked(a, b);
1341 else
1342 return isSubtypeUnchecked(a, b, warnStack.head);
1343 }
1345 // Sidecast
1346 if (s.tag == CLASS) {
1347 if ((s.tsym.flags() & INTERFACE) != 0) {
1348 return ((t.tsym.flags() & FINAL) == 0)
1349 ? sideCast(t, s, warnStack.head)
1350 : sideCastFinal(t, s, warnStack.head);
1351 } else if ((t.tsym.flags() & INTERFACE) != 0) {
1352 return ((s.tsym.flags() & FINAL) == 0)
1353 ? sideCast(t, s, warnStack.head)
1354 : sideCastFinal(t, s, warnStack.head);
1355 } else {
1356 // unrelated class types
1357 return false;
1358 }
1359 }
1360 }
1361 return false;
1362 }
1364 @Override
1365 public Boolean visitArrayType(ArrayType t, Type s) {
1366 switch (s.tag) {
1367 case ERROR:
1368 case BOT:
1369 return true;
1370 case TYPEVAR:
1371 if (isCastable(s, t, Warner.noWarnings)) {
1372 warnStack.head.warn(LintCategory.UNCHECKED);
1373 return true;
1374 } else {
1375 return false;
1376 }
1377 case CLASS:
1378 return isSubtype(t, s);
1379 case ARRAY:
1380 if (elemtype(t).isPrimitive() || elemtype(s).isPrimitive()) {
1381 return elemtype(t).tag == elemtype(s).tag;
1382 } else {
1383 return visit(elemtype(t), elemtype(s));
1384 }
1385 default:
1386 return false;
1387 }
1388 }
1390 @Override
1391 public Boolean visitTypeVar(TypeVar t, Type s) {
1392 switch (s.tag) {
1393 case ERROR:
1394 case BOT:
1395 return true;
1396 case TYPEVAR:
1397 if (isSubtype(t, s)) {
1398 return true;
1399 } else if (isCastable(t.bound, s, Warner.noWarnings)) {
1400 warnStack.head.warn(LintCategory.UNCHECKED);
1401 return true;
1402 } else {
1403 return false;
1404 }
1405 default:
1406 return isCastable(t.bound, s, warnStack.head);
1407 }
1408 }
1410 @Override
1411 public Boolean visitErrorType(ErrorType t, Type s) {
1412 return true;
1413 }
1414 };
1415 // </editor-fold>
1417 // <editor-fold defaultstate="collapsed" desc="disjointTypes">
1418 public boolean disjointTypes(List<Type> ts, List<Type> ss) {
1419 while (ts.tail != null && ss.tail != null) {
1420 if (disjointType(ts.head, ss.head)) return true;
1421 ts = ts.tail;
1422 ss = ss.tail;
1423 }
1424 return false;
1425 }
1427 /**
1428 * Two types or wildcards are considered disjoint if it can be
1429 * proven that no type can be contained in both. It is
1430 * conservative in that it is allowed to say that two types are
1431 * not disjoint, even though they actually are.
1432 *
1433 * The type {@code C<X>} is castable to {@code C<Y>} exactly if
1434 * {@code X} and {@code Y} are not disjoint.
1435 */
1436 public boolean disjointType(Type t, Type s) {
1437 return disjointType.visit(t, s);
1438 }
1439 // where
1440 private TypeRelation disjointType = new TypeRelation() {
1442 private Set<TypePair> cache = new HashSet<TypePair>();
1444 public Boolean visitType(Type t, Type s) {
1445 if (s.tag == WILDCARD)
1446 return visit(s, t);
1447 else
1448 return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
1449 }
1451 private boolean isCastableRecursive(Type t, Type s) {
1452 TypePair pair = new TypePair(t, s);
1453 if (cache.add(pair)) {
1454 try {
1455 return Types.this.isCastable(t, s);
1456 } finally {
1457 cache.remove(pair);
1458 }
1459 } else {
1460 return true;
1461 }
1462 }
1464 private boolean notSoftSubtypeRecursive(Type t, Type s) {
1465 TypePair pair = new TypePair(t, s);
1466 if (cache.add(pair)) {
1467 try {
1468 return Types.this.notSoftSubtype(t, s);
1469 } finally {
1470 cache.remove(pair);
1471 }
1472 } else {
1473 return false;
1474 }
1475 }
1477 @Override
1478 public Boolean visitWildcardType(WildcardType t, Type s) {
1479 if (t.isUnbound())
1480 return false;
1482 if (s.tag != WILDCARD) {
1483 if (t.isExtendsBound())
1484 return notSoftSubtypeRecursive(s, t.type);
1485 else // isSuperBound()
1486 return notSoftSubtypeRecursive(t.type, s);
1487 }
1489 if (s.isUnbound())
1490 return false;
1492 if (t.isExtendsBound()) {
1493 if (s.isExtendsBound())
1494 return !isCastableRecursive(t.type, upperBound(s));
1495 else if (s.isSuperBound())
1496 return notSoftSubtypeRecursive(lowerBound(s), t.type);
1497 } else if (t.isSuperBound()) {
1498 if (s.isExtendsBound())
1499 return notSoftSubtypeRecursive(t.type, upperBound(s));
1500 }
1501 return false;
1502 }
1503 };
1504 // </editor-fold>
1506 // <editor-fold defaultstate="collapsed" desc="lowerBoundArgtypes">
1507 /**
1508 * Returns the lower bounds of the formals of a method.
1509 */
1510 public List<Type> lowerBoundArgtypes(Type t) {
1511 return lowerBounds(t.getParameterTypes());
1512 }
1513 public List<Type> lowerBounds(List<Type> ts) {
1514 return map(ts, lowerBoundMapping);
1515 }
1516 private final Mapping lowerBoundMapping = new Mapping("lowerBound") {
1517 public Type apply(Type t) {
1518 return lowerBound(t);
1519 }
1520 };
1521 // </editor-fold>
1523 // <editor-fold defaultstate="collapsed" desc="notSoftSubtype">
1524 /**
1525 * This relation answers the question: is impossible that
1526 * something of type `t' can be a subtype of `s'? This is
1527 * different from the question "is `t' not a subtype of `s'?"
1528 * when type variables are involved: Integer is not a subtype of T
1529 * where {@code <T extends Number>} but it is not true that Integer cannot
1530 * possibly be a subtype of T.
1531 */
1532 public boolean notSoftSubtype(Type t, Type s) {
1533 if (t == s) return false;
1534 if (t.tag == TYPEVAR) {
1535 TypeVar tv = (TypeVar) t;
1536 return !isCastable(tv.bound,
1537 relaxBound(s),
1538 Warner.noWarnings);
1539 }
1540 if (s.tag != WILDCARD)
1541 s = upperBound(s);
1543 return !isSubtype(t, relaxBound(s));
1544 }
1546 private Type relaxBound(Type t) {
1547 if (t.tag == TYPEVAR) {
1548 while (t.tag == TYPEVAR)
1549 t = t.getUpperBound();
1550 t = rewriteQuantifiers(t, true, true);
1551 }
1552 return t;
1553 }
1554 // </editor-fold>
1556 // <editor-fold defaultstate="collapsed" desc="isReifiable">
1557 public boolean isReifiable(Type t) {
1558 return isReifiable.visit(t);
1559 }
1560 // where
1561 private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() {
1563 public Boolean visitType(Type t, Void ignored) {
1564 return true;
1565 }
1567 @Override
1568 public Boolean visitClassType(ClassType t, Void ignored) {
1569 if (t.isCompound())
1570 return false;
1571 else {
1572 if (!t.isParameterized())
1573 return true;
1575 for (Type param : t.allparams()) {
1576 if (!param.isUnbound())
1577 return false;
1578 }
1579 return true;
1580 }
1581 }
1583 @Override
1584 public Boolean visitArrayType(ArrayType t, Void ignored) {
1585 return visit(t.elemtype);
1586 }
1588 @Override
1589 public Boolean visitTypeVar(TypeVar t, Void ignored) {
1590 return false;
1591 }
1592 };
1593 // </editor-fold>
1595 // <editor-fold defaultstate="collapsed" desc="Array Utils">
1596 public boolean isArray(Type t) {
1597 while (t.tag == WILDCARD)
1598 t = upperBound(t);
1599 return t.tag == ARRAY;
1600 }
1602 /**
1603 * The element type of an array.
1604 */
1605 public Type elemtype(Type t) {
1606 switch (t.tag) {
1607 case WILDCARD:
1608 return elemtype(upperBound(t));
1609 case ARRAY:
1610 return ((ArrayType)t).elemtype;
1611 case FORALL:
1612 return elemtype(((ForAll)t).qtype);
1613 case ERROR:
1614 return t;
1615 default:
1616 return null;
1617 }
1618 }
1620 public Type elemtypeOrType(Type t) {
1621 Type elemtype = elemtype(t);
1622 return elemtype != null ?
1623 elemtype :
1624 t;
1625 }
1627 /**
1628 * Mapping to take element type of an arraytype
1629 */
1630 private Mapping elemTypeFun = new Mapping ("elemTypeFun") {
1631 public Type apply(Type t) { return elemtype(t); }
1632 };
1634 /**
1635 * The number of dimensions of an array type.
1636 */
1637 public int dimensions(Type t) {
1638 int result = 0;
1639 while (t.tag == ARRAY) {
1640 result++;
1641 t = elemtype(t);
1642 }
1643 return result;
1644 }
1646 /**
1647 * Returns an ArrayType with the component type t
1648 *
1649 * @param t The component type of the ArrayType
1650 * @return the ArrayType for the given component
1651 */
1652 public ArrayType makeArrayType(Type t) {
1653 if (t.tag == VOID ||
1654 t.tag == PACKAGE) {
1655 Assert.error("Type t must not be a VOID or PACKAGE type, " + t.toString());
1656 }
1657 return new ArrayType(t, syms.arrayClass);
1658 }
1659 // </editor-fold>
1661 // <editor-fold defaultstate="collapsed" desc="asSuper">
1662 /**
1663 * Return the (most specific) base type of t that starts with the
1664 * given symbol. If none exists, return null.
1665 *
1666 * @param t a type
1667 * @param sym a symbol
1668 */
1669 public Type asSuper(Type t, Symbol sym) {
1670 return asSuper.visit(t, sym);
1671 }
1672 // where
1673 private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor<Type,Symbol>() {
1675 public Type visitType(Type t, Symbol sym) {
1676 return null;
1677 }
1679 @Override
1680 public Type visitClassType(ClassType t, Symbol sym) {
1681 if (t.tsym == sym)
1682 return t;
1684 Type st = supertype(t);
1685 if (st.tag == CLASS || st.tag == TYPEVAR || st.tag == ERROR) {
1686 Type x = asSuper(st, sym);
1687 if (x != null)
1688 return x;
1689 }
1690 if ((sym.flags() & INTERFACE) != 0) {
1691 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
1692 Type x = asSuper(l.head, sym);
1693 if (x != null)
1694 return x;
1695 }
1696 }
1697 return null;
1698 }
1700 @Override
1701 public Type visitArrayType(ArrayType t, Symbol sym) {
1702 return isSubtype(t, sym.type) ? sym.type : null;
1703 }
1705 @Override
1706 public Type visitTypeVar(TypeVar t, Symbol sym) {
1707 if (t.tsym == sym)
1708 return t;
1709 else
1710 return asSuper(t.bound, sym);
1711 }
1713 @Override
1714 public Type visitErrorType(ErrorType t, Symbol sym) {
1715 return t;
1716 }
1717 };
1719 /**
1720 * Return the base type of t or any of its outer types that starts
1721 * with the given symbol. If none exists, return null.
1722 *
1723 * @param t a type
1724 * @param sym a symbol
1725 */
1726 public Type asOuterSuper(Type t, Symbol sym) {
1727 switch (t.tag) {
1728 case CLASS:
1729 do {
1730 Type s = asSuper(t, sym);
1731 if (s != null) return s;
1732 t = t.getEnclosingType();
1733 } while (t.tag == CLASS);
1734 return null;
1735 case ARRAY:
1736 return isSubtype(t, sym.type) ? sym.type : null;
1737 case TYPEVAR:
1738 return asSuper(t, sym);
1739 case ERROR:
1740 return t;
1741 default:
1742 return null;
1743 }
1744 }
1746 /**
1747 * Return the base type of t or any of its enclosing types that
1748 * starts with the given symbol. If none exists, return null.
1749 *
1750 * @param t a type
1751 * @param sym a symbol
1752 */
1753 public Type asEnclosingSuper(Type t, Symbol sym) {
1754 switch (t.tag) {
1755 case CLASS:
1756 do {
1757 Type s = asSuper(t, sym);
1758 if (s != null) return s;
1759 Type outer = t.getEnclosingType();
1760 t = (outer.tag == CLASS) ? outer :
1761 (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type :
1762 Type.noType;
1763 } while (t.tag == CLASS);
1764 return null;
1765 case ARRAY:
1766 return isSubtype(t, sym.type) ? sym.type : null;
1767 case TYPEVAR:
1768 return asSuper(t, sym);
1769 case ERROR:
1770 return t;
1771 default:
1772 return null;
1773 }
1774 }
1775 // </editor-fold>
1777 // <editor-fold defaultstate="collapsed" desc="memberType">
1778 /**
1779 * The type of given symbol, seen as a member of t.
1780 *
1781 * @param t a type
1782 * @param sym a symbol
1783 */
1784 public Type memberType(Type t, Symbol sym) {
1785 return (sym.flags() & STATIC) != 0
1786 ? sym.type
1787 : memberType.visit(t, sym);
1788 }
1789 // where
1790 private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor<Type,Symbol>() {
1792 public Type visitType(Type t, Symbol sym) {
1793 return sym.type;
1794 }
1796 @Override
1797 public Type visitWildcardType(WildcardType t, Symbol sym) {
1798 return memberType(upperBound(t), sym);
1799 }
1801 @Override
1802 public Type visitClassType(ClassType t, Symbol sym) {
1803 Symbol owner = sym.owner;
1804 long flags = sym.flags();
1805 if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
1806 Type base = asOuterSuper(t, owner);
1807 //if t is an intersection type T = CT & I1 & I2 ... & In
1808 //its supertypes CT, I1, ... In might contain wildcards
1809 //so we need to go through capture conversion
1810 base = t.isCompound() ? capture(base) : base;
1811 if (base != null) {
1812 List<Type> ownerParams = owner.type.allparams();
1813 List<Type> baseParams = base.allparams();
1814 if (ownerParams.nonEmpty()) {
1815 if (baseParams.isEmpty()) {
1816 // then base is a raw type
1817 return erasure(sym.type);
1818 } else {
1819 return subst(sym.type, ownerParams, baseParams);
1820 }
1821 }
1822 }
1823 }
1824 return sym.type;
1825 }
1827 @Override
1828 public Type visitTypeVar(TypeVar t, Symbol sym) {
1829 return memberType(t.bound, sym);
1830 }
1832 @Override
1833 public Type visitErrorType(ErrorType t, Symbol sym) {
1834 return t;
1835 }
1836 };
1837 // </editor-fold>
1839 // <editor-fold defaultstate="collapsed" desc="isAssignable">
1840 public boolean isAssignable(Type t, Type s) {
1841 return isAssignable(t, s, Warner.noWarnings);
1842 }
1844 /**
1845 * Is t assignable to s?<br>
1846 * Equivalent to subtype except for constant values and raw
1847 * types.<br>
1848 * (not defined for Method and ForAll types)
1849 */
1850 public boolean isAssignable(Type t, Type s, Warner warn) {
1851 if (t.tag == ERROR)
1852 return true;
1853 if (t.tag.isSubRangeOf(INT) && t.constValue() != null) {
1854 int value = ((Number)t.constValue()).intValue();
1855 switch (s.tag) {
1856 case BYTE:
1857 if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE)
1858 return true;
1859 break;
1860 case CHAR:
1861 if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE)
1862 return true;
1863 break;
1864 case SHORT:
1865 if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE)
1866 return true;
1867 break;
1868 case INT:
1869 return true;
1870 case CLASS:
1871 switch (unboxedType(s).tag) {
1872 case BYTE:
1873 case CHAR:
1874 case SHORT:
1875 return isAssignable(t, unboxedType(s), warn);
1876 }
1877 break;
1878 }
1879 }
1880 return isConvertible(t, s, warn);
1881 }
1882 // </editor-fold>
1884 // <editor-fold defaultstate="collapsed" desc="erasure">
1885 /**
1886 * The erasure of t {@code |t|} -- the type that results when all
1887 * type parameters in t are deleted.
1888 */
1889 public Type erasure(Type t) {
1890 return eraseNotNeeded(t)? t : erasure(t, false);
1891 }
1892 //where
1893 private boolean eraseNotNeeded(Type t) {
1894 // We don't want to erase primitive types and String type as that
1895 // operation is idempotent. Also, erasing these could result in loss
1896 // of information such as constant values attached to such types.
1897 return (t.isPrimitive()) || (syms.stringType.tsym == t.tsym);
1898 }
1900 private Type erasure(Type t, boolean recurse) {
1901 if (t.isPrimitive())
1902 return t; /* fast special case */
1903 else
1904 return erasure.visit(t, recurse);
1905 }
1906 // where
1907 private SimpleVisitor<Type, Boolean> erasure = new SimpleVisitor<Type, Boolean>() {
1908 public Type visitType(Type t, Boolean recurse) {
1909 if (t.isPrimitive())
1910 return t; /*fast special case*/
1911 else
1912 return t.map(recurse ? erasureRecFun : erasureFun);
1913 }
1915 @Override
1916 public Type visitWildcardType(WildcardType t, Boolean recurse) {
1917 return erasure(upperBound(t), recurse);
1918 }
1920 @Override
1921 public Type visitClassType(ClassType t, Boolean recurse) {
1922 Type erased = t.tsym.erasure(Types.this);
1923 if (recurse) {
1924 erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym);
1925 }
1926 return erased;
1927 }
1929 @Override
1930 public Type visitTypeVar(TypeVar t, Boolean recurse) {
1931 return erasure(t.bound, recurse);
1932 }
1934 @Override
1935 public Type visitErrorType(ErrorType t, Boolean recurse) {
1936 return t;
1937 }
1938 };
1940 private Mapping erasureFun = new Mapping ("erasure") {
1941 public Type apply(Type t) { return erasure(t); }
1942 };
1944 private Mapping erasureRecFun = new Mapping ("erasureRecursive") {
1945 public Type apply(Type t) { return erasureRecursive(t); }
1946 };
1948 public List<Type> erasure(List<Type> ts) {
1949 return Type.map(ts, erasureFun);
1950 }
1952 public Type erasureRecursive(Type t) {
1953 return erasure(t, true);
1954 }
1956 public List<Type> erasureRecursive(List<Type> ts) {
1957 return Type.map(ts, erasureRecFun);
1958 }
1959 // </editor-fold>
1961 // <editor-fold defaultstate="collapsed" desc="makeCompoundType">
1962 /**
1963 * Make a compound type from non-empty list of types
1964 *
1965 * @param bounds the types from which the compound type is formed
1966 * @param supertype is objectType if all bounds are interfaces,
1967 * null otherwise.
1968 */
1969 public Type makeCompoundType(List<Type> bounds,
1970 Type supertype) {
1971 ClassSymbol bc =
1972 new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
1973 Type.moreInfo
1974 ? names.fromString(bounds.toString())
1975 : names.empty,
1976 syms.noSymbol);
1977 if (bounds.head.tag == TYPEVAR)
1978 // error condition, recover
1979 bc.erasure_field = syms.objectType;
1980 else
1981 bc.erasure_field = erasure(bounds.head);
1982 bc.members_field = new Scope(bc);
1983 ClassType bt = (ClassType)bc.type;
1984 bt.allparams_field = List.nil();
1985 if (supertype != null) {
1986 bt.supertype_field = supertype;
1987 bt.interfaces_field = bounds;
1988 } else {
1989 bt.supertype_field = bounds.head;
1990 bt.interfaces_field = bounds.tail;
1991 }
1992 Assert.check(bt.supertype_field.tsym.completer != null
1993 || !bt.supertype_field.isInterface(),
1994 bt.supertype_field);
1995 return bt;
1996 }
1998 /**
1999 * Same as {@link #makeCompoundType(List,Type)}, except that the
2000 * second parameter is computed directly. Note that this might
2001 * cause a symbol completion. Hence, this version of
2002 * makeCompoundType may not be called during a classfile read.
2003 */
2004 public Type makeCompoundType(List<Type> bounds) {
2005 Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
2006 supertype(bounds.head) : null;
2007 return makeCompoundType(bounds, supertype);
2008 }
2010 /**
2011 * A convenience wrapper for {@link #makeCompoundType(List)}; the
2012 * arguments are converted to a list and passed to the other
2013 * method. Note that this might cause a symbol completion.
2014 * Hence, this version of makeCompoundType may not be called
2015 * during a classfile read.
2016 */
2017 public Type makeCompoundType(Type bound1, Type bound2) {
2018 return makeCompoundType(List.of(bound1, bound2));
2019 }
2020 // </editor-fold>
2022 // <editor-fold defaultstate="collapsed" desc="supertype">
2023 public Type supertype(Type t) {
2024 return supertype.visit(t);
2025 }
2026 // where
2027 private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() {
2029 public Type visitType(Type t, Void ignored) {
2030 // A note on wildcards: there is no good way to
2031 // determine a supertype for a super bounded wildcard.
2032 return null;
2033 }
2035 @Override
2036 public Type visitClassType(ClassType t, Void ignored) {
2037 if (t.supertype_field == null) {
2038 Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
2039 // An interface has no superclass; its supertype is Object.
2040 if (t.isInterface())
2041 supertype = ((ClassType)t.tsym.type).supertype_field;
2042 if (t.supertype_field == null) {
2043 List<Type> actuals = classBound(t).allparams();
2044 List<Type> formals = t.tsym.type.allparams();
2045 if (t.hasErasedSupertypes()) {
2046 t.supertype_field = erasureRecursive(supertype);
2047 } else if (formals.nonEmpty()) {
2048 t.supertype_field = subst(supertype, formals, actuals);
2049 }
2050 else {
2051 t.supertype_field = supertype;
2052 }
2053 }
2054 }
2055 return t.supertype_field;
2056 }
2058 /**
2059 * The supertype is always a class type. If the type
2060 * variable's bounds start with a class type, this is also
2061 * the supertype. Otherwise, the supertype is
2062 * java.lang.Object.
2063 */
2064 @Override
2065 public Type visitTypeVar(TypeVar t, Void ignored) {
2066 if (t.bound.tag == TYPEVAR ||
2067 (!t.bound.isCompound() && !t.bound.isInterface())) {
2068 return t.bound;
2069 } else {
2070 return supertype(t.bound);
2071 }
2072 }
2074 @Override
2075 public Type visitArrayType(ArrayType t, Void ignored) {
2076 if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
2077 return arraySuperType();
2078 else
2079 return new ArrayType(supertype(t.elemtype), t.tsym);
2080 }
2082 @Override
2083 public Type visitErrorType(ErrorType t, Void ignored) {
2084 return t;
2085 }
2086 };
2087 // </editor-fold>
2089 // <editor-fold defaultstate="collapsed" desc="interfaces">
2090 /**
2091 * Return the interfaces implemented by this class.
2092 */
2093 public List<Type> interfaces(Type t) {
2094 return interfaces.visit(t);
2095 }
2096 // where
2097 private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() {
2099 public List<Type> visitType(Type t, Void ignored) {
2100 return List.nil();
2101 }
2103 @Override
2104 public List<Type> visitClassType(ClassType t, Void ignored) {
2105 if (t.interfaces_field == null) {
2106 List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces();
2107 if (t.interfaces_field == null) {
2108 // If t.interfaces_field is null, then t must
2109 // be a parameterized type (not to be confused
2110 // with a generic type declaration).
2111 // Terminology:
2112 // Parameterized type: List<String>
2113 // Generic type declaration: class List<E> { ... }
2114 // So t corresponds to List<String> and
2115 // t.tsym.type corresponds to List<E>.
2116 // The reason t must be parameterized type is
2117 // that completion will happen as a side
2118 // effect of calling
2119 // ClassSymbol.getInterfaces. Since
2120 // t.interfaces_field is null after
2121 // completion, we can assume that t is not the
2122 // type of a class/interface declaration.
2123 Assert.check(t != t.tsym.type, t);
2124 List<Type> actuals = t.allparams();
2125 List<Type> formals = t.tsym.type.allparams();
2126 if (t.hasErasedSupertypes()) {
2127 t.interfaces_field = erasureRecursive(interfaces);
2128 } else if (formals.nonEmpty()) {
2129 t.interfaces_field =
2130 upperBounds(subst(interfaces, formals, actuals));
2131 }
2132 else {
2133 t.interfaces_field = interfaces;
2134 }
2135 }
2136 }
2137 return t.interfaces_field;
2138 }
2140 @Override
2141 public List<Type> visitTypeVar(TypeVar t, Void ignored) {
2142 if (t.bound.isCompound())
2143 return interfaces(t.bound);
2145 if (t.bound.isInterface())
2146 return List.of(t.bound);
2148 return List.nil();
2149 }
2150 };
2152 public boolean isDirectSuperInterface(Type t, TypeSymbol tsym) {
2153 for (Type t2 : interfaces(tsym.type)) {
2154 if (isSameType(t, t2)) return true;
2155 }
2156 return false;
2157 }
2158 // </editor-fold>
2160 // <editor-fold defaultstate="collapsed" desc="isDerivedRaw">
2161 Map<Type,Boolean> isDerivedRawCache = new HashMap<Type,Boolean>();
2163 public boolean isDerivedRaw(Type t) {
2164 Boolean result = isDerivedRawCache.get(t);
2165 if (result == null) {
2166 result = isDerivedRawInternal(t);
2167 isDerivedRawCache.put(t, result);
2168 }
2169 return result;
2170 }
2172 public boolean isDerivedRawInternal(Type t) {
2173 if (t.isErroneous())
2174 return false;
2175 return
2176 t.isRaw() ||
2177 supertype(t) != null && isDerivedRaw(supertype(t)) ||
2178 isDerivedRaw(interfaces(t));
2179 }
2181 public boolean isDerivedRaw(List<Type> ts) {
2182 List<Type> l = ts;
2183 while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
2184 return l.nonEmpty();
2185 }
2186 // </editor-fold>
2188 // <editor-fold defaultstate="collapsed" desc="setBounds">
2189 /**
2190 * Set the bounds field of the given type variable to reflect a
2191 * (possibly multiple) list of bounds.
2192 * @param t a type variable
2193 * @param bounds the bounds, must be nonempty
2194 * @param supertype is objectType if all bounds are interfaces,
2195 * null otherwise.
2196 */
2197 public void setBounds(TypeVar t, List<Type> bounds, Type supertype) {
2198 if (bounds.tail.isEmpty())
2199 t.bound = bounds.head;
2200 else
2201 t.bound = makeCompoundType(bounds, supertype);
2202 t.rank_field = -1;
2203 }
2205 /**
2206 * Same as {@link #setBounds(Type.TypeVar,List,Type)}, except that
2207 * third parameter is computed directly, as follows: if all
2208 * all bounds are interface types, the computed supertype is Object,
2209 * otherwise the supertype is simply left null (in this case, the supertype
2210 * is assumed to be the head of the bound list passed as second argument).
2211 * Note that this check might cause a symbol completion. Hence, this version of
2212 * setBounds may not be called during a classfile read.
2213 */
2214 public void setBounds(TypeVar t, List<Type> bounds) {
2215 Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
2216 syms.objectType : null;
2217 setBounds(t, bounds, supertype);
2218 t.rank_field = -1;
2219 }
2220 // </editor-fold>
2222 // <editor-fold defaultstate="collapsed" desc="getBounds">
2223 /**
2224 * Return list of bounds of the given type variable.
2225 */
2226 public List<Type> getBounds(TypeVar t) {
2227 if (t.bound.isErroneous() || !t.bound.isCompound())
2228 return List.of(t.bound);
2229 else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
2230 return interfaces(t).prepend(supertype(t));
2231 else
2232 // No superclass was given in bounds.
2233 // In this case, supertype is Object, erasure is first interface.
2234 return interfaces(t);
2235 }
2236 // </editor-fold>
2238 // <editor-fold defaultstate="collapsed" desc="classBound">
2239 /**
2240 * If the given type is a (possibly selected) type variable,
2241 * return the bounding class of this type, otherwise return the
2242 * type itself.
2243 */
2244 public Type classBound(Type t) {
2245 return classBound.visit(t);
2246 }
2247 // where
2248 private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() {
2250 public Type visitType(Type t, Void ignored) {
2251 return t;
2252 }
2254 @Override
2255 public Type visitClassType(ClassType t, Void ignored) {
2256 Type outer1 = classBound(t.getEnclosingType());
2257 if (outer1 != t.getEnclosingType())
2258 return new ClassType(outer1, t.getTypeArguments(), t.tsym);
2259 else
2260 return t;
2261 }
2263 @Override
2264 public Type visitTypeVar(TypeVar t, Void ignored) {
2265 return classBound(supertype(t));
2266 }
2268 @Override
2269 public Type visitErrorType(ErrorType t, Void ignored) {
2270 return t;
2271 }
2272 };
2273 // </editor-fold>
2275 // <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence">
2276 /**
2277 * Returns true iff the first signature is a <em>sub
2278 * signature</em> of the other. This is <b>not</b> an equivalence
2279 * relation.
2280 *
2281 * @jls section 8.4.2.
2282 * @see #overrideEquivalent(Type t, Type s)
2283 * @param t first signature (possibly raw).
2284 * @param s second signature (could be subjected to erasure).
2285 * @return true if t is a sub signature of s.
2286 */
2287 public boolean isSubSignature(Type t, Type s) {
2288 return isSubSignature(t, s, true);
2289 }
2291 public boolean isSubSignature(Type t, Type s, boolean strict) {
2292 return hasSameArgs(t, s, strict) || hasSameArgs(t, erasure(s), strict);
2293 }
2295 /**
2296 * Returns true iff these signatures are related by <em>override
2297 * equivalence</em>. This is the natural extension of
2298 * isSubSignature to an equivalence relation.
2299 *
2300 * @jls section 8.4.2.
2301 * @see #isSubSignature(Type t, Type s)
2302 * @param t a signature (possible raw, could be subjected to
2303 * erasure).
2304 * @param s a signature (possible raw, could be subjected to
2305 * erasure).
2306 * @return true if either argument is a sub signature of the other.
2307 */
2308 public boolean overrideEquivalent(Type t, Type s) {
2309 return hasSameArgs(t, s) ||
2310 hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
2311 }
2313 public boolean overridesObjectMethod(TypeSymbol origin, Symbol msym) {
2314 for (Scope.Entry e = syms.objectType.tsym.members().lookup(msym.name) ; e.scope != null ; e = e.next()) {
2315 if (msym.overrides(e.sym, origin, Types.this, true)) {
2316 return true;
2317 }
2318 }
2319 return false;
2320 }
2322 public boolean overridesObjectMethod(Symbol msym) {
2323 return ((MethodSymbol)msym).implementation(syms.objectType.tsym, this, true) != null;
2324 }
2326 // <editor-fold defaultstate="collapsed" desc="Determining method implementation in given site">
2327 class ImplementationCache {
2329 private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>> _map =
2330 new WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>>();
2332 class Entry {
2333 final MethodSymbol cachedImpl;
2334 final Filter<Symbol> implFilter;
2335 final boolean checkResult;
2336 final int prevMark;
2338 public Entry(MethodSymbol cachedImpl,
2339 Filter<Symbol> scopeFilter,
2340 boolean checkResult,
2341 int prevMark) {
2342 this.cachedImpl = cachedImpl;
2343 this.implFilter = scopeFilter;
2344 this.checkResult = checkResult;
2345 this.prevMark = prevMark;
2346 }
2348 boolean matches(Filter<Symbol> scopeFilter, boolean checkResult, int mark) {
2349 return this.implFilter == scopeFilter &&
2350 this.checkResult == checkResult &&
2351 this.prevMark == mark;
2352 }
2353 }
2355 MethodSymbol get(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
2356 SoftReference<Map<TypeSymbol, Entry>> ref_cache = _map.get(ms);
2357 Map<TypeSymbol, Entry> cache = ref_cache != null ? ref_cache.get() : null;
2358 if (cache == null) {
2359 cache = new HashMap<TypeSymbol, Entry>();
2360 _map.put(ms, new SoftReference<Map<TypeSymbol, Entry>>(cache));
2361 }
2362 Entry e = cache.get(origin);
2363 CompoundScope members = membersClosure(origin.type, true);
2364 if (e == null ||
2365 !e.matches(implFilter, checkResult, members.getMark())) {
2366 MethodSymbol impl = implementationInternal(ms, origin, checkResult, implFilter);
2367 cache.put(origin, new Entry(impl, implFilter, checkResult, members.getMark()));
2368 return impl;
2369 }
2370 else {
2371 return e.cachedImpl;
2372 }
2373 }
2375 private MethodSymbol implementationInternal(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
2376 for (Type t = origin.type; t.tag == CLASS || t.tag == TYPEVAR; t = supertype(t)) {
2377 while (t.tag == TYPEVAR)
2378 t = t.getUpperBound();
2379 TypeSymbol c = t.tsym;
2380 for (Scope.Entry e = c.members().lookup(ms.name, implFilter);
2381 e.scope != null;
2382 e = e.next(implFilter)) {
2383 if (e.sym != null &&
2384 e.sym.overrides(ms, origin, Types.this, checkResult))
2385 return (MethodSymbol)e.sym;
2386 }
2387 }
2388 return null;
2389 }
2390 }
2392 private ImplementationCache implCache = new ImplementationCache();
2394 public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
2395 return implCache.get(ms, origin, checkResult, implFilter);
2396 }
2397 // </editor-fold>
2399 // <editor-fold defaultstate="collapsed" desc="compute transitive closure of all members in given site">
2400 class MembersClosureCache extends SimpleVisitor<CompoundScope, Boolean> {
2402 private WeakHashMap<TypeSymbol, Entry> _map =
2403 new WeakHashMap<TypeSymbol, Entry>();
2405 class Entry {
2406 final boolean skipInterfaces;
2407 final CompoundScope compoundScope;
2409 public Entry(boolean skipInterfaces, CompoundScope compoundScope) {
2410 this.skipInterfaces = skipInterfaces;
2411 this.compoundScope = compoundScope;
2412 }
2414 boolean matches(boolean skipInterfaces) {
2415 return this.skipInterfaces == skipInterfaces;
2416 }
2417 }
2419 List<TypeSymbol> seenTypes = List.nil();
2421 /** members closure visitor methods **/
2423 public CompoundScope visitType(Type t, Boolean skipInterface) {
2424 return null;
2425 }
2427 @Override
2428 public CompoundScope visitClassType(ClassType t, Boolean skipInterface) {
2429 if (seenTypes.contains(t.tsym)) {
2430 //this is possible when an interface is implemented in multiple
2431 //superclasses, or when a classs hierarchy is circular - in such
2432 //cases we don't need to recurse (empty scope is returned)
2433 return new CompoundScope(t.tsym);
2434 }
2435 try {
2436 seenTypes = seenTypes.prepend(t.tsym);
2437 ClassSymbol csym = (ClassSymbol)t.tsym;
2438 Entry e = _map.get(csym);
2439 if (e == null || !e.matches(skipInterface)) {
2440 CompoundScope membersClosure = new CompoundScope(csym);
2441 if (!skipInterface) {
2442 for (Type i : interfaces(t)) {
2443 membersClosure.addSubScope(visit(i, skipInterface));
2444 }
2445 }
2446 membersClosure.addSubScope(visit(supertype(t), skipInterface));
2447 membersClosure.addSubScope(csym.members());
2448 e = new Entry(skipInterface, membersClosure);
2449 _map.put(csym, e);
2450 }
2451 return e.compoundScope;
2452 }
2453 finally {
2454 seenTypes = seenTypes.tail;
2455 }
2456 }
2458 @Override
2459 public CompoundScope visitTypeVar(TypeVar t, Boolean skipInterface) {
2460 return visit(t.getUpperBound(), skipInterface);
2461 }
2462 }
2464 private MembersClosureCache membersCache = new MembersClosureCache();
2466 public CompoundScope membersClosure(Type site, boolean skipInterface) {
2467 return membersCache.visit(site, skipInterface);
2468 }
2469 // </editor-fold>
2472 //where
2473 public List<MethodSymbol> interfaceCandidates(Type site, MethodSymbol ms) {
2474 return interfaceCandidates(site, ms, false);
2475 }
2477 public List<MethodSymbol> interfaceCandidates(Type site, MethodSymbol ms, boolean intfOnly) {
2478 Filter<Symbol> filter = new MethodFilter(ms, site, intfOnly);
2479 List<MethodSymbol> candidates = List.nil();
2480 for (Symbol s : membersClosure(site, false).getElements(filter)) {
2481 if (!site.tsym.isInterface() && !s.owner.isInterface()) {
2482 return List.of((MethodSymbol)s);
2483 } else if (!candidates.contains(s)) {
2484 candidates = candidates.prepend((MethodSymbol)s);
2485 }
2486 }
2487 return prune(candidates, ownerComparator);
2488 }
2490 public List<MethodSymbol> prune(List<MethodSymbol> methods, Comparator<MethodSymbol> cmp) {
2491 ListBuffer<MethodSymbol> methodsMin = ListBuffer.lb();
2492 for (MethodSymbol m1 : methods) {
2493 boolean isMin_m1 = true;
2494 for (MethodSymbol m2 : methods) {
2495 if (m1 == m2) continue;
2496 if (cmp.compare(m2, m1) < 0) {
2497 isMin_m1 = false;
2498 break;
2499 }
2500 }
2501 if (isMin_m1)
2502 methodsMin.append(m1);
2503 }
2504 return methodsMin.toList();
2505 }
2507 Comparator<MethodSymbol> ownerComparator = new Comparator<MethodSymbol>() {
2508 public int compare(MethodSymbol s1, MethodSymbol s2) {
2509 return s1.owner.isSubClass(s2.owner, Types.this) ? -1 : 1;
2510 }
2511 };
2512 // where
2513 private class MethodFilter implements Filter<Symbol> {
2515 Symbol msym;
2516 Type site;
2517 boolean intfOnly;
2519 MethodFilter(Symbol msym, Type site, boolean intfOnly) {
2520 this.msym = msym;
2521 this.site = site;
2522 this.intfOnly = intfOnly;
2523 }
2525 public boolean accepts(Symbol s) {
2526 return s.kind == Kinds.MTH &&
2527 (!intfOnly || s.owner.isInterface()) &&
2528 s.name == msym.name &&
2529 s.isInheritedIn(site.tsym, Types.this) &&
2530 overrideEquivalent(memberType(site, s), memberType(site, msym));
2531 }
2532 };
2533 // </editor-fold>
2535 /**
2536 * Does t have the same arguments as s? It is assumed that both
2537 * types are (possibly polymorphic) method types. Monomorphic
2538 * method types "have the same arguments", if their argument lists
2539 * are equal. Polymorphic method types "have the same arguments",
2540 * if they have the same arguments after renaming all type
2541 * variables of one to corresponding type variables in the other,
2542 * where correspondence is by position in the type parameter list.
2543 */
2544 public boolean hasSameArgs(Type t, Type s) {
2545 return hasSameArgs(t, s, true);
2546 }
2548 public boolean hasSameArgs(Type t, Type s, boolean strict) {
2549 return hasSameArgs(t, s, strict ? hasSameArgs_strict : hasSameArgs_nonstrict);
2550 }
2552 private boolean hasSameArgs(Type t, Type s, TypeRelation hasSameArgs) {
2553 return hasSameArgs.visit(t, s);
2554 }
2555 // where
2556 private class HasSameArgs extends TypeRelation {
2558 boolean strict;
2560 public HasSameArgs(boolean strict) {
2561 this.strict = strict;
2562 }
2564 public Boolean visitType(Type t, Type s) {
2565 throw new AssertionError();
2566 }
2568 @Override
2569 public Boolean visitMethodType(MethodType t, Type s) {
2570 return s.tag == METHOD
2571 && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
2572 }
2574 @Override
2575 public Boolean visitForAll(ForAll t, Type s) {
2576 if (s.tag != FORALL)
2577 return strict ? false : visitMethodType(t.asMethodType(), s);
2579 ForAll forAll = (ForAll)s;
2580 return hasSameBounds(t, forAll)
2581 && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
2582 }
2584 @Override
2585 public Boolean visitErrorType(ErrorType t, Type s) {
2586 return false;
2587 }
2588 };
2590 TypeRelation hasSameArgs_strict = new HasSameArgs(true);
2591 TypeRelation hasSameArgs_nonstrict = new HasSameArgs(false);
2593 // </editor-fold>
2595 // <editor-fold defaultstate="collapsed" desc="subst">
2596 public List<Type> subst(List<Type> ts,
2597 List<Type> from,
2598 List<Type> to) {
2599 return new Subst(from, to).subst(ts);
2600 }
2602 /**
2603 * Substitute all occurrences of a type in `from' with the
2604 * corresponding type in `to' in 't'. Match lists `from' and `to'
2605 * from the right: If lists have different length, discard leading
2606 * elements of the longer list.
2607 */
2608 public Type subst(Type t, List<Type> from, List<Type> to) {
2609 return new Subst(from, to).subst(t);
2610 }
2612 private class Subst extends UnaryVisitor<Type> {
2613 List<Type> from;
2614 List<Type> to;
2616 public Subst(List<Type> from, List<Type> to) {
2617 int fromLength = from.length();
2618 int toLength = to.length();
2619 while (fromLength > toLength) {
2620 fromLength--;
2621 from = from.tail;
2622 }
2623 while (fromLength < toLength) {
2624 toLength--;
2625 to = to.tail;
2626 }
2627 this.from = from;
2628 this.to = to;
2629 }
2631 Type subst(Type t) {
2632 if (from.tail == null)
2633 return t;
2634 else
2635 return visit(t);
2636 }
2638 List<Type> subst(List<Type> ts) {
2639 if (from.tail == null)
2640 return ts;
2641 boolean wild = false;
2642 if (ts.nonEmpty() && from.nonEmpty()) {
2643 Type head1 = subst(ts.head);
2644 List<Type> tail1 = subst(ts.tail);
2645 if (head1 != ts.head || tail1 != ts.tail)
2646 return tail1.prepend(head1);
2647 }
2648 return ts;
2649 }
2651 public Type visitType(Type t, Void ignored) {
2652 return t;
2653 }
2655 @Override
2656 public Type visitMethodType(MethodType t, Void ignored) {
2657 List<Type> argtypes = subst(t.argtypes);
2658 Type restype = subst(t.restype);
2659 List<Type> thrown = subst(t.thrown);
2660 if (argtypes == t.argtypes &&
2661 restype == t.restype &&
2662 thrown == t.thrown)
2663 return t;
2664 else
2665 return new MethodType(argtypes, restype, thrown, t.tsym);
2666 }
2668 @Override
2669 public Type visitTypeVar(TypeVar t, Void ignored) {
2670 for (List<Type> from = this.from, to = this.to;
2671 from.nonEmpty();
2672 from = from.tail, to = to.tail) {
2673 if (t == from.head) {
2674 return to.head.withTypeVar(t);
2675 }
2676 }
2677 return t;
2678 }
2680 @Override
2681 public Type visitClassType(ClassType t, Void ignored) {
2682 if (!t.isCompound()) {
2683 List<Type> typarams = t.getTypeArguments();
2684 List<Type> typarams1 = subst(typarams);
2685 Type outer = t.getEnclosingType();
2686 Type outer1 = subst(outer);
2687 if (typarams1 == typarams && outer1 == outer)
2688 return t;
2689 else
2690 return new ClassType(outer1, typarams1, t.tsym);
2691 } else {
2692 Type st = subst(supertype(t));
2693 List<Type> is = upperBounds(subst(interfaces(t)));
2694 if (st == supertype(t) && is == interfaces(t))
2695 return t;
2696 else
2697 return makeCompoundType(is.prepend(st));
2698 }
2699 }
2701 @Override
2702 public Type visitWildcardType(WildcardType t, Void ignored) {
2703 Type bound = t.type;
2704 if (t.kind != BoundKind.UNBOUND)
2705 bound = subst(bound);
2706 if (bound == t.type) {
2707 return t;
2708 } else {
2709 if (t.isExtendsBound() && bound.isExtendsBound())
2710 bound = upperBound(bound);
2711 return new WildcardType(bound, t.kind, syms.boundClass, t.bound);
2712 }
2713 }
2715 @Override
2716 public Type visitArrayType(ArrayType t, Void ignored) {
2717 Type elemtype = subst(t.elemtype);
2718 if (elemtype == t.elemtype)
2719 return t;
2720 else
2721 return new ArrayType(upperBound(elemtype), t.tsym);
2722 }
2724 @Override
2725 public Type visitForAll(ForAll t, Void ignored) {
2726 if (Type.containsAny(to, t.tvars)) {
2727 //perform alpha-renaming of free-variables in 't'
2728 //if 'to' types contain variables that are free in 't'
2729 List<Type> freevars = newInstances(t.tvars);
2730 t = new ForAll(freevars,
2731 Types.this.subst(t.qtype, t.tvars, freevars));
2732 }
2733 List<Type> tvars1 = substBounds(t.tvars, from, to);
2734 Type qtype1 = subst(t.qtype);
2735 if (tvars1 == t.tvars && qtype1 == t.qtype) {
2736 return t;
2737 } else if (tvars1 == t.tvars) {
2738 return new ForAll(tvars1, qtype1);
2739 } else {
2740 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1));
2741 }
2742 }
2744 @Override
2745 public Type visitErrorType(ErrorType t, Void ignored) {
2746 return t;
2747 }
2748 }
2750 public List<Type> substBounds(List<Type> tvars,
2751 List<Type> from,
2752 List<Type> to) {
2753 if (tvars.isEmpty())
2754 return tvars;
2755 ListBuffer<Type> newBoundsBuf = lb();
2756 boolean changed = false;
2757 // calculate new bounds
2758 for (Type t : tvars) {
2759 TypeVar tv = (TypeVar) t;
2760 Type bound = subst(tv.bound, from, to);
2761 if (bound != tv.bound)
2762 changed = true;
2763 newBoundsBuf.append(bound);
2764 }
2765 if (!changed)
2766 return tvars;
2767 ListBuffer<Type> newTvars = lb();
2768 // create new type variables without bounds
2769 for (Type t : tvars) {
2770 newTvars.append(new TypeVar(t.tsym, null, syms.botType));
2771 }
2772 // the new bounds should use the new type variables in place
2773 // of the old
2774 List<Type> newBounds = newBoundsBuf.toList();
2775 from = tvars;
2776 to = newTvars.toList();
2777 for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
2778 newBounds.head = subst(newBounds.head, from, to);
2779 }
2780 newBounds = newBoundsBuf.toList();
2781 // set the bounds of new type variables to the new bounds
2782 for (Type t : newTvars.toList()) {
2783 TypeVar tv = (TypeVar) t;
2784 tv.bound = newBounds.head;
2785 newBounds = newBounds.tail;
2786 }
2787 return newTvars.toList();
2788 }
2790 public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
2791 Type bound1 = subst(t.bound, from, to);
2792 if (bound1 == t.bound)
2793 return t;
2794 else {
2795 // create new type variable without bounds
2796 TypeVar tv = new TypeVar(t.tsym, null, syms.botType);
2797 // the new bound should use the new type variable in place
2798 // of the old
2799 tv.bound = subst(bound1, List.<Type>of(t), List.<Type>of(tv));
2800 return tv;
2801 }
2802 }
2803 // </editor-fold>
2805 // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
2806 /**
2807 * Does t have the same bounds for quantified variables as s?
2808 */
2809 boolean hasSameBounds(ForAll t, ForAll s) {
2810 List<Type> l1 = t.tvars;
2811 List<Type> l2 = s.tvars;
2812 while (l1.nonEmpty() && l2.nonEmpty() &&
2813 isSameType(l1.head.getUpperBound(),
2814 subst(l2.head.getUpperBound(),
2815 s.tvars,
2816 t.tvars))) {
2817 l1 = l1.tail;
2818 l2 = l2.tail;
2819 }
2820 return l1.isEmpty() && l2.isEmpty();
2821 }
2822 // </editor-fold>
2824 // <editor-fold defaultstate="collapsed" desc="newInstances">
2825 /** Create new vector of type variables from list of variables
2826 * changing all recursive bounds from old to new list.
2827 */
2828 public List<Type> newInstances(List<Type> tvars) {
2829 List<Type> tvars1 = Type.map(tvars, newInstanceFun);
2830 for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
2831 TypeVar tv = (TypeVar) l.head;
2832 tv.bound = subst(tv.bound, tvars, tvars1);
2833 }
2834 return tvars1;
2835 }
2836 static private Mapping newInstanceFun = new Mapping("newInstanceFun") {
2837 public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); }
2838 };
2839 // </editor-fold>
2841 public Type createMethodTypeWithParameters(Type original, List<Type> newParams) {
2842 return original.accept(methodWithParameters, newParams);
2843 }
2844 // where
2845 private final MapVisitor<List<Type>> methodWithParameters = new MapVisitor<List<Type>>() {
2846 public Type visitType(Type t, List<Type> newParams) {
2847 throw new IllegalArgumentException("Not a method type: " + t);
2848 }
2849 public Type visitMethodType(MethodType t, List<Type> newParams) {
2850 return new MethodType(newParams, t.restype, t.thrown, t.tsym);
2851 }
2852 public Type visitForAll(ForAll t, List<Type> newParams) {
2853 return new ForAll(t.tvars, t.qtype.accept(this, newParams));
2854 }
2855 };
2857 public Type createMethodTypeWithThrown(Type original, List<Type> newThrown) {
2858 return original.accept(methodWithThrown, newThrown);
2859 }
2860 // where
2861 private final MapVisitor<List<Type>> methodWithThrown = new MapVisitor<List<Type>>() {
2862 public Type visitType(Type t, List<Type> newThrown) {
2863 throw new IllegalArgumentException("Not a method type: " + t);
2864 }
2865 public Type visitMethodType(MethodType t, List<Type> newThrown) {
2866 return new MethodType(t.argtypes, t.restype, newThrown, t.tsym);
2867 }
2868 public Type visitForAll(ForAll t, List<Type> newThrown) {
2869 return new ForAll(t.tvars, t.qtype.accept(this, newThrown));
2870 }
2871 };
2873 public Type createMethodTypeWithReturn(Type original, Type newReturn) {
2874 return original.accept(methodWithReturn, newReturn);
2875 }
2876 // where
2877 private final MapVisitor<Type> methodWithReturn = new MapVisitor<Type>() {
2878 public Type visitType(Type t, Type newReturn) {
2879 throw new IllegalArgumentException("Not a method type: " + t);
2880 }
2881 public Type visitMethodType(MethodType t, Type newReturn) {
2882 return new MethodType(t.argtypes, newReturn, t.thrown, t.tsym);
2883 }
2884 public Type visitForAll(ForAll t, Type newReturn) {
2885 return new ForAll(t.tvars, t.qtype.accept(this, newReturn));
2886 }
2887 };
2889 // <editor-fold defaultstate="collapsed" desc="createErrorType">
2890 public Type createErrorType(Type originalType) {
2891 return new ErrorType(originalType, syms.errSymbol);
2892 }
2894 public Type createErrorType(ClassSymbol c, Type originalType) {
2895 return new ErrorType(c, originalType);
2896 }
2898 public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
2899 return new ErrorType(name, container, originalType);
2900 }
2901 // </editor-fold>
2903 // <editor-fold defaultstate="collapsed" desc="rank">
2904 /**
2905 * The rank of a class is the length of the longest path between
2906 * the class and java.lang.Object in the class inheritance
2907 * graph. Undefined for all but reference types.
2908 */
2909 public int rank(Type t) {
2910 switch(t.tag) {
2911 case CLASS: {
2912 ClassType cls = (ClassType)t;
2913 if (cls.rank_field < 0) {
2914 Name fullname = cls.tsym.getQualifiedName();
2915 if (fullname == names.java_lang_Object)
2916 cls.rank_field = 0;
2917 else {
2918 int r = rank(supertype(cls));
2919 for (List<Type> l = interfaces(cls);
2920 l.nonEmpty();
2921 l = l.tail) {
2922 if (rank(l.head) > r)
2923 r = rank(l.head);
2924 }
2925 cls.rank_field = r + 1;
2926 }
2927 }
2928 return cls.rank_field;
2929 }
2930 case TYPEVAR: {
2931 TypeVar tvar = (TypeVar)t;
2932 if (tvar.rank_field < 0) {
2933 int r = rank(supertype(tvar));
2934 for (List<Type> l = interfaces(tvar);
2935 l.nonEmpty();
2936 l = l.tail) {
2937 if (rank(l.head) > r) r = rank(l.head);
2938 }
2939 tvar.rank_field = r + 1;
2940 }
2941 return tvar.rank_field;
2942 }
2943 case ERROR:
2944 return 0;
2945 default:
2946 throw new AssertionError();
2947 }
2948 }
2949 // </editor-fold>
2951 /**
2952 * Helper method for generating a string representation of a given type
2953 * accordingly to a given locale
2954 */
2955 public String toString(Type t, Locale locale) {
2956 return Printer.createStandardPrinter(messages).visit(t, locale);
2957 }
2959 /**
2960 * Helper method for generating a string representation of a given type
2961 * accordingly to a given locale
2962 */
2963 public String toString(Symbol t, Locale locale) {
2964 return Printer.createStandardPrinter(messages).visit(t, locale);
2965 }
2967 // <editor-fold defaultstate="collapsed" desc="toString">
2968 /**
2969 * This toString is slightly more descriptive than the one on Type.
2970 *
2971 * @deprecated Types.toString(Type t, Locale l) provides better support
2972 * for localization
2973 */
2974 @Deprecated
2975 public String toString(Type t) {
2976 if (t.tag == FORALL) {
2977 ForAll forAll = (ForAll)t;
2978 return typaramsString(forAll.tvars) + forAll.qtype;
2979 }
2980 return "" + t;
2981 }
2982 // where
2983 private String typaramsString(List<Type> tvars) {
2984 StringBuilder s = new StringBuilder();
2985 s.append('<');
2986 boolean first = true;
2987 for (Type t : tvars) {
2988 if (!first) s.append(", ");
2989 first = false;
2990 appendTyparamString(((TypeVar)t), s);
2991 }
2992 s.append('>');
2993 return s.toString();
2994 }
2995 private void appendTyparamString(TypeVar t, StringBuilder buf) {
2996 buf.append(t);
2997 if (t.bound == null ||
2998 t.bound.tsym.getQualifiedName() == names.java_lang_Object)
2999 return;
3000 buf.append(" extends "); // Java syntax; no need for i18n
3001 Type bound = t.bound;
3002 if (!bound.isCompound()) {
3003 buf.append(bound);
3004 } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
3005 buf.append(supertype(t));
3006 for (Type intf : interfaces(t)) {
3007 buf.append('&');
3008 buf.append(intf);
3009 }
3010 } else {
3011 // No superclass was given in bounds.
3012 // In this case, supertype is Object, erasure is first interface.
3013 boolean first = true;
3014 for (Type intf : interfaces(t)) {
3015 if (!first) buf.append('&');
3016 first = false;
3017 buf.append(intf);
3018 }
3019 }
3020 }
3021 // </editor-fold>
3023 // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
3024 /**
3025 * A cache for closures.
3026 *
3027 * <p>A closure is a list of all the supertypes and interfaces of
3028 * a class or interface type, ordered by ClassSymbol.precedes
3029 * (that is, subclasses come first, arbitrary but fixed
3030 * otherwise).
3031 */
3032 private Map<Type,List<Type>> closureCache = new HashMap<Type,List<Type>>();
3034 /**
3035 * Returns the closure of a class or interface type.
3036 */
3037 public List<Type> closure(Type t) {
3038 List<Type> cl = closureCache.get(t);
3039 if (cl == null) {
3040 Type st = supertype(t);
3041 if (!t.isCompound()) {
3042 if (st.tag == CLASS) {
3043 cl = insert(closure(st), t);
3044 } else if (st.tag == TYPEVAR) {
3045 cl = closure(st).prepend(t);
3046 } else {
3047 cl = List.of(t);
3048 }
3049 } else {
3050 cl = closure(supertype(t));
3051 }
3052 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
3053 cl = union(cl, closure(l.head));
3054 closureCache.put(t, cl);
3055 }
3056 return cl;
3057 }
3059 /**
3060 * Insert a type in a closure
3061 */
3062 public List<Type> insert(List<Type> cl, Type t) {
3063 if (cl.isEmpty() || t.tsym.precedes(cl.head.tsym, this)) {
3064 return cl.prepend(t);
3065 } else if (cl.head.tsym.precedes(t.tsym, this)) {
3066 return insert(cl.tail, t).prepend(cl.head);
3067 } else {
3068 return cl;
3069 }
3070 }
3072 /**
3073 * Form the union of two closures
3074 */
3075 public List<Type> union(List<Type> cl1, List<Type> cl2) {
3076 if (cl1.isEmpty()) {
3077 return cl2;
3078 } else if (cl2.isEmpty()) {
3079 return cl1;
3080 } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
3081 return union(cl1.tail, cl2).prepend(cl1.head);
3082 } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
3083 return union(cl1, cl2.tail).prepend(cl2.head);
3084 } else {
3085 return union(cl1.tail, cl2.tail).prepend(cl1.head);
3086 }
3087 }
3089 /**
3090 * Intersect two closures
3091 */
3092 public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
3093 if (cl1 == cl2)
3094 return cl1;
3095 if (cl1.isEmpty() || cl2.isEmpty())
3096 return List.nil();
3097 if (cl1.head.tsym.precedes(cl2.head.tsym, this))
3098 return intersect(cl1.tail, cl2);
3099 if (cl2.head.tsym.precedes(cl1.head.tsym, this))
3100 return intersect(cl1, cl2.tail);
3101 if (isSameType(cl1.head, cl2.head))
3102 return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
3103 if (cl1.head.tsym == cl2.head.tsym &&
3104 cl1.head.tag == CLASS && cl2.head.tag == CLASS) {
3105 if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
3106 Type merge = merge(cl1.head,cl2.head);
3107 return intersect(cl1.tail, cl2.tail).prepend(merge);
3108 }
3109 if (cl1.head.isRaw() || cl2.head.isRaw())
3110 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
3111 }
3112 return intersect(cl1.tail, cl2.tail);
3113 }
3114 // where
3115 class TypePair {
3116 final Type t1;
3117 final Type t2;
3118 TypePair(Type t1, Type t2) {
3119 this.t1 = t1;
3120 this.t2 = t2;
3121 }
3122 @Override
3123 public int hashCode() {
3124 return 127 * Types.hashCode(t1) + Types.hashCode(t2);
3125 }
3126 @Override
3127 public boolean equals(Object obj) {
3128 if (!(obj instanceof TypePair))
3129 return false;
3130 TypePair typePair = (TypePair)obj;
3131 return isSameType(t1, typePair.t1)
3132 && isSameType(t2, typePair.t2);
3133 }
3134 }
3135 Set<TypePair> mergeCache = new HashSet<TypePair>();
3136 private Type merge(Type c1, Type c2) {
3137 ClassType class1 = (ClassType) c1;
3138 List<Type> act1 = class1.getTypeArguments();
3139 ClassType class2 = (ClassType) c2;
3140 List<Type> act2 = class2.getTypeArguments();
3141 ListBuffer<Type> merged = new ListBuffer<Type>();
3142 List<Type> typarams = class1.tsym.type.getTypeArguments();
3144 while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
3145 if (containsType(act1.head, act2.head)) {
3146 merged.append(act1.head);
3147 } else if (containsType(act2.head, act1.head)) {
3148 merged.append(act2.head);
3149 } else {
3150 TypePair pair = new TypePair(c1, c2);
3151 Type m;
3152 if (mergeCache.add(pair)) {
3153 m = new WildcardType(lub(upperBound(act1.head),
3154 upperBound(act2.head)),
3155 BoundKind.EXTENDS,
3156 syms.boundClass);
3157 mergeCache.remove(pair);
3158 } else {
3159 m = new WildcardType(syms.objectType,
3160 BoundKind.UNBOUND,
3161 syms.boundClass);
3162 }
3163 merged.append(m.withTypeVar(typarams.head));
3164 }
3165 act1 = act1.tail;
3166 act2 = act2.tail;
3167 typarams = typarams.tail;
3168 }
3169 Assert.check(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
3170 return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
3171 }
3173 /**
3174 * Return the minimum type of a closure, a compound type if no
3175 * unique minimum exists.
3176 */
3177 private Type compoundMin(List<Type> cl) {
3178 if (cl.isEmpty()) return syms.objectType;
3179 List<Type> compound = closureMin(cl);
3180 if (compound.isEmpty())
3181 return null;
3182 else if (compound.tail.isEmpty())
3183 return compound.head;
3184 else
3185 return makeCompoundType(compound);
3186 }
3188 /**
3189 * Return the minimum types of a closure, suitable for computing
3190 * compoundMin or glb.
3191 */
3192 private List<Type> closureMin(List<Type> cl) {
3193 ListBuffer<Type> classes = lb();
3194 ListBuffer<Type> interfaces = lb();
3195 while (!cl.isEmpty()) {
3196 Type current = cl.head;
3197 if (current.isInterface())
3198 interfaces.append(current);
3199 else
3200 classes.append(current);
3201 ListBuffer<Type> candidates = lb();
3202 for (Type t : cl.tail) {
3203 if (!isSubtypeNoCapture(current, t))
3204 candidates.append(t);
3205 }
3206 cl = candidates.toList();
3207 }
3208 return classes.appendList(interfaces).toList();
3209 }
3211 /**
3212 * Return the least upper bound of pair of types. if the lub does
3213 * not exist return null.
3214 */
3215 public Type lub(Type t1, Type t2) {
3216 return lub(List.of(t1, t2));
3217 }
3219 /**
3220 * Return the least upper bound (lub) of set of types. If the lub
3221 * does not exist return the type of null (bottom).
3222 */
3223 public Type lub(List<Type> ts) {
3224 final int ARRAY_BOUND = 1;
3225 final int CLASS_BOUND = 2;
3226 int boundkind = 0;
3227 for (Type t : ts) {
3228 switch (t.tag) {
3229 case CLASS:
3230 boundkind |= CLASS_BOUND;
3231 break;
3232 case ARRAY:
3233 boundkind |= ARRAY_BOUND;
3234 break;
3235 case TYPEVAR:
3236 do {
3237 t = t.getUpperBound();
3238 } while (t.tag == TYPEVAR);
3239 if (t.tag == ARRAY) {
3240 boundkind |= ARRAY_BOUND;
3241 } else {
3242 boundkind |= CLASS_BOUND;
3243 }
3244 break;
3245 default:
3246 if (t.isPrimitive())
3247 return syms.errType;
3248 }
3249 }
3250 switch (boundkind) {
3251 case 0:
3252 return syms.botType;
3254 case ARRAY_BOUND:
3255 // calculate lub(A[], B[])
3256 List<Type> elements = Type.map(ts, elemTypeFun);
3257 for (Type t : elements) {
3258 if (t.isPrimitive()) {
3259 // if a primitive type is found, then return
3260 // arraySuperType unless all the types are the
3261 // same
3262 Type first = ts.head;
3263 for (Type s : ts.tail) {
3264 if (!isSameType(first, s)) {
3265 // lub(int[], B[]) is Cloneable & Serializable
3266 return arraySuperType();
3267 }
3268 }
3269 // all the array types are the same, return one
3270 // lub(int[], int[]) is int[]
3271 return first;
3272 }
3273 }
3274 // lub(A[], B[]) is lub(A, B)[]
3275 return new ArrayType(lub(elements), syms.arrayClass);
3277 case CLASS_BOUND:
3278 // calculate lub(A, B)
3279 while (ts.head.tag != CLASS && ts.head.tag != TYPEVAR)
3280 ts = ts.tail;
3281 Assert.check(!ts.isEmpty());
3282 //step 1 - compute erased candidate set (EC)
3283 List<Type> cl = erasedSupertypes(ts.head);
3284 for (Type t : ts.tail) {
3285 if (t.tag == CLASS || t.tag == TYPEVAR)
3286 cl = intersect(cl, erasedSupertypes(t));
3287 }
3288 //step 2 - compute minimal erased candidate set (MEC)
3289 List<Type> mec = closureMin(cl);
3290 //step 3 - for each element G in MEC, compute lci(Inv(G))
3291 List<Type> candidates = List.nil();
3292 for (Type erasedSupertype : mec) {
3293 List<Type> lci = List.of(asSuper(ts.head, erasedSupertype.tsym));
3294 for (Type t : ts) {
3295 lci = intersect(lci, List.of(asSuper(t, erasedSupertype.tsym)));
3296 }
3297 candidates = candidates.appendList(lci);
3298 }
3299 //step 4 - let MEC be { G1, G2 ... Gn }, then we have that
3300 //lub = lci(Inv(G1)) & lci(Inv(G2)) & ... & lci(Inv(Gn))
3301 return compoundMin(candidates);
3303 default:
3304 // calculate lub(A, B[])
3305 List<Type> classes = List.of(arraySuperType());
3306 for (Type t : ts) {
3307 if (t.tag != ARRAY) // Filter out any arrays
3308 classes = classes.prepend(t);
3309 }
3310 // lub(A, B[]) is lub(A, arraySuperType)
3311 return lub(classes);
3312 }
3313 }
3314 // where
3315 List<Type> erasedSupertypes(Type t) {
3316 ListBuffer<Type> buf = lb();
3317 for (Type sup : closure(t)) {
3318 if (sup.tag == TYPEVAR) {
3319 buf.append(sup);
3320 } else {
3321 buf.append(erasure(sup));
3322 }
3323 }
3324 return buf.toList();
3325 }
3327 private Type arraySuperType = null;
3328 private Type arraySuperType() {
3329 // initialized lazily to avoid problems during compiler startup
3330 if (arraySuperType == null) {
3331 synchronized (this) {
3332 if (arraySuperType == null) {
3333 // JLS 10.8: all arrays implement Cloneable and Serializable.
3334 arraySuperType = makeCompoundType(List.of(syms.serializableType,
3335 syms.cloneableType),
3336 syms.objectType);
3337 }
3338 }
3339 }
3340 return arraySuperType;
3341 }
3342 // </editor-fold>
3344 // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
3345 public Type glb(List<Type> ts) {
3346 Type t1 = ts.head;
3347 for (Type t2 : ts.tail) {
3348 if (t1.isErroneous())
3349 return t1;
3350 t1 = glb(t1, t2);
3351 }
3352 return t1;
3353 }
3354 //where
3355 public Type glb(Type t, Type s) {
3356 if (s == null)
3357 return t;
3358 else if (t.isPrimitive() || s.isPrimitive())
3359 return syms.errType;
3360 else if (isSubtypeNoCapture(t, s))
3361 return t;
3362 else if (isSubtypeNoCapture(s, t))
3363 return s;
3365 List<Type> closure = union(closure(t), closure(s));
3366 List<Type> bounds = closureMin(closure);
3368 if (bounds.isEmpty()) { // length == 0
3369 return syms.objectType;
3370 } else if (bounds.tail.isEmpty()) { // length == 1
3371 return bounds.head;
3372 } else { // length > 1
3373 int classCount = 0;
3374 for (Type bound : bounds)
3375 if (!bound.isInterface())
3376 classCount++;
3377 if (classCount > 1)
3378 return createErrorType(t);
3379 }
3380 return makeCompoundType(bounds);
3381 }
3382 // </editor-fold>
3384 // <editor-fold defaultstate="collapsed" desc="hashCode">
3385 /**
3386 * Compute a hash code on a type.
3387 */
3388 public static int hashCode(Type t) {
3389 return hashCode.visit(t);
3390 }
3391 // where
3392 private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
3394 public Integer visitType(Type t, Void ignored) {
3395 return t.tag.ordinal();
3396 }
3398 @Override
3399 public Integer visitClassType(ClassType t, Void ignored) {
3400 int result = visit(t.getEnclosingType());
3401 result *= 127;
3402 result += t.tsym.flatName().hashCode();
3403 for (Type s : t.getTypeArguments()) {
3404 result *= 127;
3405 result += visit(s);
3406 }
3407 return result;
3408 }
3410 @Override
3411 public Integer visitWildcardType(WildcardType t, Void ignored) {
3412 int result = t.kind.hashCode();
3413 if (t.type != null) {
3414 result *= 127;
3415 result += visit(t.type);
3416 }
3417 return result;
3418 }
3420 @Override
3421 public Integer visitArrayType(ArrayType t, Void ignored) {
3422 return visit(t.elemtype) + 12;
3423 }
3425 @Override
3426 public Integer visitTypeVar(TypeVar t, Void ignored) {
3427 return System.identityHashCode(t.tsym);
3428 }
3430 @Override
3431 public Integer visitUndetVar(UndetVar t, Void ignored) {
3432 return System.identityHashCode(t);
3433 }
3435 @Override
3436 public Integer visitErrorType(ErrorType t, Void ignored) {
3437 return 0;
3438 }
3439 };
3440 // </editor-fold>
3442 // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
3443 /**
3444 * Does t have a result that is a subtype of the result type of s,
3445 * suitable for covariant returns? It is assumed that both types
3446 * are (possibly polymorphic) method types. Monomorphic method
3447 * types are handled in the obvious way. Polymorphic method types
3448 * require renaming all type variables of one to corresponding
3449 * type variables in the other, where correspondence is by
3450 * position in the type parameter list. */
3451 public boolean resultSubtype(Type t, Type s, Warner warner) {
3452 List<Type> tvars = t.getTypeArguments();
3453 List<Type> svars = s.getTypeArguments();
3454 Type tres = t.getReturnType();
3455 Type sres = subst(s.getReturnType(), svars, tvars);
3456 return covariantReturnType(tres, sres, warner);
3457 }
3459 /**
3460 * Return-Type-Substitutable.
3461 * @jls section 8.4.5
3462 */
3463 public boolean returnTypeSubstitutable(Type r1, Type r2) {
3464 if (hasSameArgs(r1, r2))
3465 return resultSubtype(r1, r2, Warner.noWarnings);
3466 else
3467 return covariantReturnType(r1.getReturnType(),
3468 erasure(r2.getReturnType()),
3469 Warner.noWarnings);
3470 }
3472 public boolean returnTypeSubstitutable(Type r1,
3473 Type r2, Type r2res,
3474 Warner warner) {
3475 if (isSameType(r1.getReturnType(), r2res))
3476 return true;
3477 if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
3478 return false;
3480 if (hasSameArgs(r1, r2))
3481 return covariantReturnType(r1.getReturnType(), r2res, warner);
3482 if (!allowCovariantReturns)
3483 return false;
3484 if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
3485 return true;
3486 if (!isSubtype(r1.getReturnType(), erasure(r2res)))
3487 return false;
3488 warner.warn(LintCategory.UNCHECKED);
3489 return true;
3490 }
3492 /**
3493 * Is t an appropriate return type in an overrider for a
3494 * method that returns s?
3495 */
3496 public boolean covariantReturnType(Type t, Type s, Warner warner) {
3497 return
3498 isSameType(t, s) ||
3499 allowCovariantReturns &&
3500 !t.isPrimitive() &&
3501 !s.isPrimitive() &&
3502 isAssignable(t, s, warner);
3503 }
3504 // </editor-fold>
3506 // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
3507 /**
3508 * Return the class that boxes the given primitive.
3509 */
3510 public ClassSymbol boxedClass(Type t) {
3511 return reader.enterClass(syms.boxedName[t.tag.ordinal()]);
3512 }
3514 /**
3515 * Return the boxed type if 't' is primitive, otherwise return 't' itself.
3516 */
3517 public Type boxedTypeOrType(Type t) {
3518 return t.isPrimitive() ?
3519 boxedClass(t).type :
3520 t;
3521 }
3523 /**
3524 * Return the primitive type corresponding to a boxed type.
3525 */
3526 public Type unboxedType(Type t) {
3527 if (allowBoxing) {
3528 for (int i=0; i<syms.boxedName.length; i++) {
3529 Name box = syms.boxedName[i];
3530 if (box != null &&
3531 asSuper(t, reader.enterClass(box)) != null)
3532 return syms.typeOfTag[i];
3533 }
3534 }
3535 return Type.noType;
3536 }
3538 /**
3539 * Return the unboxed type if 't' is a boxed class, otherwise return 't' itself.
3540 */
3541 public Type unboxedTypeOrType(Type t) {
3542 Type unboxedType = unboxedType(t);
3543 return unboxedType.tag == NONE ? t : unboxedType;
3544 }
3545 // </editor-fold>
3547 // <editor-fold defaultstate="collapsed" desc="Capture conversion">
3548 /*
3549 * JLS 5.1.10 Capture Conversion:
3550 *
3551 * Let G name a generic type declaration with n formal type
3552 * parameters A1 ... An with corresponding bounds U1 ... Un. There
3553 * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
3554 * where, for 1 <= i <= n:
3555 *
3556 * + If Ti is a wildcard type argument (4.5.1) of the form ? then
3557 * Si is a fresh type variable whose upper bound is
3558 * Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
3559 * type.
3560 *
3561 * + If Ti is a wildcard type argument of the form ? extends Bi,
3562 * then Si is a fresh type variable whose upper bound is
3563 * glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
3564 * the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
3565 * a compile-time error if for any two classes (not interfaces)
3566 * Vi and Vj,Vi is not a subclass of Vj or vice versa.
3567 *
3568 * + If Ti is a wildcard type argument of the form ? super Bi,
3569 * then Si is a fresh type variable whose upper bound is
3570 * Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
3571 *
3572 * + Otherwise, Si = Ti.
3573 *
3574 * Capture conversion on any type other than a parameterized type
3575 * (4.5) acts as an identity conversion (5.1.1). Capture
3576 * conversions never require a special action at run time and
3577 * therefore never throw an exception at run time.
3578 *
3579 * Capture conversion is not applied recursively.
3580 */
3581 /**
3582 * Capture conversion as specified by the JLS.
3583 */
3585 public List<Type> capture(List<Type> ts) {
3586 List<Type> buf = List.nil();
3587 for (Type t : ts) {
3588 buf = buf.prepend(capture(t));
3589 }
3590 return buf.reverse();
3591 }
3592 public Type capture(Type t) {
3593 if (t.tag != CLASS)
3594 return t;
3595 if (t.getEnclosingType() != Type.noType) {
3596 Type capturedEncl = capture(t.getEnclosingType());
3597 if (capturedEncl != t.getEnclosingType()) {
3598 Type type1 = memberType(capturedEncl, t.tsym);
3599 t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments());
3600 }
3601 }
3602 ClassType cls = (ClassType)t;
3603 if (cls.isRaw() || !cls.isParameterized())
3604 return cls;
3606 ClassType G = (ClassType)cls.asElement().asType();
3607 List<Type> A = G.getTypeArguments();
3608 List<Type> T = cls.getTypeArguments();
3609 List<Type> S = freshTypeVariables(T);
3611 List<Type> currentA = A;
3612 List<Type> currentT = T;
3613 List<Type> currentS = S;
3614 boolean captured = false;
3615 while (!currentA.isEmpty() &&
3616 !currentT.isEmpty() &&
3617 !currentS.isEmpty()) {
3618 if (currentS.head != currentT.head) {
3619 captured = true;
3620 WildcardType Ti = (WildcardType)currentT.head;
3621 Type Ui = currentA.head.getUpperBound();
3622 CapturedType Si = (CapturedType)currentS.head;
3623 if (Ui == null)
3624 Ui = syms.objectType;
3625 switch (Ti.kind) {
3626 case UNBOUND:
3627 Si.bound = subst(Ui, A, S);
3628 Si.lower = syms.botType;
3629 break;
3630 case EXTENDS:
3631 Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
3632 Si.lower = syms.botType;
3633 break;
3634 case SUPER:
3635 Si.bound = subst(Ui, A, S);
3636 Si.lower = Ti.getSuperBound();
3637 break;
3638 }
3639 if (Si.bound == Si.lower)
3640 currentS.head = Si.bound;
3641 }
3642 currentA = currentA.tail;
3643 currentT = currentT.tail;
3644 currentS = currentS.tail;
3645 }
3646 if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
3647 return erasure(t); // some "rare" type involved
3649 if (captured)
3650 return new ClassType(cls.getEnclosingType(), S, cls.tsym);
3651 else
3652 return t;
3653 }
3654 // where
3655 public List<Type> freshTypeVariables(List<Type> types) {
3656 ListBuffer<Type> result = lb();
3657 for (Type t : types) {
3658 if (t.tag == WILDCARD) {
3659 Type bound = ((WildcardType)t).getExtendsBound();
3660 if (bound == null)
3661 bound = syms.objectType;
3662 result.append(new CapturedType(capturedName,
3663 syms.noSymbol,
3664 bound,
3665 syms.botType,
3666 (WildcardType)t));
3667 } else {
3668 result.append(t);
3669 }
3670 }
3671 return result.toList();
3672 }
3673 // </editor-fold>
3675 // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
3676 private List<Type> upperBounds(List<Type> ss) {
3677 if (ss.isEmpty()) return ss;
3678 Type head = upperBound(ss.head);
3679 List<Type> tail = upperBounds(ss.tail);
3680 if (head != ss.head || tail != ss.tail)
3681 return tail.prepend(head);
3682 else
3683 return ss;
3684 }
3686 private boolean sideCast(Type from, Type to, Warner warn) {
3687 // We are casting from type $from$ to type $to$, which are
3688 // non-final unrelated types. This method
3689 // tries to reject a cast by transferring type parameters
3690 // from $to$ to $from$ by common superinterfaces.
3691 boolean reverse = false;
3692 Type target = to;
3693 if ((to.tsym.flags() & INTERFACE) == 0) {
3694 Assert.check((from.tsym.flags() & INTERFACE) != 0);
3695 reverse = true;
3696 to = from;
3697 from = target;
3698 }
3699 List<Type> commonSupers = superClosure(to, erasure(from));
3700 boolean giveWarning = commonSupers.isEmpty();
3701 // The arguments to the supers could be unified here to
3702 // get a more accurate analysis
3703 while (commonSupers.nonEmpty()) {
3704 Type t1 = asSuper(from, commonSupers.head.tsym);
3705 Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
3706 if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
3707 return false;
3708 giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
3709 commonSupers = commonSupers.tail;
3710 }
3711 if (giveWarning && !isReifiable(reverse ? from : to))
3712 warn.warn(LintCategory.UNCHECKED);
3713 if (!allowCovariantReturns)
3714 // reject if there is a common method signature with
3715 // incompatible return types.
3716 chk.checkCompatibleAbstracts(warn.pos(), from, to);
3717 return true;
3718 }
3720 private boolean sideCastFinal(Type from, Type to, Warner warn) {
3721 // We are casting from type $from$ to type $to$, which are
3722 // unrelated types one of which is final and the other of
3723 // which is an interface. This method
3724 // tries to reject a cast by transferring type parameters
3725 // from the final class to the interface.
3726 boolean reverse = false;
3727 Type target = to;
3728 if ((to.tsym.flags() & INTERFACE) == 0) {
3729 Assert.check((from.tsym.flags() & INTERFACE) != 0);
3730 reverse = true;
3731 to = from;
3732 from = target;
3733 }
3734 Assert.check((from.tsym.flags() & FINAL) != 0);
3735 Type t1 = asSuper(from, to.tsym);
3736 if (t1 == null) return false;
3737 Type t2 = to;
3738 if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
3739 return false;
3740 if (!allowCovariantReturns)
3741 // reject if there is a common method signature with
3742 // incompatible return types.
3743 chk.checkCompatibleAbstracts(warn.pos(), from, to);
3744 if (!isReifiable(target) &&
3745 (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
3746 warn.warn(LintCategory.UNCHECKED);
3747 return true;
3748 }
3750 private boolean giveWarning(Type from, Type to) {
3751 Type subFrom = asSub(from, to.tsym);
3752 return to.isParameterized() &&
3753 (!(isUnbounded(to) ||
3754 isSubtype(from, to) ||
3755 ((subFrom != null) && containsType(to.allparams(), subFrom.allparams()))));
3756 }
3758 private List<Type> superClosure(Type t, Type s) {
3759 List<Type> cl = List.nil();
3760 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
3761 if (isSubtype(s, erasure(l.head))) {
3762 cl = insert(cl, l.head);
3763 } else {
3764 cl = union(cl, superClosure(l.head, s));
3765 }
3766 }
3767 return cl;
3768 }
3770 private boolean containsTypeEquivalent(Type t, Type s) {
3771 return
3772 isSameType(t, s) || // shortcut
3773 containsType(t, s) && containsType(s, t);
3774 }
3776 // <editor-fold defaultstate="collapsed" desc="adapt">
3777 /**
3778 * Adapt a type by computing a substitution which maps a source
3779 * type to a target type.
3780 *
3781 * @param source the source type
3782 * @param target the target type
3783 * @param from the type variables of the computed substitution
3784 * @param to the types of the computed substitution.
3785 */
3786 public void adapt(Type source,
3787 Type target,
3788 ListBuffer<Type> from,
3789 ListBuffer<Type> to) throws AdaptFailure {
3790 new Adapter(from, to).adapt(source, target);
3791 }
3793 class Adapter extends SimpleVisitor<Void, Type> {
3795 ListBuffer<Type> from;
3796 ListBuffer<Type> to;
3797 Map<Symbol,Type> mapping;
3799 Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
3800 this.from = from;
3801 this.to = to;
3802 mapping = new HashMap<Symbol,Type>();
3803 }
3805 public void adapt(Type source, Type target) throws AdaptFailure {
3806 visit(source, target);
3807 List<Type> fromList = from.toList();
3808 List<Type> toList = to.toList();
3809 while (!fromList.isEmpty()) {
3810 Type val = mapping.get(fromList.head.tsym);
3811 if (toList.head != val)
3812 toList.head = val;
3813 fromList = fromList.tail;
3814 toList = toList.tail;
3815 }
3816 }
3818 @Override
3819 public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
3820 if (target.tag == CLASS)
3821 adaptRecursive(source.allparams(), target.allparams());
3822 return null;
3823 }
3825 @Override
3826 public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
3827 if (target.tag == ARRAY)
3828 adaptRecursive(elemtype(source), elemtype(target));
3829 return null;
3830 }
3832 @Override
3833 public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
3834 if (source.isExtendsBound())
3835 adaptRecursive(upperBound(source), upperBound(target));
3836 else if (source.isSuperBound())
3837 adaptRecursive(lowerBound(source), lowerBound(target));
3838 return null;
3839 }
3841 @Override
3842 public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
3843 // Check to see if there is
3844 // already a mapping for $source$, in which case
3845 // the old mapping will be merged with the new
3846 Type val = mapping.get(source.tsym);
3847 if (val != null) {
3848 if (val.isSuperBound() && target.isSuperBound()) {
3849 val = isSubtype(lowerBound(val), lowerBound(target))
3850 ? target : val;
3851 } else if (val.isExtendsBound() && target.isExtendsBound()) {
3852 val = isSubtype(upperBound(val), upperBound(target))
3853 ? val : target;
3854 } else if (!isSameType(val, target)) {
3855 throw new AdaptFailure();
3856 }
3857 } else {
3858 val = target;
3859 from.append(source);
3860 to.append(target);
3861 }
3862 mapping.put(source.tsym, val);
3863 return null;
3864 }
3866 @Override
3867 public Void visitType(Type source, Type target) {
3868 return null;
3869 }
3871 private Set<TypePair> cache = new HashSet<TypePair>();
3873 private void adaptRecursive(Type source, Type target) {
3874 TypePair pair = new TypePair(source, target);
3875 if (cache.add(pair)) {
3876 try {
3877 visit(source, target);
3878 } finally {
3879 cache.remove(pair);
3880 }
3881 }
3882 }
3884 private void adaptRecursive(List<Type> source, List<Type> target) {
3885 if (source.length() == target.length()) {
3886 while (source.nonEmpty()) {
3887 adaptRecursive(source.head, target.head);
3888 source = source.tail;
3889 target = target.tail;
3890 }
3891 }
3892 }
3893 }
3895 public static class AdaptFailure extends RuntimeException {
3896 static final long serialVersionUID = -7490231548272701566L;
3897 }
3899 private void adaptSelf(Type t,
3900 ListBuffer<Type> from,
3901 ListBuffer<Type> to) {
3902 try {
3903 //if (t.tsym.type != t)
3904 adapt(t.tsym.type, t, from, to);
3905 } catch (AdaptFailure ex) {
3906 // Adapt should never fail calculating a mapping from
3907 // t.tsym.type to t as there can be no merge problem.
3908 throw new AssertionError(ex);
3909 }
3910 }
3911 // </editor-fold>
3913 /**
3914 * Rewrite all type variables (universal quantifiers) in the given
3915 * type to wildcards (existential quantifiers). This is used to
3916 * determine if a cast is allowed. For example, if high is true
3917 * and {@code T <: Number}, then {@code List<T>} is rewritten to
3918 * {@code List<? extends Number>}. Since {@code List<Integer> <:
3919 * List<? extends Number>} a {@code List<T>} can be cast to {@code
3920 * List<Integer>} with a warning.
3921 * @param t a type
3922 * @param high if true return an upper bound; otherwise a lower
3923 * bound
3924 * @param rewriteTypeVars only rewrite captured wildcards if false;
3925 * otherwise rewrite all type variables
3926 * @return the type rewritten with wildcards (existential
3927 * quantifiers) only
3928 */
3929 private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
3930 return new Rewriter(high, rewriteTypeVars).visit(t);
3931 }
3933 class Rewriter extends UnaryVisitor<Type> {
3935 boolean high;
3936 boolean rewriteTypeVars;
3938 Rewriter(boolean high, boolean rewriteTypeVars) {
3939 this.high = high;
3940 this.rewriteTypeVars = rewriteTypeVars;
3941 }
3943 @Override
3944 public Type visitClassType(ClassType t, Void s) {
3945 ListBuffer<Type> rewritten = new ListBuffer<Type>();
3946 boolean changed = false;
3947 for (Type arg : t.allparams()) {
3948 Type bound = visit(arg);
3949 if (arg != bound) {
3950 changed = true;
3951 }
3952 rewritten.append(bound);
3953 }
3954 if (changed)
3955 return subst(t.tsym.type,
3956 t.tsym.type.allparams(),
3957 rewritten.toList());
3958 else
3959 return t;
3960 }
3962 public Type visitType(Type t, Void s) {
3963 return high ? upperBound(t) : lowerBound(t);
3964 }
3966 @Override
3967 public Type visitCapturedType(CapturedType t, Void s) {
3968 Type w_bound = t.wildcard.type;
3969 Type bound = w_bound.contains(t) ?
3970 erasure(w_bound) :
3971 visit(w_bound);
3972 return rewriteAsWildcardType(visit(bound), t.wildcard.bound, t.wildcard.kind);
3973 }
3975 @Override
3976 public Type visitTypeVar(TypeVar t, Void s) {
3977 if (rewriteTypeVars) {
3978 Type bound = t.bound.contains(t) ?
3979 erasure(t.bound) :
3980 visit(t.bound);
3981 return rewriteAsWildcardType(bound, t, EXTENDS);
3982 } else {
3983 return t;
3984 }
3985 }
3987 @Override
3988 public Type visitWildcardType(WildcardType t, Void s) {
3989 Type bound2 = visit(t.type);
3990 return t.type == bound2 ? t : rewriteAsWildcardType(bound2, t.bound, t.kind);
3991 }
3993 private Type rewriteAsWildcardType(Type bound, TypeVar formal, BoundKind bk) {
3994 switch (bk) {
3995 case EXTENDS: return high ?
3996 makeExtendsWildcard(B(bound), formal) :
3997 makeExtendsWildcard(syms.objectType, formal);
3998 case SUPER: return high ?
3999 makeSuperWildcard(syms.botType, formal) :
4000 makeSuperWildcard(B(bound), formal);
4001 case UNBOUND: return makeExtendsWildcard(syms.objectType, formal);
4002 default:
4003 Assert.error("Invalid bound kind " + bk);
4004 return null;
4005 }
4006 }
4008 Type B(Type t) {
4009 while (t.tag == WILDCARD) {
4010 WildcardType w = (WildcardType)t;
4011 t = high ?
4012 w.getExtendsBound() :
4013 w.getSuperBound();
4014 if (t == null) {
4015 t = high ? syms.objectType : syms.botType;
4016 }
4017 }
4018 return t;
4019 }
4020 }
4023 /**
4024 * Create a wildcard with the given upper (extends) bound; create
4025 * an unbounded wildcard if bound is Object.
4026 *
4027 * @param bound the upper bound
4028 * @param formal the formal type parameter that will be
4029 * substituted by the wildcard
4030 */
4031 private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
4032 if (bound == syms.objectType) {
4033 return new WildcardType(syms.objectType,
4034 BoundKind.UNBOUND,
4035 syms.boundClass,
4036 formal);
4037 } else {
4038 return new WildcardType(bound,
4039 BoundKind.EXTENDS,
4040 syms.boundClass,
4041 formal);
4042 }
4043 }
4045 /**
4046 * Create a wildcard with the given lower (super) bound; create an
4047 * unbounded wildcard if bound is bottom (type of {@code null}).
4048 *
4049 * @param bound the lower bound
4050 * @param formal the formal type parameter that will be
4051 * substituted by the wildcard
4052 */
4053 private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
4054 if (bound.tag == BOT) {
4055 return new WildcardType(syms.objectType,
4056 BoundKind.UNBOUND,
4057 syms.boundClass,
4058 formal);
4059 } else {
4060 return new WildcardType(bound,
4061 BoundKind.SUPER,
4062 syms.boundClass,
4063 formal);
4064 }
4065 }
4067 /**
4068 * A wrapper for a type that allows use in sets.
4069 */
4070 class SingletonType {
4071 final Type t;
4072 SingletonType(Type t) {
4073 this.t = t;
4074 }
4075 public int hashCode() {
4076 return Types.hashCode(t);
4077 }
4078 public boolean equals(Object obj) {
4079 return (obj instanceof SingletonType) &&
4080 isSameType(t, ((SingletonType)obj).t);
4081 }
4082 public String toString() {
4083 return t.toString();
4084 }
4085 }
4086 // </editor-fold>
4088 // <editor-fold defaultstate="collapsed" desc="Visitors">
4089 /**
4090 * A default visitor for types. All visitor methods except
4091 * visitType are implemented by delegating to visitType. Concrete
4092 * subclasses must provide an implementation of visitType and can
4093 * override other methods as needed.
4094 *
4095 * @param <R> the return type of the operation implemented by this
4096 * visitor; use Void if no return type is needed.
4097 * @param <S> the type of the second argument (the first being the
4098 * type itself) of the operation implemented by this visitor; use
4099 * Void if a second argument is not needed.
4100 */
4101 public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
4102 final public R visit(Type t, S s) { return t.accept(this, s); }
4103 public R visitClassType(ClassType t, S s) { return visitType(t, s); }
4104 public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
4105 public R visitArrayType(ArrayType t, S s) { return visitType(t, s); }
4106 public R visitMethodType(MethodType t, S s) { return visitType(t, s); }
4107 public R visitPackageType(PackageType t, S s) { return visitType(t, s); }
4108 public R visitTypeVar(TypeVar t, S s) { return visitType(t, s); }
4109 public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
4110 public R visitForAll(ForAll t, S s) { return visitType(t, s); }
4111 public R visitUndetVar(UndetVar t, S s) { return visitType(t, s); }
4112 public R visitErrorType(ErrorType t, S s) { return visitType(t, s); }
4113 }
4115 /**
4116 * A default visitor for symbols. All visitor methods except
4117 * visitSymbol are implemented by delegating to visitSymbol. Concrete
4118 * subclasses must provide an implementation of visitSymbol and can
4119 * override other methods as needed.
4120 *
4121 * @param <R> the return type of the operation implemented by this
4122 * visitor; use Void if no return type is needed.
4123 * @param <S> the type of the second argument (the first being the
4124 * symbol itself) of the operation implemented by this visitor; use
4125 * Void if a second argument is not needed.
4126 */
4127 public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
4128 final public R visit(Symbol s, S arg) { return s.accept(this, arg); }
4129 public R visitClassSymbol(ClassSymbol s, S arg) { return visitSymbol(s, arg); }
4130 public R visitMethodSymbol(MethodSymbol s, S arg) { return visitSymbol(s, arg); }
4131 public R visitOperatorSymbol(OperatorSymbol s, S arg) { return visitSymbol(s, arg); }
4132 public R visitPackageSymbol(PackageSymbol s, S arg) { return visitSymbol(s, arg); }
4133 public R visitTypeSymbol(TypeSymbol s, S arg) { return visitSymbol(s, arg); }
4134 public R visitVarSymbol(VarSymbol s, S arg) { return visitSymbol(s, arg); }
4135 }
4137 /**
4138 * A <em>simple</em> visitor for types. This visitor is simple as
4139 * captured wildcards, for-all types (generic methods), and
4140 * undetermined type variables (part of inference) are hidden.
4141 * Captured wildcards are hidden by treating them as type
4142 * variables and the rest are hidden by visiting their qtypes.
4143 *
4144 * @param <R> the return type of the operation implemented by this
4145 * visitor; use Void if no return type is needed.
4146 * @param <S> the type of the second argument (the first being the
4147 * type itself) of the operation implemented by this visitor; use
4148 * Void if a second argument is not needed.
4149 */
4150 public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
4151 @Override
4152 public R visitCapturedType(CapturedType t, S s) {
4153 return visitTypeVar(t, s);
4154 }
4155 @Override
4156 public R visitForAll(ForAll t, S s) {
4157 return visit(t.qtype, s);
4158 }
4159 @Override
4160 public R visitUndetVar(UndetVar t, S s) {
4161 return visit(t.qtype, s);
4162 }
4163 }
4165 /**
4166 * A plain relation on types. That is a 2-ary function on the
4167 * form Type × Type → Boolean.
4168 * <!-- In plain text: Type x Type -> Boolean -->
4169 */
4170 public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
4172 /**
4173 * A convenience visitor for implementing operations that only
4174 * require one argument (the type itself), that is, unary
4175 * operations.
4176 *
4177 * @param <R> the return type of the operation implemented by this
4178 * visitor; use Void if no return type is needed.
4179 */
4180 public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
4181 final public R visit(Type t) { return t.accept(this, null); }
4182 }
4184 /**
4185 * A visitor for implementing a mapping from types to types. The
4186 * default behavior of this class is to implement the identity
4187 * mapping (mapping a type to itself). This can be overridden in
4188 * subclasses.
4189 *
4190 * @param <S> the type of the second argument (the first being the
4191 * type itself) of this mapping; use Void if a second argument is
4192 * not needed.
4193 */
4194 public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
4195 final public Type visit(Type t) { return t.accept(this, null); }
4196 public Type visitType(Type t, S s) { return t; }
4197 }
4198 // </editor-fold>
4201 // <editor-fold defaultstate="collapsed" desc="Annotation support">
4203 public RetentionPolicy getRetention(Attribute.Compound a) {
4204 return getRetention(a.type.tsym);
4205 }
4207 public RetentionPolicy getRetention(Symbol sym) {
4208 RetentionPolicy vis = RetentionPolicy.CLASS; // the default
4209 Attribute.Compound c = sym.attribute(syms.retentionType.tsym);
4210 if (c != null) {
4211 Attribute value = c.member(names.value);
4212 if (value != null && value instanceof Attribute.Enum) {
4213 Name levelName = ((Attribute.Enum)value).value.name;
4214 if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE;
4215 else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS;
4216 else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME;
4217 else ;// /* fail soft */ throw new AssertionError(levelName);
4218 }
4219 }
4220 return vis;
4221 }
4222 // </editor-fold>
4223 }