|
The Types.java Java example source code
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.code;
import java.lang.ref.SoftReference;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import javax.tools.JavaFileObject;
import com.sun.tools.javac.code.Attribute.RetentionPolicy;
import com.sun.tools.javac.code.Lint.LintCategory;
import com.sun.tools.javac.code.Type.UndetVar.InferenceBound;
import com.sun.tools.javac.comp.AttrContext;
import com.sun.tools.javac.comp.Check;
import com.sun.tools.javac.comp.Enter;
import com.sun.tools.javac.comp.Env;
import com.sun.tools.javac.jvm.ClassReader;
import com.sun.tools.javac.util.*;
import static com.sun.tools.javac.code.BoundKind.*;
import static com.sun.tools.javac.code.Flags.*;
import static com.sun.tools.javac.code.Scope.*;
import static com.sun.tools.javac.code.Symbol.*;
import static com.sun.tools.javac.code.Type.*;
import static com.sun.tools.javac.code.TypeTag.*;
import static com.sun.tools.javac.jvm.ClassFile.externalize;
/**
* Utility class containing various operations on types.
*
* <p>Unless other names are more illustrative, the following naming
* conventions should be observed in this file:
*
* <dl>
* <dt>t
* <dd>If the first argument to an operation is a type, it should be named t.
* <dt>s
* <dd>Similarly, if the second argument to an operation is a type, it should be named s.
* <dt>ts
* <dd>If an operations takes a list of types, the first should be named ts.
* <dt>ss
* <dd>A second list of types should be named ss.
* </dl>
*
* <p>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Types {
protected static final Context.Key<Types> typesKey =
new Context.Key<Types>();
final Symtab syms;
final JavacMessages messages;
final Names names;
final boolean allowBoxing;
final boolean allowCovariantReturns;
final boolean allowObjectToPrimitiveCast;
final boolean allowDefaultMethods;
final ClassReader reader;
final Check chk;
final Enter enter;
JCDiagnostic.Factory diags;
List<Warner> warnStack = List.nil();
final Name capturedName;
private final FunctionDescriptorLookupError functionDescriptorLookupError;
public final Warner noWarnings;
// <editor-fold defaultstate="collapsed" desc="Instantiating">
public static Types instance(Context context) {
Types instance = context.get(typesKey);
if (instance == null)
instance = new Types(context);
return instance;
}
protected Types(Context context) {
context.put(typesKey, this);
syms = Symtab.instance(context);
names = Names.instance(context);
Source source = Source.instance(context);
allowBoxing = source.allowBoxing();
allowCovariantReturns = source.allowCovariantReturns();
allowObjectToPrimitiveCast = source.allowObjectToPrimitiveCast();
allowDefaultMethods = source.allowDefaultMethods();
reader = ClassReader.instance(context);
chk = Check.instance(context);
enter = Enter.instance(context);
capturedName = names.fromString("<captured wildcard>");
messages = JavacMessages.instance(context);
diags = JCDiagnostic.Factory.instance(context);
functionDescriptorLookupError = new FunctionDescriptorLookupError();
noWarnings = new Warner(null);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="upperBound">
/**
* The "rvalue conversion".<br>
* The upper bound of most types is the type
* itself. Wildcards, on the other hand have upper
* and lower bounds.
* @param t a type
* @return the upper bound of the given type
*/
public Type upperBound(Type t) {
return upperBound.visit(t).unannotatedType();
}
// where
private final MapVisitor<Void> upperBound = new MapVisitor() {
@Override
public Type visitWildcardType(WildcardType t, Void ignored) {
if (t.isSuperBound())
return t.bound == null ? syms.objectType : t.bound.bound;
else
return visit(t.type);
}
@Override
public Type visitCapturedType(CapturedType t, Void ignored) {
return visit(t.bound);
}
};
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="lowerBound">
/**
* The "lvalue conversion".<br>
* The lower bound of most types is the type
* itself. Wildcards, on the other hand have upper
* and lower bounds.
* @param t a type
* @return the lower bound of the given type
*/
public Type lowerBound(Type t) {
return lowerBound.visit(t);
}
// where
private final MapVisitor<Void> lowerBound = new MapVisitor() {
@Override
public Type visitWildcardType(WildcardType t, Void ignored) {
return t.isExtendsBound() ? syms.botType : visit(t.type);
}
@Override
public Type visitCapturedType(CapturedType t, Void ignored) {
return visit(t.getLowerBound());
}
};
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="isUnbounded">
/**
* Checks that all the arguments to a class are unbounded
* wildcards or something else that doesn't make any restrictions
* on the arguments. If a class isUnbounded, a raw super- or
* subclass can be cast to it without a warning.
* @param t a type
* @return true iff the given type is unbounded or raw
*/
public boolean isUnbounded(Type t) {
return isUnbounded.visit(t);
}
// where
private final UnaryVisitor<Boolean> isUnbounded = new UnaryVisitor() {
public Boolean visitType(Type t, Void ignored) {
return true;
}
@Override
public Boolean visitClassType(ClassType t, Void ignored) {
List<Type> parms = t.tsym.type.allparams();
List<Type> args = t.allparams();
while (parms.nonEmpty()) {
WildcardType unb = new WildcardType(syms.objectType,
BoundKind.UNBOUND,
syms.boundClass,
(TypeVar)parms.head.unannotatedType());
if (!containsType(args.head, unb))
return false;
parms = parms.tail;
args = args.tail;
}
return true;
}
};
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="asSub">
/**
* Return the least specific subtype of t that starts with symbol
* sym. If none exists, return null. The least specific subtype
* is determined as follows:
*
* <p>If there is exactly one parameterized instance of sym that is a
* subtype of t, that parameterized instance is returned.<br>
* Otherwise, if the plain type or raw type `sym' is a subtype of
* type t, the type `sym' itself is returned. Otherwise, null is
* returned.
*/
public Type asSub(Type t, Symbol sym) {
return asSub.visit(t, sym);
}
// where
private final SimpleVisitor<Type,Symbol> asSub = new SimpleVisitor() {
public Type visitType(Type t, Symbol sym) {
return null;
}
@Override
public Type visitClassType(ClassType t, Symbol sym) {
if (t.tsym == sym)
return t;
Type base = asSuper(sym.type, t.tsym);
if (base == null)
return null;
ListBuffer<Type> from = new ListBuffer();
ListBuffer<Type> to = new ListBuffer();
try {
adapt(base, t, from, to);
} catch (AdaptFailure ex) {
return null;
}
Type res = subst(sym.type, from.toList(), to.toList());
if (!isSubtype(res, t))
return null;
ListBuffer<Type> openVars = new ListBuffer();
for (List<Type> l = sym.type.allparams();
l.nonEmpty(); l = l.tail)
if (res.contains(l.head) && !t.contains(l.head))
openVars.append(l.head);
if (openVars.nonEmpty()) {
if (t.isRaw()) {
// The subtype of a raw type is raw
res = erasure(res);
} else {
// Unbound type arguments default to ?
List<Type> opens = openVars.toList();
ListBuffer<Type> qs = new ListBuffer();
for (List<Type> iter = opens; iter.nonEmpty(); iter = iter.tail) {
qs.append(new WildcardType(syms.objectType, BoundKind.UNBOUND, syms.boundClass, (TypeVar) iter.head.unannotatedType()));
}
res = subst(res, opens, qs.toList());
}
}
return res;
}
@Override
public Type visitErrorType(ErrorType t, Symbol sym) {
return t;
}
};
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="isConvertible">
/**
* Is t a subtype of or convertible via boxing/unboxing
* conversion to s?
*/
public boolean isConvertible(Type t, Type s, Warner warn) {
if (t.hasTag(ERROR)) {
return true;
}
boolean tPrimitive = t.isPrimitive();
boolean sPrimitive = s.isPrimitive();
if (tPrimitive == sPrimitive) {
return isSubtypeUnchecked(t, s, warn);
}
if (!allowBoxing) return false;
return tPrimitive
? isSubtype(boxedClass(t).type, s)
: isSubtype(unboxedType(t), s);
}
/**
* Is t a subtype of or convertiable via boxing/unboxing
* convertions to s?
*/
public boolean isConvertible(Type t, Type s) {
return isConvertible(t, s, noWarnings);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="findSam">
/**
* Exception used to report a function descriptor lookup failure. The exception
* wraps a diagnostic that can be used to generate more details error
* messages.
*/
public static class FunctionDescriptorLookupError extends RuntimeException {
private static final long serialVersionUID = 0;
JCDiagnostic diagnostic;
FunctionDescriptorLookupError() {
this.diagnostic = null;
}
FunctionDescriptorLookupError setMessage(JCDiagnostic diag) {
this.diagnostic = diag;
return this;
}
public JCDiagnostic getDiagnostic() {
return diagnostic;
}
}
/**
* A cache that keeps track of function descriptors associated with given
* functional interfaces.
*/
class DescriptorCache {
private WeakHashMap<TypeSymbol, Entry> _map = new WeakHashMap();
class FunctionDescriptor {
Symbol descSym;
FunctionDescriptor(Symbol descSym) {
this.descSym = descSym;
}
public Symbol getSymbol() {
return descSym;
}
public Type getType(Type site) {
site = removeWildcards(site);
if (!chk.checkValidGenericType(site)) {
//if the inferred functional interface type is not well-formed,
//or if it's not a subtype of the original target, issue an error
throw failure(diags.fragment("no.suitable.functional.intf.inst", site));
}
return memberType(site, descSym);
}
}
class Entry {
final FunctionDescriptor cachedDescRes;
final int prevMark;
public Entry(FunctionDescriptor cachedDescRes,
int prevMark) {
this.cachedDescRes = cachedDescRes;
this.prevMark = prevMark;
}
boolean matches(int mark) {
return this.prevMark == mark;
}
}
FunctionDescriptor get(TypeSymbol origin) throws FunctionDescriptorLookupError {
Entry e = _map.get(origin);
CompoundScope members = membersClosure(origin.type, false);
if (e == null ||
!e.matches(members.getMark())) {
FunctionDescriptor descRes = findDescriptorInternal(origin, members);
_map.put(origin, new Entry(descRes, members.getMark()));
return descRes;
}
else {
return e.cachedDescRes;
}
}
/**
* Compute the function descriptor associated with a given functional interface
*/
public FunctionDescriptor findDescriptorInternal(TypeSymbol origin,
CompoundScope membersCache) throws FunctionDescriptorLookupError {
if (!origin.isInterface() || (origin.flags() & ANNOTATION) != 0) {
//t must be an interface
throw failure("not.a.functional.intf", origin);
}
final ListBuffer<Symbol> abstracts = new ListBuffer<>();
for (Symbol sym : membersCache.getElements(new DescriptorFilter(origin))) {
Type mtype = memberType(origin.type, sym);
if (abstracts.isEmpty() ||
(sym.name == abstracts.first().name &&
overrideEquivalent(mtype, memberType(origin.type, abstracts.first())))) {
abstracts.append(sym);
} else {
//the target method(s) should be the only abstract members of t
throw failure("not.a.functional.intf.1", origin,
diags.fragment("incompatible.abstracts", Kinds.kindName(origin), origin));
}
}
if (abstracts.isEmpty()) {
//t must define a suitable non-generic method
throw failure("not.a.functional.intf.1", origin,
diags.fragment("no.abstracts", Kinds.kindName(origin), origin));
} else if (abstracts.size() == 1) {
return new FunctionDescriptor(abstracts.first());
} else { // size > 1
FunctionDescriptor descRes = mergeDescriptors(origin, abstracts.toList());
if (descRes == null) {
//we can get here if the functional interface is ill-formed
ListBuffer<JCDiagnostic> descriptors = new ListBuffer<>();
for (Symbol desc : abstracts) {
String key = desc.type.getThrownTypes().nonEmpty() ?
"descriptor.throws" : "descriptor";
descriptors.append(diags.fragment(key, desc.name,
desc.type.getParameterTypes(),
desc.type.getReturnType(),
desc.type.getThrownTypes()));
}
JCDiagnostic.MultilineDiagnostic incompatibleDescriptors =
new JCDiagnostic.MultilineDiagnostic(diags.fragment("incompatible.descs.in.functional.intf",
Kinds.kindName(origin), origin), descriptors.toList());
throw failure(incompatibleDescriptors);
}
return descRes;
}
}
/**
* Compute a synthetic type for the target descriptor given a list
* of override-equivalent methods in the functional interface type.
* The resulting method type is a method type that is override-equivalent
* and return-type substitutable with each method in the original list.
*/
private FunctionDescriptor mergeDescriptors(TypeSymbol origin, List<Symbol> methodSyms) {
//pick argument types - simply take the signature that is a
//subsignature of all other signatures in the list (as per JLS 8.4.2)
List<Symbol> mostSpecific = List.nil();
outer: for (Symbol msym1 : methodSyms) {
Type mt1 = memberType(origin.type, msym1);
for (Symbol msym2 : methodSyms) {
Type mt2 = memberType(origin.type, msym2);
if (!isSubSignature(mt1, mt2)) {
continue outer;
}
}
mostSpecific = mostSpecific.prepend(msym1);
}
if (mostSpecific.isEmpty()) {
return null;
}
//pick return types - this is done in two phases: (i) first, the most
//specific return type is chosen using strict subtyping; if this fails,
//a second attempt is made using return type substitutability (see JLS 8.4.5)
boolean phase2 = false;
Symbol bestSoFar = null;
while (bestSoFar == null) {
outer: for (Symbol msym1 : mostSpecific) {
Type mt1 = memberType(origin.type, msym1);
for (Symbol msym2 : methodSyms) {
Type mt2 = memberType(origin.type, msym2);
if (phase2 ?
!returnTypeSubstitutable(mt1, mt2) :
!isSubtypeInternal(mt1.getReturnType(), mt2.getReturnType())) {
continue outer;
}
}
bestSoFar = msym1;
}
if (phase2) {
break;
} else {
phase2 = true;
}
}
if (bestSoFar == null) return null;
//merge thrown types - form the intersection of all the thrown types in
//all the signatures in the list
boolean toErase = !bestSoFar.type.hasTag(FORALL);
List<Type> thrown = null;
Type mt1 = memberType(origin.type, bestSoFar);
for (Symbol msym2 : methodSyms) {
Type mt2 = memberType(origin.type, msym2);
List<Type> thrown_mt2 = mt2.getThrownTypes();
if (toErase) {
thrown_mt2 = erasure(thrown_mt2);
} else {
/* If bestSoFar is generic then all the methods are generic.
* The opposite is not true: a non generic method can override
* a generic method (raw override) so it's safe to cast mt1 and
* mt2 to ForAll.
*/
ForAll fa1 = (ForAll)mt1;
ForAll fa2 = (ForAll)mt2;
thrown_mt2 = subst(thrown_mt2, fa2.tvars, fa1.tvars);
}
thrown = (thrown == null) ?
thrown_mt2 :
chk.intersect(thrown_mt2, thrown);
}
final List<Type> thrown1 = thrown;
return new FunctionDescriptor(bestSoFar) {
@Override
public Type getType(Type origin) {
Type mt = memberType(origin, getSymbol());
return createMethodTypeWithThrown(mt, thrown1);
}
};
}
boolean isSubtypeInternal(Type s, Type t) {
return (s.isPrimitive() && t.isPrimitive()) ?
isSameType(t, s) :
isSubtype(s, t);
}
FunctionDescriptorLookupError failure(String msg, Object... args) {
return failure(diags.fragment(msg, args));
}
FunctionDescriptorLookupError failure(JCDiagnostic diag) {
return functionDescriptorLookupError.setMessage(diag);
}
}
private DescriptorCache descCache = new DescriptorCache();
/**
* Find the method descriptor associated to this class symbol - if the
* symbol 'origin' is not a functional interface, an exception is thrown.
*/
public Symbol findDescriptorSymbol(TypeSymbol origin) throws FunctionDescriptorLookupError {
return descCache.get(origin).getSymbol();
}
/**
* Find the type of the method descriptor associated to this class symbol -
* if the symbol 'origin' is not a functional interface, an exception is thrown.
*/
public Type findDescriptorType(Type origin) throws FunctionDescriptorLookupError {
return descCache.get(origin.tsym).getType(origin);
}
/**
* Is given type a functional interface?
*/
public boolean isFunctionalInterface(TypeSymbol tsym) {
try {
findDescriptorSymbol(tsym);
return true;
} catch (FunctionDescriptorLookupError ex) {
return false;
}
}
public boolean isFunctionalInterface(Type site) {
try {
findDescriptorType(site);
return true;
} catch (FunctionDescriptorLookupError ex) {
return false;
}
}
public Type removeWildcards(Type site) {
Type capturedSite = capture(site);
if (capturedSite != site) {
Type formalInterface = site.tsym.type;
ListBuffer<Type> typeargs = new ListBuffer<>();
List<Type> actualTypeargs = site.getTypeArguments();
List<Type> capturedTypeargs = capturedSite.getTypeArguments();
//simply replace the wildcards with its bound
for (Type t : formalInterface.getTypeArguments()) {
if (actualTypeargs.head.hasTag(WILDCARD)) {
WildcardType wt = (WildcardType)actualTypeargs.head.unannotatedType();
Type bound;
switch (wt.kind) {
case EXTENDS:
case UNBOUND:
CapturedType capVar = (CapturedType)capturedTypeargs.head.unannotatedType();
//use declared bound if it doesn't depend on formal type-args
bound = capVar.bound.containsAny(capturedSite.getTypeArguments()) ?
wt.type : capVar.bound;
break;
default:
bound = wt.type;
}
typeargs.append(bound);
} else {
typeargs.append(actualTypeargs.head);
}
actualTypeargs = actualTypeargs.tail;
capturedTypeargs = capturedTypeargs.tail;
}
return subst(formalInterface, formalInterface.getTypeArguments(), typeargs.toList());
} else {
return site;
}
}
/**
* Create a symbol for a class that implements a given functional interface
* and overrides its functional descriptor. This routine is used for two
* main purposes: (i) checking well-formedness of a functional interface;
* (ii) perform functional interface bridge calculation.
*/
public ClassSymbol makeFunctionalInterfaceClass(Env<AttrContext> env, Name name, List targets, long cflags) {
if (targets.isEmpty() || !isFunctionalInterface(targets.head)) {
return null;
}
Symbol descSym = findDescriptorSymbol(targets.head.tsym);
Type descType = findDescriptorType(targets.head);
ClassSymbol csym = new ClassSymbol(cflags, name, env.enclClass.sym.outermostClass());
csym.completer = null;
csym.members_field = new Scope(csym);
MethodSymbol instDescSym = new MethodSymbol(descSym.flags(), descSym.name, descType, csym);
csym.members_field.enter(instDescSym);
Type.ClassType ctype = new Type.ClassType(Type.noType, List.<Type>nil(), csym);
ctype.supertype_field = syms.objectType;
ctype.interfaces_field = targets;
csym.type = ctype;
csym.sourcefile = ((ClassSymbol)csym.owner).sourcefile;
return csym;
}
/**
* Find the minimal set of methods that are overridden by the functional
* descriptor in 'origin'. All returned methods are assumed to have different
* erased signatures.
*/
public List<Symbol> functionalInterfaceBridges(TypeSymbol origin) {
Assert.check(isFunctionalInterface(origin));
Symbol descSym = findDescriptorSymbol(origin);
CompoundScope members = membersClosure(origin.type, false);
ListBuffer<Symbol> overridden = new ListBuffer<>();
outer: for (Symbol m2 : members.getElementsByName(descSym.name, bridgeFilter)) {
if (m2 == descSym) continue;
else if (descSym.overrides(m2, origin, Types.this, false)) {
for (Symbol m3 : overridden) {
if (isSameType(m3.erasure(Types.this), m2.erasure(Types.this)) ||
(m3.overrides(m2, origin, Types.this, false) &&
(pendingBridges((ClassSymbol)origin, m3.enclClass()) ||
(((MethodSymbol)m2).binaryImplementation((ClassSymbol)m3.owner, Types.this) != null)))) {
continue outer;
}
}
overridden.add(m2);
}
}
return overridden.toList();
}
//where
private Filter<Symbol> bridgeFilter = new Filter() {
public boolean accepts(Symbol t) {
return t.kind == Kinds.MTH &&
t.name != names.init &&
t.name != names.clinit &&
(t.flags() & SYNTHETIC) == 0;
}
};
private boolean pendingBridges(ClassSymbol origin, TypeSymbol s) {
//a symbol will be completed from a classfile if (a) symbol has
//an associated file object with CLASS kind and (b) the symbol has
//not been entered
if (origin.classfile != null &&
origin.classfile.getKind() == JavaFileObject.Kind.CLASS &&
enter.getEnv(origin) == null) {
return false;
}
if (origin == s) {
return true;
}
for (Type t : interfaces(origin.type)) {
if (pendingBridges((ClassSymbol)t.tsym, s)) {
return true;
}
}
return false;
}
// </editor-fold>
/**
* Scope filter used to skip methods that should be ignored (such as methods
* overridden by j.l.Object) during function interface conversion interface check
*/
class DescriptorFilter implements Filter<Symbol> {
TypeSymbol origin;
DescriptorFilter(TypeSymbol origin) {
this.origin = origin;
}
@Override
public boolean accepts(Symbol sym) {
return sym.kind == Kinds.MTH &&
(sym.flags() & (ABSTRACT | DEFAULT)) == ABSTRACT &&
!overridesObjectMethod(origin, sym) &&
(interfaceCandidates(origin.type, (MethodSymbol)sym).head.flags() & DEFAULT) == 0;
}
};
// <editor-fold defaultstate="collapsed" desc="isSubtype">
/**
* Is t an unchecked subtype of s?
*/
public boolean isSubtypeUnchecked(Type t, Type s) {
return isSubtypeUnchecked(t, s, noWarnings);
}
/**
* Is t an unchecked subtype of s?
*/
public boolean isSubtypeUnchecked(Type t, Type s, Warner warn) {
boolean result = isSubtypeUncheckedInternal(t, s, warn);
if (result) {
checkUnsafeVarargsConversion(t, s, warn);
}
return result;
}
//where
private boolean isSubtypeUncheckedInternal(Type t, Type s, Warner warn) {
if (t.hasTag(ARRAY) && s.hasTag(ARRAY)) {
t = t.unannotatedType();
s = s.unannotatedType();
if (((ArrayType)t).elemtype.isPrimitive()) {
return isSameType(elemtype(t), elemtype(s));
} else {
return isSubtypeUnchecked(elemtype(t), elemtype(s), warn);
}
} else if (isSubtype(t, s)) {
return true;
} else if (t.hasTag(TYPEVAR)) {
return isSubtypeUnchecked(t.getUpperBound(), s, warn);
} else if (!s.isRaw()) {
Type t2 = asSuper(t, s.tsym);
if (t2 != null && t2.isRaw()) {
if (isReifiable(s)) {
warn.silentWarn(LintCategory.UNCHECKED);
} else {
warn.warn(LintCategory.UNCHECKED);
}
return true;
}
}
return false;
}
private void checkUnsafeVarargsConversion(Type t, Type s, Warner warn) {
if (!t.hasTag(ARRAY) || isReifiable(t)) {
return;
}
t = t.unannotatedType();
s = s.unannotatedType();
ArrayType from = (ArrayType)t;
boolean shouldWarn = false;
switch (s.getTag()) {
case ARRAY:
ArrayType to = (ArrayType)s;
shouldWarn = from.isVarargs() &&
!to.isVarargs() &&
!isReifiable(from);
break;
case CLASS:
shouldWarn = from.isVarargs();
break;
}
if (shouldWarn) {
warn.warn(LintCategory.VARARGS);
}
}
/**
* Is t a subtype of s?<br>
* (not defined for Method and ForAll types)
*/
final public boolean isSubtype(Type t, Type s) {
return isSubtype(t, s, true);
}
final public boolean isSubtypeNoCapture(Type t, Type s) {
return isSubtype(t, s, false);
}
public boolean isSubtype(Type t, Type s, boolean capture) {
if (t == s)
return true;
t = t.unannotatedType();
s = s.unannotatedType();
if (t == s)
return true;
if (s.isPartial())
return isSuperType(s, t);
if (s.isCompound()) {
for (Type s2 : interfaces(s).prepend(supertype(s))) {
if (!isSubtype(t, s2, capture))
return false;
}
return true;
}
Type lower = lowerBound(s);
if (s != lower)
return isSubtype(capture ? capture(t) : t, lower, false);
return isSubtype.visit(capture ? capture(t) : t, s);
}
// where
private TypeRelation isSubtype = new TypeRelation()
{
@Override
public Boolean visitType(Type t, Type s) {
switch (t.getTag()) {
case BYTE:
return (!s.hasTag(CHAR) && t.getTag().isSubRangeOf(s.getTag()));
case CHAR:
return (!s.hasTag(SHORT) && t.getTag().isSubRangeOf(s.getTag()));
case SHORT: case INT: case LONG:
case FLOAT: case DOUBLE:
return t.getTag().isSubRangeOf(s.getTag());
case BOOLEAN: case VOID:
return t.hasTag(s.getTag());
case TYPEVAR:
return isSubtypeNoCapture(t.getUpperBound(), s);
case BOT:
return
s.hasTag(BOT) || s.hasTag(CLASS) ||
s.hasTag(ARRAY) || s.hasTag(TYPEVAR);
case WILDCARD: //we shouldn't be here - avoids crash (see 7034495)
case NONE:
return false;
default:
throw new AssertionError("isSubtype " + t.getTag());
}
}
private Set<TypePair> cache = new HashSet();
private boolean containsTypeRecursive(Type t, Type s) {
TypePair pair = new TypePair(t, s);
if (cache.add(pair)) {
try {
return containsType(t.getTypeArguments(),
s.getTypeArguments());
} finally {
cache.remove(pair);
}
} else {
return containsType(t.getTypeArguments(),
rewriteSupers(s).getTypeArguments());
}
}
private Type rewriteSupers(Type t) {
if (!t.isParameterized())
return t;
ListBuffer<Type> from = new ListBuffer<>();
ListBuffer<Type> to = new ListBuffer<>();
adaptSelf(t, from, to);
if (from.isEmpty())
return t;
ListBuffer<Type> rewrite = new ListBuffer<>();
boolean changed = false;
for (Type orig : to.toList()) {
Type s = rewriteSupers(orig);
if (s.isSuperBound() && !s.isExtendsBound()) {
s = new WildcardType(syms.objectType,
BoundKind.UNBOUND,
syms.boundClass);
changed = true;
} else if (s != orig) {
s = new WildcardType(upperBound(s),
BoundKind.EXTENDS,
syms.boundClass);
changed = true;
}
rewrite.append(s);
}
if (changed)
return subst(t.tsym.type, from.toList(), rewrite.toList());
else
return t;
}
@Override
public Boolean visitClassType(ClassType t, Type s) {
Type sup = asSuper(t, s.tsym);
return sup != null
&& sup.tsym == s.tsym
// You're not allowed to write
// Vector<Object> vec = new Vector();
// But with wildcards you can write
// Vector<? extends Object> vec = new Vector();
// which means that subtype checking must be done
// here instead of same-type checking (via containsType).
&& (!s.isParameterized() || containsTypeRecursive(s, sup))
&& isSubtypeNoCapture(sup.getEnclosingType(),
s.getEnclosingType());
}
@Override
public Boolean visitArrayType(ArrayType t, Type s) {
if (s.hasTag(ARRAY)) {
if (t.elemtype.isPrimitive())
return isSameType(t.elemtype, elemtype(s));
else
return isSubtypeNoCapture(t.elemtype, elemtype(s));
}
if (s.hasTag(CLASS)) {
Name sname = s.tsym.getQualifiedName();
return sname == names.java_lang_Object
|| sname == names.java_lang_Cloneable
|| sname == names.java_io_Serializable;
}
return false;
}
@Override
public Boolean visitUndetVar(UndetVar t, Type s) {
//todo: test against origin needed? or replace with substitution?
if (t == s || t.qtype == s || s.hasTag(ERROR) || s.hasTag(UNKNOWN)) {
return true;
} else if (s.hasTag(BOT)) {
//if 's' is 'null' there's no instantiated type U for which
//U <: s (but 'null' itself, which is not a valid type)
return false;
}
t.addBound(InferenceBound.UPPER, s, Types.this);
return true;
}
@Override
public Boolean visitErrorType(ErrorType t, Type s) {
return true;
}
};
/**
* Is t a subtype of every type in given list `ts'?<br>
* (not defined for Method and ForAll types)<br>
* Allows unchecked conversions.
*/
public boolean isSubtypeUnchecked(Type t, List<Type> ts, Warner warn) {
for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
if (!isSubtypeUnchecked(t, l.head, warn))
return false;
return true;
}
/**
* Are corresponding elements of ts subtypes of ss? If lists are
* of different length, return false.
*/
public boolean isSubtypes(List<Type> ts, List ss) {
while (ts.tail != null && ss.tail != null
/*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
isSubtype(ts.head, ss.head)) {
ts = ts.tail;
ss = ss.tail;
}
return ts.tail == null && ss.tail == null;
/*inlined: ts.isEmpty() && ss.isEmpty();*/
}
/**
* Are corresponding elements of ts subtypes of ss, allowing
* unchecked conversions? If lists are of different length,
* return false.
**/
public boolean isSubtypesUnchecked(List<Type> ts, List ss, Warner warn) {
while (ts.tail != null && ss.tail != null
/*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
isSubtypeUnchecked(ts.head, ss.head, warn)) {
ts = ts.tail;
ss = ss.tail;
}
return ts.tail == null && ss.tail == null;
/*inlined: ts.isEmpty() && ss.isEmpty();*/
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="isSuperType">
/**
* Is t a supertype of s?
*/
public boolean isSuperType(Type t, Type s) {
switch (t.getTag()) {
case ERROR:
return true;
case UNDETVAR: {
UndetVar undet = (UndetVar)t;
if (t == s ||
undet.qtype == s ||
s.hasTag(ERROR) ||
s.hasTag(BOT)) {
return true;
}
undet.addBound(InferenceBound.LOWER, s, this);
return true;
}
default:
return isSubtype(s, t);
}
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="isSameType">
/**
* Are corresponding elements of the lists the same type? If
* lists are of different length, return false.
*/
public boolean isSameTypes(List<Type> ts, List ss) {
return isSameTypes(ts, ss, false);
}
public boolean isSameTypes(List<Type> ts, List ss, boolean strict) {
while (ts.tail != null && ss.tail != null
/*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
isSameType(ts.head, ss.head, strict)) {
ts = ts.tail;
ss = ss.tail;
}
return ts.tail == null && ss.tail == null;
/*inlined: ts.isEmpty() && ss.isEmpty();*/
}
/**
* A polymorphic signature method (JLS SE 7, 8.4.1) is a method that
* (i) is declared in the java.lang.invoke.MethodHandle class, (ii) takes
* a single variable arity parameter (iii) whose declared type is Object[],
* (iv) has a return type of Object and (v) is native.
*/
public boolean isSignaturePolymorphic(MethodSymbol msym) {
List<Type> argtypes = msym.type.getParameterTypes();
return (msym.flags_field & NATIVE) != 0 &&
msym.owner == syms.methodHandleType.tsym &&
argtypes.tail.tail == null &&
argtypes.head.hasTag(TypeTag.ARRAY) &&
msym.type.getReturnType().tsym == syms.objectType.tsym &&
((ArrayType)argtypes.head).elemtype.tsym == syms.objectType.tsym;
}
/**
* Is t the same type as s?
*/
public boolean isSameType(Type t, Type s) {
return isSameType(t, s, false);
}
public boolean isSameType(Type t, Type s, boolean strict) {
return strict ?
isSameTypeStrict.visit(t, s) :
isSameTypeLoose.visit(t, s);
}
public boolean isSameAnnotatedType(Type t, Type s) {
return isSameAnnotatedType.visit(t, s);
}
// where
abstract class SameTypeVisitor extends TypeRelation {
public Boolean visitType(Type t, Type s) {
if (t == s)
return true;
if (s.isPartial())
return visit(s, t);
switch (t.getTag()) {
case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
return t.hasTag(s.getTag());
case TYPEVAR: {
if (s.hasTag(TYPEVAR)) {
//type-substitution does not preserve type-var types
//check that type var symbols and bounds are indeed the same
return sameTypeVars((TypeVar)t.unannotatedType(), (TypeVar)s.unannotatedType());
}
else {
//special case for s == ? super X, where upper(s) = u
//check that u == t, where u has been set by Type.withTypeVar
return s.isSuperBound() &&
!s.isExtendsBound() &&
visit(t, upperBound(s));
}
}
default:
throw new AssertionError("isSameType " + t.getTag());
}
}
abstract boolean sameTypeVars(TypeVar tv1, TypeVar tv2);
@Override
public Boolean visitWildcardType(WildcardType t, Type s) {
if (s.isPartial())
return visit(s, t);
else
return false;
}
@Override
public Boolean visitClassType(ClassType t, Type s) {
if (t == s)
return true;
if (s.isPartial())
return visit(s, t);
if (s.isSuperBound() && !s.isExtendsBound())
return visit(t, upperBound(s)) && visit(t, lowerBound(s));
if (t.isCompound() && s.isCompound()) {
if (!visit(supertype(t), supertype(s)))
return false;
HashSet<UniqueType> set = new HashSet();
for (Type x : interfaces(t))
set.add(new UniqueType(x.unannotatedType(), Types.this));
for (Type x : interfaces(s)) {
if (!set.remove(new UniqueType(x.unannotatedType(), Types.this)))
return false;
}
return (set.isEmpty());
}
return t.tsym == s.tsym
&& visit(t.getEnclosingType(), s.getEnclosingType())
&& containsTypes(t.getTypeArguments(), s.getTypeArguments());
}
abstract protected boolean containsTypes(List<Type> ts1, List ts2);
@Override
public Boolean visitArrayType(ArrayType t, Type s) {
if (t == s)
return true;
if (s.isPartial())
return visit(s, t);
return s.hasTag(ARRAY)
&& containsTypeEquivalent(t.elemtype, elemtype(s));
}
@Override
public Boolean visitMethodType(MethodType t, Type s) {
// isSameType for methods does not take thrown
// exceptions into account!
return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType());
}
@Override
public Boolean visitPackageType(PackageType t, Type s) {
return t == s;
}
@Override
public Boolean visitForAll(ForAll t, Type s) {
if (!s.hasTag(FORALL)) {
return false;
}
ForAll forAll = (ForAll)s;
return hasSameBounds(t, forAll)
&& visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
}
@Override
public Boolean visitUndetVar(UndetVar t, Type s) {
if (s.hasTag(WILDCARD)) {
// FIXME, this might be leftovers from before capture conversion
return false;
}
if (t == s || t.qtype == s || s.hasTag(ERROR) || s.hasTag(UNKNOWN)) {
return true;
}
t.addBound(InferenceBound.EQ, s, Types.this);
return true;
}
@Override
public Boolean visitErrorType(ErrorType t, Type s) {
return true;
}
}
/**
* Standard type-equality relation - type variables are considered
* equals if they share the same type symbol.
*/
TypeRelation isSameTypeLoose = new LooseSameTypeVisitor();
private class LooseSameTypeVisitor extends SameTypeVisitor {
@Override
boolean sameTypeVars(TypeVar tv1, TypeVar tv2) {
return tv1.tsym == tv2.tsym && visit(tv1.getUpperBound(), tv2.getUpperBound());
}
@Override
protected boolean containsTypes(List<Type> ts1, List ts2) {
return containsTypeEquivalent(ts1, ts2);
}
};
/**
* Strict type-equality relation - type variables are considered
* equals if they share the same object identity.
*/
TypeRelation isSameTypeStrict = new SameTypeVisitor() {
@Override
boolean sameTypeVars(TypeVar tv1, TypeVar tv2) {
return tv1 == tv2;
}
@Override
protected boolean containsTypes(List<Type> ts1, List ts2) {
return isSameTypes(ts1, ts2, true);
}
@Override
public Boolean visitWildcardType(WildcardType t, Type s) {
if (!s.hasTag(WILDCARD)) {
return false;
} else {
WildcardType t2 = (WildcardType)s.unannotatedType();
return t.kind == t2.kind &&
isSameType(t.type, t2.type, true);
}
}
};
/**
* A version of LooseSameTypeVisitor that takes AnnotatedTypes
* into account.
*/
TypeRelation isSameAnnotatedType = new LooseSameTypeVisitor() {
@Override
public Boolean visitAnnotatedType(AnnotatedType t, Type s) {
if (!s.isAnnotated())
return false;
if (!t.getAnnotationMirrors().containsAll(s.getAnnotationMirrors()))
return false;
if (!s.getAnnotationMirrors().containsAll(t.getAnnotationMirrors()))
return false;
return visit(t.unannotatedType(), s);
}
};
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Contains Type">
public boolean containedBy(Type t, Type s) {
switch (t.getTag()) {
case UNDETVAR:
if (s.hasTag(WILDCARD)) {
UndetVar undetvar = (UndetVar)t;
WildcardType wt = (WildcardType)s.unannotatedType();
switch(wt.kind) {
case UNBOUND: //similar to ? extends Object
case EXTENDS: {
Type bound = upperBound(s);
undetvar.addBound(InferenceBound.UPPER, bound, this);
break;
}
case SUPER: {
Type bound = lowerBound(s);
undetvar.addBound(InferenceBound.LOWER, bound, this);
break;
}
}
return true;
} else {
return isSameType(t, s);
}
case ERROR:
return true;
default:
return containsType(s, t);
}
}
boolean containsType(List<Type> ts, List ss) {
while (ts.nonEmpty() && ss.nonEmpty()
&& containsType(ts.head, ss.head)) {
ts = ts.tail;
ss = ss.tail;
}
return ts.isEmpty() && ss.isEmpty();
}
/**
* Check if t contains s.
*
* <p>T contains S if:
*
* <p>{@code L(T) <: L(S) && U(S) <: U(T)}
*
* <p>This relation is only used by ClassType.isSubtype(), that
* is,
*
* <p>{@code C <: C if T contains S.}
*
* <p>Because of F-bounds, this relation can lead to infinite
* recursion. Thus we must somehow break that recursion. Notice
* that containsType() is only called from ClassType.isSubtype().
* Since the arguments have already been checked against their
* bounds, we know:
*
* <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)}
*
* <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)}
*
* @param t a type
* @param s a type
*/
public boolean containsType(Type t, Type s) {
return containsType.visit(t, s);
}
// where
private TypeRelation containsType = new TypeRelation() {
private Type U(Type t) {
while (t.hasTag(WILDCARD)) {
WildcardType w = (WildcardType)t.unannotatedType();
if (w.isSuperBound())
return w.bound == null ? syms.objectType : w.bound.bound;
else
t = w.type;
}
return t;
}
private Type L(Type t) {
while (t.hasTag(WILDCARD)) {
WildcardType w = (WildcardType)t.unannotatedType();
if (w.isExtendsBound())
return syms.botType;
else
t = w.type;
}
return t;
}
public Boolean visitType(Type t, Type s) {
if (s.isPartial())
return containedBy(s, t);
else
return isSameType(t, s);
}
// void debugContainsType(WildcardType t, Type s) {
// System.err.println();
// System.err.format(" does %s contain %s?%n", t, s);
// System.err.format(" %s U(%s) <: U(%s) %s = %s%n",
// upperBound(s), s, t, U(t),
// t.isSuperBound()
// || isSubtypeNoCapture(upperBound(s), U(t)));
// System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
// L(t), t, s, lowerBound(s),
// t.isExtendsBound()
// || isSubtypeNoCapture(L(t), lowerBound(s)));
// System.err.println();
// }
@Override
public Boolean visitWildcardType(WildcardType t, Type s) {
if (s.isPartial())
return containedBy(s, t);
else {
// debugContainsType(t, s);
return isSameWildcard(t, s)
|| isCaptureOf(s, t)
|| ((t.isExtendsBound() || isSubtypeNoCapture(L(t), lowerBound(s))) &&
(t.isSuperBound() || isSubtypeNoCapture(upperBound(s), U(t))));
}
}
@Override
public Boolean visitUndetVar(UndetVar t, Type s) {
if (!s.hasTag(WILDCARD)) {
return isSameType(t, s);
} else {
return false;
}
}
@Override
public Boolean visitErrorType(ErrorType t, Type s) {
return true;
}
};
public boolean isCaptureOf(Type s, WildcardType t) {
if (!s.hasTag(TYPEVAR) || !((TypeVar)s.unannotatedType()).isCaptured())
return false;
return isSameWildcard(t, ((CapturedType)s.unannotatedType()).wildcard);
}
public boolean isSameWildcard(WildcardType t, Type s) {
if (!s.hasTag(WILDCARD))
return false;
WildcardType w = (WildcardType)s.unannotatedType();
return w.kind == t.kind && w.type == t.type;
}
public boolean containsTypeEquivalent(List<Type> ts, List ss) {
while (ts.nonEmpty() && ss.nonEmpty()
&& containsTypeEquivalent(ts.head, ss.head)) {
ts = ts.tail;
ss = ss.tail;
}
return ts.isEmpty() && ss.isEmpty();
}
// </editor-fold>
/**
* Can t and s be compared for equality? Any primitive ==
* primitive or primitive == object comparisons here are an error.
* Unboxing and correct primitive == primitive comparisons are
* already dealt with in Attr.visitBinary.
*
*/
public boolean isEqualityComparable(Type s, Type t, Warner warn) {
if (t.isNumeric() && s.isNumeric())
return true;
boolean tPrimitive = t.isPrimitive();
boolean sPrimitive = s.isPrimitive();
if (!tPrimitive && !sPrimitive) {
return isCastable(s, t, warn) || isCastable(t, s, warn);
} else {
return false;
}
}
// <editor-fold defaultstate="collapsed" desc="isCastable">
public boolean isCastable(Type t, Type s) {
return isCastable(t, s, noWarnings);
}
/**
* Is t is castable to s?<br>
* s is assumed to be an erased type.<br>
* (not defined for Method and ForAll types).
*/
public boolean isCastable(Type t, Type s, Warner warn) {
if (t == s)
return true;
if (t.isPrimitive() != s.isPrimitive())
return allowBoxing && (
isConvertible(t, s, warn)
|| (allowObjectToPrimitiveCast &&
s.isPrimitive() &&
isSubtype(boxedClass(s).type, t)));
if (warn != warnStack.head) {
try {
warnStack = warnStack.prepend(warn);
checkUnsafeVarargsConversion(t, s, warn);
return isCastable.visit(t,s);
} finally {
warnStack = warnStack.tail;
}
} else {
return isCastable.visit(t,s);
}
}
// where
private TypeRelation isCastable = new TypeRelation() {
public Boolean visitType(Type t, Type s) {
if (s.hasTag(ERROR))
return true;
switch (t.getTag()) {
case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
case DOUBLE:
return s.isNumeric();
case BOOLEAN:
return s.hasTag(BOOLEAN);
case VOID:
return false;
case BOT:
return isSubtype(t, s);
default:
throw new AssertionError();
}
}
@Override
public Boolean visitWildcardType(WildcardType t, Type s) {
return isCastable(upperBound(t), s, warnStack.head);
}
@Override
public Boolean visitClassType(ClassType t, Type s) {
if (s.hasTag(ERROR) || s.hasTag(BOT))
return true;
if (s.hasTag(TYPEVAR)) {
if (isCastable(t, s.getUpperBound(), noWarnings)) {
warnStack.head.warn(LintCategory.UNCHECKED);
return true;
} else {
return false;
}
}
if (t.isCompound() || s.isCompound()) {
return !t.isCompound() ?
visitIntersectionType((IntersectionClassType)s.unannotatedType(), t, true) :
visitIntersectionType((IntersectionClassType)t.unannotatedType(), s, false);
}
if (s.hasTag(CLASS) || s.hasTag(ARRAY)) {
boolean upcast;
if ((upcast = isSubtype(erasure(t), erasure(s)))
|| isSubtype(erasure(s), erasure(t))) {
if (!upcast && s.hasTag(ARRAY)) {
if (!isReifiable(s))
warnStack.head.warn(LintCategory.UNCHECKED);
return true;
} else if (s.isRaw()) {
return true;
} else if (t.isRaw()) {
if (!isUnbounded(s))
warnStack.head.warn(LintCategory.UNCHECKED);
return true;
}
// Assume |a| <: |b|
final Type a = upcast ? t : s;
final Type b = upcast ? s : t;
final boolean HIGH = true;
final boolean LOW = false;
final boolean DONT_REWRITE_TYPEVARS = false;
Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS);
Type aLow = rewriteQuantifiers(a, LOW, DONT_REWRITE_TYPEVARS);
Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS);
Type bLow = rewriteQuantifiers(b, LOW, DONT_REWRITE_TYPEVARS);
Type lowSub = asSub(bLow, aLow.tsym);
Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
if (highSub == null) {
final boolean REWRITE_TYPEVARS = true;
aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS);
aLow = rewriteQuantifiers(a, LOW, REWRITE_TYPEVARS);
bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS);
bLow = rewriteQuantifiers(b, LOW, REWRITE_TYPEVARS);
lowSub = asSub(bLow, aLow.tsym);
highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
}
if (highSub != null) {
if (!(a.tsym == highSub.tsym && a.tsym == lowSub.tsym)) {
Assert.error(a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym);
}
if (!disjointTypes(aHigh.allparams(), highSub.allparams())
&& !disjointTypes(aHigh.allparams(), lowSub.allparams())
&& !disjointTypes(aLow.allparams(), highSub.allparams())
&& !disjointTypes(aLow.allparams(), lowSub.allparams())) {
if (upcast ? giveWarning(a, b) :
giveWarning(b, a))
warnStack.head.warn(LintCategory.UNCHECKED);
return true;
}
}
if (isReifiable(s))
return isSubtypeUnchecked(a, b);
else
return isSubtypeUnchecked(a, b, warnStack.head);
}
// Sidecast
if (s.hasTag(CLASS)) {
if ((s.tsym.flags() & INTERFACE) != 0) {
return ((t.tsym.flags() & FINAL) == 0)
? sideCast(t, s, warnStack.head)
: sideCastFinal(t, s, warnStack.head);
} else if ((t.tsym.flags() & INTERFACE) != 0) {
return ((s.tsym.flags() & FINAL) == 0)
? sideCast(t, s, warnStack.head)
: sideCastFinal(t, s, warnStack.head);
} else {
// unrelated class types
return false;
}
}
}
return false;
}
boolean visitIntersectionType(IntersectionClassType ict, Type s, boolean reverse) {
Warner warn = noWarnings;
for (Type c : ict.getComponents()) {
warn.clear();
if (reverse ? !isCastable(s, c, warn) : !isCastable(c, s, warn))
return false;
}
if (warn.hasLint(LintCategory.UNCHECKED))
warnStack.head.warn(LintCategory.UNCHECKED);
return true;
}
@Override
public Boolean visitArrayType(ArrayType t, Type s) {
switch (s.getTag()) {
case ERROR:
case BOT:
return true;
case TYPEVAR:
if (isCastable(s, t, noWarnings)) {
warnStack.head.warn(LintCategory.UNCHECKED);
return true;
} else {
return false;
}
case CLASS:
return isSubtype(t, s);
case ARRAY:
if (elemtype(t).isPrimitive() || elemtype(s).isPrimitive()) {
return elemtype(t).hasTag(elemtype(s).getTag());
} else {
return visit(elemtype(t), elemtype(s));
}
default:
return false;
}
}
@Override
public Boolean visitTypeVar(TypeVar t, Type s) {
switch (s.getTag()) {
case ERROR:
case BOT:
return true;
case TYPEVAR:
if (isSubtype(t, s)) {
return true;
} else if (isCastable(t.bound, s, noWarnings)) {
warnStack.head.warn(LintCategory.UNCHECKED);
return true;
} else {
return false;
}
default:
return isCastable(t.bound, s, warnStack.head);
}
}
@Override
public Boolean visitErrorType(ErrorType t, Type s) {
return true;
}
};
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="disjointTypes">
public boolean disjointTypes(List<Type> ts, List ss) {
while (ts.tail != null && ss.tail != null) {
if (disjointType(ts.head, ss.head)) return true;
ts = ts.tail;
ss = ss.tail;
}
return false;
}
/**
* Two types or wildcards are considered disjoint if it can be
* proven that no type can be contained in both. It is
* conservative in that it is allowed to say that two types are
* not disjoint, even though they actually are.
*
* The type {@code C<X>} is castable to {@code C} exactly if
* {@code X} and {@code Y} are not disjoint.
*/
public boolean disjointType(Type t, Type s) {
return disjointType.visit(t, s);
}
// where
private TypeRelation disjointType = new TypeRelation() {
private Set<TypePair> cache = new HashSet();
@Override
public Boolean visitType(Type t, Type s) {
if (s.hasTag(WILDCARD))
return visit(s, t);
else
return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
}
private boolean isCastableRecursive(Type t, Type s) {
TypePair pair = new TypePair(t, s);
if (cache.add(pair)) {
try {
return Types.this.isCastable(t, s);
} finally {
cache.remove(pair);
}
} else {
return true;
}
}
private boolean notSoftSubtypeRecursive(Type t, Type s) {
TypePair pair = new TypePair(t, s);
if (cache.add(pair)) {
try {
return Types.this.notSoftSubtype(t, s);
} finally {
cache.remove(pair);
}
} else {
return false;
}
}
@Override
public Boolean visitWildcardType(WildcardType t, Type s) {
if (t.isUnbound())
return false;
if (!s.hasTag(WILDCARD)) {
if (t.isExtendsBound())
return notSoftSubtypeRecursive(s, t.type);
else
return notSoftSubtypeRecursive(t.type, s);
}
if (s.isUnbound())
return false;
if (t.isExtendsBound()) {
if (s.isExtendsBound())
return !isCastableRecursive(t.type, upperBound(s));
else if (s.isSuperBound())
return notSoftSubtypeRecursive(lowerBound(s), t.type);
} else if (t.isSuperBound()) {
if (s.isExtendsBound())
return notSoftSubtypeRecursive(t.type, upperBound(s));
}
return false;
}
};
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="lowerBoundArgtypes">
/**
* Returns the lower bounds of the formals of a method.
*/
public List<Type> lowerBoundArgtypes(Type t) {
return lowerBounds(t.getParameterTypes());
}
public List<Type> lowerBounds(List ts) {
return map(ts, lowerBoundMapping);
}
private final Mapping lowerBoundMapping = new Mapping("lowerBound") {
public Type apply(Type t) {
return lowerBound(t);
}
};
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="notSoftSubtype">
/**
* This relation answers the question: is impossible that
* something of type `t' can be a subtype of `s'? This is
* different from the question "is `t' not a subtype of `s'?"
* when type variables are involved: Integer is not a subtype of T
* where {@code <T extends Number>} but it is not true that Integer cannot
* possibly be a subtype of T.
*/
public boolean notSoftSubtype(Type t, Type s) {
if (t == s) return false;
if (t.hasTag(TYPEVAR)) {
TypeVar tv = (TypeVar) t;
return !isCastable(tv.bound,
relaxBound(s),
noWarnings);
}
if (!s.hasTag(WILDCARD))
s = upperBound(s);
return !isSubtype(t, relaxBound(s));
}
private Type relaxBound(Type t) {
if (t.hasTag(TYPEVAR)) {
while (t.hasTag(TYPEVAR))
t = t.getUpperBound();
t = rewriteQuantifiers(t, true, true);
}
return t;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="isReifiable">
public boolean isReifiable(Type t) {
return isReifiable.visit(t);
}
// where
private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor() {
public Boolean visitType(Type t, Void ignored) {
return true;
}
@Override
public Boolean visitClassType(ClassType t, Void ignored) {
if (t.isCompound())
return false;
else {
if (!t.isParameterized())
return true;
for (Type param : t.allparams()) {
if (!param.isUnbound())
return false;
}
return true;
}
}
@Override
public Boolean visitArrayType(ArrayType t, Void ignored) {
return visit(t.elemtype);
}
@Override
public Boolean visitTypeVar(TypeVar t, Void ignored) {
return false;
}
};
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Array Utils">
public boolean isArray(Type t) {
while (t.hasTag(WILDCARD))
t = upperBound(t);
return t.hasTag(ARRAY);
}
/**
* The element type of an array.
*/
public Type elemtype(Type t) {
switch (t.getTag()) {
case WILDCARD:
return elemtype(upperBound(t));
case ARRAY:
t = t.unannotatedType();
return ((ArrayType)t).elemtype;
case FORALL:
return elemtype(((ForAll)t).qtype);
case ERROR:
return t;
default:
return null;
}
}
public Type elemtypeOrType(Type t) {
Type elemtype = elemtype(t);
return elemtype != null ?
elemtype :
t;
}
/**
* Mapping to take element type of an arraytype
*/
private Mapping elemTypeFun = new Mapping ("elemTypeFun") {
public Type apply(Type t) { return elemtype(t); }
};
/**
* The number of dimensions of an array type.
*/
public int dimensions(Type t) {
int result = 0;
while (t.hasTag(ARRAY)) {
result++;
t = elemtype(t);
}
return result;
}
/**
* Returns an ArrayType with the component type t
*
* @param t The component type of the ArrayType
* @return the ArrayType for the given component
*/
public ArrayType makeArrayType(Type t) {
if (t.hasTag(VOID) || t.hasTag(PACKAGE)) {
Assert.error("Type t must not be a VOID or PACKAGE type, " + t.toString());
}
return new ArrayType(t, syms.arrayClass);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="asSuper">
/**
* Return the (most specific) base type of t that starts with the
* given symbol. If none exists, return null.
*
* @param t a type
* @param sym a symbol
*/
public Type asSuper(Type t, Symbol sym) {
return asSuper.visit(t, sym);
}
// where
private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor() {
public Type visitType(Type t, Symbol sym) {
return null;
}
@Override
public Type visitClassType(ClassType t, Symbol sym) {
if (t.tsym == sym)
return t;
Type st = supertype(t);
if (st.hasTag(CLASS) || st.hasTag(TYPEVAR) || st.hasTag(ERROR)) {
Type x = asSuper(st, sym);
if (x != null)
return x;
}
if ((sym.flags() & INTERFACE) != 0) {
for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
Type x = asSuper(l.head, sym);
if (x != null)
return x;
}
}
return null;
}
@Override
public Type visitArrayType(ArrayType t, Symbol sym) {
return isSubtype(t, sym.type) ? sym.type : null;
}
@Override
public Type visitTypeVar(TypeVar t, Symbol sym) {
if (t.tsym == sym)
return t;
else
return asSuper(t.bound, sym);
}
@Override
public Type visitErrorType(ErrorType t, Symbol sym) {
return t;
}
};
/**
* Return the base type of t or any of its outer types that starts
* with the given symbol. If none exists, return null.
*
* @param t a type
* @param sym a symbol
*/
public Type asOuterSuper(Type t, Symbol sym) {
switch (t.getTag()) {
case CLASS:
do {
Type s = asSuper(t, sym);
if (s != null) return s;
t = t.getEnclosingType();
} while (t.hasTag(CLASS));
return null;
case ARRAY:
return isSubtype(t, sym.type) ? sym.type : null;
case TYPEVAR:
return asSuper(t, sym);
case ERROR:
return t;
default:
return null;
}
}
/**
* Return the base type of t or any of its enclosing types that
* starts with the given symbol. If none exists, return null.
*
* @param t a type
* @param sym a symbol
*/
public Type asEnclosingSuper(Type t, Symbol sym) {
switch (t.getTag()) {
case CLASS:
do {
Type s = asSuper(t, sym);
if (s != null) return s;
Type outer = t.getEnclosingType();
t = (outer.hasTag(CLASS)) ? outer :
(t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type :
Type.noType;
} while (t.hasTag(CLASS));
return null;
case ARRAY:
return isSubtype(t, sym.type) ? sym.type : null;
case TYPEVAR:
return asSuper(t, sym);
case ERROR:
return t;
default:
return null;
}
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="memberType">
/**
* The type of given symbol, seen as a member of t.
*
* @param t a type
* @param sym a symbol
*/
public Type memberType(Type t, Symbol sym) {
return (sym.flags() & STATIC) != 0
? sym.type
: memberType.visit(t, sym);
}
// where
private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor() {
public Type visitType(Type t, Symbol sym) {
return sym.type;
}
@Override
public Type visitWildcardType(WildcardType t, Symbol sym) {
return memberType(upperBound(t), sym);
}
@Override
public Type visitClassType(ClassType t, Symbol sym) {
Symbol owner = sym.owner;
long flags = sym.flags();
if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
Type base = asOuterSuper(t, owner);
//if t is an intersection type T = CT & I1 & I2 ... & In
//its supertypes CT, I1, ... In might contain wildcards
//so we need to go through capture conversion
base = t.isCompound() ? capture(base) : base;
if (base != null) {
List<Type> ownerParams = owner.type.allparams();
List<Type> baseParams = base.allparams();
if (ownerParams.nonEmpty()) {
if (baseParams.isEmpty()) {
// then base is a raw type
return erasure(sym.type);
} else {
return subst(sym.type, ownerParams, baseParams);
}
}
}
}
return sym.type;
}
@Override
public Type visitTypeVar(TypeVar t, Symbol sym) {
return memberType(t.bound, sym);
}
@Override
public Type visitErrorType(ErrorType t, Symbol sym) {
return t;
}
};
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="isAssignable">
public boolean isAssignable(Type t, Type s) {
return isAssignable(t, s, noWarnings);
}
/**
* Is t assignable to s?<br>
* Equivalent to subtype except for constant values and raw
* types.<br>
* (not defined for Method and ForAll types)
*/
public boolean isAssignable(Type t, Type s, Warner warn) {
if (t.hasTag(ERROR))
return true;
if (t.getTag().isSubRangeOf(INT) && t.constValue() != null) {
int value = ((Number)t.constValue()).intValue();
switch (s.getTag()) {
case BYTE:
if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE)
return true;
break;
case CHAR:
if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE)
return true;
break;
case SHORT:
if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE)
return true;
break;
case INT:
return true;
case CLASS:
switch (unboxedType(s).getTag()) {
case BYTE:
case CHAR:
case SHORT:
return isAssignable(t, unboxedType(s), warn);
}
break;
}
}
return isConvertible(t, s, warn);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="erasure">
/**
* The erasure of t {@code |t|} -- the type that results when all
* type parameters in t are deleted.
*/
public Type erasure(Type t) {
return eraseNotNeeded(t)? t : erasure(t, false);
}
//where
private boolean eraseNotNeeded(Type t) {
// We don't want to erase primitive types and String type as that
// operation is idempotent. Also, erasing these could result in loss
// of information such as constant values attached to such types.
return (t.isPrimitive()) || (syms.stringType.tsym == t.tsym);
}
private Type erasure(Type t, boolean recurse) {
if (t.isPrimitive())
return t; /* fast special case */
else
return erasure.visit(t, recurse);
}
// where
private SimpleVisitor<Type, Boolean> erasure = new SimpleVisitor() {
public Type visitType(Type t, Boolean recurse) {
if (t.isPrimitive())
return t; /*fast special case*/
else
return t.map(recurse ? erasureRecFun : erasureFun);
}
@Override
public Type visitWildcardType(WildcardType t, Boolean recurse) {
return erasure(upperBound(t), recurse);
}
@Override
public Type visitClassType(ClassType t, Boolean recurse) {
Type erased = t.tsym.erasure(Types.this);
if (recurse) {
erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym);
}
return erased;
}
@Override
public Type visitTypeVar(TypeVar t, Boolean recurse) {
return erasure(t.bound, recurse);
}
@Override
public Type visitErrorType(ErrorType t, Boolean recurse) {
return t;
}
@Override
public Type visitAnnotatedType(AnnotatedType t, Boolean recurse) {
Type erased = erasure(t.unannotatedType(), recurse);
if (erased.isAnnotated()) {
// This can only happen when the underlying type is a
// type variable and the upper bound of it is annotated.
// The annotation on the type variable overrides the one
// on the bound.
erased = ((AnnotatedType)erased).unannotatedType();
}
return erased.annotatedType(t.getAnnotationMirrors());
}
};
private Mapping erasureFun = new Mapping ("erasure") {
public Type apply(Type t) { return erasure(t); }
};
private Mapping erasureRecFun = new Mapping ("erasureRecursive") {
public Type apply(Type t) { return erasureRecursive(t); }
};
public List<Type> erasure(List ts) {
return Type.map(ts, erasureFun);
}
public Type erasureRecursive(Type t) {
return erasure(t, true);
}
public List<Type> erasureRecursive(List ts) {
return Type.map(ts, erasureRecFun);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="makeCompoundType">
/**
* Make a compound type from non-empty list of types
*
* @param bounds the types from which the compound type is formed
* @param supertype is objectType if all bounds are interfaces,
* null otherwise.
*/
public Type makeCompoundType(List<Type> bounds) {
return makeCompoundType(bounds, bounds.head.tsym.isInterface());
}
public Type makeCompoundType(List<Type> bounds, boolean allInterfaces) {
Assert.check(bounds.nonEmpty());
Type firstExplicitBound = bounds.head;
if (allInterfaces) {
bounds = bounds.prepend(syms.objectType);
}
ClassSymbol bc =
new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
Type.moreInfo
? names.fromString(bounds.toString())
: names.empty,
null,
syms.noSymbol);
bc.type = new IntersectionClassType(bounds, bc, allInterfaces);
bc.erasure_field = (bounds.head.hasTag(TYPEVAR)) ?
syms.objectType : // error condition, recover
erasure(firstExplicitBound);
bc.members_field = new Scope(bc);
return bc.type;
}
/**
* A convenience wrapper for {@link #makeCompoundType(List)}; the
* arguments are converted to a list and passed to the other
* method. Note that this might cause a symbol completion.
* Hence, this version of makeCompoundType may not be called
* during a classfile read.
*/
public Type makeCompoundType(Type bound1, Type bound2) {
return makeCompoundType(List.of(bound1, bound2));
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="supertype">
public Type supertype(Type t) {
return supertype.visit(t);
}
// where
private UnaryVisitor<Type> supertype = new UnaryVisitor() {
public Type visitType(Type t, Void ignored) {
// A note on wildcards: there is no good way to
// determine a supertype for a super bounded wildcard.
return null;
}
@Override
public Type visitClassType(ClassType t, Void ignored) {
if (t.supertype_field == null) {
Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
// An interface has no superclass; its supertype is Object.
if (t.isInterface())
supertype = ((ClassType)t.tsym.type).supertype_field;
if (t.supertype_field == null) {
List<Type> actuals = classBound(t).allparams();
List<Type> formals = t.tsym.type.allparams();
if (t.hasErasedSupertypes()) {
t.supertype_field = erasureRecursive(supertype);
} else if (formals.nonEmpty()) {
t.supertype_field = subst(supertype, formals, actuals);
}
else {
t.supertype_field = supertype;
}
}
}
return t.supertype_field;
}
/**
* The supertype is always a class type. If the type
* variable's bounds start with a class type, this is also
* the supertype. Otherwise, the supertype is
* java.lang.Object.
*/
@Override
public Type visitTypeVar(TypeVar t, Void ignored) {
if (t.bound.hasTag(TYPEVAR) ||
(!t.bound.isCompound() && !t.bound.isInterface())) {
return t.bound;
} else {
return supertype(t.bound);
}
}
@Override
public Type visitArrayType(ArrayType t, Void ignored) {
if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
return arraySuperType();
else
return new ArrayType(supertype(t.elemtype), t.tsym);
}
@Override
public Type visitErrorType(ErrorType t, Void ignored) {
return Type.noType;
}
};
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="interfaces">
/**
* Return the interfaces implemented by this class.
*/
public List<Type> interfaces(Type t) {
return interfaces.visit(t);
}
// where
private UnaryVisitor<List interfaces = new UnaryVisitor>() {
public List<Type> visitType(Type t, Void ignored) {
return List.nil();
}
@Override
public List<Type> visitClassType(ClassType t, Void ignored) {
if (t.interfaces_field == null) {
List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces();
if (t.interfaces_field == null) {
// If t.interfaces_field is null, then t must
// be a parameterized type (not to be confused
// with a generic type declaration).
// Terminology:
// Parameterized type: List<String>
// Generic type declaration: class List<E> { ... }
// So t corresponds to List<String> and
// t.tsym.type corresponds to List<E>.
// The reason t must be parameterized type is
// that completion will happen as a side
// effect of calling
// ClassSymbol.getInterfaces. Since
// t.interfaces_field is null after
// completion, we can assume that t is not the
// type of a class/interface declaration.
Assert.check(t != t.tsym.type, t);
List<Type> actuals = t.allparams();
List<Type> formals = t.tsym.type.allparams();
if (t.hasErasedSupertypes()) {
t.interfaces_field = erasureRecursive(interfaces);
} else if (formals.nonEmpty()) {
t.interfaces_field =
upperBounds(subst(interfaces, formals, actuals));
}
else {
t.interfaces_field = interfaces;
}
}
}
return t.interfaces_field;
}
@Override
public List<Type> visitTypeVar(TypeVar t, Void ignored) {
if (t.bound.isCompound())
return interfaces(t.bound);
if (t.bound.isInterface())
return List.of(t.bound);
return List.nil();
}
};
public List<Type> directSupertypes(Type t) {
return directSupertypes.visit(t);
}
// where
private final UnaryVisitor<List directSupertypes = new UnaryVisitor>() {
public List<Type> visitType(final Type type, final Void ignored) {
if (!type.isCompound()) {
final Type sup = supertype(type);
return (sup == Type.noType || sup == type || sup == null)
? interfaces(type)
: interfaces(type).prepend(sup);
} else {
return visitIntersectionType((IntersectionClassType) type);
}
}
private List<Type> visitIntersectionType(final IntersectionClassType it) {
return it.getExplicitComponents();
}
};
public boolean isDirectSuperInterface(TypeSymbol isym, TypeSymbol origin) {
for (Type i2 : interfaces(origin.type)) {
if (isym == i2.tsym) return true;
}
return false;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="isDerivedRaw">
Map<Type,Boolean> isDerivedRawCache = new HashMap();
public boolean isDerivedRaw(Type t) {
Boolean result = isDerivedRawCache.get(t);
if (result == null) {
result = isDerivedRawInternal(t);
isDerivedRawCache.put(t, result);
}
return result;
}
public boolean isDerivedRawInternal(Type t) {
if (t.isErroneous())
return false;
return
t.isRaw() ||
supertype(t) != null && isDerivedRaw(supertype(t)) ||
isDerivedRaw(interfaces(t));
}
public boolean isDerivedRaw(List<Type> ts) {
List<Type> l = ts;
while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
return l.nonEmpty();
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="setBounds">
/**
* Set the bounds field of the given type variable to reflect a
* (possibly multiple) list of bounds.
* @param t a type variable
* @param bounds the bounds, must be nonempty
* @param supertype is objectType if all bounds are interfaces,
* null otherwise.
*/
public void setBounds(TypeVar t, List<Type> bounds) {
setBounds(t, bounds, bounds.head.tsym.isInterface());
}
/**
* Same as {@link #setBounds(Type.TypeVar,List,Type)}, except that
* third parameter is computed directly, as follows: if all
* all bounds are interface types, the computed supertype is Object,
* otherwise the supertype is simply left null (in this case, the supertype
* is assumed to be the head of the bound list passed as second argument).
* Note that this check might cause a symbol completion. Hence, this version of
* setBounds may not be called during a classfile read.
*/
public void setBounds(TypeVar t, List<Type> bounds, boolean allInterfaces) {
t.bound = bounds.tail.isEmpty() ?
bounds.head :
makeCompoundType(bounds, allInterfaces);
t.rank_field = -1;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getBounds">
/**
* Return list of bounds of the given type variable.
*/
public List<Type> getBounds(TypeVar t) {
if (t.bound.hasTag(NONE))
return List.nil();
else if (t.bound.isErroneous() || !t.bound.isCompound())
return List.of(t.bound);
else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
return interfaces(t).prepend(supertype(t));
else
// No superclass was given in bounds.
// In this case, supertype is Object, erasure is first interface.
return interfaces(t);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="classBound">
/**
* If the given type is a (possibly selected) type variable,
* return the bounding class of this type, otherwise return the
* type itself.
*/
public Type classBound(Type t) {
return classBound.visit(t);
}
// where
private UnaryVisitor<Type> classBound = new UnaryVisitor() {
public Type visitType(Type t, Void ignored) {
return t;
}
@Override
public Type visitClassType(ClassType t, Void ignored) {
Type outer1 = classBound(t.getEnclosingType());
if (outer1 != t.getEnclosingType())
return new ClassType(outer1, t.getTypeArguments(), t.tsym);
else
return t;
}
@Override
public Type visitTypeVar(TypeVar t, Void ignored) {
return classBound(supertype(t));
}
@Override
public Type visitErrorType(ErrorType t, Void ignored) {
return t;
}
};
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence">
/**
* Returns true iff the first signature is a <em>sub
* signature</em> of the other. This is not an equivalence
* relation.
*
* @jls section 8.4.2.
* @see #overrideEquivalent(Type t, Type s)
* @param t first signature (possibly raw).
* @param s second signature (could be subjected to erasure).
* @return true if t is a sub signature of s.
*/
public boolean isSubSignature(Type t, Type s) {
return isSubSignature(t, s, true);
}
public boolean isSubSignature(Type t, Type s, boolean strict) {
return hasSameArgs(t, s, strict) || hasSameArgs(t, erasure(s), strict);
}
/**
* Returns true iff these signatures are related by <em>override
* equivalence</em>. This is the natural extension of
* isSubSignature to an equivalence relation.
*
* @jls section 8.4.2.
* @see #isSubSignature(Type t, Type s)
* @param t a signature (possible raw, could be subjected to
* erasure).
* @param s a signature (possible raw, could be subjected to
* erasure).
* @return true if either argument is a sub signature of the other.
*/
public boolean overrideEquivalent(Type t, Type s) {
return hasSameArgs(t, s) ||
hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
}
public boolean overridesObjectMethod(TypeSymbol origin, Symbol msym) {
for (Scope.Entry e = syms.objectType.tsym.members().lookup(msym.name) ; e.scope != null ; e = e.next()) {
if (msym.overrides(e.sym, origin, Types.this, true)) {
return true;
}
}
return false;
}
// <editor-fold defaultstate="collapsed" desc="Determining method implementation in given site">
class ImplementationCache {
private WeakHashMap<MethodSymbol, SoftReference
Other Java examples (source code examples)
Here is a short list of links related to this Java Types.java source code file:
|