Types.java revision 3031:286fc9270404
1252190Srpaulo/* 2252190Srpaulo * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. 3252190Srpaulo * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4252190Srpaulo * 5252190Srpaulo * This code is free software; you can redistribute it and/or modify it 6252190Srpaulo * under the terms of the GNU General Public License version 2 only, as 7252190Srpaulo * published by the Free Software Foundation. Oracle designates this 8252190Srpaulo * particular file as subject to the "Classpath" exception as provided 9252190Srpaulo * by Oracle in the LICENSE file that accompanied this code. 10252190Srpaulo * 11252190Srpaulo * This code is distributed in the hope that it will be useful, but WITHOUT 12346981Scy * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13252190Srpaulo * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14346981Scy * version 2 for more details (a copy is included in the LICENSE file that 15289549Srpaulo * accompanied this code). 16346981Scy * 17252190Srpaulo * You should have received a copy of the GNU General Public License version 18252190Srpaulo * 2 along with this work; if not, write to the Free Software Foundation, 19252190Srpaulo * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20252190Srpaulo * 21252190Srpaulo * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22252190Srpaulo * or visit www.oracle.com if you need additional information or have any 23281806Srpaulo * questions. 24281806Srpaulo */ 25252190Srpaulo 26252190Srpaulopackage com.sun.tools.javac.code; 27252190Srpaulo 28252190Srpauloimport java.lang.ref.SoftReference; 29252190Srpauloimport java.util.HashSet; 30252190Srpauloimport java.util.HashMap; 31252190Srpauloimport java.util.Locale; 32289549Srpauloimport java.util.Map; 33351611Scyimport java.util.Set; 34252190Srpauloimport java.util.WeakHashMap; 35346981Scyimport java.util.function.BiPredicate; 36346981Scyimport java.util.stream.Collector; 37252190Srpaulo 38252190Srpauloimport javax.tools.JavaFileObject; 39252190Srpaulo 40252190Srpauloimport com.sun.tools.javac.code.Attribute.RetentionPolicy; 41252190Srpauloimport com.sun.tools.javac.code.Lint.LintCategory; 42252190Srpauloimport com.sun.tools.javac.code.Type.UndetVar.InferenceBound; 43252190Srpauloimport com.sun.tools.javac.code.TypeMetadata.Entry.Kind; 44252190Srpauloimport com.sun.tools.javac.comp.AttrContext; 45346981Scyimport com.sun.tools.javac.comp.Check; 46346981Scyimport com.sun.tools.javac.comp.Enter; 47346981Scyimport com.sun.tools.javac.comp.Env; 48346981Scyimport com.sun.tools.javac.util.*; 49346981Scy 50346981Scyimport static com.sun.tools.javac.code.BoundKind.*; 51252190Srpauloimport static com.sun.tools.javac.code.Flags.*; 52252190Srpauloimport static com.sun.tools.javac.code.Kinds.Kind.*; 53252190Srpauloimport static com.sun.tools.javac.code.Scope.*; 54281806Srpauloimport static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE; 55252190Srpauloimport static com.sun.tools.javac.code.Symbol.*; 56252190Srpauloimport static com.sun.tools.javac.code.Type.*; 57252190Srpauloimport static com.sun.tools.javac.code.TypeTag.*; 58351611Scyimport static com.sun.tools.javac.jvm.ClassFile.externalize; 59351611Scy 60351611Scy/** 61252190Srpaulo * Utility class containing various operations on types. 62252190Srpaulo * 63252190Srpaulo * <p>Unless other names are more illustrative, the following naming 64252190Srpaulo * conventions should be observed in this file: 65252190Srpaulo * 66252190Srpaulo * <dl> 67252190Srpaulo * <dt>t</dt> 68252190Srpaulo * <dd>If the first argument to an operation is a type, it should be named t.</dd> 69252190Srpaulo * <dt>s</dt> 70252190Srpaulo * <dd>Similarly, if the second argument to an operation is a type, it should be named s.</dd> 71281806Srpaulo * <dt>ts</dt> 72281806Srpaulo * <dd>If an operations takes a list of types, the first should be named ts.</dd> 73252190Srpaulo * <dt>ss</dt> 74252190Srpaulo * <dd>A second list of types should be named ss.</dd> 75252190Srpaulo * </dl> 76252190Srpaulo * 77252190Srpaulo * <p><b>This is NOT part of any supported API. 78252190Srpaulo * If you write code that depends on this, you do so at your own risk. 79252190Srpaulo * This code and its internal interfaces are subject to change or 80252190Srpaulo * deletion without notice.</b> 81252190Srpaulo */ 82252190Srpaulopublic class Types { 83252190Srpaulo protected static final Context.Key<Types> typesKey = new Context.Key<>(); 84252190Srpaulo 85252190Srpaulo final Symtab syms; 86252190Srpaulo final JavacMessages messages; 87252190Srpaulo final Names names; 88252190Srpaulo final boolean allowObjectToPrimitiveCast; 89252190Srpaulo final boolean allowDefaultMethods; 90252190Srpaulo final Check chk; 91252190Srpaulo final Enter enter; 92252190Srpaulo JCDiagnostic.Factory diags; 93252190Srpaulo List<Warner> warnStack = List.nil(); 94252190Srpaulo final Name capturedName; 95252190Srpaulo private final FunctionDescriptorLookupError functionDescriptorLookupError; 96252190Srpaulo 97281806Srpaulo public final Warner noWarnings; 98289549Srpaulo 99351611Scy // <editor-fold defaultstate="collapsed" desc="Instantiating"> 100252190Srpaulo public static Types instance(Context context) { 101289549Srpaulo Types instance = context.get(typesKey); 102252190Srpaulo if (instance == null) 103252190Srpaulo instance = new Types(context); 104252190Srpaulo return instance; 105252190Srpaulo } 106252190Srpaulo 107252190Srpaulo protected Types(Context context) { 108252190Srpaulo context.put(typesKey, this); 109252190Srpaulo syms = Symtab.instance(context); 110252190Srpaulo names = Names.instance(context); 111252190Srpaulo Source source = Source.instance(context); 112252190Srpaulo allowObjectToPrimitiveCast = source.allowObjectToPrimitiveCast(); 113252190Srpaulo allowDefaultMethods = source.allowDefaultMethods(); 114252190Srpaulo chk = Check.instance(context); 115252190Srpaulo enter = Enter.instance(context); 116252190Srpaulo capturedName = names.fromString("<captured wildcard>"); 117252190Srpaulo messages = JavacMessages.instance(context); 118252190Srpaulo diags = JCDiagnostic.Factory.instance(context); 119252190Srpaulo functionDescriptorLookupError = new FunctionDescriptorLookupError(); 120252190Srpaulo noWarnings = new Warner(null); 121252190Srpaulo } 122252190Srpaulo // </editor-fold> 123252190Srpaulo 124252190Srpaulo // <editor-fold defaultstate="collapsed" desc="bounds"> 125252190Srpaulo /** 126252190Srpaulo * Get a wildcard's upper bound, returning non-wildcards unchanged. 127252190Srpaulo * @param t a type argument, either a wildcard or a type 128252190Srpaulo */ 129281806Srpaulo public Type wildUpperBound(Type t) { 130252190Srpaulo if (t.hasTag(WILDCARD)) { 131252190Srpaulo WildcardType w = (WildcardType) t; 132252190Srpaulo if (w.isSuperBound()) 133252190Srpaulo return w.bound == null ? syms.objectType : w.bound.bound; 134252190Srpaulo else 135289549Srpaulo return wildUpperBound(w.type); 136252190Srpaulo } 137351611Scy else return t; 138351611Scy } 139351611Scy 140351611Scy /** 141351611Scy * Get a capture variable's upper bound, returning other types unchanged. 142351611Scy * @param t a type 143351611Scy */ 144351611Scy public Type cvarUpperBound(Type t) { 145351611Scy if (t.hasTag(TYPEVAR)) { 146351611Scy TypeVar v = (TypeVar) t; 147351611Scy return v.isCaptured() ? cvarUpperBound(v.bound) : v; 148351611Scy } 149351611Scy else return t; 150351611Scy } 151351611Scy 152351611Scy /** 153351611Scy * Get a wildcard's lower bound, returning non-wildcards unchanged. 154351611Scy * @param t a type argument, either a wildcard or a type 155351611Scy */ 156351611Scy public Type wildLowerBound(Type t) { 157351611Scy if (t.hasTag(WILDCARD)) { 158351611Scy WildcardType w = (WildcardType) t; 159351611Scy return w.isExtendsBound() ? syms.botType : wildLowerBound(w.type); 160351611Scy } 161252190Srpaulo else return t; 162252190Srpaulo } 163281806Srpaulo 164281806Srpaulo /** 165281806Srpaulo * Get a capture variable's lower bound, returning other types unchanged. 166281806Srpaulo * @param t a type 167281806Srpaulo */ 168252190Srpaulo public Type cvarLowerBound(Type t) { 169252190Srpaulo if (t.hasTag(TYPEVAR) && ((TypeVar) t).isCaptured()) { 170252190Srpaulo return cvarLowerBound(t.getLowerBound()); 171252190Srpaulo } 172351611Scy else return t; 173351611Scy } 174351611Scy 175252190Srpaulo /** 176252190Srpaulo * Recursively skip type-variables until a class/array type is found; capture conversion is then 177252190Srpaulo * (optionally) applied to the resulting type. This is useful for i.e. computing a site that is 178252190Srpaulo * suitable for a method lookup. 179252190Srpaulo */ 180252190Srpaulo public Type skipTypeVars(Type site, boolean capture) { 181252190Srpaulo while (site.hasTag(TYPEVAR)) { 182346981Scy site = site.getUpperBound(); 183346981Scy } 184346981Scy return capture ? capture(site) : site; 185346981Scy } 186346981Scy // </editor-fold> 187346981Scy 188281806Srpaulo // <editor-fold defaultstate="collapsed" desc="isUnbounded"> 189281806Srpaulo /** 190281806Srpaulo * Checks that all the arguments to a class are unbounded 191252190Srpaulo * wildcards or something else that doesn't make any restrictions 192346981Scy * on the arguments. If a class isUnbounded, a raw super- or 193346981Scy * subclass can be cast to it without a warning. 194252190Srpaulo * @param t a type 195252190Srpaulo * @return true iff the given type is unbounded or raw 196281806Srpaulo */ 197281806Srpaulo public boolean isUnbounded(Type t) { 198351611Scy return isUnbounded.visit(t); 199281806Srpaulo } 200252190Srpaulo // where 201252190Srpaulo private final UnaryVisitor<Boolean> isUnbounded = new UnaryVisitor<Boolean>() { 202252190Srpaulo 203252190Srpaulo public Boolean visitType(Type t, Void ignored) { 204252190Srpaulo return true; 205252190Srpaulo } 206252190Srpaulo 207252190Srpaulo @Override 208252190Srpaulo public Boolean visitClassType(ClassType t, Void ignored) { 209252190Srpaulo List<Type> parms = t.tsym.type.allparams(); 210252190Srpaulo List<Type> args = t.allparams(); 211346981Scy while (parms.nonEmpty()) { 212252190Srpaulo WildcardType unb = new WildcardType(syms.objectType, 213252190Srpaulo BoundKind.UNBOUND, 214252190Srpaulo syms.boundClass, 215252190Srpaulo (TypeVar)parms.head); 216252190Srpaulo if (!containsType(args.head, unb)) 217252190Srpaulo return false; 218252190Srpaulo parms = parms.tail; 219252190Srpaulo args = args.tail; 220252190Srpaulo } 221281806Srpaulo return true; 222281806Srpaulo } 223281806Srpaulo }; 224281806Srpaulo // </editor-fold> 225281806Srpaulo 226281806Srpaulo // <editor-fold defaultstate="collapsed" desc="asSub"> 227281806Srpaulo /** 228281806Srpaulo * Return the least specific subtype of t that starts with symbol 229346981Scy * sym. If none exists, return null. The least specific subtype 230281806Srpaulo * is determined as follows: 231281806Srpaulo * 232281806Srpaulo * <p>If there is exactly one parameterized instance of sym that is a 233281806Srpaulo * subtype of t, that parameterized instance is returned.<br> 234281806Srpaulo * Otherwise, if the plain type or raw type `sym' is a subtype of 235281806Srpaulo * type t, the type `sym' itself is returned. Otherwise, null is 236281806Srpaulo * returned. 237281806Srpaulo */ 238281806Srpaulo public Type asSub(Type t, Symbol sym) { 239351611Scy return asSub.visit(t, sym); 240351611Scy } 241351611Scy // where 242351611Scy private final SimpleVisitor<Type,Symbol> asSub = new SimpleVisitor<Type,Symbol>() { 243351611Scy 244351611Scy public Type visitType(Type t, Symbol sym) { 245351611Scy return null; 246351611Scy } 247351611Scy 248351611Scy @Override 249351611Scy public Type visitClassType(ClassType t, Symbol sym) { 250351611Scy if (t.tsym == sym) 251252190Srpaulo return t; 252252190Srpaulo Type base = asSuper(sym.type, t.tsym); 253252190Srpaulo if (base == null) 254252190Srpaulo return null; 255252190Srpaulo ListBuffer<Type> from = new ListBuffer<>(); 256252190Srpaulo ListBuffer<Type> to = new ListBuffer<>(); 257252190Srpaulo try { 258252190Srpaulo adapt(base, t, from, to); 259252190Srpaulo } catch (AdaptFailure ex) { 260252190Srpaulo return null; 261252190Srpaulo } 262252190Srpaulo Type res = subst(sym.type, from.toList(), to.toList()); 263252190Srpaulo if (!isSubtype(res, t)) 264252190Srpaulo return null; 265252190Srpaulo ListBuffer<Type> openVars = new ListBuffer<>(); 266252190Srpaulo for (List<Type> l = sym.type.allparams(); 267252190Srpaulo l.nonEmpty(); l = l.tail) 268252190Srpaulo if (res.contains(l.head) && !t.contains(l.head)) 269252190Srpaulo openVars.append(l.head); 270252190Srpaulo if (openVars.nonEmpty()) { 271252190Srpaulo if (t.isRaw()) { 272252190Srpaulo // The subtype of a raw type is raw 273289549Srpaulo res = erasure(res); 274289549Srpaulo } else { 275289549Srpaulo // Unbound type arguments default to ? 276351611Scy List<Type> opens = openVars.toList(); 277351611Scy ListBuffer<Type> qs = new ListBuffer<>(); 278351611Scy for (List<Type> iter = opens; iter.nonEmpty(); iter = iter.tail) { 279351611Scy qs.append(new WildcardType(syms.objectType, BoundKind.UNBOUND, 280351611Scy syms.boundClass, (TypeVar) iter.head)); 281252190Srpaulo } 282252190Srpaulo res = subst(res, opens, qs.toList()); 283252190Srpaulo } 284252190Srpaulo } 285289549Srpaulo return res; 286346981Scy } 287346981Scy 288346981Scy @Override 289346981Scy public Type visitErrorType(ErrorType t, Symbol sym) { 290289549Srpaulo return t; 291289549Srpaulo } 292289549Srpaulo }; 293289549Srpaulo // </editor-fold> 294289549Srpaulo 295289549Srpaulo // <editor-fold defaultstate="collapsed" desc="isConvertible"> 296289549Srpaulo /** 297289549Srpaulo * Is t a subtype of or convertible via boxing/unboxing 298289549Srpaulo * conversion to s? 299289549Srpaulo */ 300289549Srpaulo public boolean isConvertible(Type t, Type s, Warner warn) { 301289549Srpaulo if (t.hasTag(ERROR)) { 302289549Srpaulo return true; 303289549Srpaulo } 304252190Srpaulo boolean tPrimitive = t.isPrimitive(); 305252190Srpaulo boolean sPrimitive = s.isPrimitive(); 306252190Srpaulo if (tPrimitive == sPrimitive) { 307346981Scy return isSubtypeUnchecked(t, s, warn); 308346981Scy } 309346981Scy return tPrimitive 310346981Scy ? isSubtype(boxedClass(t).type, s) 311346981Scy : isSubtype(unboxedType(t), s); 312346981Scy } 313346981Scy 314346981Scy /** 315346981Scy * Is t a subtype of or convertible via boxing/unboxing 316252190Srpaulo * conversions to s? 317252190Srpaulo */ 318252190Srpaulo public boolean isConvertible(Type t, Type s) { 319252190Srpaulo return isConvertible(t, s, noWarnings); 320252190Srpaulo } 321252190Srpaulo // </editor-fold> 322252190Srpaulo 323252190Srpaulo // <editor-fold defaultstate="collapsed" desc="findSam"> 324252190Srpaulo 325252190Srpaulo /** 326252190Srpaulo * Exception used to report a function descriptor lookup failure. The exception 327346981Scy * wraps a diagnostic that can be used to generate more details error 328281806Srpaulo * messages. 329252190Srpaulo */ 330252190Srpaulo public static class FunctionDescriptorLookupError extends RuntimeException { 331252190Srpaulo private static final long serialVersionUID = 0; 332252190Srpaulo 333252190Srpaulo JCDiagnostic diagnostic; 334252190Srpaulo 335346981Scy FunctionDescriptorLookupError() { 336346981Scy this.diagnostic = null; 337346981Scy } 338346981Scy 339346981Scy FunctionDescriptorLookupError setMessage(JCDiagnostic diag) { 340346981Scy this.diagnostic = diag; 341346981Scy return this; 342346981Scy } 343346981Scy 344346981Scy public JCDiagnostic getDiagnostic() { 345346981Scy return diagnostic; 346346981Scy } 347346981Scy } 348346981Scy 349346981Scy /** 350346981Scy * A cache that keeps track of function descriptors associated with given 351346981Scy * functional interfaces. 352346981Scy */ 353346981Scy class DescriptorCache { 354346981Scy 355346981Scy private WeakHashMap<TypeSymbol, Entry> _map = new WeakHashMap<>(); 356346981Scy 357346981Scy class FunctionDescriptor { 358346981Scy Symbol descSym; 359346981Scy 360346981Scy FunctionDescriptor(Symbol descSym) { 361346981Scy this.descSym = descSym; 362346981Scy } 363346981Scy 364346981Scy public Symbol getSymbol() { 365346981Scy return descSym; 366346981Scy } 367346981Scy 368346981Scy public Type getType(Type site) { 369346981Scy site = removeWildcards(site); 370346981Scy if (!chk.checkValidGenericType(site)) { 371346981Scy //if the inferred functional interface type is not well-formed, 372346981Scy //or if it's not a subtype of the original target, issue an error 373346981Scy throw failure(diags.fragment("no.suitable.functional.intf.inst", site)); 374346981Scy } 375346981Scy return memberType(site, descSym); 376346981Scy } 377346981Scy } 378346981Scy 379346981Scy class Entry { 380346981Scy final FunctionDescriptor cachedDescRes; 381346981Scy final int prevMark; 382346981Scy 383346981Scy public Entry(FunctionDescriptor cachedDescRes, 384346981Scy int prevMark) { 385346981Scy this.cachedDescRes = cachedDescRes; 386346981Scy this.prevMark = prevMark; 387346981Scy } 388346981Scy 389346981Scy boolean matches(int mark) { 390289549Srpaulo return this.prevMark == mark; 391289549Srpaulo } 392289549Srpaulo } 393289549Srpaulo 394289549Srpaulo FunctionDescriptor get(TypeSymbol origin) throws FunctionDescriptorLookupError { 395289549Srpaulo Entry e = _map.get(origin); 396346981Scy CompoundScope members = membersClosure(origin.type, false); 397346981Scy if (e == null || 398346981Scy !e.matches(members.getMark())) { 399346981Scy FunctionDescriptor descRes = findDescriptorInternal(origin, members); 400346981Scy _map.put(origin, new Entry(descRes, members.getMark())); 401346981Scy return descRes; 402346981Scy } 403289549Srpaulo else { 404289549Srpaulo return e.cachedDescRes; 405289549Srpaulo } 406289549Srpaulo } 407289549Srpaulo 408289549Srpaulo /** 409289549Srpaulo * Compute the function descriptor associated with a given functional interface 410289549Srpaulo */ 411289549Srpaulo public FunctionDescriptor findDescriptorInternal(TypeSymbol origin, 412351611Scy CompoundScope membersCache) throws FunctionDescriptorLookupError { 413289549Srpaulo if (!origin.isInterface() || (origin.flags() & ANNOTATION) != 0) { 414289549Srpaulo //t must be an interface 415289549Srpaulo throw failure("not.a.functional.intf", origin); 416289549Srpaulo } 417289549Srpaulo 418289549Srpaulo final ListBuffer<Symbol> abstracts = new ListBuffer<>(); 419289549Srpaulo for (Symbol sym : membersCache.getSymbols(new DescriptorFilter(origin))) { 420289549Srpaulo Type mtype = memberType(origin.type, sym); 421289549Srpaulo if (abstracts.isEmpty() || 422289549Srpaulo (sym.name == abstracts.first().name && 423346981Scy overrideEquivalent(mtype, memberType(origin.type, abstracts.first())))) { 424346981Scy abstracts.append(sym); 425346981Scy } else { 426346981Scy //the target method(s) should be the only abstract members of t 427346981Scy throw failure("not.a.functional.intf.1", origin, 428346981Scy diags.fragment("incompatible.abstracts", Kinds.kindName(origin), origin)); 429346981Scy } 430346981Scy } 431346981Scy if (abstracts.isEmpty()) { 432346981Scy //t must define a suitable non-generic method 433346981Scy throw failure("not.a.functional.intf.1", origin, 434346981Scy diags.fragment("no.abstracts", Kinds.kindName(origin), origin)); 435346981Scy } else if (abstracts.size() == 1) { 436346981Scy return new FunctionDescriptor(abstracts.first()); 437346981Scy } else { // size > 1 438346981Scy FunctionDescriptor descRes = mergeDescriptors(origin, abstracts.toList()); 439346981Scy if (descRes == null) { 440346981Scy //we can get here if the functional interface is ill-formed 441346981Scy ListBuffer<JCDiagnostic> descriptors = new ListBuffer<>(); 442346981Scy for (Symbol desc : abstracts) { 443346981Scy String key = desc.type.getThrownTypes().nonEmpty() ? 444346981Scy "descriptor.throws" : "descriptor"; 445346981Scy descriptors.append(diags.fragment(key, desc.name, 446346981Scy desc.type.getParameterTypes(), 447346981Scy desc.type.getReturnType(), 448346981Scy desc.type.getThrownTypes())); 449346981Scy } 450346981Scy JCDiagnostic.MultilineDiagnostic incompatibleDescriptors = 451346981Scy new JCDiagnostic.MultilineDiagnostic(diags.fragment("incompatible.descs.in.functional.intf", 452346981Scy Kinds.kindName(origin), origin), descriptors.toList()); 453346981Scy throw failure(incompatibleDescriptors); 454346981Scy } 455346981Scy return descRes; 456346981Scy } 457346981Scy } 458346981Scy 459346981Scy /** 460346981Scy * Compute a synthetic type for the target descriptor given a list 461346981Scy * of override-equivalent methods in the functional interface type. 462346981Scy * The resulting method type is a method type that is override-equivalent 463346981Scy * and return-type substitutable with each method in the original list. 464346981Scy */ 465346981Scy private FunctionDescriptor mergeDescriptors(TypeSymbol origin, List<Symbol> methodSyms) { 466346981Scy //pick argument types - simply take the signature that is a 467346981Scy //subsignature of all other signatures in the list (as per JLS 8.4.2) 468346981Scy List<Symbol> mostSpecific = List.nil(); 469346981Scy outer: for (Symbol msym1 : methodSyms) { 470346981Scy Type mt1 = memberType(origin.type, msym1); 471346981Scy for (Symbol msym2 : methodSyms) { 472346981Scy Type mt2 = memberType(origin.type, msym2); 473346981Scy if (!isSubSignature(mt1, mt2)) { 474346981Scy continue outer; 475346981Scy } 476346981Scy } 477346981Scy mostSpecific = mostSpecific.prepend(msym1); 478346981Scy } 479346981Scy if (mostSpecific.isEmpty()) { 480346981Scy return null; 481346981Scy } 482346981Scy 483346981Scy 484346981Scy //pick return types - this is done in two phases: (i) first, the most 485346981Scy //specific return type is chosen using strict subtyping; if this fails, 486346981Scy //a second attempt is made using return type substitutability (see JLS 8.4.5) 487346981Scy boolean phase2 = false; 488346981Scy Symbol bestSoFar = null; 489346981Scy while (bestSoFar == null) { 490346981Scy outer: for (Symbol msym1 : mostSpecific) { 491346981Scy Type mt1 = memberType(origin.type, msym1); 492346981Scy for (Symbol msym2 : methodSyms) { 493346981Scy Type mt2 = memberType(origin.type, msym2); 494346981Scy if (phase2 ? 495346981Scy !returnTypeSubstitutable(mt1, mt2) : 496346981Scy !isSubtypeInternal(mt1.getReturnType(), mt2.getReturnType())) { 497346981Scy continue outer; 498346981Scy } 499346981Scy } 500346981Scy bestSoFar = msym1; 501346981Scy } 502346981Scy if (phase2) { 503346981Scy break; 504346981Scy } else { 505346981Scy phase2 = true; 506346981Scy } 507346981Scy } 508346981Scy if (bestSoFar == null) return null; 509346981Scy 510346981Scy //merge thrown types - form the intersection of all the thrown types in 511346981Scy //all the signatures in the list 512346981Scy boolean toErase = !bestSoFar.type.hasTag(FORALL); 513346981Scy List<Type> thrown = null; 514346981Scy Type mt1 = memberType(origin.type, bestSoFar); 515346981Scy for (Symbol msym2 : methodSyms) { 516346981Scy Type mt2 = memberType(origin.type, msym2); 517346981Scy List<Type> thrown_mt2 = mt2.getThrownTypes(); 518346981Scy if (toErase) { 519346981Scy thrown_mt2 = erasure(thrown_mt2); 520346981Scy } else { 521346981Scy /* If bestSoFar is generic then all the methods are generic. 522346981Scy * The opposite is not true: a non generic method can override 523346981Scy * a generic method (raw override) so it's safe to cast mt1 and 524346981Scy * mt2 to ForAll. 525346981Scy */ 526346981Scy ForAll fa1 = (ForAll)mt1; 527346981Scy ForAll fa2 = (ForAll)mt2; 528346981Scy thrown_mt2 = subst(thrown_mt2, fa2.tvars, fa1.tvars); 529346981Scy } 530346981Scy thrown = (thrown == null) ? 531346981Scy thrown_mt2 : 532346981Scy chk.intersect(thrown_mt2, thrown); 533346981Scy } 534346981Scy 535346981Scy final List<Type> thrown1 = thrown; 536346981Scy return new FunctionDescriptor(bestSoFar) { 537346981Scy @Override 538346981Scy public Type getType(Type origin) { 539346981Scy Type mt = memberType(origin, getSymbol()); 540346981Scy return createMethodTypeWithThrown(mt, thrown1); 541346981Scy } 542346981Scy }; 543346981Scy } 544346981Scy 545346981Scy boolean isSubtypeInternal(Type s, Type t) { 546346981Scy return (s.isPrimitive() && t.isPrimitive()) ? 547289549Srpaulo isSameType(t, s) : 548289549Srpaulo isSubtype(s, t); 549346981Scy } 550346981Scy 551346981Scy FunctionDescriptorLookupError failure(String msg, Object... args) { 552346981Scy return failure(diags.fragment(msg, args)); 553346981Scy } 554346981Scy 555346981Scy FunctionDescriptorLookupError failure(JCDiagnostic diag) { 556289549Srpaulo return functionDescriptorLookupError.setMessage(diag); 557289549Srpaulo } 558252190Srpaulo } 559289549Srpaulo 560289549Srpaulo private DescriptorCache descCache = new DescriptorCache(); 561289549Srpaulo 562289549Srpaulo /** 563346981Scy * Find the method descriptor associated to this class symbol - if the 564351611Scy * symbol 'origin' is not a functional interface, an exception is thrown. 565351611Scy */ 566289549Srpaulo public Symbol findDescriptorSymbol(TypeSymbol origin) throws FunctionDescriptorLookupError { 567252190Srpaulo return descCache.get(origin).getSymbol(); 568252190Srpaulo } 569252190Srpaulo 570252190Srpaulo /** 571252190Srpaulo * Find the type of the method descriptor associated to this class symbol - 572252190Srpaulo * if the symbol 'origin' is not a functional interface, an exception is thrown. 573346981Scy */ 574252190Srpaulo public Type findDescriptorType(Type origin) throws FunctionDescriptorLookupError { 575346981Scy return descCache.get(origin.tsym).getType(origin); 576346981Scy } 577346981Scy 578346981Scy /** 579346981Scy * Is given type a functional interface? 580346981Scy */ 581252190Srpaulo public boolean isFunctionalInterface(TypeSymbol tsym) { 582252190Srpaulo try { 583252190Srpaulo findDescriptorSymbol(tsym); 584252190Srpaulo return true; 585346981Scy } catch (FunctionDescriptorLookupError ex) { 586346981Scy return false; 587252190Srpaulo } 588252190Srpaulo } 589346981Scy 590346981Scy public boolean isFunctionalInterface(Type site) { 591252190Srpaulo try { 592252190Srpaulo findDescriptorType(site); 593252190Srpaulo return true; 594252190Srpaulo } catch (FunctionDescriptorLookupError ex) { 595252190Srpaulo return false; 596252190Srpaulo } 597346981Scy } 598252190Srpaulo 599252190Srpaulo public Type removeWildcards(Type site) { 600252190Srpaulo Type capturedSite = capture(site); 601252190Srpaulo if (capturedSite != site) { 602252190Srpaulo Type formalInterface = site.tsym.type; 603346981Scy ListBuffer<Type> typeargs = new ListBuffer<>(); 604346981Scy List<Type> actualTypeargs = site.getTypeArguments(); 605346981Scy List<Type> capturedTypeargs = capturedSite.getTypeArguments(); 606252190Srpaulo //simply replace the wildcards with its bound 607252190Srpaulo for (Type t : formalInterface.getTypeArguments()) { 608252190Srpaulo if (actualTypeargs.head.hasTag(WILDCARD)) { 609252190Srpaulo WildcardType wt = (WildcardType)actualTypeargs.head; 610252190Srpaulo Type bound; 611252190Srpaulo switch (wt.kind) { 612346981Scy case EXTENDS: 613346981Scy case UNBOUND: 614252190Srpaulo CapturedType capVar = (CapturedType)capturedTypeargs.head; 615252190Srpaulo //use declared bound if it doesn't depend on formal type-args 616252190Srpaulo bound = capVar.bound.containsAny(capturedSite.getTypeArguments()) ? 617252190Srpaulo wt.type : capVar.bound; 618346981Scy break; 619346981Scy default: 620346981Scy bound = wt.type; 621346981Scy } 622346981Scy typeargs.append(bound); 623346981Scy } else { 624252190Srpaulo typeargs.append(actualTypeargs.head); 625252190Srpaulo } 626252190Srpaulo actualTypeargs = actualTypeargs.tail; 627346981Scy capturedTypeargs = capturedTypeargs.tail; 628346981Scy } 629346981Scy return subst(formalInterface, formalInterface.getTypeArguments(), typeargs.toList()); 630346981Scy } else { 631346981Scy return site; 632346981Scy } 633252190Srpaulo } 634252190Srpaulo 635252190Srpaulo /** 636252190Srpaulo * Create a symbol for a class that implements a given functional interface 637252190Srpaulo * and overrides its functional descriptor. This routine is used for two 638252190Srpaulo * main purposes: (i) checking well-formedness of a functional interface; 639346981Scy * (ii) perform functional interface bridge calculation. 640252190Srpaulo */ 641252190Srpaulo public ClassSymbol makeFunctionalInterfaceClass(Env<AttrContext> env, Name name, List<Type> targets, long cflags) { 642252190Srpaulo if (targets.isEmpty()) { 643252190Srpaulo return null; 644346981Scy } 645252190Srpaulo Symbol descSym = findDescriptorSymbol(targets.head.tsym); 646252190Srpaulo Type descType = findDescriptorType(targets.head); 647252190Srpaulo ClassSymbol csym = new ClassSymbol(cflags, name, env.enclClass.sym.outermostClass()); 648252190Srpaulo csym.completer = Completer.NULL_COMPLETER; 649252190Srpaulo csym.members_field = WriteableScope.create(csym); 650346981Scy MethodSymbol instDescSym = new MethodSymbol(descSym.flags(), descSym.name, descType, csym); 651252190Srpaulo csym.members_field.enter(instDescSym); 652252190Srpaulo Type.ClassType ctype = new Type.ClassType(Type.noType, List.<Type>nil(), csym); 653252190Srpaulo ctype.supertype_field = syms.objectType; 654252190Srpaulo ctype.interfaces_field = targets; 655252190Srpaulo csym.type = ctype; 656252190Srpaulo csym.sourcefile = ((ClassSymbol)csym.owner).sourcefile; 657346981Scy return csym; 658346981Scy } 659252190Srpaulo 660346981Scy /** 661346981Scy * Find the minimal set of methods that are overridden by the functional 662346981Scy * descriptor in 'origin'. All returned methods are assumed to have different 663252190Srpaulo * erased signatures. 664252190Srpaulo */ 665252190Srpaulo public List<Symbol> functionalInterfaceBridges(TypeSymbol origin) { 666252190Srpaulo Assert.check(isFunctionalInterface(origin)); 667252190Srpaulo Symbol descSym = findDescriptorSymbol(origin); 668252190Srpaulo CompoundScope members = membersClosure(origin.type, false); 669346981Scy ListBuffer<Symbol> overridden = new ListBuffer<>(); 670346981Scy outer: for (Symbol m2 : members.getSymbolsByName(descSym.name, bridgeFilter)) { 671346981Scy if (m2 == descSym) continue; 672346981Scy else if (descSym.overrides(m2, origin, Types.this, false)) { 673252190Srpaulo for (Symbol m3 : overridden) { 674346981Scy if (isSameType(m3.erasure(Types.this), m2.erasure(Types.this)) || 675252190Srpaulo (m3.overrides(m2, origin, Types.this, false) && 676252190Srpaulo (pendingBridges((ClassSymbol)origin, m3.enclClass()) || 677346981Scy (((MethodSymbol)m2).binaryImplementation((ClassSymbol)m3.owner, Types.this) != null)))) { 678346981Scy continue outer; 679252190Srpaulo } 680252190Srpaulo } 681252190Srpaulo overridden.add(m2); 682252190Srpaulo } 683252190Srpaulo } 684252190Srpaulo return overridden.toList(); 685252190Srpaulo } 686252190Srpaulo //where 687252190Srpaulo private Filter<Symbol> bridgeFilter = new Filter<Symbol>() { 688252190Srpaulo public boolean accepts(Symbol t) { 689252190Srpaulo return t.kind == MTH && 690252190Srpaulo t.name != names.init && 691252190Srpaulo t.name != names.clinit && 692346981Scy (t.flags() & SYNTHETIC) == 0; 693252190Srpaulo } 694252190Srpaulo }; 695252190Srpaulo private boolean pendingBridges(ClassSymbol origin, TypeSymbol s) { 696346981Scy //a symbol will be completed from a classfile if (a) symbol has 697252190Srpaulo //an associated file object with CLASS kind and (b) the symbol has 698289549Srpaulo //not been entered 699289549Srpaulo if (origin.classfile != null && 700289549Srpaulo origin.classfile.getKind() == JavaFileObject.Kind.CLASS && 701289549Srpaulo enter.getEnv(origin) == null) { 702289549Srpaulo return false; 703289549Srpaulo } 704289549Srpaulo if (origin == s) { 705289549Srpaulo return true; 706289549Srpaulo } 707289549Srpaulo for (Type t : interfaces(origin.type)) { 708289549Srpaulo if (pendingBridges((ClassSymbol)t.tsym, s)) { 709289549Srpaulo return true; 710346981Scy } 711346981Scy } 712346981Scy return false; 713252190Srpaulo } 714252190Srpaulo // </editor-fold> 715252190Srpaulo 716252190Srpaulo /** 717252190Srpaulo * Scope filter used to skip methods that should be ignored (such as methods 718252190Srpaulo * overridden by j.l.Object) during function interface conversion interface check 719252190Srpaulo */ 720252190Srpaulo class DescriptorFilter implements Filter<Symbol> { 721252190Srpaulo 722252190Srpaulo TypeSymbol origin; 723252190Srpaulo 724252190Srpaulo DescriptorFilter(TypeSymbol origin) { 725346981Scy this.origin = origin; 726346981Scy } 727346981Scy 728252190Srpaulo @Override 729252190Srpaulo public boolean accepts(Symbol sym) { 730252190Srpaulo return sym.kind == MTH && 731252190Srpaulo (sym.flags() & (ABSTRACT | DEFAULT)) == ABSTRACT && 732252190Srpaulo !overridesObjectMethod(origin, sym) && 733252190Srpaulo (interfaceCandidates(origin.type, (MethodSymbol)sym).head.flags() & DEFAULT) == 0; 734252190Srpaulo } 735252190Srpaulo } 736252190Srpaulo 737252190Srpaulo // <editor-fold defaultstate="collapsed" desc="isSubtype"> 738252190Srpaulo /** 739252190Srpaulo * Is t an unchecked subtype of s? 740252190Srpaulo */ 741252190Srpaulo public boolean isSubtypeUnchecked(Type t, Type s) { 742252190Srpaulo return isSubtypeUnchecked(t, s, noWarnings); 743252190Srpaulo } 744252190Srpaulo /** 745346981Scy * Is t an unchecked subtype of s? 746346981Scy */ 747252190Srpaulo public boolean isSubtypeUnchecked(Type t, Type s, Warner warn) { 748252190Srpaulo boolean result = isSubtypeUncheckedInternal(t, s, warn); 749346981Scy if (result) { 750346981Scy checkUnsafeVarargsConversion(t, s, warn); 751252190Srpaulo } 752252190Srpaulo return result; 753252190Srpaulo } 754252190Srpaulo //where 755346981Scy private boolean isSubtypeUncheckedInternal(Type t, Type s, Warner warn) { 756252190Srpaulo if (t.hasTag(ARRAY) && s.hasTag(ARRAY)) { 757252190Srpaulo if (((ArrayType)t).elemtype.isPrimitive()) { 758346981Scy return isSameType(elemtype(t), elemtype(s)); 759346981Scy } else { 760252190Srpaulo return isSubtypeUnchecked(elemtype(t), elemtype(s), warn); 761252190Srpaulo } 762346981Scy } else if (isSubtype(t, s)) { 763346981Scy return true; 764252190Srpaulo } else if (t.hasTag(TYPEVAR)) { 765252190Srpaulo return isSubtypeUnchecked(t.getUpperBound(), s, warn); 766252190Srpaulo } else if (!s.isRaw()) { 767252190Srpaulo Type t2 = asSuper(t, s.tsym); 768346981Scy if (t2 != null && t2.isRaw()) { 769252190Srpaulo if (isReifiable(s)) { 770252190Srpaulo warn.silentWarn(LintCategory.UNCHECKED); 771346981Scy } else { 772346981Scy warn.warn(LintCategory.UNCHECKED); 773252190Srpaulo } 774252190Srpaulo return true; 775252190Srpaulo } 776252190Srpaulo } 777252190Srpaulo return false; 778252190Srpaulo } 779346981Scy 780252190Srpaulo private void checkUnsafeVarargsConversion(Type t, Type s, Warner warn) { 781252190Srpaulo if (!t.hasTag(ARRAY) || isReifiable(t)) { 782281806Srpaulo return; 783252190Srpaulo } 784252190Srpaulo ArrayType from = (ArrayType)t; 785252190Srpaulo boolean shouldWarn = false; 786252190Srpaulo switch (s.getTag()) { 787252190Srpaulo case ARRAY: 788252190Srpaulo ArrayType to = (ArrayType)s; 789252190Srpaulo shouldWarn = from.isVarargs() && 790252190Srpaulo !to.isVarargs() && 791252190Srpaulo !isReifiable(from); 792252190Srpaulo break; 793252190Srpaulo case CLASS: 794252190Srpaulo shouldWarn = from.isVarargs(); 795252190Srpaulo break; 796252190Srpaulo } 797252190Srpaulo if (shouldWarn) { 798252190Srpaulo warn.warn(LintCategory.VARARGS); 799346981Scy } 800346981Scy } 801252190Srpaulo 802252190Srpaulo /** 803346981Scy * Is t a subtype of s?<br> 804346981Scy * (not defined for Method and ForAll types) 805252190Srpaulo */ 806252190Srpaulo final public boolean isSubtype(Type t, Type s) { 807252190Srpaulo return isSubtype(t, s, true); 808252190Srpaulo } 809346981Scy final public boolean isSubtypeNoCapture(Type t, Type s) { 810252190Srpaulo return isSubtype(t, s, false); 811252190Srpaulo } 812346981Scy public boolean isSubtype(Type t, Type s, boolean capture) { 813346981Scy if (t.equalsIgnoreMetadata(s)) 814252190Srpaulo return true; 815252190Srpaulo if (s.isPartial()) 816346981Scy return isSuperType(s, t); 817346981Scy 818252190Srpaulo if (s.isCompound()) { 819252190Srpaulo for (Type s2 : interfaces(s).prepend(supertype(s))) { 820252190Srpaulo if (!isSubtype(t, s2, capture)) 821252190Srpaulo return false; 822346981Scy } 823252190Srpaulo return true; 824252190Srpaulo } 825346981Scy 826346981Scy // Generally, if 's' is a lower-bounded type variable, recur on lower bound; but 827252190Srpaulo // for inference variables and intersections, we need to keep 's' 828252190Srpaulo // (see JLS 4.10.2 for intersections and 18.2.3 for inference vars) 829252190Srpaulo if (!t.hasTag(UNDETVAR) && !t.isCompound()) { 830252190Srpaulo // TODO: JDK-8039198, bounds checking sometimes passes in a wildcard as s 831252190Srpaulo Type lower = cvarLowerBound(wildLowerBound(s)); 832252190Srpaulo if (s != lower && !lower.hasTag(BOT)) 833346981Scy return isSubtype(capture ? capture(t) : t, lower, false); 834252190Srpaulo } 835346981Scy 836252190Srpaulo return isSubtype.visit(capture ? capture(t) : t, s); 837281806Srpaulo } 838252190Srpaulo // where 839252190Srpaulo private TypeRelation isSubtype = new TypeRelation() 840252190Srpaulo { 841252190Srpaulo @Override 842252190Srpaulo public Boolean visitType(Type t, Type s) { 843252190Srpaulo switch (t.getTag()) { 844252190Srpaulo case BYTE: 845252190Srpaulo return (!s.hasTag(CHAR) && t.getTag().isSubRangeOf(s.getTag())); 846252190Srpaulo case CHAR: 847252190Srpaulo return (!s.hasTag(SHORT) && t.getTag().isSubRangeOf(s.getTag())); 848252190Srpaulo case SHORT: case INT: case LONG: 849252190Srpaulo case FLOAT: case DOUBLE: 850346981Scy return t.getTag().isSubRangeOf(s.getTag()); 851252190Srpaulo case BOOLEAN: case VOID: 852281806Srpaulo return t.hasTag(s.getTag()); 853252190Srpaulo case TYPEVAR: 854252190Srpaulo return isSubtypeNoCapture(t.getUpperBound(), s); 855252190Srpaulo case BOT: 856281806Srpaulo return 857252190Srpaulo s.hasTag(BOT) || s.hasTag(CLASS) || 858346981Scy s.hasTag(ARRAY) || s.hasTag(TYPEVAR); 859346981Scy case WILDCARD: //we shouldn't be here - avoids crash (see 7034495) 860346981Scy case NONE: 861346981Scy return false; 862252190Srpaulo default: 863252190Srpaulo throw new AssertionError("isSubtype " + t.getTag()); 864252190Srpaulo } 865252190Srpaulo } 866252190Srpaulo 867252190Srpaulo private Set<TypePair> cache = new HashSet<>(); 868252190Srpaulo 869252190Srpaulo private boolean containsTypeRecursive(Type t, Type s) { 870252190Srpaulo TypePair pair = new TypePair(t, s); 871252190Srpaulo if (cache.add(pair)) { 872252190Srpaulo try { 873252190Srpaulo return containsType(t.getTypeArguments(), 874252190Srpaulo s.getTypeArguments()); 875252190Srpaulo } finally { 876252190Srpaulo cache.remove(pair); 877252190Srpaulo } 878252190Srpaulo } else { 879252190Srpaulo return containsType(t.getTypeArguments(), 880252190Srpaulo rewriteSupers(s).getTypeArguments()); 881252190Srpaulo } 882252190Srpaulo } 883252190Srpaulo 884252190Srpaulo private Type rewriteSupers(Type t) { 885252190Srpaulo if (!t.isParameterized()) 886252190Srpaulo return t; 887252190Srpaulo ListBuffer<Type> from = new ListBuffer<>(); 888252190Srpaulo ListBuffer<Type> to = new ListBuffer<>(); 889252190Srpaulo adaptSelf(t, from, to); 890252190Srpaulo if (from.isEmpty()) 891252190Srpaulo return t; 892252190Srpaulo ListBuffer<Type> rewrite = new ListBuffer<>(); 893252190Srpaulo boolean changed = false; 894252190Srpaulo for (Type orig : to.toList()) { 895252190Srpaulo Type s = rewriteSupers(orig); 896252190Srpaulo if (s.isSuperBound() && !s.isExtendsBound()) { 897252190Srpaulo s = new WildcardType(syms.objectType, 898252190Srpaulo BoundKind.UNBOUND, 899252190Srpaulo syms.boundClass, 900252190Srpaulo s.getMetadata()); 901252190Srpaulo changed = true; 902252190Srpaulo } else if (s != orig) { 903252190Srpaulo s = new WildcardType(wildUpperBound(s), 904252190Srpaulo BoundKind.EXTENDS, 905252190Srpaulo syms.boundClass, 906252190Srpaulo s.getMetadata()); 907252190Srpaulo changed = true; 908252190Srpaulo } 909252190Srpaulo rewrite.append(s); 910252190Srpaulo } 911252190Srpaulo if (changed) 912252190Srpaulo return subst(t.tsym.type, from.toList(), rewrite.toList()); 913252190Srpaulo else 914252190Srpaulo return t; 915252190Srpaulo } 916252190Srpaulo 917252190Srpaulo @Override 918252190Srpaulo public Boolean visitClassType(ClassType t, Type s) { 919252190Srpaulo Type sup = asSuper(t, s.tsym); 920252190Srpaulo if (sup == null) return false; 921252190Srpaulo // If t is an intersection, sup might not be a class type 922252190Srpaulo if (!sup.hasTag(CLASS)) return isSubtypeNoCapture(sup, s); 923252190Srpaulo return sup.tsym == s.tsym 924252190Srpaulo // Check type variable containment 925252190Srpaulo && (!s.isParameterized() || containsTypeRecursive(s, sup)) 926252190Srpaulo && isSubtypeNoCapture(sup.getEnclosingType(), 927252190Srpaulo s.getEnclosingType()); 928252190Srpaulo } 929252190Srpaulo 930252190Srpaulo @Override 931252190Srpaulo public Boolean visitArrayType(ArrayType t, Type s) { 932252190Srpaulo if (s.hasTag(ARRAY)) { 933252190Srpaulo if (t.elemtype.isPrimitive()) 934252190Srpaulo return isSameType(t.elemtype, elemtype(s)); 935252190Srpaulo else 936252190Srpaulo return isSubtypeNoCapture(t.elemtype, elemtype(s)); 937281806Srpaulo } 938281806Srpaulo 939281806Srpaulo if (s.hasTag(CLASS)) { 940281806Srpaulo Name sname = s.tsym.getQualifiedName(); 941281806Srpaulo return sname == names.java_lang_Object 942252190Srpaulo || sname == names.java_lang_Cloneable 943252190Srpaulo || sname == names.java_io_Serializable; 944252190Srpaulo } 945252190Srpaulo 946252190Srpaulo return false; 947252190Srpaulo } 948252190Srpaulo 949252190Srpaulo @Override 950252190Srpaulo public Boolean visitUndetVar(UndetVar t, Type s) { 951289549Srpaulo //todo: test against origin needed? or replace with substitution? 952289549Srpaulo if (t == s || t.qtype == s || s.hasTag(ERROR) || s.hasTag(UNKNOWN)) { 953289549Srpaulo return true; 954289549Srpaulo } else if (s.hasTag(BOT)) { 955289549Srpaulo //if 's' is 'null' there's no instantiated type U for which 956289549Srpaulo //U <: s (but 'null' itself, which is not a valid type) 957252190Srpaulo return false; 958252190Srpaulo } 959252190Srpaulo 960281806Srpaulo t.addBound(InferenceBound.UPPER, s, Types.this); 961281806Srpaulo return true; 962289549Srpaulo } 963289549Srpaulo 964289549Srpaulo @Override 965289549Srpaulo public Boolean visitErrorType(ErrorType t, Type s) { 966289549Srpaulo return true; 967289549Srpaulo } 968252190Srpaulo }; 969252190Srpaulo 970252190Srpaulo /** 971252190Srpaulo * Is t a subtype of every type in given list `ts'?<br> 972252190Srpaulo * (not defined for Method and ForAll types)<br> 973252190Srpaulo * Allows unchecked conversions. 974289549Srpaulo */ 975252190Srpaulo public boolean isSubtypeUnchecked(Type t, List<Type> ts, Warner warn) { 976252190Srpaulo for (List<Type> l = ts; l.nonEmpty(); l = l.tail) 977252190Srpaulo if (!isSubtypeUnchecked(t, l.head, warn)) 978252190Srpaulo return false; 979252190Srpaulo return true; 980252190Srpaulo } 981337817Scy 982346981Scy /** 983346981Scy * Are corresponding elements of ts subtypes of ss? If lists are 984346981Scy * of different length, return false. 985346981Scy */ 986346981Scy public boolean isSubtypes(List<Type> ts, List<Type> ss) { 987346981Scy while (ts.tail != null && ss.tail != null 988346981Scy /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ && 989252190Srpaulo isSubtype(ts.head, ss.head)) { 990252190Srpaulo ts = ts.tail; 991252190Srpaulo ss = ss.tail; 992252190Srpaulo } 993252190Srpaulo return ts.tail == null && ss.tail == null; 994252190Srpaulo /*inlined: ts.isEmpty() && ss.isEmpty();*/ 995252190Srpaulo } 996281806Srpaulo 997252190Srpaulo /** 998252190Srpaulo * Are corresponding elements of ts subtypes of ss, allowing 999252190Srpaulo * unchecked conversions? If lists are of different length, 1000252190Srpaulo * return false. 1001337817Scy **/ 1002337817Scy public boolean isSubtypesUnchecked(List<Type> ts, List<Type> ss, Warner warn) { 1003252190Srpaulo while (ts.tail != null && ss.tail != null 1004252190Srpaulo /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ && 1005252190Srpaulo isSubtypeUnchecked(ts.head, ss.head, warn)) { 1006252190Srpaulo ts = ts.tail; 1007252190Srpaulo ss = ss.tail; 1008252190Srpaulo } 1009252190Srpaulo return ts.tail == null && ss.tail == null; 1010252190Srpaulo /*inlined: ts.isEmpty() && ss.isEmpty();*/ 1011252190Srpaulo } 1012252190Srpaulo // </editor-fold> 1013252190Srpaulo 1014252190Srpaulo // <editor-fold defaultstate="collapsed" desc="isSuperType"> 1015346981Scy /** 1016252190Srpaulo * Is t a supertype of s? 1017252190Srpaulo */ 1018252190Srpaulo public boolean isSuperType(Type t, Type s) { 1019252190Srpaulo switch (t.getTag()) { 1020252190Srpaulo case ERROR: 1021252190Srpaulo return true; 1022252190Srpaulo case UNDETVAR: { 1023252190Srpaulo UndetVar undet = (UndetVar)t; 1024252190Srpaulo if (t == s || 1025252190Srpaulo undet.qtype == s || 1026252190Srpaulo s.hasTag(ERROR) || 1027252190Srpaulo s.hasTag(BOT)) { 1028252190Srpaulo return true; 1029252190Srpaulo } 1030252190Srpaulo undet.addBound(InferenceBound.LOWER, s, this); 1031252190Srpaulo return true; 1032252190Srpaulo } 1033252190Srpaulo default: 1034252190Srpaulo return isSubtype(s, t); 1035252190Srpaulo } 1036252190Srpaulo } 1037252190Srpaulo // </editor-fold> 1038252190Srpaulo 1039252190Srpaulo // <editor-fold defaultstate="collapsed" desc="isSameType"> 1040252190Srpaulo /** 1041252190Srpaulo * Are corresponding elements of the lists the same type? If 1042252190Srpaulo * lists are of different length, return false. 1043252190Srpaulo */ 1044252190Srpaulo public boolean isSameTypes(List<Type> ts, List<Type> ss) { 1045252190Srpaulo return isSameTypes(ts, ss, false); 1046252190Srpaulo } 1047281806Srpaulo public boolean isSameTypes(List<Type> ts, List<Type> ss, boolean strict) { 1048252190Srpaulo while (ts.tail != null && ss.tail != null 1049252190Srpaulo /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ && 1050252190Srpaulo isSameType(ts.head, ss.head, strict)) { 1051281806Srpaulo ts = ts.tail; 1052281806Srpaulo ss = ss.tail; 1053281806Srpaulo } 1054252190Srpaulo return ts.tail == null && ss.tail == null; 1055281806Srpaulo /*inlined: ts.isEmpty() && ss.isEmpty();*/ 1056252190Srpaulo } 1057252190Srpaulo 1058252190Srpaulo /** 1059252190Srpaulo * A polymorphic signature method (JLS SE 7, 8.4.1) is a method that 1060289549Srpaulo * (i) is declared in the java.lang.invoke.MethodHandle class, (ii) takes 1061252190Srpaulo * a single variable arity parameter (iii) whose declared type is Object[], 1062252190Srpaulo * (iv) has a return type of Object and (v) is native. 1063252190Srpaulo */ 1064252190Srpaulo public boolean isSignaturePolymorphic(MethodSymbol msym) { 1065252190Srpaulo List<Type> argtypes = msym.type.getParameterTypes(); 1066252190Srpaulo return (msym.flags_field & NATIVE) != 0 && 1067252190Srpaulo msym.owner == syms.methodHandleType.tsym && 1068252190Srpaulo argtypes.tail.tail == null && 1069252190Srpaulo argtypes.head.hasTag(TypeTag.ARRAY) && 1070252190Srpaulo msym.type.getReturnType().tsym == syms.objectType.tsym && 1071252190Srpaulo ((ArrayType)argtypes.head).elemtype.tsym == syms.objectType.tsym; 1072252190Srpaulo } 1073252190Srpaulo 1074252190Srpaulo /** 1075252190Srpaulo * Is t the same type as s? 1076252190Srpaulo */ 1077252190Srpaulo public boolean isSameType(Type t, Type s) { 1078252190Srpaulo return isSameType(t, s, false); 1079252190Srpaulo } 1080252190Srpaulo public boolean isSameType(Type t, Type s, boolean strict) { 1081252190Srpaulo return strict ? 1082252190Srpaulo isSameTypeStrict.visit(t, s) : 1083252190Srpaulo isSameTypeLoose.visit(t, s); 1084252190Srpaulo } 1085252190Srpaulo // where 1086252190Srpaulo abstract class SameTypeVisitor extends TypeRelation { 1087252190Srpaulo 1088252190Srpaulo public Boolean visitType(Type t, Type s) { 1089252190Srpaulo if (t.equalsIgnoreMetadata(s)) 1090252190Srpaulo return true; 1091252190Srpaulo 1092252190Srpaulo if (s.isPartial()) 1093252190Srpaulo return visit(s, t); 1094252190Srpaulo 1095252190Srpaulo switch (t.getTag()) { 1096252190Srpaulo case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT: 1097252190Srpaulo case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE: 1098252190Srpaulo return t.hasTag(s.getTag()); 1099281806Srpaulo case TYPEVAR: { 1100281806Srpaulo if (s.hasTag(TYPEVAR)) { 1101281806Srpaulo //type-substitution does not preserve type-var types 1102281806Srpaulo //check that type var symbols and bounds are indeed the same 1103281806Srpaulo return sameTypeVars((TypeVar)t, (TypeVar)s); 1104252190Srpaulo } 1105252190Srpaulo else { 1106252190Srpaulo //special case for s == ? super X, where upper(s) = u 1107252190Srpaulo //check that u == t, where u has been set by Type.withTypeVar 1108252190Srpaulo return s.isSuperBound() && 1109252190Srpaulo !s.isExtendsBound() && 1110252190Srpaulo visit(t, wildUpperBound(s)); 1111252190Srpaulo } 1112252190Srpaulo } 1113252190Srpaulo default: 1114252190Srpaulo throw new AssertionError("isSameType " + t.getTag()); 1115252190Srpaulo } 1116252190Srpaulo } 1117252190Srpaulo 1118252190Srpaulo abstract boolean sameTypeVars(TypeVar tv1, TypeVar tv2); 1119252190Srpaulo 1120252190Srpaulo @Override 1121252190Srpaulo public Boolean visitWildcardType(WildcardType t, Type s) { 1122252190Srpaulo if (s.isPartial()) 1123252190Srpaulo return visit(s, t); 1124252190Srpaulo else 1125252190Srpaulo return false; 1126252190Srpaulo } 1127252190Srpaulo 1128252190Srpaulo @Override 1129252190Srpaulo public Boolean visitClassType(ClassType t, Type s) { 1130252190Srpaulo if (t == s) 1131252190Srpaulo return true; 1132252190Srpaulo 1133252190Srpaulo if (s.isPartial()) 1134252190Srpaulo return visit(s, t); 1135252190Srpaulo 1136252190Srpaulo if (s.isSuperBound() && !s.isExtendsBound()) 1137252190Srpaulo return visit(t, wildUpperBound(s)) && visit(t, wildLowerBound(s)); 1138252190Srpaulo 1139252190Srpaulo if (t.isCompound() && s.isCompound()) { 1140252190Srpaulo if (!visit(supertype(t), supertype(s))) 1141252190Srpaulo return false; 1142252190Srpaulo 1143252190Srpaulo HashSet<UniqueType> set = new HashSet<>(); 1144252190Srpaulo for (Type x : interfaces(t)) 1145252190Srpaulo set.add(new UniqueType(x, Types.this)); 1146252190Srpaulo for (Type x : interfaces(s)) { 1147252190Srpaulo if (!set.remove(new UniqueType(x, Types.this))) 1148252190Srpaulo return false; 1149281806Srpaulo } 1150252190Srpaulo return (set.isEmpty()); 1151252190Srpaulo } 1152337817Scy return t.tsym == s.tsym 1153252190Srpaulo && visit(t.getEnclosingType(), s.getEnclosingType()) 1154 && containsTypes(t.getTypeArguments(), s.getTypeArguments()); 1155 } 1156 1157 abstract protected boolean containsTypes(List<Type> ts1, List<Type> ts2); 1158 1159 @Override 1160 public Boolean visitArrayType(ArrayType t, Type s) { 1161 if (t == s) 1162 return true; 1163 1164 if (s.isPartial()) 1165 return visit(s, t); 1166 1167 return s.hasTag(ARRAY) 1168 && containsTypeEquivalent(t.elemtype, elemtype(s)); 1169 } 1170 1171 @Override 1172 public Boolean visitMethodType(MethodType t, Type s) { 1173 // isSameType for methods does not take thrown 1174 // exceptions into account! 1175 return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType()); 1176 } 1177 1178 @Override 1179 public Boolean visitPackageType(PackageType t, Type s) { 1180 return t == s; 1181 } 1182 1183 @Override 1184 public Boolean visitForAll(ForAll t, Type s) { 1185 if (!s.hasTag(FORALL)) { 1186 return false; 1187 } 1188 1189 ForAll forAll = (ForAll)s; 1190 return hasSameBounds(t, forAll) 1191 && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars)); 1192 } 1193 1194 @Override 1195 public Boolean visitUndetVar(UndetVar t, Type s) { 1196 if (s.hasTag(WILDCARD)) { 1197 // FIXME, this might be leftovers from before capture conversion 1198 return false; 1199 } 1200 1201 if (t == s || t.qtype == s || s.hasTag(ERROR) || s.hasTag(UNKNOWN)) { 1202 return true; 1203 } 1204 1205 t.addBound(InferenceBound.EQ, s, Types.this); 1206 1207 return true; 1208 } 1209 1210 @Override 1211 public Boolean visitErrorType(ErrorType t, Type s) { 1212 return true; 1213 } 1214 } 1215 1216 /** 1217 * Standard type-equality relation - type variables are considered 1218 * equals if they share the same type symbol. 1219 */ 1220 TypeRelation isSameTypeLoose = new LooseSameTypeVisitor(); 1221 1222 private class LooseSameTypeVisitor extends SameTypeVisitor { 1223 1224 /** cache of the type-variable pairs being (recursively) tested. */ 1225 private Set<TypePair> cache = new HashSet<>(); 1226 1227 @Override 1228 boolean sameTypeVars(TypeVar tv1, TypeVar tv2) { 1229 return tv1.tsym == tv2.tsym && checkSameBounds(tv1, tv2); 1230 } 1231 @Override 1232 protected boolean containsTypes(List<Type> ts1, List<Type> ts2) { 1233 return containsTypeEquivalent(ts1, ts2); 1234 } 1235 1236 /** 1237 * Since type-variable bounds can be recursive, we need to protect against 1238 * infinite loops - where the same bounds are checked over and over recursively. 1239 */ 1240 private boolean checkSameBounds(TypeVar tv1, TypeVar tv2) { 1241 TypePair p = new TypePair(tv1, tv2, true); 1242 if (cache.add(p)) { 1243 try { 1244 return visit(tv1.getUpperBound(), tv2.getUpperBound()); 1245 } finally { 1246 cache.remove(p); 1247 } 1248 } else { 1249 return false; 1250 } 1251 } 1252 }; 1253 1254 /** 1255 * Strict type-equality relation - type variables are considered 1256 * equals if they share the same object identity. 1257 */ 1258 TypeRelation isSameTypeStrict = new SameTypeVisitor() { 1259 @Override 1260 boolean sameTypeVars(TypeVar tv1, TypeVar tv2) { 1261 return tv1 == tv2; 1262 } 1263 @Override 1264 protected boolean containsTypes(List<Type> ts1, List<Type> ts2) { 1265 return isSameTypes(ts1, ts2, true); 1266 } 1267 1268 @Override 1269 public Boolean visitWildcardType(WildcardType t, Type s) { 1270 if (!s.hasTag(WILDCARD)) { 1271 return false; 1272 } else { 1273 WildcardType t2 = (WildcardType)s; 1274 return t.kind == t2.kind && 1275 isSameType(t.type, t2.type, true); 1276 } 1277 } 1278 }; 1279 1280 // </editor-fold> 1281 1282 // <editor-fold defaultstate="collapsed" desc="Contains Type"> 1283 public boolean containedBy(Type t, Type s) { 1284 switch (t.getTag()) { 1285 case UNDETVAR: 1286 if (s.hasTag(WILDCARD)) { 1287 UndetVar undetvar = (UndetVar)t; 1288 WildcardType wt = (WildcardType)s; 1289 switch(wt.kind) { 1290 case UNBOUND: 1291 break; 1292 case EXTENDS: { 1293 Type bound = wildUpperBound(s); 1294 undetvar.addBound(InferenceBound.UPPER, bound, this); 1295 break; 1296 } 1297 case SUPER: { 1298 Type bound = wildLowerBound(s); 1299 undetvar.addBound(InferenceBound.LOWER, bound, this); 1300 break; 1301 } 1302 } 1303 return true; 1304 } else { 1305 return isSameType(t, s); 1306 } 1307 case ERROR: 1308 return true; 1309 default: 1310 return containsType(s, t); 1311 } 1312 } 1313 1314 boolean containsType(List<Type> ts, List<Type> ss) { 1315 while (ts.nonEmpty() && ss.nonEmpty() 1316 && containsType(ts.head, ss.head)) { 1317 ts = ts.tail; 1318 ss = ss.tail; 1319 } 1320 return ts.isEmpty() && ss.isEmpty(); 1321 } 1322 1323 /** 1324 * Check if t contains s. 1325 * 1326 * <p>T contains S if: 1327 * 1328 * <p>{@code L(T) <: L(S) && U(S) <: U(T)} 1329 * 1330 * <p>This relation is only used by ClassType.isSubtype(), that 1331 * is, 1332 * 1333 * <p>{@code C<S> <: C<T> if T contains S.} 1334 * 1335 * <p>Because of F-bounds, this relation can lead to infinite 1336 * recursion. Thus we must somehow break that recursion. Notice 1337 * that containsType() is only called from ClassType.isSubtype(). 1338 * Since the arguments have already been checked against their 1339 * bounds, we know: 1340 * 1341 * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)} 1342 * 1343 * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)} 1344 * 1345 * @param t a type 1346 * @param s a type 1347 */ 1348 public boolean containsType(Type t, Type s) { 1349 return containsType.visit(t, s); 1350 } 1351 // where 1352 private TypeRelation containsType = new TypeRelation() { 1353 1354 public Boolean visitType(Type t, Type s) { 1355 if (s.isPartial()) 1356 return containedBy(s, t); 1357 else 1358 return isSameType(t, s); 1359 } 1360 1361// void debugContainsType(WildcardType t, Type s) { 1362// System.err.println(); 1363// System.err.format(" does %s contain %s?%n", t, s); 1364// System.err.format(" %s U(%s) <: U(%s) %s = %s%n", 1365// wildUpperBound(s), s, t, wildUpperBound(t), 1366// t.isSuperBound() 1367// || isSubtypeNoCapture(wildUpperBound(s), wildUpperBound(t))); 1368// System.err.format(" %s L(%s) <: L(%s) %s = %s%n", 1369// wildLowerBound(t), t, s, wildLowerBound(s), 1370// t.isExtendsBound() 1371// || isSubtypeNoCapture(wildLowerBound(t), wildLowerBound(s))); 1372// System.err.println(); 1373// } 1374 1375 @Override 1376 public Boolean visitWildcardType(WildcardType t, Type s) { 1377 if (s.isPartial()) 1378 return containedBy(s, t); 1379 else { 1380// debugContainsType(t, s); 1381 return isSameWildcard(t, s) 1382 || isCaptureOf(s, t) 1383 || ((t.isExtendsBound() || isSubtypeNoCapture(wildLowerBound(t), wildLowerBound(s))) && 1384 (t.isSuperBound() || isSubtypeNoCapture(wildUpperBound(s), wildUpperBound(t)))); 1385 } 1386 } 1387 1388 @Override 1389 public Boolean visitUndetVar(UndetVar t, Type s) { 1390 if (!s.hasTag(WILDCARD)) { 1391 return isSameType(t, s); 1392 } else { 1393 return false; 1394 } 1395 } 1396 1397 @Override 1398 public Boolean visitErrorType(ErrorType t, Type s) { 1399 return true; 1400 } 1401 }; 1402 1403 public boolean isCaptureOf(Type s, WildcardType t) { 1404 if (!s.hasTag(TYPEVAR) || !((TypeVar)s).isCaptured()) 1405 return false; 1406 return isSameWildcard(t, ((CapturedType)s).wildcard); 1407 } 1408 1409 public boolean isSameWildcard(WildcardType t, Type s) { 1410 if (!s.hasTag(WILDCARD)) 1411 return false; 1412 WildcardType w = (WildcardType)s; 1413 return w.kind == t.kind && w.type == t.type; 1414 } 1415 1416 public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) { 1417 while (ts.nonEmpty() && ss.nonEmpty() 1418 && containsTypeEquivalent(ts.head, ss.head)) { 1419 ts = ts.tail; 1420 ss = ss.tail; 1421 } 1422 return ts.isEmpty() && ss.isEmpty(); 1423 } 1424 // </editor-fold> 1425 1426 // <editor-fold defaultstate="collapsed" desc="isCastable"> 1427 public boolean isCastable(Type t, Type s) { 1428 return isCastable(t, s, noWarnings); 1429 } 1430 1431 /** 1432 * Is t is castable to s?<br> 1433 * s is assumed to be an erased type.<br> 1434 * (not defined for Method and ForAll types). 1435 */ 1436 public boolean isCastable(Type t, Type s, Warner warn) { 1437 if (t == s) 1438 return true; 1439 1440 if (t.isPrimitive() != s.isPrimitive()) 1441 return (isConvertible(t, s, warn) 1442 || (allowObjectToPrimitiveCast && 1443 s.isPrimitive() && 1444 isSubtype(boxedClass(s).type, t))); 1445 if (warn != warnStack.head) { 1446 try { 1447 warnStack = warnStack.prepend(warn); 1448 checkUnsafeVarargsConversion(t, s, warn); 1449 return isCastable.visit(t,s); 1450 } finally { 1451 warnStack = warnStack.tail; 1452 } 1453 } else { 1454 return isCastable.visit(t,s); 1455 } 1456 } 1457 // where 1458 private TypeRelation isCastable = new TypeRelation() { 1459 1460 public Boolean visitType(Type t, Type s) { 1461 if (s.hasTag(ERROR)) 1462 return true; 1463 1464 switch (t.getTag()) { 1465 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT: 1466 case DOUBLE: 1467 return s.isNumeric(); 1468 case BOOLEAN: 1469 return s.hasTag(BOOLEAN); 1470 case VOID: 1471 return false; 1472 case BOT: 1473 return isSubtype(t, s); 1474 default: 1475 throw new AssertionError(); 1476 } 1477 } 1478 1479 @Override 1480 public Boolean visitWildcardType(WildcardType t, Type s) { 1481 return isCastable(wildUpperBound(t), s, warnStack.head); 1482 } 1483 1484 @Override 1485 public Boolean visitClassType(ClassType t, Type s) { 1486 if (s.hasTag(ERROR) || s.hasTag(BOT)) 1487 return true; 1488 1489 if (s.hasTag(TYPEVAR)) { 1490 if (isCastable(t, s.getUpperBound(), noWarnings)) { 1491 warnStack.head.warn(LintCategory.UNCHECKED); 1492 return true; 1493 } else { 1494 return false; 1495 } 1496 } 1497 1498 if (t.isIntersection() || s.isIntersection()) { 1499 return !t.isIntersection() ? 1500 visitIntersectionType((IntersectionClassType)s, t, true) : 1501 visitIntersectionType((IntersectionClassType)t, s, false); 1502 } 1503 1504 if (s.hasTag(CLASS) || s.hasTag(ARRAY)) { 1505 boolean upcast; 1506 if ((upcast = isSubtype(erasure(t), erasure(s))) 1507 || isSubtype(erasure(s), erasure(t))) { 1508 if (!upcast && s.hasTag(ARRAY)) { 1509 if (!isReifiable(s)) 1510 warnStack.head.warn(LintCategory.UNCHECKED); 1511 return true; 1512 } else if (s.isRaw()) { 1513 return true; 1514 } else if (t.isRaw()) { 1515 if (!isUnbounded(s)) 1516 warnStack.head.warn(LintCategory.UNCHECKED); 1517 return true; 1518 } 1519 // Assume |a| <: |b| 1520 final Type a = upcast ? t : s; 1521 final Type b = upcast ? s : t; 1522 final boolean HIGH = true; 1523 final boolean LOW = false; 1524 final boolean DONT_REWRITE_TYPEVARS = false; 1525 Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS); 1526 Type aLow = rewriteQuantifiers(a, LOW, DONT_REWRITE_TYPEVARS); 1527 Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS); 1528 Type bLow = rewriteQuantifiers(b, LOW, DONT_REWRITE_TYPEVARS); 1529 Type lowSub = asSub(bLow, aLow.tsym); 1530 Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym); 1531 if (highSub == null) { 1532 final boolean REWRITE_TYPEVARS = true; 1533 aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS); 1534 aLow = rewriteQuantifiers(a, LOW, REWRITE_TYPEVARS); 1535 bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS); 1536 bLow = rewriteQuantifiers(b, LOW, REWRITE_TYPEVARS); 1537 lowSub = asSub(bLow, aLow.tsym); 1538 highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym); 1539 } 1540 if (highSub != null) { 1541 if (!(a.tsym == highSub.tsym && a.tsym == lowSub.tsym)) { 1542 Assert.error(a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym); 1543 } 1544 if (!disjointTypes(aHigh.allparams(), highSub.allparams()) 1545 && !disjointTypes(aHigh.allparams(), lowSub.allparams()) 1546 && !disjointTypes(aLow.allparams(), highSub.allparams()) 1547 && !disjointTypes(aLow.allparams(), lowSub.allparams())) { 1548 if (upcast ? giveWarning(a, b) : 1549 giveWarning(b, a)) 1550 warnStack.head.warn(LintCategory.UNCHECKED); 1551 return true; 1552 } 1553 } 1554 if (isReifiable(s)) 1555 return isSubtypeUnchecked(a, b); 1556 else 1557 return isSubtypeUnchecked(a, b, warnStack.head); 1558 } 1559 1560 // Sidecast 1561 if (s.hasTag(CLASS)) { 1562 if ((s.tsym.flags() & INTERFACE) != 0) { 1563 return ((t.tsym.flags() & FINAL) == 0) 1564 ? sideCast(t, s, warnStack.head) 1565 : sideCastFinal(t, s, warnStack.head); 1566 } else if ((t.tsym.flags() & INTERFACE) != 0) { 1567 return ((s.tsym.flags() & FINAL) == 0) 1568 ? sideCast(t, s, warnStack.head) 1569 : sideCastFinal(t, s, warnStack.head); 1570 } else { 1571 // unrelated class types 1572 return false; 1573 } 1574 } 1575 } 1576 return false; 1577 } 1578 1579 boolean visitIntersectionType(IntersectionClassType ict, Type s, boolean reverse) { 1580 Warner warn = noWarnings; 1581 for (Type c : ict.getComponents()) { 1582 warn.clear(); 1583 if (reverse ? !isCastable(s, c, warn) : !isCastable(c, s, warn)) 1584 return false; 1585 } 1586 if (warn.hasLint(LintCategory.UNCHECKED)) 1587 warnStack.head.warn(LintCategory.UNCHECKED); 1588 return true; 1589 } 1590 1591 @Override 1592 public Boolean visitArrayType(ArrayType t, Type s) { 1593 switch (s.getTag()) { 1594 case ERROR: 1595 case BOT: 1596 return true; 1597 case TYPEVAR: 1598 if (isCastable(s, t, noWarnings)) { 1599 warnStack.head.warn(LintCategory.UNCHECKED); 1600 return true; 1601 } else { 1602 return false; 1603 } 1604 case CLASS: 1605 return isSubtype(t, s); 1606 case ARRAY: 1607 if (elemtype(t).isPrimitive() || elemtype(s).isPrimitive()) { 1608 return elemtype(t).hasTag(elemtype(s).getTag()); 1609 } else { 1610 return visit(elemtype(t), elemtype(s)); 1611 } 1612 default: 1613 return false; 1614 } 1615 } 1616 1617 @Override 1618 public Boolean visitTypeVar(TypeVar t, Type s) { 1619 switch (s.getTag()) { 1620 case ERROR: 1621 case BOT: 1622 return true; 1623 case TYPEVAR: 1624 if (isSubtype(t, s)) { 1625 return true; 1626 } else if (isCastable(t.bound, s, noWarnings)) { 1627 warnStack.head.warn(LintCategory.UNCHECKED); 1628 return true; 1629 } else { 1630 return false; 1631 } 1632 default: 1633 return isCastable(t.bound, s, warnStack.head); 1634 } 1635 } 1636 1637 @Override 1638 public Boolean visitErrorType(ErrorType t, Type s) { 1639 return true; 1640 } 1641 }; 1642 // </editor-fold> 1643 1644 // <editor-fold defaultstate="collapsed" desc="disjointTypes"> 1645 public boolean disjointTypes(List<Type> ts, List<Type> ss) { 1646 while (ts.tail != null && ss.tail != null) { 1647 if (disjointType(ts.head, ss.head)) return true; 1648 ts = ts.tail; 1649 ss = ss.tail; 1650 } 1651 return false; 1652 } 1653 1654 /** 1655 * Two types or wildcards are considered disjoint if it can be 1656 * proven that no type can be contained in both. It is 1657 * conservative in that it is allowed to say that two types are 1658 * not disjoint, even though they actually are. 1659 * 1660 * The type {@code C<X>} is castable to {@code C<Y>} exactly if 1661 * {@code X} and {@code Y} are not disjoint. 1662 */ 1663 public boolean disjointType(Type t, Type s) { 1664 return disjointType.visit(t, s); 1665 } 1666 // where 1667 private TypeRelation disjointType = new TypeRelation() { 1668 1669 private Set<TypePair> cache = new HashSet<>(); 1670 1671 @Override 1672 public Boolean visitType(Type t, Type s) { 1673 if (s.hasTag(WILDCARD)) 1674 return visit(s, t); 1675 else 1676 return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t); 1677 } 1678 1679 private boolean isCastableRecursive(Type t, Type s) { 1680 TypePair pair = new TypePair(t, s); 1681 if (cache.add(pair)) { 1682 try { 1683 return Types.this.isCastable(t, s); 1684 } finally { 1685 cache.remove(pair); 1686 } 1687 } else { 1688 return true; 1689 } 1690 } 1691 1692 private boolean notSoftSubtypeRecursive(Type t, Type s) { 1693 TypePair pair = new TypePair(t, s); 1694 if (cache.add(pair)) { 1695 try { 1696 return Types.this.notSoftSubtype(t, s); 1697 } finally { 1698 cache.remove(pair); 1699 } 1700 } else { 1701 return false; 1702 } 1703 } 1704 1705 @Override 1706 public Boolean visitWildcardType(WildcardType t, Type s) { 1707 if (t.isUnbound()) 1708 return false; 1709 1710 if (!s.hasTag(WILDCARD)) { 1711 if (t.isExtendsBound()) 1712 return notSoftSubtypeRecursive(s, t.type); 1713 else 1714 return notSoftSubtypeRecursive(t.type, s); 1715 } 1716 1717 if (s.isUnbound()) 1718 return false; 1719 1720 if (t.isExtendsBound()) { 1721 if (s.isExtendsBound()) 1722 return !isCastableRecursive(t.type, wildUpperBound(s)); 1723 else if (s.isSuperBound()) 1724 return notSoftSubtypeRecursive(wildLowerBound(s), t.type); 1725 } else if (t.isSuperBound()) { 1726 if (s.isExtendsBound()) 1727 return notSoftSubtypeRecursive(t.type, wildUpperBound(s)); 1728 } 1729 return false; 1730 } 1731 }; 1732 // </editor-fold> 1733 1734 // <editor-fold defaultstate="collapsed" desc="cvarLowerBounds"> 1735 public List<Type> cvarLowerBounds(List<Type> ts) { 1736 return ts.map(cvarLowerBoundMapping); 1737 } 1738 private final TypeMapping<Void> cvarLowerBoundMapping = new TypeMapping<Void>() { 1739 @Override 1740 public Type visitCapturedType(CapturedType t, Void _unused) { 1741 return cvarLowerBound(t); 1742 } 1743 }; 1744 // </editor-fold> 1745 1746 // <editor-fold defaultstate="collapsed" desc="notSoftSubtype"> 1747 /** 1748 * This relation answers the question: is impossible that 1749 * something of type `t' can be a subtype of `s'? This is 1750 * different from the question "is `t' not a subtype of `s'?" 1751 * when type variables are involved: Integer is not a subtype of T 1752 * where {@code <T extends Number>} but it is not true that Integer cannot 1753 * possibly be a subtype of T. 1754 */ 1755 public boolean notSoftSubtype(Type t, Type s) { 1756 if (t == s) return false; 1757 if (t.hasTag(TYPEVAR)) { 1758 TypeVar tv = (TypeVar) t; 1759 return !isCastable(tv.bound, 1760 relaxBound(s), 1761 noWarnings); 1762 } 1763 if (!s.hasTag(WILDCARD)) 1764 s = cvarUpperBound(s); 1765 1766 return !isSubtype(t, relaxBound(s)); 1767 } 1768 1769 private Type relaxBound(Type t) { 1770 return (t.hasTag(TYPEVAR)) ? 1771 rewriteQuantifiers(skipTypeVars(t, false), true, true) : 1772 t; 1773 } 1774 // </editor-fold> 1775 1776 // <editor-fold defaultstate="collapsed" desc="isReifiable"> 1777 public boolean isReifiable(Type t) { 1778 return isReifiable.visit(t); 1779 } 1780 // where 1781 private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() { 1782 1783 public Boolean visitType(Type t, Void ignored) { 1784 return true; 1785 } 1786 1787 @Override 1788 public Boolean visitClassType(ClassType t, Void ignored) { 1789 if (t.isCompound()) 1790 return false; 1791 else { 1792 if (!t.isParameterized()) 1793 return true; 1794 1795 for (Type param : t.allparams()) { 1796 if (!param.isUnbound()) 1797 return false; 1798 } 1799 return true; 1800 } 1801 } 1802 1803 @Override 1804 public Boolean visitArrayType(ArrayType t, Void ignored) { 1805 return visit(t.elemtype); 1806 } 1807 1808 @Override 1809 public Boolean visitTypeVar(TypeVar t, Void ignored) { 1810 return false; 1811 } 1812 }; 1813 // </editor-fold> 1814 1815 // <editor-fold defaultstate="collapsed" desc="Array Utils"> 1816 public boolean isArray(Type t) { 1817 while (t.hasTag(WILDCARD)) 1818 t = wildUpperBound(t); 1819 return t.hasTag(ARRAY); 1820 } 1821 1822 /** 1823 * The element type of an array. 1824 */ 1825 public Type elemtype(Type t) { 1826 switch (t.getTag()) { 1827 case WILDCARD: 1828 return elemtype(wildUpperBound(t)); 1829 case ARRAY: 1830 return ((ArrayType)t).elemtype; 1831 case FORALL: 1832 return elemtype(((ForAll)t).qtype); 1833 case ERROR: 1834 return t; 1835 default: 1836 return null; 1837 } 1838 } 1839 1840 public Type elemtypeOrType(Type t) { 1841 Type elemtype = elemtype(t); 1842 return elemtype != null ? 1843 elemtype : 1844 t; 1845 } 1846 1847 /** 1848 * Mapping to take element type of an arraytype 1849 */ 1850 private TypeMapping<Void> elemTypeFun = new TypeMapping<Void>() { 1851 @Override 1852 public Type visitArrayType(ArrayType t, Void _unused) { 1853 return t.elemtype; 1854 } 1855 1856 @Override 1857 public Type visitTypeVar(TypeVar t, Void _unused) { 1858 return visit(skipTypeVars(t, false)); 1859 } 1860 }; 1861 1862 /** 1863 * The number of dimensions of an array type. 1864 */ 1865 public int dimensions(Type t) { 1866 int result = 0; 1867 while (t.hasTag(ARRAY)) { 1868 result++; 1869 t = elemtype(t); 1870 } 1871 return result; 1872 } 1873 1874 /** 1875 * Returns an ArrayType with the component type t 1876 * 1877 * @param t The component type of the ArrayType 1878 * @return the ArrayType for the given component 1879 */ 1880 public ArrayType makeArrayType(Type t) { 1881 if (t.hasTag(VOID) || t.hasTag(PACKAGE)) { 1882 Assert.error("Type t must not be a VOID or PACKAGE type, " + t.toString()); 1883 } 1884 return new ArrayType(t, syms.arrayClass); 1885 } 1886 // </editor-fold> 1887 1888 // <editor-fold defaultstate="collapsed" desc="asSuper"> 1889 /** 1890 * Return the (most specific) base type of t that starts with the 1891 * given symbol. If none exists, return null. 1892 * 1893 * Caveat Emptor: Since javac represents the class of all arrays with a singleton 1894 * symbol Symtab.arrayClass, which by being a singleton cannot hold any discriminant, 1895 * this method could yield surprising answers when invoked on arrays. For example when 1896 * invoked with t being byte [] and sym being t.sym itself, asSuper would answer null. 1897 * 1898 * @param t a type 1899 * @param sym a symbol 1900 */ 1901 public Type asSuper(Type t, Symbol sym) { 1902 /* Some examples: 1903 * 1904 * (Enum<E>, Comparable) => Comparable<E> 1905 * (c.s.s.d.AttributeTree.ValueKind, Enum) => Enum<c.s.s.d.AttributeTree.ValueKind> 1906 * (c.s.s.t.ExpressionTree, c.s.s.t.Tree) => c.s.s.t.Tree 1907 * (j.u.List<capture#160 of ? extends c.s.s.d.DocTree>, Iterable) => 1908 * Iterable<capture#160 of ? extends c.s.s.d.DocTree> 1909 */ 1910 if (sym.type == syms.objectType) { //optimization 1911 return syms.objectType; 1912 } 1913 return asSuper.visit(t, sym); 1914 } 1915 // where 1916 private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor<Type,Symbol>() { 1917 1918 public Type visitType(Type t, Symbol sym) { 1919 return null; 1920 } 1921 1922 @Override 1923 public Type visitClassType(ClassType t, Symbol sym) { 1924 if (t.tsym == sym) 1925 return t; 1926 1927 Type st = supertype(t); 1928 if (st.hasTag(CLASS) || st.hasTag(TYPEVAR)) { 1929 Type x = asSuper(st, sym); 1930 if (x != null) 1931 return x; 1932 } 1933 if ((sym.flags() & INTERFACE) != 0) { 1934 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) { 1935 if (!l.head.hasTag(ERROR)) { 1936 Type x = asSuper(l.head, sym); 1937 if (x != null) 1938 return x; 1939 } 1940 } 1941 } 1942 return null; 1943 } 1944 1945 @Override 1946 public Type visitArrayType(ArrayType t, Symbol sym) { 1947 return isSubtype(t, sym.type) ? sym.type : null; 1948 } 1949 1950 @Override 1951 public Type visitTypeVar(TypeVar t, Symbol sym) { 1952 if (t.tsym == sym) 1953 return t; 1954 else 1955 return asSuper(t.bound, sym); 1956 } 1957 1958 @Override 1959 public Type visitErrorType(ErrorType t, Symbol sym) { 1960 return t; 1961 } 1962 }; 1963 1964 /** 1965 * Return the base type of t or any of its outer types that starts 1966 * with the given symbol. If none exists, return null. 1967 * 1968 * @param t a type 1969 * @param sym a symbol 1970 */ 1971 public Type asOuterSuper(Type t, Symbol sym) { 1972 switch (t.getTag()) { 1973 case CLASS: 1974 do { 1975 Type s = asSuper(t, sym); 1976 if (s != null) return s; 1977 t = t.getEnclosingType(); 1978 } while (t.hasTag(CLASS)); 1979 return null; 1980 case ARRAY: 1981 return isSubtype(t, sym.type) ? sym.type : null; 1982 case TYPEVAR: 1983 return asSuper(t, sym); 1984 case ERROR: 1985 return t; 1986 default: 1987 return null; 1988 } 1989 } 1990 1991 /** 1992 * Return the base type of t or any of its enclosing types that 1993 * starts with the given symbol. If none exists, return null. 1994 * 1995 * @param t a type 1996 * @param sym a symbol 1997 */ 1998 public Type asEnclosingSuper(Type t, Symbol sym) { 1999 switch (t.getTag()) { 2000 case CLASS: 2001 do { 2002 Type s = asSuper(t, sym); 2003 if (s != null) return s; 2004 Type outer = t.getEnclosingType(); 2005 t = (outer.hasTag(CLASS)) ? outer : 2006 (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type : 2007 Type.noType; 2008 } while (t.hasTag(CLASS)); 2009 return null; 2010 case ARRAY: 2011 return isSubtype(t, sym.type) ? sym.type : null; 2012 case TYPEVAR: 2013 return asSuper(t, sym); 2014 case ERROR: 2015 return t; 2016 default: 2017 return null; 2018 } 2019 } 2020 // </editor-fold> 2021 2022 // <editor-fold defaultstate="collapsed" desc="memberType"> 2023 /** 2024 * The type of given symbol, seen as a member of t. 2025 * 2026 * @param t a type 2027 * @param sym a symbol 2028 */ 2029 public Type memberType(Type t, Symbol sym) { 2030 return (sym.flags() & STATIC) != 0 2031 ? sym.type 2032 : memberType.visit(t, sym); 2033 } 2034 // where 2035 private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor<Type,Symbol>() { 2036 2037 public Type visitType(Type t, Symbol sym) { 2038 return sym.type; 2039 } 2040 2041 @Override 2042 public Type visitWildcardType(WildcardType t, Symbol sym) { 2043 return memberType(wildUpperBound(t), sym); 2044 } 2045 2046 @Override 2047 public Type visitClassType(ClassType t, Symbol sym) { 2048 Symbol owner = sym.owner; 2049 long flags = sym.flags(); 2050 if (((flags & STATIC) == 0) && owner.type.isParameterized()) { 2051 Type base = asOuterSuper(t, owner); 2052 //if t is an intersection type T = CT & I1 & I2 ... & In 2053 //its supertypes CT, I1, ... In might contain wildcards 2054 //so we need to go through capture conversion 2055 base = t.isCompound() ? capture(base) : base; 2056 if (base != null) { 2057 List<Type> ownerParams = owner.type.allparams(); 2058 List<Type> baseParams = base.allparams(); 2059 if (ownerParams.nonEmpty()) { 2060 if (baseParams.isEmpty()) { 2061 // then base is a raw type 2062 return erasure(sym.type); 2063 } else { 2064 return subst(sym.type, ownerParams, baseParams); 2065 } 2066 } 2067 } 2068 } 2069 return sym.type; 2070 } 2071 2072 @Override 2073 public Type visitTypeVar(TypeVar t, Symbol sym) { 2074 return memberType(t.bound, sym); 2075 } 2076 2077 @Override 2078 public Type visitErrorType(ErrorType t, Symbol sym) { 2079 return t; 2080 } 2081 }; 2082 // </editor-fold> 2083 2084 // <editor-fold defaultstate="collapsed" desc="isAssignable"> 2085 public boolean isAssignable(Type t, Type s) { 2086 return isAssignable(t, s, noWarnings); 2087 } 2088 2089 /** 2090 * Is t assignable to s?<br> 2091 * Equivalent to subtype except for constant values and raw 2092 * types.<br> 2093 * (not defined for Method and ForAll types) 2094 */ 2095 public boolean isAssignable(Type t, Type s, Warner warn) { 2096 if (t.hasTag(ERROR)) 2097 return true; 2098 if (t.getTag().isSubRangeOf(INT) && t.constValue() != null) { 2099 int value = ((Number)t.constValue()).intValue(); 2100 switch (s.getTag()) { 2101 case BYTE: 2102 if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE) 2103 return true; 2104 break; 2105 case CHAR: 2106 if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE) 2107 return true; 2108 break; 2109 case SHORT: 2110 if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE) 2111 return true; 2112 break; 2113 case INT: 2114 return true; 2115 case CLASS: 2116 switch (unboxedType(s).getTag()) { 2117 case BYTE: 2118 case CHAR: 2119 case SHORT: 2120 return isAssignable(t, unboxedType(s), warn); 2121 } 2122 break; 2123 } 2124 } 2125 return isConvertible(t, s, warn); 2126 } 2127 // </editor-fold> 2128 2129 // <editor-fold defaultstate="collapsed" desc="erasure"> 2130 /** 2131 * The erasure of t {@code |t|} -- the type that results when all 2132 * type parameters in t are deleted. 2133 */ 2134 public Type erasure(Type t) { 2135 return eraseNotNeeded(t) ? t : erasure(t, false); 2136 } 2137 //where 2138 private boolean eraseNotNeeded(Type t) { 2139 // We don't want to erase primitive types and String type as that 2140 // operation is idempotent. Also, erasing these could result in loss 2141 // of information such as constant values attached to such types. 2142 return (t.isPrimitive()) || (syms.stringType.tsym == t.tsym); 2143 } 2144 2145 private Type erasure(Type t, boolean recurse) { 2146 if (t.isPrimitive()) { 2147 return t; /* fast special case */ 2148 } else { 2149 Type out = erasure.visit(t, recurse); 2150 return out; 2151 } 2152 } 2153 // where 2154 private TypeMapping<Boolean> erasure = new TypeMapping<Boolean>() { 2155 private Type combineMetadata(final Type s, 2156 final Type t) { 2157 if (t.getMetadata() != TypeMetadata.EMPTY) { 2158 switch (s.getKind()) { 2159 case OTHER: 2160 case UNION: 2161 case INTERSECTION: 2162 case PACKAGE: 2163 case EXECUTABLE: 2164 case NONE: 2165 case VOID: 2166 case ERROR: 2167 return s; 2168 default: return s.cloneWithMetadata(s.getMetadata().without(Kind.ANNOTATIONS)); 2169 } 2170 } else { 2171 return s; 2172 } 2173 } 2174 2175 public Type visitType(Type t, Boolean recurse) { 2176 if (t.isPrimitive()) 2177 return t; /*fast special case*/ 2178 else { 2179 //other cases already handled 2180 return combineMetadata(t, t); 2181 } 2182 } 2183 2184 @Override 2185 public Type visitClassType(ClassType t, Boolean recurse) { 2186 Type erased = t.tsym.erasure(Types.this); 2187 if (recurse) { 2188 erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym, 2189 t.getMetadata().without(Kind.ANNOTATIONS)); 2190 return erased; 2191 } else { 2192 return combineMetadata(erased, t); 2193 } 2194 } 2195 2196 @Override 2197 public Type visitTypeVar(TypeVar t, Boolean recurse) { 2198 Type erased = erasure(t.bound, recurse); 2199 return combineMetadata(erased, t); 2200 } 2201 }; 2202 2203 public List<Type> erasure(List<Type> ts) { 2204 return erasure.visit(ts, false); 2205 } 2206 2207 public Type erasureRecursive(Type t) { 2208 return erasure(t, true); 2209 } 2210 2211 public List<Type> erasureRecursive(List<Type> ts) { 2212 return erasure.visit(ts, true); 2213 } 2214 // </editor-fold> 2215 2216 // <editor-fold defaultstate="collapsed" desc="makeIntersectionType"> 2217 /** 2218 * Make an intersection type from non-empty list of types. The list should be ordered according to 2219 * {@link TypeSymbol#precedes(TypeSymbol, Types)}. Note that this might cause a symbol completion. 2220 * Hence, this version of makeIntersectionType may not be called during a classfile read. 2221 * 2222 * @param bounds the types from which the intersection type is formed 2223 */ 2224 public IntersectionClassType makeIntersectionType(List<Type> bounds) { 2225 return makeIntersectionType(bounds, bounds.head.tsym.isInterface()); 2226 } 2227 2228 /** 2229 * Make an intersection type from non-empty list of types. The list should be ordered according to 2230 * {@link TypeSymbol#precedes(TypeSymbol, Types)}. This does not cause symbol completion as 2231 * an extra parameter indicates as to whether all bounds are interfaces - in which case the 2232 * supertype is implicitly assumed to be 'Object'. 2233 * 2234 * @param bounds the types from which the intersection type is formed 2235 * @param allInterfaces are all bounds interface types? 2236 */ 2237 public IntersectionClassType makeIntersectionType(List<Type> bounds, boolean allInterfaces) { 2238 Assert.check(bounds.nonEmpty()); 2239 Type firstExplicitBound = bounds.head; 2240 if (allInterfaces) { 2241 bounds = bounds.prepend(syms.objectType); 2242 } 2243 ClassSymbol bc = 2244 new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC, 2245 Type.moreInfo 2246 ? names.fromString(bounds.toString()) 2247 : names.empty, 2248 null, 2249 syms.noSymbol); 2250 IntersectionClassType intersectionType = new IntersectionClassType(bounds, bc, allInterfaces); 2251 bc.type = intersectionType; 2252 bc.erasure_field = (bounds.head.hasTag(TYPEVAR)) ? 2253 syms.objectType : // error condition, recover 2254 erasure(firstExplicitBound); 2255 bc.members_field = WriteableScope.create(bc); 2256 return intersectionType; 2257 } 2258 // </editor-fold> 2259 2260 // <editor-fold defaultstate="collapsed" desc="supertype"> 2261 public Type supertype(Type t) { 2262 return supertype.visit(t); 2263 } 2264 // where 2265 private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() { 2266 2267 public Type visitType(Type t, Void ignored) { 2268 // A note on wildcards: there is no good way to 2269 // determine a supertype for a super bounded wildcard. 2270 return Type.noType; 2271 } 2272 2273 @Override 2274 public Type visitClassType(ClassType t, Void ignored) { 2275 if (t.supertype_field == null) { 2276 Type supertype = ((ClassSymbol)t.tsym).getSuperclass(); 2277 // An interface has no superclass; its supertype is Object. 2278 if (t.isInterface()) 2279 supertype = ((ClassType)t.tsym.type).supertype_field; 2280 if (t.supertype_field == null) { 2281 List<Type> actuals = classBound(t).allparams(); 2282 List<Type> formals = t.tsym.type.allparams(); 2283 if (t.hasErasedSupertypes()) { 2284 t.supertype_field = erasureRecursive(supertype); 2285 } else if (formals.nonEmpty()) { 2286 t.supertype_field = subst(supertype, formals, actuals); 2287 } 2288 else { 2289 t.supertype_field = supertype; 2290 } 2291 } 2292 } 2293 return t.supertype_field; 2294 } 2295 2296 /** 2297 * The supertype is always a class type. If the type 2298 * variable's bounds start with a class type, this is also 2299 * the supertype. Otherwise, the supertype is 2300 * java.lang.Object. 2301 */ 2302 @Override 2303 public Type visitTypeVar(TypeVar t, Void ignored) { 2304 if (t.bound.hasTag(TYPEVAR) || 2305 (!t.bound.isCompound() && !t.bound.isInterface())) { 2306 return t.bound; 2307 } else { 2308 return supertype(t.bound); 2309 } 2310 } 2311 2312 @Override 2313 public Type visitArrayType(ArrayType t, Void ignored) { 2314 if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType)) 2315 return arraySuperType(); 2316 else 2317 return new ArrayType(supertype(t.elemtype), t.tsym); 2318 } 2319 2320 @Override 2321 public Type visitErrorType(ErrorType t, Void ignored) { 2322 return Type.noType; 2323 } 2324 }; 2325 // </editor-fold> 2326 2327 // <editor-fold defaultstate="collapsed" desc="interfaces"> 2328 /** 2329 * Return the interfaces implemented by this class. 2330 */ 2331 public List<Type> interfaces(Type t) { 2332 return interfaces.visit(t); 2333 } 2334 // where 2335 private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() { 2336 2337 public List<Type> visitType(Type t, Void ignored) { 2338 return List.nil(); 2339 } 2340 2341 @Override 2342 public List<Type> visitClassType(ClassType t, Void ignored) { 2343 if (t.interfaces_field == null) { 2344 List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces(); 2345 if (t.interfaces_field == null) { 2346 // If t.interfaces_field is null, then t must 2347 // be a parameterized type (not to be confused 2348 // with a generic type declaration). 2349 // Terminology: 2350 // Parameterized type: List<String> 2351 // Generic type declaration: class List<E> { ... } 2352 // So t corresponds to List<String> and 2353 // t.tsym.type corresponds to List<E>. 2354 // The reason t must be parameterized type is 2355 // that completion will happen as a side 2356 // effect of calling 2357 // ClassSymbol.getInterfaces. Since 2358 // t.interfaces_field is null after 2359 // completion, we can assume that t is not the 2360 // type of a class/interface declaration. 2361 Assert.check(t != t.tsym.type, t); 2362 List<Type> actuals = t.allparams(); 2363 List<Type> formals = t.tsym.type.allparams(); 2364 if (t.hasErasedSupertypes()) { 2365 t.interfaces_field = erasureRecursive(interfaces); 2366 } else if (formals.nonEmpty()) { 2367 t.interfaces_field = subst(interfaces, formals, actuals); 2368 } 2369 else { 2370 t.interfaces_field = interfaces; 2371 } 2372 } 2373 } 2374 return t.interfaces_field; 2375 } 2376 2377 @Override 2378 public List<Type> visitTypeVar(TypeVar t, Void ignored) { 2379 if (t.bound.isCompound()) 2380 return interfaces(t.bound); 2381 2382 if (t.bound.isInterface()) 2383 return List.of(t.bound); 2384 2385 return List.nil(); 2386 } 2387 }; 2388 2389 public List<Type> directSupertypes(Type t) { 2390 return directSupertypes.visit(t); 2391 } 2392 // where 2393 private final UnaryVisitor<List<Type>> directSupertypes = new UnaryVisitor<List<Type>>() { 2394 2395 public List<Type> visitType(final Type type, final Void ignored) { 2396 if (!type.isIntersection()) { 2397 final Type sup = supertype(type); 2398 return (sup == Type.noType || sup == type || sup == null) 2399 ? interfaces(type) 2400 : interfaces(type).prepend(sup); 2401 } else { 2402 return visitIntersectionType((IntersectionClassType) type); 2403 } 2404 } 2405 2406 private List<Type> visitIntersectionType(final IntersectionClassType it) { 2407 return it.getExplicitComponents(); 2408 } 2409 2410 }; 2411 2412 public boolean isDirectSuperInterface(TypeSymbol isym, TypeSymbol origin) { 2413 for (Type i2 : interfaces(origin.type)) { 2414 if (isym == i2.tsym) return true; 2415 } 2416 return false; 2417 } 2418 // </editor-fold> 2419 2420 // <editor-fold defaultstate="collapsed" desc="isDerivedRaw"> 2421 Map<Type,Boolean> isDerivedRawCache = new HashMap<>(); 2422 2423 public boolean isDerivedRaw(Type t) { 2424 Boolean result = isDerivedRawCache.get(t); 2425 if (result == null) { 2426 result = isDerivedRawInternal(t); 2427 isDerivedRawCache.put(t, result); 2428 } 2429 return result; 2430 } 2431 2432 public boolean isDerivedRawInternal(Type t) { 2433 if (t.isErroneous()) 2434 return false; 2435 return 2436 t.isRaw() || 2437 supertype(t) != Type.noType && isDerivedRaw(supertype(t)) || 2438 isDerivedRaw(interfaces(t)); 2439 } 2440 2441 public boolean isDerivedRaw(List<Type> ts) { 2442 List<Type> l = ts; 2443 while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail; 2444 return l.nonEmpty(); 2445 } 2446 // </editor-fold> 2447 2448 // <editor-fold defaultstate="collapsed" desc="setBounds"> 2449 /** 2450 * Same as {@link Types#setBounds(TypeVar, List, boolean)}, except that third parameter is computed directly, 2451 * as follows: if all all bounds are interface types, the computed supertype is Object,otherwise 2452 * the supertype is simply left null (in this case, the supertype is assumed to be the head of 2453 * the bound list passed as second argument). Note that this check might cause a symbol completion. 2454 * Hence, this version of setBounds may not be called during a classfile read. 2455 * 2456 * @param t a type variable 2457 * @param bounds the bounds, must be nonempty 2458 */ 2459 public void setBounds(TypeVar t, List<Type> bounds) { 2460 setBounds(t, bounds, bounds.head.tsym.isInterface()); 2461 } 2462 2463 /** 2464 * Set the bounds field of the given type variable to reflect a (possibly multiple) list of bounds. 2465 * This does not cause symbol completion as an extra parameter indicates as to whether all bounds 2466 * are interfaces - in which case the supertype is implicitly assumed to be 'Object'. 2467 * 2468 * @param t a type variable 2469 * @param bounds the bounds, must be nonempty 2470 * @param allInterfaces are all bounds interface types? 2471 */ 2472 public void setBounds(TypeVar t, List<Type> bounds, boolean allInterfaces) { 2473 t.bound = bounds.tail.isEmpty() ? 2474 bounds.head : 2475 makeIntersectionType(bounds, allInterfaces); 2476 t.rank_field = -1; 2477 } 2478 // </editor-fold> 2479 2480 // <editor-fold defaultstate="collapsed" desc="getBounds"> 2481 /** 2482 * Return list of bounds of the given type variable. 2483 */ 2484 public List<Type> getBounds(TypeVar t) { 2485 if (t.bound.hasTag(NONE)) 2486 return List.nil(); 2487 else if (t.bound.isErroneous() || !t.bound.isCompound()) 2488 return List.of(t.bound); 2489 else if ((erasure(t).tsym.flags() & INTERFACE) == 0) 2490 return interfaces(t).prepend(supertype(t)); 2491 else 2492 // No superclass was given in bounds. 2493 // In this case, supertype is Object, erasure is first interface. 2494 return interfaces(t); 2495 } 2496 // </editor-fold> 2497 2498 // <editor-fold defaultstate="collapsed" desc="classBound"> 2499 /** 2500 * If the given type is a (possibly selected) type variable, 2501 * return the bounding class of this type, otherwise return the 2502 * type itself. 2503 */ 2504 public Type classBound(Type t) { 2505 return classBound.visit(t); 2506 } 2507 // where 2508 private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() { 2509 2510 public Type visitType(Type t, Void ignored) { 2511 return t; 2512 } 2513 2514 @Override 2515 public Type visitClassType(ClassType t, Void ignored) { 2516 Type outer1 = classBound(t.getEnclosingType()); 2517 if (outer1 != t.getEnclosingType()) 2518 return new ClassType(outer1, t.getTypeArguments(), t.tsym, 2519 t.getMetadata()); 2520 else 2521 return t; 2522 } 2523 2524 @Override 2525 public Type visitTypeVar(TypeVar t, Void ignored) { 2526 return classBound(supertype(t)); 2527 } 2528 2529 @Override 2530 public Type visitErrorType(ErrorType t, Void ignored) { 2531 return t; 2532 } 2533 }; 2534 // </editor-fold> 2535 2536 // <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence"> 2537 /** 2538 * Returns true iff the first signature is a <em>sub 2539 * signature</em> of the other. This is <b>not</b> an equivalence 2540 * relation. 2541 * 2542 * @jls section 8.4.2. 2543 * @see #overrideEquivalent(Type t, Type s) 2544 * @param t first signature (possibly raw). 2545 * @param s second signature (could be subjected to erasure). 2546 * @return true if t is a sub signature of s. 2547 */ 2548 public boolean isSubSignature(Type t, Type s) { 2549 return isSubSignature(t, s, true); 2550 } 2551 2552 public boolean isSubSignature(Type t, Type s, boolean strict) { 2553 return hasSameArgs(t, s, strict) || hasSameArgs(t, erasure(s), strict); 2554 } 2555 2556 /** 2557 * Returns true iff these signatures are related by <em>override 2558 * equivalence</em>. This is the natural extension of 2559 * isSubSignature to an equivalence relation. 2560 * 2561 * @jls section 8.4.2. 2562 * @see #isSubSignature(Type t, Type s) 2563 * @param t a signature (possible raw, could be subjected to 2564 * erasure). 2565 * @param s a signature (possible raw, could be subjected to 2566 * erasure). 2567 * @return true if either argument is a sub signature of the other. 2568 */ 2569 public boolean overrideEquivalent(Type t, Type s) { 2570 return hasSameArgs(t, s) || 2571 hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s); 2572 } 2573 2574 public boolean overridesObjectMethod(TypeSymbol origin, Symbol msym) { 2575 for (Symbol sym : syms.objectType.tsym.members().getSymbolsByName(msym.name)) { 2576 if (msym.overrides(sym, origin, Types.this, true)) { 2577 return true; 2578 } 2579 } 2580 return false; 2581 } 2582 2583 // <editor-fold defaultstate="collapsed" desc="Determining method implementation in given site"> 2584 class ImplementationCache { 2585 2586 private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>> _map = new WeakHashMap<>(); 2587 2588 class Entry { 2589 final MethodSymbol cachedImpl; 2590 final Filter<Symbol> implFilter; 2591 final boolean checkResult; 2592 final int prevMark; 2593 2594 public Entry(MethodSymbol cachedImpl, 2595 Filter<Symbol> scopeFilter, 2596 boolean checkResult, 2597 int prevMark) { 2598 this.cachedImpl = cachedImpl; 2599 this.implFilter = scopeFilter; 2600 this.checkResult = checkResult; 2601 this.prevMark = prevMark; 2602 } 2603 2604 boolean matches(Filter<Symbol> scopeFilter, boolean checkResult, int mark) { 2605 return this.implFilter == scopeFilter && 2606 this.checkResult == checkResult && 2607 this.prevMark == mark; 2608 } 2609 } 2610 2611 MethodSymbol get(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) { 2612 SoftReference<Map<TypeSymbol, Entry>> ref_cache = _map.get(ms); 2613 Map<TypeSymbol, Entry> cache = ref_cache != null ? ref_cache.get() : null; 2614 if (cache == null) { 2615 cache = new HashMap<>(); 2616 _map.put(ms, new SoftReference<>(cache)); 2617 } 2618 Entry e = cache.get(origin); 2619 CompoundScope members = membersClosure(origin.type, true); 2620 if (e == null || 2621 !e.matches(implFilter, checkResult, members.getMark())) { 2622 MethodSymbol impl = implementationInternal(ms, origin, checkResult, implFilter); 2623 cache.put(origin, new Entry(impl, implFilter, checkResult, members.getMark())); 2624 return impl; 2625 } 2626 else { 2627 return e.cachedImpl; 2628 } 2629 } 2630 2631 private MethodSymbol implementationInternal(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) { 2632 for (Type t = origin.type; t.hasTag(CLASS) || t.hasTag(TYPEVAR); t = supertype(t)) { 2633 t = skipTypeVars(t, false); 2634 TypeSymbol c = t.tsym; 2635 Symbol bestSoFar = null; 2636 for (Symbol sym : c.members().getSymbolsByName(ms.name, implFilter)) { 2637 if (sym != null && sym.overrides(ms, origin, Types.this, checkResult)) { 2638 bestSoFar = sym; 2639 if ((sym.flags() & ABSTRACT) == 0) { 2640 //if concrete impl is found, exit immediately 2641 break; 2642 } 2643 } 2644 } 2645 if (bestSoFar != null) { 2646 //return either the (only) concrete implementation or the first abstract one 2647 return (MethodSymbol)bestSoFar; 2648 } 2649 } 2650 return null; 2651 } 2652 } 2653 2654 private ImplementationCache implCache = new ImplementationCache(); 2655 2656 public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) { 2657 return implCache.get(ms, origin, checkResult, implFilter); 2658 } 2659 // </editor-fold> 2660 2661 // <editor-fold defaultstate="collapsed" desc="compute transitive closure of all members in given site"> 2662 class MembersClosureCache extends SimpleVisitor<Scope.CompoundScope, Void> { 2663 2664 private Map<TypeSymbol, CompoundScope> _map = new HashMap<>(); 2665 2666 Set<TypeSymbol> seenTypes = new HashSet<>(); 2667 2668 class MembersScope extends CompoundScope { 2669 2670 CompoundScope scope; 2671 2672 public MembersScope(CompoundScope scope) { 2673 super(scope.owner); 2674 this.scope = scope; 2675 } 2676 2677 Filter<Symbol> combine(Filter<Symbol> sf) { 2678 return s -> !s.owner.isInterface() && (sf == null || sf.accepts(s)); 2679 } 2680 2681 @Override 2682 public Iterable<Symbol> getSymbols(Filter<Symbol> sf, LookupKind lookupKind) { 2683 return scope.getSymbols(combine(sf), lookupKind); 2684 } 2685 2686 @Override 2687 public Iterable<Symbol> getSymbolsByName(Name name, Filter<Symbol> sf, LookupKind lookupKind) { 2688 return scope.getSymbolsByName(name, combine(sf), lookupKind); 2689 } 2690 2691 @Override 2692 public int getMark() { 2693 return scope.getMark(); 2694 } 2695 } 2696 2697 CompoundScope nilScope; 2698 2699 /** members closure visitor methods **/ 2700 2701 public CompoundScope visitType(Type t, Void _unused) { 2702 if (nilScope == null) { 2703 nilScope = new CompoundScope(syms.noSymbol); 2704 } 2705 return nilScope; 2706 } 2707 2708 @Override 2709 public CompoundScope visitClassType(ClassType t, Void _unused) { 2710 if (!seenTypes.add(t.tsym)) { 2711 //this is possible when an interface is implemented in multiple 2712 //superclasses, or when a class hierarchy is circular - in such 2713 //cases we don't need to recurse (empty scope is returned) 2714 return new CompoundScope(t.tsym); 2715 } 2716 try { 2717 seenTypes.add(t.tsym); 2718 ClassSymbol csym = (ClassSymbol)t.tsym; 2719 CompoundScope membersClosure = _map.get(csym); 2720 if (membersClosure == null) { 2721 membersClosure = new CompoundScope(csym); 2722 for (Type i : interfaces(t)) { 2723 membersClosure.prependSubScope(visit(i, null)); 2724 } 2725 membersClosure.prependSubScope(visit(supertype(t), null)); 2726 membersClosure.prependSubScope(csym.members()); 2727 _map.put(csym, membersClosure); 2728 } 2729 return membersClosure; 2730 } 2731 finally { 2732 seenTypes.remove(t.tsym); 2733 } 2734 } 2735 2736 @Override 2737 public CompoundScope visitTypeVar(TypeVar t, Void _unused) { 2738 return visit(t.getUpperBound(), null); 2739 } 2740 } 2741 2742 private MembersClosureCache membersCache = new MembersClosureCache(); 2743 2744 public CompoundScope membersClosure(Type site, boolean skipInterface) { 2745 CompoundScope cs = membersCache.visit(site, null); 2746 Assert.checkNonNull(cs, () -> "type " + site); 2747 return skipInterface ? membersCache.new MembersScope(cs) : cs; 2748 } 2749 // </editor-fold> 2750 2751 2752 /** Return first abstract member of class `sym'. 2753 */ 2754 public MethodSymbol firstUnimplementedAbstract(ClassSymbol sym) { 2755 try { 2756 return firstUnimplementedAbstractImpl(sym, sym); 2757 } catch (CompletionFailure ex) { 2758 chk.completionError(enter.getEnv(sym).tree.pos(), ex); 2759 return null; 2760 } 2761 } 2762 //where: 2763 private MethodSymbol firstUnimplementedAbstractImpl(ClassSymbol impl, ClassSymbol c) { 2764 MethodSymbol undef = null; 2765 // Do not bother to search in classes that are not abstract, 2766 // since they cannot have abstract members. 2767 if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) { 2768 Scope s = c.members(); 2769 for (Symbol sym : s.getSymbols(NON_RECURSIVE)) { 2770 if (sym.kind == MTH && 2771 (sym.flags() & (ABSTRACT|IPROXY|DEFAULT|PRIVATE)) == ABSTRACT) { 2772 MethodSymbol absmeth = (MethodSymbol)sym; 2773 MethodSymbol implmeth = absmeth.implementation(impl, this, true); 2774 if (implmeth == null || implmeth == absmeth) { 2775 //look for default implementations 2776 if (allowDefaultMethods) { 2777 MethodSymbol prov = interfaceCandidates(impl.type, absmeth).head; 2778 if (prov != null && prov.overrides(absmeth, impl, this, true)) { 2779 implmeth = prov; 2780 } 2781 } 2782 } 2783 if (implmeth == null || implmeth == absmeth) { 2784 undef = absmeth; 2785 break; 2786 } 2787 } 2788 } 2789 if (undef == null) { 2790 Type st = supertype(c.type); 2791 if (st.hasTag(CLASS)) 2792 undef = firstUnimplementedAbstractImpl(impl, (ClassSymbol)st.tsym); 2793 } 2794 for (List<Type> l = interfaces(c.type); 2795 undef == null && l.nonEmpty(); 2796 l = l.tail) { 2797 undef = firstUnimplementedAbstractImpl(impl, (ClassSymbol)l.head.tsym); 2798 } 2799 } 2800 return undef; 2801 } 2802 2803 2804 //where 2805 public List<MethodSymbol> interfaceCandidates(Type site, MethodSymbol ms) { 2806 Filter<Symbol> filter = new MethodFilter(ms, site); 2807 List<MethodSymbol> candidates = List.nil(); 2808 for (Symbol s : membersClosure(site, false).getSymbols(filter)) { 2809 if (!site.tsym.isInterface() && !s.owner.isInterface()) { 2810 return List.of((MethodSymbol)s); 2811 } else if (!candidates.contains(s)) { 2812 candidates = candidates.prepend((MethodSymbol)s); 2813 } 2814 } 2815 return prune(candidates); 2816 } 2817 2818 public List<MethodSymbol> prune(List<MethodSymbol> methods) { 2819 ListBuffer<MethodSymbol> methodsMin = new ListBuffer<>(); 2820 for (MethodSymbol m1 : methods) { 2821 boolean isMin_m1 = true; 2822 for (MethodSymbol m2 : methods) { 2823 if (m1 == m2) continue; 2824 if (m2.owner != m1.owner && 2825 asSuper(m2.owner.type, m1.owner) != null) { 2826 isMin_m1 = false; 2827 break; 2828 } 2829 } 2830 if (isMin_m1) 2831 methodsMin.append(m1); 2832 } 2833 return methodsMin.toList(); 2834 } 2835 // where 2836 private class MethodFilter implements Filter<Symbol> { 2837 2838 Symbol msym; 2839 Type site; 2840 2841 MethodFilter(Symbol msym, Type site) { 2842 this.msym = msym; 2843 this.site = site; 2844 } 2845 2846 public boolean accepts(Symbol s) { 2847 return s.kind == MTH && 2848 s.name == msym.name && 2849 (s.flags() & SYNTHETIC) == 0 && 2850 s.isInheritedIn(site.tsym, Types.this) && 2851 overrideEquivalent(memberType(site, s), memberType(site, msym)); 2852 } 2853 } 2854 // </editor-fold> 2855 2856 /** 2857 * Does t have the same arguments as s? It is assumed that both 2858 * types are (possibly polymorphic) method types. Monomorphic 2859 * method types "have the same arguments", if their argument lists 2860 * are equal. Polymorphic method types "have the same arguments", 2861 * if they have the same arguments after renaming all type 2862 * variables of one to corresponding type variables in the other, 2863 * where correspondence is by position in the type parameter list. 2864 */ 2865 public boolean hasSameArgs(Type t, Type s) { 2866 return hasSameArgs(t, s, true); 2867 } 2868 2869 public boolean hasSameArgs(Type t, Type s, boolean strict) { 2870 return hasSameArgs(t, s, strict ? hasSameArgs_strict : hasSameArgs_nonstrict); 2871 } 2872 2873 private boolean hasSameArgs(Type t, Type s, TypeRelation hasSameArgs) { 2874 return hasSameArgs.visit(t, s); 2875 } 2876 // where 2877 private class HasSameArgs extends TypeRelation { 2878 2879 boolean strict; 2880 2881 public HasSameArgs(boolean strict) { 2882 this.strict = strict; 2883 } 2884 2885 public Boolean visitType(Type t, Type s) { 2886 throw new AssertionError(); 2887 } 2888 2889 @Override 2890 public Boolean visitMethodType(MethodType t, Type s) { 2891 return s.hasTag(METHOD) 2892 && containsTypeEquivalent(t.argtypes, s.getParameterTypes()); 2893 } 2894 2895 @Override 2896 public Boolean visitForAll(ForAll t, Type s) { 2897 if (!s.hasTag(FORALL)) 2898 return strict ? false : visitMethodType(t.asMethodType(), s); 2899 2900 ForAll forAll = (ForAll)s; 2901 return hasSameBounds(t, forAll) 2902 && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars)); 2903 } 2904 2905 @Override 2906 public Boolean visitErrorType(ErrorType t, Type s) { 2907 return false; 2908 } 2909 } 2910 2911 TypeRelation hasSameArgs_strict = new HasSameArgs(true); 2912 TypeRelation hasSameArgs_nonstrict = new HasSameArgs(false); 2913 2914 // </editor-fold> 2915 2916 // <editor-fold defaultstate="collapsed" desc="subst"> 2917 public List<Type> subst(List<Type> ts, 2918 List<Type> from, 2919 List<Type> to) { 2920 return ts.map(new Subst(from, to)); 2921 } 2922 2923 /** 2924 * Substitute all occurrences of a type in `from' with the 2925 * corresponding type in `to' in 't'. Match lists `from' and `to' 2926 * from the right: If lists have different length, discard leading 2927 * elements of the longer list. 2928 */ 2929 public Type subst(Type t, List<Type> from, List<Type> to) { 2930 return t.map(new Subst(from, to)); 2931 } 2932 2933 private class Subst extends TypeMapping<Void> { 2934 List<Type> from; 2935 List<Type> to; 2936 2937 public Subst(List<Type> from, List<Type> to) { 2938 int fromLength = from.length(); 2939 int toLength = to.length(); 2940 while (fromLength > toLength) { 2941 fromLength--; 2942 from = from.tail; 2943 } 2944 while (fromLength < toLength) { 2945 toLength--; 2946 to = to.tail; 2947 } 2948 this.from = from; 2949 this.to = to; 2950 } 2951 2952 @Override 2953 public Type visitTypeVar(TypeVar t, Void ignored) { 2954 for (List<Type> from = this.from, to = this.to; 2955 from.nonEmpty(); 2956 from = from.tail, to = to.tail) { 2957 if (t.equalsIgnoreMetadata(from.head)) { 2958 return to.head.withTypeVar(t); 2959 } 2960 } 2961 return t; 2962 } 2963 2964 @Override 2965 public Type visitClassType(ClassType t, Void ignored) { 2966 if (!t.isCompound()) { 2967 return super.visitClassType(t, ignored); 2968 } else { 2969 Type st = visit(supertype(t)); 2970 List<Type> is = visit(interfaces(t), ignored); 2971 if (st == supertype(t) && is == interfaces(t)) 2972 return t; 2973 else 2974 return makeIntersectionType(is.prepend(st)); 2975 } 2976 } 2977 2978 @Override 2979 public Type visitWildcardType(WildcardType t, Void ignored) { 2980 WildcardType t2 = (WildcardType)super.visitWildcardType(t, ignored); 2981 if (t2 != t && t.isExtendsBound() && t2.type.isExtendsBound()) { 2982 t2.type = wildUpperBound(t2.type); 2983 } 2984 return t2; 2985 } 2986 2987 @Override 2988 public Type visitForAll(ForAll t, Void ignored) { 2989 if (Type.containsAny(to, t.tvars)) { 2990 //perform alpha-renaming of free-variables in 't' 2991 //if 'to' types contain variables that are free in 't' 2992 List<Type> freevars = newInstances(t.tvars); 2993 t = new ForAll(freevars, 2994 Types.this.subst(t.qtype, t.tvars, freevars)); 2995 } 2996 List<Type> tvars1 = substBounds(t.tvars, from, to); 2997 Type qtype1 = visit(t.qtype); 2998 if (tvars1 == t.tvars && qtype1 == t.qtype) { 2999 return t; 3000 } else if (tvars1 == t.tvars) { 3001 return new ForAll(tvars1, qtype1) { 3002 @Override 3003 public boolean needsStripping() { 3004 return true; 3005 } 3006 }; 3007 } else { 3008 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1)) { 3009 @Override 3010 public boolean needsStripping() { 3011 return true; 3012 } 3013 }; 3014 } 3015 } 3016 } 3017 3018 public List<Type> substBounds(List<Type> tvars, 3019 List<Type> from, 3020 List<Type> to) { 3021 if (tvars.isEmpty()) 3022 return tvars; 3023 ListBuffer<Type> newBoundsBuf = new ListBuffer<>(); 3024 boolean changed = false; 3025 // calculate new bounds 3026 for (Type t : tvars) { 3027 TypeVar tv = (TypeVar) t; 3028 Type bound = subst(tv.bound, from, to); 3029 if (bound != tv.bound) 3030 changed = true; 3031 newBoundsBuf.append(bound); 3032 } 3033 if (!changed) 3034 return tvars; 3035 ListBuffer<Type> newTvars = new ListBuffer<>(); 3036 // create new type variables without bounds 3037 for (Type t : tvars) { 3038 newTvars.append(new TypeVar(t.tsym, null, syms.botType, 3039 t.getMetadata())); 3040 } 3041 // the new bounds should use the new type variables in place 3042 // of the old 3043 List<Type> newBounds = newBoundsBuf.toList(); 3044 from = tvars; 3045 to = newTvars.toList(); 3046 for (; !newBounds.isEmpty(); newBounds = newBounds.tail) { 3047 newBounds.head = subst(newBounds.head, from, to); 3048 } 3049 newBounds = newBoundsBuf.toList(); 3050 // set the bounds of new type variables to the new bounds 3051 for (Type t : newTvars.toList()) { 3052 TypeVar tv = (TypeVar) t; 3053 tv.bound = newBounds.head; 3054 newBounds = newBounds.tail; 3055 } 3056 return newTvars.toList(); 3057 } 3058 3059 public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) { 3060 Type bound1 = subst(t.bound, from, to); 3061 if (bound1 == t.bound) 3062 return t; 3063 else { 3064 // create new type variable without bounds 3065 TypeVar tv = new TypeVar(t.tsym, null, syms.botType, 3066 t.getMetadata()); 3067 // the new bound should use the new type variable in place 3068 // of the old 3069 tv.bound = subst(bound1, List.<Type>of(t), List.<Type>of(tv)); 3070 return tv; 3071 } 3072 } 3073 // </editor-fold> 3074 3075 // <editor-fold defaultstate="collapsed" desc="hasSameBounds"> 3076 /** 3077 * Does t have the same bounds for quantified variables as s? 3078 */ 3079 public boolean hasSameBounds(ForAll t, ForAll s) { 3080 List<Type> l1 = t.tvars; 3081 List<Type> l2 = s.tvars; 3082 while (l1.nonEmpty() && l2.nonEmpty() && 3083 isSameType(l1.head.getUpperBound(), 3084 subst(l2.head.getUpperBound(), 3085 s.tvars, 3086 t.tvars))) { 3087 l1 = l1.tail; 3088 l2 = l2.tail; 3089 } 3090 return l1.isEmpty() && l2.isEmpty(); 3091 } 3092 // </editor-fold> 3093 3094 // <editor-fold defaultstate="collapsed" desc="newInstances"> 3095 /** Create new vector of type variables from list of variables 3096 * changing all recursive bounds from old to new list. 3097 */ 3098 public List<Type> newInstances(List<Type> tvars) { 3099 List<Type> tvars1 = tvars.map(newInstanceFun); 3100 for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) { 3101 TypeVar tv = (TypeVar) l.head; 3102 tv.bound = subst(tv.bound, tvars, tvars1); 3103 } 3104 return tvars1; 3105 } 3106 private static final TypeMapping<Void> newInstanceFun = new TypeMapping<Void>() { 3107 @Override 3108 public TypeVar visitTypeVar(TypeVar t, Void _unused) { 3109 return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound(), t.getMetadata()); 3110 } 3111 }; 3112 // </editor-fold> 3113 3114 public Type createMethodTypeWithParameters(Type original, List<Type> newParams) { 3115 return original.accept(methodWithParameters, newParams); 3116 } 3117 // where 3118 private final MapVisitor<List<Type>> methodWithParameters = new MapVisitor<List<Type>>() { 3119 public Type visitType(Type t, List<Type> newParams) { 3120 throw new IllegalArgumentException("Not a method type: " + t); 3121 } 3122 public Type visitMethodType(MethodType t, List<Type> newParams) { 3123 return new MethodType(newParams, t.restype, t.thrown, t.tsym); 3124 } 3125 public Type visitForAll(ForAll t, List<Type> newParams) { 3126 return new ForAll(t.tvars, t.qtype.accept(this, newParams)); 3127 } 3128 }; 3129 3130 public Type createMethodTypeWithThrown(Type original, List<Type> newThrown) { 3131 return original.accept(methodWithThrown, newThrown); 3132 } 3133 // where 3134 private final MapVisitor<List<Type>> methodWithThrown = new MapVisitor<List<Type>>() { 3135 public Type visitType(Type t, List<Type> newThrown) { 3136 throw new IllegalArgumentException("Not a method type: " + t); 3137 } 3138 public Type visitMethodType(MethodType t, List<Type> newThrown) { 3139 return new MethodType(t.argtypes, t.restype, newThrown, t.tsym); 3140 } 3141 public Type visitForAll(ForAll t, List<Type> newThrown) { 3142 return new ForAll(t.tvars, t.qtype.accept(this, newThrown)); 3143 } 3144 }; 3145 3146 public Type createMethodTypeWithReturn(Type original, Type newReturn) { 3147 return original.accept(methodWithReturn, newReturn); 3148 } 3149 // where 3150 private final MapVisitor<Type> methodWithReturn = new MapVisitor<Type>() { 3151 public Type visitType(Type t, Type newReturn) { 3152 throw new IllegalArgumentException("Not a method type: " + t); 3153 } 3154 public Type visitMethodType(MethodType t, Type newReturn) { 3155 return new MethodType(t.argtypes, newReturn, t.thrown, t.tsym) { 3156 @Override 3157 public Type baseType() { 3158 return t; 3159 } 3160 }; 3161 } 3162 public Type visitForAll(ForAll t, Type newReturn) { 3163 return new ForAll(t.tvars, t.qtype.accept(this, newReturn)) { 3164 @Override 3165 public Type baseType() { 3166 return t; 3167 } 3168 }; 3169 } 3170 }; 3171 3172 // <editor-fold defaultstate="collapsed" desc="createErrorType"> 3173 public Type createErrorType(Type originalType) { 3174 return new ErrorType(originalType, syms.errSymbol); 3175 } 3176 3177 public Type createErrorType(ClassSymbol c, Type originalType) { 3178 return new ErrorType(c, originalType); 3179 } 3180 3181 public Type createErrorType(Name name, TypeSymbol container, Type originalType) { 3182 return new ErrorType(name, container, originalType); 3183 } 3184 // </editor-fold> 3185 3186 // <editor-fold defaultstate="collapsed" desc="rank"> 3187 /** 3188 * The rank of a class is the length of the longest path between 3189 * the class and java.lang.Object in the class inheritance 3190 * graph. Undefined for all but reference types. 3191 */ 3192 public int rank(Type t) { 3193 switch(t.getTag()) { 3194 case CLASS: { 3195 ClassType cls = (ClassType)t; 3196 if (cls.rank_field < 0) { 3197 Name fullname = cls.tsym.getQualifiedName(); 3198 if (fullname == names.java_lang_Object) 3199 cls.rank_field = 0; 3200 else { 3201 int r = rank(supertype(cls)); 3202 for (List<Type> l = interfaces(cls); 3203 l.nonEmpty(); 3204 l = l.tail) { 3205 if (rank(l.head) > r) 3206 r = rank(l.head); 3207 } 3208 cls.rank_field = r + 1; 3209 } 3210 } 3211 return cls.rank_field; 3212 } 3213 case TYPEVAR: { 3214 TypeVar tvar = (TypeVar)t; 3215 if (tvar.rank_field < 0) { 3216 int r = rank(supertype(tvar)); 3217 for (List<Type> l = interfaces(tvar); 3218 l.nonEmpty(); 3219 l = l.tail) { 3220 if (rank(l.head) > r) r = rank(l.head); 3221 } 3222 tvar.rank_field = r + 1; 3223 } 3224 return tvar.rank_field; 3225 } 3226 case ERROR: 3227 case NONE: 3228 return 0; 3229 default: 3230 throw new AssertionError(); 3231 } 3232 } 3233 // </editor-fold> 3234 3235 /** 3236 * Helper method for generating a string representation of a given type 3237 * accordingly to a given locale 3238 */ 3239 public String toString(Type t, Locale locale) { 3240 return Printer.createStandardPrinter(messages).visit(t, locale); 3241 } 3242 3243 /** 3244 * Helper method for generating a string representation of a given type 3245 * accordingly to a given locale 3246 */ 3247 public String toString(Symbol t, Locale locale) { 3248 return Printer.createStandardPrinter(messages).visit(t, locale); 3249 } 3250 3251 // <editor-fold defaultstate="collapsed" desc="toString"> 3252 /** 3253 * This toString is slightly more descriptive than the one on Type. 3254 * 3255 * @deprecated Types.toString(Type t, Locale l) provides better support 3256 * for localization 3257 */ 3258 @Deprecated 3259 public String toString(Type t) { 3260 if (t.hasTag(FORALL)) { 3261 ForAll forAll = (ForAll)t; 3262 return typaramsString(forAll.tvars) + forAll.qtype; 3263 } 3264 return "" + t; 3265 } 3266 // where 3267 private String typaramsString(List<Type> tvars) { 3268 StringBuilder s = new StringBuilder(); 3269 s.append('<'); 3270 boolean first = true; 3271 for (Type t : tvars) { 3272 if (!first) s.append(", "); 3273 first = false; 3274 appendTyparamString(((TypeVar)t), s); 3275 } 3276 s.append('>'); 3277 return s.toString(); 3278 } 3279 private void appendTyparamString(TypeVar t, StringBuilder buf) { 3280 buf.append(t); 3281 if (t.bound == null || 3282 t.bound.tsym.getQualifiedName() == names.java_lang_Object) 3283 return; 3284 buf.append(" extends "); // Java syntax; no need for i18n 3285 Type bound = t.bound; 3286 if (!bound.isCompound()) { 3287 buf.append(bound); 3288 } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) { 3289 buf.append(supertype(t)); 3290 for (Type intf : interfaces(t)) { 3291 buf.append('&'); 3292 buf.append(intf); 3293 } 3294 } else { 3295 // No superclass was given in bounds. 3296 // In this case, supertype is Object, erasure is first interface. 3297 boolean first = true; 3298 for (Type intf : interfaces(t)) { 3299 if (!first) buf.append('&'); 3300 first = false; 3301 buf.append(intf); 3302 } 3303 } 3304 } 3305 // </editor-fold> 3306 3307 // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types"> 3308 /** 3309 * A cache for closures. 3310 * 3311 * <p>A closure is a list of all the supertypes and interfaces of 3312 * a class or interface type, ordered by ClassSymbol.precedes 3313 * (that is, subclasses come first, arbitrary but fixed 3314 * otherwise). 3315 */ 3316 private Map<Type,List<Type>> closureCache = new HashMap<>(); 3317 3318 /** 3319 * Returns the closure of a class or interface type. 3320 */ 3321 public List<Type> closure(Type t) { 3322 List<Type> cl = closureCache.get(t); 3323 if (cl == null) { 3324 Type st = supertype(t); 3325 if (!t.isCompound()) { 3326 if (st.hasTag(CLASS)) { 3327 cl = insert(closure(st), t); 3328 } else if (st.hasTag(TYPEVAR)) { 3329 cl = closure(st).prepend(t); 3330 } else { 3331 cl = List.of(t); 3332 } 3333 } else { 3334 cl = closure(supertype(t)); 3335 } 3336 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) 3337 cl = union(cl, closure(l.head)); 3338 closureCache.put(t, cl); 3339 } 3340 return cl; 3341 } 3342 3343 /** 3344 * Collect types into a new closure (using a @code{ClosureHolder}) 3345 */ 3346 public Collector<Type, ClosureHolder, List<Type>> closureCollector(boolean minClosure, BiPredicate<Type, Type> shouldSkip) { 3347 return Collector.of(() -> new ClosureHolder(minClosure, shouldSkip), 3348 ClosureHolder::add, 3349 ClosureHolder::merge, 3350 ClosureHolder::closure); 3351 } 3352 //where 3353 class ClosureHolder { 3354 List<Type> closure; 3355 final boolean minClosure; 3356 final BiPredicate<Type, Type> shouldSkip; 3357 3358 ClosureHolder(boolean minClosure, BiPredicate<Type, Type> shouldSkip) { 3359 this.closure = List.nil(); 3360 this.minClosure = minClosure; 3361 this.shouldSkip = shouldSkip; 3362 } 3363 3364 void add(Type type) { 3365 closure = insert(closure, type, shouldSkip); 3366 } 3367 3368 ClosureHolder merge(ClosureHolder other) { 3369 closure = union(closure, other.closure, shouldSkip); 3370 return this; 3371 } 3372 3373 List<Type> closure() { 3374 return minClosure ? closureMin(closure) : closure; 3375 } 3376 } 3377 3378 BiPredicate<Type, Type> basicClosureSkip = (t1, t2) -> t1.tsym == t2.tsym; 3379 3380 /** 3381 * Insert a type in a closure 3382 */ 3383 public List<Type> insert(List<Type> cl, Type t, BiPredicate<Type, Type> shouldSkip) { 3384 if (cl.isEmpty()) { 3385 return cl.prepend(t); 3386 } else if (shouldSkip.test(t, cl.head)) { 3387 return cl; 3388 } else if (t.tsym.precedes(cl.head.tsym, this)) { 3389 return cl.prepend(t); 3390 } else { 3391 // t comes after head, or the two are unrelated 3392 return insert(cl.tail, t, shouldSkip).prepend(cl.head); 3393 } 3394 } 3395 3396 public List<Type> insert(List<Type> cl, Type t) { 3397 return insert(cl, t, basicClosureSkip); 3398 } 3399 3400 /** 3401 * Form the union of two closures 3402 */ 3403 public List<Type> union(List<Type> cl1, List<Type> cl2, BiPredicate<Type, Type> shouldSkip) { 3404 if (cl1.isEmpty()) { 3405 return cl2; 3406 } else if (cl2.isEmpty()) { 3407 return cl1; 3408 } else if (shouldSkip.test(cl1.head, cl2.head)) { 3409 return union(cl1.tail, cl2.tail, shouldSkip).prepend(cl1.head); 3410 } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) { 3411 return union(cl1.tail, cl2, shouldSkip).prepend(cl1.head); 3412 } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) { 3413 return union(cl1, cl2.tail, shouldSkip).prepend(cl2.head); 3414 } else { 3415 // unrelated types 3416 return union(cl1.tail, cl2, shouldSkip).prepend(cl1.head); 3417 } 3418 } 3419 3420 public List<Type> union(List<Type> cl1, List<Type> cl2) { 3421 return union(cl1, cl2, basicClosureSkip); 3422 } 3423 3424 /** 3425 * Intersect two closures 3426 */ 3427 public List<Type> intersect(List<Type> cl1, List<Type> cl2) { 3428 if (cl1 == cl2) 3429 return cl1; 3430 if (cl1.isEmpty() || cl2.isEmpty()) 3431 return List.nil(); 3432 if (cl1.head.tsym.precedes(cl2.head.tsym, this)) 3433 return intersect(cl1.tail, cl2); 3434 if (cl2.head.tsym.precedes(cl1.head.tsym, this)) 3435 return intersect(cl1, cl2.tail); 3436 if (isSameType(cl1.head, cl2.head)) 3437 return intersect(cl1.tail, cl2.tail).prepend(cl1.head); 3438 if (cl1.head.tsym == cl2.head.tsym && 3439 cl1.head.hasTag(CLASS) && cl2.head.hasTag(CLASS)) { 3440 if (cl1.head.isParameterized() && cl2.head.isParameterized()) { 3441 Type merge = merge(cl1.head,cl2.head); 3442 return intersect(cl1.tail, cl2.tail).prepend(merge); 3443 } 3444 if (cl1.head.isRaw() || cl2.head.isRaw()) 3445 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head)); 3446 } 3447 return intersect(cl1.tail, cl2.tail); 3448 } 3449 // where 3450 class TypePair { 3451 final Type t1; 3452 final Type t2; 3453 boolean strict; 3454 3455 TypePair(Type t1, Type t2) { 3456 this(t1, t2, false); 3457 } 3458 3459 TypePair(Type t1, Type t2, boolean strict) { 3460 this.t1 = t1; 3461 this.t2 = t2; 3462 this.strict = strict; 3463 } 3464 @Override 3465 public int hashCode() { 3466 return 127 * Types.this.hashCode(t1) + Types.this.hashCode(t2); 3467 } 3468 @Override 3469 public boolean equals(Object obj) { 3470 if (!(obj instanceof TypePair)) 3471 return false; 3472 TypePair typePair = (TypePair)obj; 3473 return isSameType(t1, typePair.t1, strict) 3474 && isSameType(t2, typePair.t2, strict); 3475 } 3476 } 3477 Set<TypePair> mergeCache = new HashSet<>(); 3478 private Type merge(Type c1, Type c2) { 3479 ClassType class1 = (ClassType) c1; 3480 List<Type> act1 = class1.getTypeArguments(); 3481 ClassType class2 = (ClassType) c2; 3482 List<Type> act2 = class2.getTypeArguments(); 3483 ListBuffer<Type> merged = new ListBuffer<>(); 3484 List<Type> typarams = class1.tsym.type.getTypeArguments(); 3485 3486 while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) { 3487 if (containsType(act1.head, act2.head)) { 3488 merged.append(act1.head); 3489 } else if (containsType(act2.head, act1.head)) { 3490 merged.append(act2.head); 3491 } else { 3492 TypePair pair = new TypePair(c1, c2); 3493 Type m; 3494 if (mergeCache.add(pair)) { 3495 m = new WildcardType(lub(wildUpperBound(act1.head), 3496 wildUpperBound(act2.head)), 3497 BoundKind.EXTENDS, 3498 syms.boundClass); 3499 mergeCache.remove(pair); 3500 } else { 3501 m = new WildcardType(syms.objectType, 3502 BoundKind.UNBOUND, 3503 syms.boundClass); 3504 } 3505 merged.append(m.withTypeVar(typarams.head)); 3506 } 3507 act1 = act1.tail; 3508 act2 = act2.tail; 3509 typarams = typarams.tail; 3510 } 3511 Assert.check(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty()); 3512 // There is no spec detailing how type annotations are to 3513 // be inherited. So set it to noAnnotations for now 3514 return new ClassType(class1.getEnclosingType(), merged.toList(), 3515 class1.tsym); 3516 } 3517 3518 /** 3519 * Return the minimum type of a closure, a compound type if no 3520 * unique minimum exists. 3521 */ 3522 private Type compoundMin(List<Type> cl) { 3523 if (cl.isEmpty()) return syms.objectType; 3524 List<Type> compound = closureMin(cl); 3525 if (compound.isEmpty()) 3526 return null; 3527 else if (compound.tail.isEmpty()) 3528 return compound.head; 3529 else 3530 return makeIntersectionType(compound); 3531 } 3532 3533 /** 3534 * Return the minimum types of a closure, suitable for computing 3535 * compoundMin or glb. 3536 */ 3537 private List<Type> closureMin(List<Type> cl) { 3538 ListBuffer<Type> classes = new ListBuffer<>(); 3539 ListBuffer<Type> interfaces = new ListBuffer<>(); 3540 Set<Type> toSkip = new HashSet<>(); 3541 while (!cl.isEmpty()) { 3542 Type current = cl.head; 3543 boolean keep = !toSkip.contains(current); 3544 if (keep && current.hasTag(TYPEVAR)) { 3545 // skip lower-bounded variables with a subtype in cl.tail 3546 for (Type t : cl.tail) { 3547 if (isSubtypeNoCapture(t, current)) { 3548 keep = false; 3549 break; 3550 } 3551 } 3552 } 3553 if (keep) { 3554 if (current.isInterface()) 3555 interfaces.append(current); 3556 else 3557 classes.append(current); 3558 for (Type t : cl.tail) { 3559 // skip supertypes of 'current' in cl.tail 3560 if (isSubtypeNoCapture(current, t)) 3561 toSkip.add(t); 3562 } 3563 } 3564 cl = cl.tail; 3565 } 3566 return classes.appendList(interfaces).toList(); 3567 } 3568 3569 /** 3570 * Return the least upper bound of list of types. if the lub does 3571 * not exist return null. 3572 */ 3573 public Type lub(List<Type> ts) { 3574 return lub(ts.toArray(new Type[ts.length()])); 3575 } 3576 3577 /** 3578 * Return the least upper bound (lub) of set of types. If the lub 3579 * does not exist return the type of null (bottom). 3580 */ 3581 public Type lub(Type... ts) { 3582 final int UNKNOWN_BOUND = 0; 3583 final int ARRAY_BOUND = 1; 3584 final int CLASS_BOUND = 2; 3585 3586 int[] kinds = new int[ts.length]; 3587 3588 int boundkind = UNKNOWN_BOUND; 3589 for (int i = 0 ; i < ts.length ; i++) { 3590 Type t = ts[i]; 3591 switch (t.getTag()) { 3592 case CLASS: 3593 boundkind |= kinds[i] = CLASS_BOUND; 3594 break; 3595 case ARRAY: 3596 boundkind |= kinds[i] = ARRAY_BOUND; 3597 break; 3598 case TYPEVAR: 3599 do { 3600 t = t.getUpperBound(); 3601 } while (t.hasTag(TYPEVAR)); 3602 if (t.hasTag(ARRAY)) { 3603 boundkind |= kinds[i] = ARRAY_BOUND; 3604 } else { 3605 boundkind |= kinds[i] = CLASS_BOUND; 3606 } 3607 break; 3608 default: 3609 kinds[i] = UNKNOWN_BOUND; 3610 if (t.isPrimitive()) 3611 return syms.errType; 3612 } 3613 } 3614 switch (boundkind) { 3615 case 0: 3616 return syms.botType; 3617 3618 case ARRAY_BOUND: 3619 // calculate lub(A[], B[]) 3620 Type[] elements = new Type[ts.length]; 3621 for (int i = 0 ; i < ts.length ; i++) { 3622 Type elem = elements[i] = elemTypeFun.apply(ts[i]); 3623 if (elem.isPrimitive()) { 3624 // if a primitive type is found, then return 3625 // arraySuperType unless all the types are the 3626 // same 3627 Type first = ts[0]; 3628 for (int j = 1 ; j < ts.length ; j++) { 3629 if (!isSameType(first, ts[j])) { 3630 // lub(int[], B[]) is Cloneable & Serializable 3631 return arraySuperType(); 3632 } 3633 } 3634 // all the array types are the same, return one 3635 // lub(int[], int[]) is int[] 3636 return first; 3637 } 3638 } 3639 // lub(A[], B[]) is lub(A, B)[] 3640 return new ArrayType(lub(elements), syms.arrayClass); 3641 3642 case CLASS_BOUND: 3643 // calculate lub(A, B) 3644 int startIdx = 0; 3645 for (int i = 0; i < ts.length ; i++) { 3646 Type t = ts[i]; 3647 if (t.hasTag(CLASS) || t.hasTag(TYPEVAR)) { 3648 break; 3649 } else { 3650 startIdx++; 3651 } 3652 } 3653 Assert.check(startIdx < ts.length); 3654 //step 1 - compute erased candidate set (EC) 3655 List<Type> cl = erasedSupertypes(ts[startIdx]); 3656 for (int i = startIdx + 1 ; i < ts.length ; i++) { 3657 Type t = ts[i]; 3658 if (t.hasTag(CLASS) || t.hasTag(TYPEVAR)) 3659 cl = intersect(cl, erasedSupertypes(t)); 3660 } 3661 //step 2 - compute minimal erased candidate set (MEC) 3662 List<Type> mec = closureMin(cl); 3663 //step 3 - for each element G in MEC, compute lci(Inv(G)) 3664 List<Type> candidates = List.nil(); 3665 for (Type erasedSupertype : mec) { 3666 List<Type> lci = List.of(asSuper(ts[startIdx], erasedSupertype.tsym)); 3667 for (int i = startIdx + 1 ; i < ts.length ; i++) { 3668 Type superType = asSuper(ts[i], erasedSupertype.tsym); 3669 lci = intersect(lci, superType != null ? List.of(superType) : List.<Type>nil()); 3670 } 3671 candidates = candidates.appendList(lci); 3672 } 3673 //step 4 - let MEC be { G1, G2 ... Gn }, then we have that 3674 //lub = lci(Inv(G1)) & lci(Inv(G2)) & ... & lci(Inv(Gn)) 3675 return compoundMin(candidates); 3676 3677 default: 3678 // calculate lub(A, B[]) 3679 List<Type> classes = List.of(arraySuperType()); 3680 for (int i = 0 ; i < ts.length ; i++) { 3681 if (kinds[i] != ARRAY_BOUND) // Filter out any arrays 3682 classes = classes.prepend(ts[i]); 3683 } 3684 // lub(A, B[]) is lub(A, arraySuperType) 3685 return lub(classes); 3686 } 3687 } 3688 // where 3689 List<Type> erasedSupertypes(Type t) { 3690 ListBuffer<Type> buf = new ListBuffer<>(); 3691 for (Type sup : closure(t)) { 3692 if (sup.hasTag(TYPEVAR)) { 3693 buf.append(sup); 3694 } else { 3695 buf.append(erasure(sup)); 3696 } 3697 } 3698 return buf.toList(); 3699 } 3700 3701 private Type arraySuperType = null; 3702 private Type arraySuperType() { 3703 // initialized lazily to avoid problems during compiler startup 3704 if (arraySuperType == null) { 3705 synchronized (this) { 3706 if (arraySuperType == null) { 3707 // JLS 10.8: all arrays implement Cloneable and Serializable. 3708 arraySuperType = makeIntersectionType(List.of(syms.serializableType, 3709 syms.cloneableType), true); 3710 } 3711 } 3712 } 3713 return arraySuperType; 3714 } 3715 // </editor-fold> 3716 3717 // <editor-fold defaultstate="collapsed" desc="Greatest lower bound"> 3718 public Type glb(List<Type> ts) { 3719 Type t1 = ts.head; 3720 for (Type t2 : ts.tail) { 3721 if (t1.isErroneous()) 3722 return t1; 3723 t1 = glb(t1, t2); 3724 } 3725 return t1; 3726 } 3727 //where 3728 public Type glb(Type t, Type s) { 3729 if (s == null) 3730 return t; 3731 else if (t.isPrimitive() || s.isPrimitive()) 3732 return syms.errType; 3733 else if (isSubtypeNoCapture(t, s)) 3734 return t; 3735 else if (isSubtypeNoCapture(s, t)) 3736 return s; 3737 3738 List<Type> closure = union(closure(t), closure(s)); 3739 return glbFlattened(closure, t); 3740 } 3741 //where 3742 /** 3743 * Perform glb for a list of non-primitive, non-error, non-compound types; 3744 * redundant elements are removed. Bounds should be ordered according to 3745 * {@link Symbol#precedes(TypeSymbol,Types)}. 3746 * 3747 * @param flatBounds List of type to glb 3748 * @param errT Original type to use if the result is an error type 3749 */ 3750 private Type glbFlattened(List<Type> flatBounds, Type errT) { 3751 List<Type> bounds = closureMin(flatBounds); 3752 3753 if (bounds.isEmpty()) { // length == 0 3754 return syms.objectType; 3755 } else if (bounds.tail.isEmpty()) { // length == 1 3756 return bounds.head; 3757 } else { // length > 1 3758 int classCount = 0; 3759 List<Type> lowers = List.nil(); 3760 for (Type bound : bounds) { 3761 if (!bound.isInterface()) { 3762 classCount++; 3763 Type lower = cvarLowerBound(bound); 3764 if (bound != lower && !lower.hasTag(BOT)) 3765 lowers = insert(lowers, lower); 3766 } 3767 } 3768 if (classCount > 1) { 3769 if (lowers.isEmpty()) 3770 return createErrorType(errT); 3771 else 3772 return glbFlattened(union(bounds, lowers), errT); 3773 } 3774 } 3775 return makeIntersectionType(bounds); 3776 } 3777 // </editor-fold> 3778 3779 // <editor-fold defaultstate="collapsed" desc="hashCode"> 3780 /** 3781 * Compute a hash code on a type. 3782 */ 3783 public int hashCode(Type t) { 3784 return hashCode.visit(t); 3785 } 3786 // where 3787 private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() { 3788 3789 public Integer visitType(Type t, Void ignored) { 3790 return t.getTag().ordinal(); 3791 } 3792 3793 @Override 3794 public Integer visitClassType(ClassType t, Void ignored) { 3795 int result = visit(t.getEnclosingType()); 3796 result *= 127; 3797 result += t.tsym.flatName().hashCode(); 3798 for (Type s : t.getTypeArguments()) { 3799 result *= 127; 3800 result += visit(s); 3801 } 3802 return result; 3803 } 3804 3805 @Override 3806 public Integer visitMethodType(MethodType t, Void ignored) { 3807 int h = METHOD.ordinal(); 3808 for (List<Type> thisargs = t.argtypes; 3809 thisargs.tail != null; 3810 thisargs = thisargs.tail) 3811 h = (h << 5) + visit(thisargs.head); 3812 return (h << 5) + visit(t.restype); 3813 } 3814 3815 @Override 3816 public Integer visitWildcardType(WildcardType t, Void ignored) { 3817 int result = t.kind.hashCode(); 3818 if (t.type != null) { 3819 result *= 127; 3820 result += visit(t.type); 3821 } 3822 return result; 3823 } 3824 3825 @Override 3826 public Integer visitArrayType(ArrayType t, Void ignored) { 3827 return visit(t.elemtype) + 12; 3828 } 3829 3830 @Override 3831 public Integer visitTypeVar(TypeVar t, Void ignored) { 3832 return System.identityHashCode(t.tsym); 3833 } 3834 3835 @Override 3836 public Integer visitUndetVar(UndetVar t, Void ignored) { 3837 return System.identityHashCode(t); 3838 } 3839 3840 @Override 3841 public Integer visitErrorType(ErrorType t, Void ignored) { 3842 return 0; 3843 } 3844 }; 3845 // </editor-fold> 3846 3847 // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable"> 3848 /** 3849 * Does t have a result that is a subtype of the result type of s, 3850 * suitable for covariant returns? It is assumed that both types 3851 * are (possibly polymorphic) method types. Monomorphic method 3852 * types are handled in the obvious way. Polymorphic method types 3853 * require renaming all type variables of one to corresponding 3854 * type variables in the other, where correspondence is by 3855 * position in the type parameter list. */ 3856 public boolean resultSubtype(Type t, Type s, Warner warner) { 3857 List<Type> tvars = t.getTypeArguments(); 3858 List<Type> svars = s.getTypeArguments(); 3859 Type tres = t.getReturnType(); 3860 Type sres = subst(s.getReturnType(), svars, tvars); 3861 return covariantReturnType(tres, sres, warner); 3862 } 3863 3864 /** 3865 * Return-Type-Substitutable. 3866 * @jls section 8.4.5 3867 */ 3868 public boolean returnTypeSubstitutable(Type r1, Type r2) { 3869 if (hasSameArgs(r1, r2)) 3870 return resultSubtype(r1, r2, noWarnings); 3871 else 3872 return covariantReturnType(r1.getReturnType(), 3873 erasure(r2.getReturnType()), 3874 noWarnings); 3875 } 3876 3877 public boolean returnTypeSubstitutable(Type r1, 3878 Type r2, Type r2res, 3879 Warner warner) { 3880 if (isSameType(r1.getReturnType(), r2res)) 3881 return true; 3882 if (r1.getReturnType().isPrimitive() || r2res.isPrimitive()) 3883 return false; 3884 3885 if (hasSameArgs(r1, r2)) 3886 return covariantReturnType(r1.getReturnType(), r2res, warner); 3887 if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner)) 3888 return true; 3889 if (!isSubtype(r1.getReturnType(), erasure(r2res))) 3890 return false; 3891 warner.warn(LintCategory.UNCHECKED); 3892 return true; 3893 } 3894 3895 /** 3896 * Is t an appropriate return type in an overrider for a 3897 * method that returns s? 3898 */ 3899 public boolean covariantReturnType(Type t, Type s, Warner warner) { 3900 return 3901 isSameType(t, s) || 3902 !t.isPrimitive() && 3903 !s.isPrimitive() && 3904 isAssignable(t, s, warner); 3905 } 3906 // </editor-fold> 3907 3908 // <editor-fold defaultstate="collapsed" desc="Box/unbox support"> 3909 /** 3910 * Return the class that boxes the given primitive. 3911 */ 3912 public ClassSymbol boxedClass(Type t) { 3913 return syms.enterClass(syms.boxedName[t.getTag().ordinal()]); 3914 } 3915 3916 /** 3917 * Return the boxed type if 't' is primitive, otherwise return 't' itself. 3918 */ 3919 public Type boxedTypeOrType(Type t) { 3920 return t.isPrimitive() ? 3921 boxedClass(t).type : 3922 t; 3923 } 3924 3925 /** 3926 * Return the primitive type corresponding to a boxed type. 3927 */ 3928 public Type unboxedType(Type t) { 3929 for (int i=0; i<syms.boxedName.length; i++) { 3930 Name box = syms.boxedName[i]; 3931 if (box != null && 3932 asSuper(t, syms.enterClass(box)) != null) 3933 return syms.typeOfTag[i]; 3934 } 3935 return Type.noType; 3936 } 3937 3938 /** 3939 * Return the unboxed type if 't' is a boxed class, otherwise return 't' itself. 3940 */ 3941 public Type unboxedTypeOrType(Type t) { 3942 Type unboxedType = unboxedType(t); 3943 return unboxedType.hasTag(NONE) ? t : unboxedType; 3944 } 3945 // </editor-fold> 3946 3947 // <editor-fold defaultstate="collapsed" desc="Capture conversion"> 3948 /* 3949 * JLS 5.1.10 Capture Conversion: 3950 * 3951 * Let G name a generic type declaration with n formal type 3952 * parameters A1 ... An with corresponding bounds U1 ... Un. There 3953 * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>, 3954 * where, for 1 <= i <= n: 3955 * 3956 * + If Ti is a wildcard type argument (4.5.1) of the form ? then 3957 * Si is a fresh type variable whose upper bound is 3958 * Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null 3959 * type. 3960 * 3961 * + If Ti is a wildcard type argument of the form ? extends Bi, 3962 * then Si is a fresh type variable whose upper bound is 3963 * glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is 3964 * the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is 3965 * a compile-time error if for any two classes (not interfaces) 3966 * Vi and Vj,Vi is not a subclass of Vj or vice versa. 3967 * 3968 * + If Ti is a wildcard type argument of the form ? super Bi, 3969 * then Si is a fresh type variable whose upper bound is 3970 * Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi. 3971 * 3972 * + Otherwise, Si = Ti. 3973 * 3974 * Capture conversion on any type other than a parameterized type 3975 * (4.5) acts as an identity conversion (5.1.1). Capture 3976 * conversions never require a special action at run time and 3977 * therefore never throw an exception at run time. 3978 * 3979 * Capture conversion is not applied recursively. 3980 */ 3981 /** 3982 * Capture conversion as specified by the JLS. 3983 */ 3984 3985 public List<Type> capture(List<Type> ts) { 3986 List<Type> buf = List.nil(); 3987 for (Type t : ts) { 3988 buf = buf.prepend(capture(t)); 3989 } 3990 return buf.reverse(); 3991 } 3992 3993 public Type capture(Type t) { 3994 if (!t.hasTag(CLASS)) { 3995 return t; 3996 } 3997 if (t.getEnclosingType() != Type.noType) { 3998 Type capturedEncl = capture(t.getEnclosingType()); 3999 if (capturedEncl != t.getEnclosingType()) { 4000 Type type1 = memberType(capturedEncl, t.tsym); 4001 t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments()); 4002 } 4003 } 4004 ClassType cls = (ClassType)t; 4005 if (cls.isRaw() || !cls.isParameterized()) 4006 return cls; 4007 4008 ClassType G = (ClassType)cls.asElement().asType(); 4009 List<Type> A = G.getTypeArguments(); 4010 List<Type> T = cls.getTypeArguments(); 4011 List<Type> S = freshTypeVariables(T); 4012 4013 List<Type> currentA = A; 4014 List<Type> currentT = T; 4015 List<Type> currentS = S; 4016 boolean captured = false; 4017 while (!currentA.isEmpty() && 4018 !currentT.isEmpty() && 4019 !currentS.isEmpty()) { 4020 if (currentS.head != currentT.head) { 4021 captured = true; 4022 WildcardType Ti = (WildcardType)currentT.head; 4023 Type Ui = currentA.head.getUpperBound(); 4024 CapturedType Si = (CapturedType)currentS.head; 4025 if (Ui == null) 4026 Ui = syms.objectType; 4027 switch (Ti.kind) { 4028 case UNBOUND: 4029 Si.bound = subst(Ui, A, S); 4030 Si.lower = syms.botType; 4031 break; 4032 case EXTENDS: 4033 Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S)); 4034 Si.lower = syms.botType; 4035 break; 4036 case SUPER: 4037 Si.bound = subst(Ui, A, S); 4038 Si.lower = Ti.getSuperBound(); 4039 break; 4040 } 4041 Type tmpBound = Si.bound.hasTag(UNDETVAR) ? ((UndetVar)Si.bound).qtype : Si.bound; 4042 Type tmpLower = Si.lower.hasTag(UNDETVAR) ? ((UndetVar)Si.lower).qtype : Si.lower; 4043 if (!Si.bound.hasTag(ERROR) && 4044 !Si.lower.hasTag(ERROR) && 4045 isSameType(tmpBound, tmpLower, false)) { 4046 currentS.head = Si.bound; 4047 } 4048 } 4049 currentA = currentA.tail; 4050 currentT = currentT.tail; 4051 currentS = currentS.tail; 4052 } 4053 if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty()) 4054 return erasure(t); // some "rare" type involved 4055 4056 if (captured) 4057 return new ClassType(cls.getEnclosingType(), S, cls.tsym, 4058 cls.getMetadata()); 4059 else 4060 return t; 4061 } 4062 // where 4063 public List<Type> freshTypeVariables(List<Type> types) { 4064 ListBuffer<Type> result = new ListBuffer<>(); 4065 for (Type t : types) { 4066 if (t.hasTag(WILDCARD)) { 4067 Type bound = ((WildcardType)t).getExtendsBound(); 4068 if (bound == null) 4069 bound = syms.objectType; 4070 result.append(new CapturedType(capturedName, 4071 syms.noSymbol, 4072 bound, 4073 syms.botType, 4074 (WildcardType)t)); 4075 } else { 4076 result.append(t); 4077 } 4078 } 4079 return result.toList(); 4080 } 4081 // </editor-fold> 4082 4083 // <editor-fold defaultstate="collapsed" desc="Internal utility methods"> 4084 private boolean sideCast(Type from, Type to, Warner warn) { 4085 // We are casting from type $from$ to type $to$, which are 4086 // non-final unrelated types. This method 4087 // tries to reject a cast by transferring type parameters 4088 // from $to$ to $from$ by common superinterfaces. 4089 boolean reverse = false; 4090 Type target = to; 4091 if ((to.tsym.flags() & INTERFACE) == 0) { 4092 Assert.check((from.tsym.flags() & INTERFACE) != 0); 4093 reverse = true; 4094 to = from; 4095 from = target; 4096 } 4097 List<Type> commonSupers = superClosure(to, erasure(from)); 4098 boolean giveWarning = commonSupers.isEmpty(); 4099 // The arguments to the supers could be unified here to 4100 // get a more accurate analysis 4101 while (commonSupers.nonEmpty()) { 4102 Type t1 = asSuper(from, commonSupers.head.tsym); 4103 Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym); 4104 if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments())) 4105 return false; 4106 giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)); 4107 commonSupers = commonSupers.tail; 4108 } 4109 if (giveWarning && !isReifiable(reverse ? from : to)) 4110 warn.warn(LintCategory.UNCHECKED); 4111 return true; 4112 } 4113 4114 private boolean sideCastFinal(Type from, Type to, Warner warn) { 4115 // We are casting from type $from$ to type $to$, which are 4116 // unrelated types one of which is final and the other of 4117 // which is an interface. This method 4118 // tries to reject a cast by transferring type parameters 4119 // from the final class to the interface. 4120 boolean reverse = false; 4121 Type target = to; 4122 if ((to.tsym.flags() & INTERFACE) == 0) { 4123 Assert.check((from.tsym.flags() & INTERFACE) != 0); 4124 reverse = true; 4125 to = from; 4126 from = target; 4127 } 4128 Assert.check((from.tsym.flags() & FINAL) != 0); 4129 Type t1 = asSuper(from, to.tsym); 4130 if (t1 == null) return false; 4131 Type t2 = to; 4132 if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments())) 4133 return false; 4134 if (!isReifiable(target) && 4135 (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2))) 4136 warn.warn(LintCategory.UNCHECKED); 4137 return true; 4138 } 4139 4140 private boolean giveWarning(Type from, Type to) { 4141 List<Type> bounds = to.isCompound() ? 4142 ((IntersectionClassType)to).getComponents() : List.of(to); 4143 for (Type b : bounds) { 4144 Type subFrom = asSub(from, b.tsym); 4145 if (b.isParameterized() && 4146 (!(isUnbounded(b) || 4147 isSubtype(from, b) || 4148 ((subFrom != null) && containsType(b.allparams(), subFrom.allparams()))))) { 4149 return true; 4150 } 4151 } 4152 return false; 4153 } 4154 4155 private List<Type> superClosure(Type t, Type s) { 4156 List<Type> cl = List.nil(); 4157 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) { 4158 if (isSubtype(s, erasure(l.head))) { 4159 cl = insert(cl, l.head); 4160 } else { 4161 cl = union(cl, superClosure(l.head, s)); 4162 } 4163 } 4164 return cl; 4165 } 4166 4167 private boolean containsTypeEquivalent(Type t, Type s) { 4168 return isSameType(t, s) || // shortcut 4169 containsType(t, s) && containsType(s, t); 4170 } 4171 4172 // <editor-fold defaultstate="collapsed" desc="adapt"> 4173 /** 4174 * Adapt a type by computing a substitution which maps a source 4175 * type to a target type. 4176 * 4177 * @param source the source type 4178 * @param target the target type 4179 * @param from the type variables of the computed substitution 4180 * @param to the types of the computed substitution. 4181 */ 4182 public void adapt(Type source, 4183 Type target, 4184 ListBuffer<Type> from, 4185 ListBuffer<Type> to) throws AdaptFailure { 4186 new Adapter(from, to).adapt(source, target); 4187 } 4188 4189 class Adapter extends SimpleVisitor<Void, Type> { 4190 4191 ListBuffer<Type> from; 4192 ListBuffer<Type> to; 4193 Map<Symbol,Type> mapping; 4194 4195 Adapter(ListBuffer<Type> from, ListBuffer<Type> to) { 4196 this.from = from; 4197 this.to = to; 4198 mapping = new HashMap<>(); 4199 } 4200 4201 public void adapt(Type source, Type target) throws AdaptFailure { 4202 visit(source, target); 4203 List<Type> fromList = from.toList(); 4204 List<Type> toList = to.toList(); 4205 while (!fromList.isEmpty()) { 4206 Type val = mapping.get(fromList.head.tsym); 4207 if (toList.head != val) 4208 toList.head = val; 4209 fromList = fromList.tail; 4210 toList = toList.tail; 4211 } 4212 } 4213 4214 @Override 4215 public Void visitClassType(ClassType source, Type target) throws AdaptFailure { 4216 if (target.hasTag(CLASS)) 4217 adaptRecursive(source.allparams(), target.allparams()); 4218 return null; 4219 } 4220 4221 @Override 4222 public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure { 4223 if (target.hasTag(ARRAY)) 4224 adaptRecursive(elemtype(source), elemtype(target)); 4225 return null; 4226 } 4227 4228 @Override 4229 public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure { 4230 if (source.isExtendsBound()) 4231 adaptRecursive(wildUpperBound(source), wildUpperBound(target)); 4232 else if (source.isSuperBound()) 4233 adaptRecursive(wildLowerBound(source), wildLowerBound(target)); 4234 return null; 4235 } 4236 4237 @Override 4238 public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure { 4239 // Check to see if there is 4240 // already a mapping for $source$, in which case 4241 // the old mapping will be merged with the new 4242 Type val = mapping.get(source.tsym); 4243 if (val != null) { 4244 if (val.isSuperBound() && target.isSuperBound()) { 4245 val = isSubtype(wildLowerBound(val), wildLowerBound(target)) 4246 ? target : val; 4247 } else if (val.isExtendsBound() && target.isExtendsBound()) { 4248 val = isSubtype(wildUpperBound(val), wildUpperBound(target)) 4249 ? val : target; 4250 } else if (!isSameType(val, target)) { 4251 throw new AdaptFailure(); 4252 } 4253 } else { 4254 val = target; 4255 from.append(source); 4256 to.append(target); 4257 } 4258 mapping.put(source.tsym, val); 4259 return null; 4260 } 4261 4262 @Override 4263 public Void visitType(Type source, Type target) { 4264 return null; 4265 } 4266 4267 private Set<TypePair> cache = new HashSet<>(); 4268 4269 private void adaptRecursive(Type source, Type target) { 4270 TypePair pair = new TypePair(source, target); 4271 if (cache.add(pair)) { 4272 try { 4273 visit(source, target); 4274 } finally { 4275 cache.remove(pair); 4276 } 4277 } 4278 } 4279 4280 private void adaptRecursive(List<Type> source, List<Type> target) { 4281 if (source.length() == target.length()) { 4282 while (source.nonEmpty()) { 4283 adaptRecursive(source.head, target.head); 4284 source = source.tail; 4285 target = target.tail; 4286 } 4287 } 4288 } 4289 } 4290 4291 public static class AdaptFailure extends RuntimeException { 4292 static final long serialVersionUID = -7490231548272701566L; 4293 } 4294 4295 private void adaptSelf(Type t, 4296 ListBuffer<Type> from, 4297 ListBuffer<Type> to) { 4298 try { 4299 //if (t.tsym.type != t) 4300 adapt(t.tsym.type, t, from, to); 4301 } catch (AdaptFailure ex) { 4302 // Adapt should never fail calculating a mapping from 4303 // t.tsym.type to t as there can be no merge problem. 4304 throw new AssertionError(ex); 4305 } 4306 } 4307 // </editor-fold> 4308 4309 /** 4310 * Rewrite all type variables (universal quantifiers) in the given 4311 * type to wildcards (existential quantifiers). This is used to 4312 * determine if a cast is allowed. For example, if high is true 4313 * and {@code T <: Number}, then {@code List<T>} is rewritten to 4314 * {@code List<? extends Number>}. Since {@code List<Integer> <: 4315 * List<? extends Number>} a {@code List<T>} can be cast to {@code 4316 * List<Integer>} with a warning. 4317 * @param t a type 4318 * @param high if true return an upper bound; otherwise a lower 4319 * bound 4320 * @param rewriteTypeVars only rewrite captured wildcards if false; 4321 * otherwise rewrite all type variables 4322 * @return the type rewritten with wildcards (existential 4323 * quantifiers) only 4324 */ 4325 private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) { 4326 return new Rewriter(high, rewriteTypeVars).visit(t); 4327 } 4328 4329 class Rewriter extends UnaryVisitor<Type> { 4330 4331 boolean high; 4332 boolean rewriteTypeVars; 4333 4334 Rewriter(boolean high, boolean rewriteTypeVars) { 4335 this.high = high; 4336 this.rewriteTypeVars = rewriteTypeVars; 4337 } 4338 4339 @Override 4340 public Type visitClassType(ClassType t, Void s) { 4341 ListBuffer<Type> rewritten = new ListBuffer<>(); 4342 boolean changed = false; 4343 for (Type arg : t.allparams()) { 4344 Type bound = visit(arg); 4345 if (arg != bound) { 4346 changed = true; 4347 } 4348 rewritten.append(bound); 4349 } 4350 if (changed) 4351 return subst(t.tsym.type, 4352 t.tsym.type.allparams(), 4353 rewritten.toList()); 4354 else 4355 return t; 4356 } 4357 4358 public Type visitType(Type t, Void s) { 4359 return t; 4360 } 4361 4362 @Override 4363 public Type visitCapturedType(CapturedType t, Void s) { 4364 Type w_bound = t.wildcard.type; 4365 Type bound = w_bound.contains(t) ? 4366 erasure(w_bound) : 4367 visit(w_bound); 4368 return rewriteAsWildcardType(visit(bound), t.wildcard.bound, t.wildcard.kind); 4369 } 4370 4371 @Override 4372 public Type visitTypeVar(TypeVar t, Void s) { 4373 if (rewriteTypeVars) { 4374 Type bound = t.bound.contains(t) ? 4375 erasure(t.bound) : 4376 visit(t.bound); 4377 return rewriteAsWildcardType(bound, t, EXTENDS); 4378 } else { 4379 return t; 4380 } 4381 } 4382 4383 @Override 4384 public Type visitWildcardType(WildcardType t, Void s) { 4385 Type bound2 = visit(t.type); 4386 return t.type == bound2 ? t : rewriteAsWildcardType(bound2, t.bound, t.kind); 4387 } 4388 4389 private Type rewriteAsWildcardType(Type bound, TypeVar formal, BoundKind bk) { 4390 switch (bk) { 4391 case EXTENDS: return high ? 4392 makeExtendsWildcard(B(bound), formal) : 4393 makeExtendsWildcard(syms.objectType, formal); 4394 case SUPER: return high ? 4395 makeSuperWildcard(syms.botType, formal) : 4396 makeSuperWildcard(B(bound), formal); 4397 case UNBOUND: return makeExtendsWildcard(syms.objectType, formal); 4398 default: 4399 Assert.error("Invalid bound kind " + bk); 4400 return null; 4401 } 4402 } 4403 4404 Type B(Type t) { 4405 while (t.hasTag(WILDCARD)) { 4406 WildcardType w = (WildcardType)t; 4407 t = high ? 4408 w.getExtendsBound() : 4409 w.getSuperBound(); 4410 if (t == null) { 4411 t = high ? syms.objectType : syms.botType; 4412 } 4413 } 4414 return t; 4415 } 4416 } 4417 4418 4419 /** 4420 * Create a wildcard with the given upper (extends) bound; create 4421 * an unbounded wildcard if bound is Object. 4422 * 4423 * @param bound the upper bound 4424 * @param formal the formal type parameter that will be 4425 * substituted by the wildcard 4426 */ 4427 private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) { 4428 if (bound == syms.objectType) { 4429 return new WildcardType(syms.objectType, 4430 BoundKind.UNBOUND, 4431 syms.boundClass, 4432 formal); 4433 } else { 4434 return new WildcardType(bound, 4435 BoundKind.EXTENDS, 4436 syms.boundClass, 4437 formal); 4438 } 4439 } 4440 4441 /** 4442 * Create a wildcard with the given lower (super) bound; create an 4443 * unbounded wildcard if bound is bottom (type of {@code null}). 4444 * 4445 * @param bound the lower bound 4446 * @param formal the formal type parameter that will be 4447 * substituted by the wildcard 4448 */ 4449 private WildcardType makeSuperWildcard(Type bound, TypeVar formal) { 4450 if (bound.hasTag(BOT)) { 4451 return new WildcardType(syms.objectType, 4452 BoundKind.UNBOUND, 4453 syms.boundClass, 4454 formal); 4455 } else { 4456 return new WildcardType(bound, 4457 BoundKind.SUPER, 4458 syms.boundClass, 4459 formal); 4460 } 4461 } 4462 4463 /** 4464 * A wrapper for a type that allows use in sets. 4465 */ 4466 public static class UniqueType { 4467 public final Type type; 4468 final Types types; 4469 4470 public UniqueType(Type type, Types types) { 4471 this.type = type; 4472 this.types = types; 4473 } 4474 4475 public int hashCode() { 4476 return types.hashCode(type); 4477 } 4478 4479 public boolean equals(Object obj) { 4480 return (obj instanceof UniqueType) && 4481 types.isSameType(type, ((UniqueType)obj).type); 4482 } 4483 4484 public String toString() { 4485 return type.toString(); 4486 } 4487 4488 } 4489 // </editor-fold> 4490 4491 // <editor-fold defaultstate="collapsed" desc="Visitors"> 4492 /** 4493 * A default visitor for types. All visitor methods except 4494 * visitType are implemented by delegating to visitType. Concrete 4495 * subclasses must provide an implementation of visitType and can 4496 * override other methods as needed. 4497 * 4498 * @param <R> the return type of the operation implemented by this 4499 * visitor; use Void if no return type is needed. 4500 * @param <S> the type of the second argument (the first being the 4501 * type itself) of the operation implemented by this visitor; use 4502 * Void if a second argument is not needed. 4503 */ 4504 public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> { 4505 final public R visit(Type t, S s) { return t.accept(this, s); } 4506 public R visitClassType(ClassType t, S s) { return visitType(t, s); } 4507 public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); } 4508 public R visitArrayType(ArrayType t, S s) { return visitType(t, s); } 4509 public R visitMethodType(MethodType t, S s) { return visitType(t, s); } 4510 public R visitPackageType(PackageType t, S s) { return visitType(t, s); } 4511 public R visitTypeVar(TypeVar t, S s) { return visitType(t, s); } 4512 public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); } 4513 public R visitForAll(ForAll t, S s) { return visitType(t, s); } 4514 public R visitUndetVar(UndetVar t, S s) { return visitType(t, s); } 4515 public R visitErrorType(ErrorType t, S s) { return visitType(t, s); } 4516 } 4517 4518 /** 4519 * A default visitor for symbols. All visitor methods except 4520 * visitSymbol are implemented by delegating to visitSymbol. Concrete 4521 * subclasses must provide an implementation of visitSymbol and can 4522 * override other methods as needed. 4523 * 4524 * @param <R> the return type of the operation implemented by this 4525 * visitor; use Void if no return type is needed. 4526 * @param <S> the type of the second argument (the first being the 4527 * symbol itself) of the operation implemented by this visitor; use 4528 * Void if a second argument is not needed. 4529 */ 4530 public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> { 4531 final public R visit(Symbol s, S arg) { return s.accept(this, arg); } 4532 public R visitClassSymbol(ClassSymbol s, S arg) { return visitSymbol(s, arg); } 4533 public R visitMethodSymbol(MethodSymbol s, S arg) { return visitSymbol(s, arg); } 4534 public R visitOperatorSymbol(OperatorSymbol s, S arg) { return visitSymbol(s, arg); } 4535 public R visitPackageSymbol(PackageSymbol s, S arg) { return visitSymbol(s, arg); } 4536 public R visitTypeSymbol(TypeSymbol s, S arg) { return visitSymbol(s, arg); } 4537 public R visitVarSymbol(VarSymbol s, S arg) { return visitSymbol(s, arg); } 4538 } 4539 4540 /** 4541 * A <em>simple</em> visitor for types. This visitor is simple as 4542 * captured wildcards, for-all types (generic methods), and 4543 * undetermined type variables (part of inference) are hidden. 4544 * Captured wildcards are hidden by treating them as type 4545 * variables and the rest are hidden by visiting their qtypes. 4546 * 4547 * @param <R> the return type of the operation implemented by this 4548 * visitor; use Void if no return type is needed. 4549 * @param <S> the type of the second argument (the first being the 4550 * type itself) of the operation implemented by this visitor; use 4551 * Void if a second argument is not needed. 4552 */ 4553 public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> { 4554 @Override 4555 public R visitCapturedType(CapturedType t, S s) { 4556 return visitTypeVar(t, s); 4557 } 4558 @Override 4559 public R visitForAll(ForAll t, S s) { 4560 return visit(t.qtype, s); 4561 } 4562 @Override 4563 public R visitUndetVar(UndetVar t, S s) { 4564 return visit(t.qtype, s); 4565 } 4566 } 4567 4568 /** 4569 * A plain relation on types. That is a 2-ary function on the 4570 * form Type × Type → Boolean. 4571 * <!-- In plain text: Type x Type -> Boolean --> 4572 */ 4573 public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {} 4574 4575 /** 4576 * A convenience visitor for implementing operations that only 4577 * require one argument (the type itself), that is, unary 4578 * operations. 4579 * 4580 * @param <R> the return type of the operation implemented by this 4581 * visitor; use Void if no return type is needed. 4582 */ 4583 public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> { 4584 final public R visit(Type t) { return t.accept(this, null); } 4585 } 4586 4587 /** 4588 * A visitor for implementing a mapping from types to types. The 4589 * default behavior of this class is to implement the identity 4590 * mapping (mapping a type to itself). This can be overridden in 4591 * subclasses. 4592 * 4593 * @param <S> the type of the second argument (the first being the 4594 * type itself) of this mapping; use Void if a second argument is 4595 * not needed. 4596 */ 4597 public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> { 4598 final public Type visit(Type t) { return t.accept(this, null); } 4599 public Type visitType(Type t, S s) { return t; } 4600 } 4601 // </editor-fold> 4602 4603 4604 // <editor-fold defaultstate="collapsed" desc="Annotation support"> 4605 4606 public RetentionPolicy getRetention(Attribute.Compound a) { 4607 return getRetention(a.type.tsym); 4608 } 4609 4610 public RetentionPolicy getRetention(TypeSymbol sym) { 4611 RetentionPolicy vis = RetentionPolicy.CLASS; // the default 4612 Attribute.Compound c = sym.attribute(syms.retentionType.tsym); 4613 if (c != null) { 4614 Attribute value = c.member(names.value); 4615 if (value != null && value instanceof Attribute.Enum) { 4616 Name levelName = ((Attribute.Enum)value).value.name; 4617 if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE; 4618 else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS; 4619 else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME; 4620 else ;// /* fail soft */ throw new AssertionError(levelName); 4621 } 4622 } 4623 return vis; 4624 } 4625 // </editor-fold> 4626 4627 // <editor-fold defaultstate="collapsed" desc="Signature Generation"> 4628 4629 public static abstract class SignatureGenerator { 4630 4631 private final Types types; 4632 4633 protected abstract void append(char ch); 4634 protected abstract void append(byte[] ba); 4635 protected abstract void append(Name name); 4636 protected void classReference(ClassSymbol c) { /* by default: no-op */ } 4637 4638 protected SignatureGenerator(Types types) { 4639 this.types = types; 4640 } 4641 4642 /** 4643 * Assemble signature of given type in string buffer. 4644 */ 4645 public void assembleSig(Type type) { 4646 switch (type.getTag()) { 4647 case BYTE: 4648 append('B'); 4649 break; 4650 case SHORT: 4651 append('S'); 4652 break; 4653 case CHAR: 4654 append('C'); 4655 break; 4656 case INT: 4657 append('I'); 4658 break; 4659 case LONG: 4660 append('J'); 4661 break; 4662 case FLOAT: 4663 append('F'); 4664 break; 4665 case DOUBLE: 4666 append('D'); 4667 break; 4668 case BOOLEAN: 4669 append('Z'); 4670 break; 4671 case VOID: 4672 append('V'); 4673 break; 4674 case CLASS: 4675 append('L'); 4676 assembleClassSig(type); 4677 append(';'); 4678 break; 4679 case ARRAY: 4680 ArrayType at = (ArrayType) type; 4681 append('['); 4682 assembleSig(at.elemtype); 4683 break; 4684 case METHOD: 4685 MethodType mt = (MethodType) type; 4686 append('('); 4687 assembleSig(mt.argtypes); 4688 append(')'); 4689 assembleSig(mt.restype); 4690 if (hasTypeVar(mt.thrown)) { 4691 for (List<Type> l = mt.thrown; l.nonEmpty(); l = l.tail) { 4692 append('^'); 4693 assembleSig(l.head); 4694 } 4695 } 4696 break; 4697 case WILDCARD: { 4698 Type.WildcardType ta = (Type.WildcardType) type; 4699 switch (ta.kind) { 4700 case SUPER: 4701 append('-'); 4702 assembleSig(ta.type); 4703 break; 4704 case EXTENDS: 4705 append('+'); 4706 assembleSig(ta.type); 4707 break; 4708 case UNBOUND: 4709 append('*'); 4710 break; 4711 default: 4712 throw new AssertionError(ta.kind); 4713 } 4714 break; 4715 } 4716 case TYPEVAR: 4717 append('T'); 4718 append(type.tsym.name); 4719 append(';'); 4720 break; 4721 case FORALL: 4722 Type.ForAll ft = (Type.ForAll) type; 4723 assembleParamsSig(ft.tvars); 4724 assembleSig(ft.qtype); 4725 break; 4726 default: 4727 throw new AssertionError("typeSig " + type.getTag()); 4728 } 4729 } 4730 4731 public boolean hasTypeVar(List<Type> l) { 4732 while (l.nonEmpty()) { 4733 if (l.head.hasTag(TypeTag.TYPEVAR)) { 4734 return true; 4735 } 4736 l = l.tail; 4737 } 4738 return false; 4739 } 4740 4741 public void assembleClassSig(Type type) { 4742 ClassType ct = (ClassType) type; 4743 ClassSymbol c = (ClassSymbol) ct.tsym; 4744 classReference(c); 4745 Type outer = ct.getEnclosingType(); 4746 if (outer.allparams().nonEmpty()) { 4747 boolean rawOuter = 4748 c.owner.kind == MTH || // either a local class 4749 c.name == types.names.empty; // or anonymous 4750 assembleClassSig(rawOuter 4751 ? types.erasure(outer) 4752 : outer); 4753 append(rawOuter ? '$' : '.'); 4754 Assert.check(c.flatname.startsWith(c.owner.enclClass().flatname)); 4755 append(rawOuter 4756 ? c.flatname.subName(c.owner.enclClass().flatname.getByteLength() + 1, c.flatname.getByteLength()) 4757 : c.name); 4758 } else { 4759 append(externalize(c.flatname)); 4760 } 4761 if (ct.getTypeArguments().nonEmpty()) { 4762 append('<'); 4763 assembleSig(ct.getTypeArguments()); 4764 append('>'); 4765 } 4766 } 4767 4768 public void assembleParamsSig(List<Type> typarams) { 4769 append('<'); 4770 for (List<Type> ts = typarams; ts.nonEmpty(); ts = ts.tail) { 4771 Type.TypeVar tvar = (Type.TypeVar) ts.head; 4772 append(tvar.tsym.name); 4773 List<Type> bounds = types.getBounds(tvar); 4774 if ((bounds.head.tsym.flags() & INTERFACE) != 0) { 4775 append(':'); 4776 } 4777 for (List<Type> l = bounds; l.nonEmpty(); l = l.tail) { 4778 append(':'); 4779 assembleSig(l.head); 4780 } 4781 } 4782 append('>'); 4783 } 4784 4785 private void assembleSig(List<Type> types) { 4786 for (List<Type> ts = types; ts.nonEmpty(); ts = ts.tail) { 4787 assembleSig(ts.head); 4788 } 4789 } 4790 } 4791 // </editor-fold> 4792 4793 public void newRound() { 4794 descCache._map.clear(); 4795 isDerivedRawCache.clear(); 4796 implCache._map.clear(); 4797 membersCache._map.clear(); 4798 closureCache.clear(); 4799 } 4800} 4801