< prev index next >

src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java

Print this page

  36 import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
  37 import com.sun.tools.javac.comp.DeferredAttr.DeferredAttrContext;
  38 import com.sun.tools.javac.comp.DeferredAttr.DeferredType;
  39 import com.sun.tools.javac.comp.Resolve.MethodResolutionContext.Candidate;
  40 import com.sun.tools.javac.comp.Resolve.MethodResolutionDiagHelper.Template;
  41 import com.sun.tools.javac.comp.Resolve.ReferenceLookupResult.StaticKind;
  42 import com.sun.tools.javac.jvm.*;
  43 import com.sun.tools.javac.main.Option;
  44 import com.sun.tools.javac.resources.CompilerProperties.Errors;
  45 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
  46 import com.sun.tools.javac.resources.CompilerProperties.Warnings;
  47 import com.sun.tools.javac.tree.*;
  48 import com.sun.tools.javac.tree.JCTree.*;
  49 import com.sun.tools.javac.tree.JCTree.JCMemberReference.ReferenceKind;
  50 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
  51 import com.sun.tools.javac.util.*;
  52 import com.sun.tools.javac.util.DefinedBy.Api;
  53 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
  54 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
  55 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType;
  56 import com.sun.tools.javac.util.JCDiagnostic.Warning;
  57 
  58 import java.util.Arrays;
  59 import java.util.Collection;
  60 import java.util.EnumSet;
  61 import java.util.HashSet;
  62 import java.util.Iterator;
  63 import java.util.LinkedHashMap;
  64 import java.util.Map;
  65 import java.util.Set;
  66 import java.util.function.BiFunction;
  67 import java.util.function.BiPredicate;
  68 import java.util.function.Consumer;
  69 import java.util.function.Function;
  70 import java.util.function.Predicate;
  71 import java.util.function.UnaryOperator;
  72 import java.util.stream.Stream;
  73 import java.util.stream.StreamSupport;
  74 
  75 import javax.lang.model.element.ElementVisitor;
  76 
  77 import static com.sun.tools.javac.code.Flags.*;
  78 import static com.sun.tools.javac.code.Flags.BLOCK;
  79 import static com.sun.tools.javac.code.Flags.STATIC;
  80 import static com.sun.tools.javac.code.Kinds.*;
  81 import static com.sun.tools.javac.code.Kinds.Kind.*;
  82 import static com.sun.tools.javac.code.TypeTag.*;
  83 import static com.sun.tools.javac.comp.Resolve.MethodResolutionPhase.*;
  84 import static com.sun.tools.javac.tree.JCTree.Tag.*;
  85 import static com.sun.tools.javac.util.Iterators.createCompoundIterator;
  86 
  87 /** Helper class for name resolution, used mostly by the attribution phase.
  88  *

  91  *  This code and its internal interfaces are subject to change or
  92  *  deletion without notice.</b>
  93  */
  94 public class Resolve {
  95     protected static final Context.Key<Resolve> resolveKey = new Context.Key<>();
  96 
  97     Names names;
  98     Log log;
  99     Symtab syms;
 100     Attr attr;
 101     AttrRecover attrRecover;
 102     DeferredAttr deferredAttr;
 103     Check chk;
 104     Infer infer;
 105     ClassFinder finder;
 106     ModuleFinder moduleFinder;
 107     Types types;
 108     JCDiagnostic.Factory diags;
 109     public final boolean allowModules;
 110     public final boolean allowRecords;

 111     private final boolean compactMethodDiags;
 112     private final boolean allowLocalVariableTypeInference;
 113     private final boolean allowYieldStatement;
 114     final EnumSet<VerboseResolutionMode> verboseResolutionMode;
 115     final boolean dumpMethodReferenceSearchResults;

 116 
 117     WriteableScope polymorphicSignatureScope;
 118 
 119     protected Resolve(Context context) {
 120         context.put(resolveKey, this);
 121         syms = Symtab.instance(context);
 122 
 123         varNotFound = new SymbolNotFoundError(ABSENT_VAR);
 124         methodNotFound = new SymbolNotFoundError(ABSENT_MTH);
 125         typeNotFound = new SymbolNotFoundError(ABSENT_TYP);
 126         referenceNotFound = ReferenceLookupResult.error(methodNotFound);
 127 
 128         names = Names.instance(context);
 129         log = Log.instance(context);
 130         attr = Attr.instance(context);
 131         attrRecover = AttrRecover.instance(context);
 132         deferredAttr = DeferredAttr.instance(context);
 133         chk = Check.instance(context);
 134         infer = Infer.instance(context);
 135         finder = ClassFinder.instance(context);
 136         moduleFinder = ModuleFinder.instance(context);
 137         types = Types.instance(context);
 138         diags = JCDiagnostic.Factory.instance(context);
 139         Preview preview = Preview.instance(context);
 140         Source source = Source.instance(context);
 141         Options options = Options.instance(context);
 142         compactMethodDiags = options.isSet(Option.XDIAGS, "compact") ||
 143                 options.isUnset(Option.XDIAGS) && options.isUnset("rawDiagnostics");
 144         verboseResolutionMode = VerboseResolutionMode.getVerboseResolutionMode(options);
 145         Target target = Target.instance(context);
 146         allowLocalVariableTypeInference = Feature.LOCAL_VARIABLE_TYPE_INFERENCE.allowedInSource(source);
 147         allowYieldStatement = Feature.SWITCH_EXPRESSION.allowedInSource(source);
 148         polymorphicSignatureScope = WriteableScope.create(syms.noSymbol);
 149         allowModules = Feature.MODULES.allowedInSource(source);
 150         allowRecords = Feature.RECORDS.allowedInSource(source);
 151         dumpMethodReferenceSearchResults = options.isSet("debug.dumpMethodReferenceSearchResults");


 152     }
 153 
 154     /** error symbols, which are returned when resolution fails
 155      */
 156     private final SymbolNotFoundError varNotFound;
 157     private final SymbolNotFoundError methodNotFound;
 158     private final SymbolNotFoundError typeNotFound;
 159 
 160     /** empty reference lookup result */
 161     private final ReferenceLookupResult referenceNotFound;
 162 
 163     public static Resolve instance(Context context) {
 164         Resolve instance = context.get(resolveKey);
 165         if (instance == null)
 166             instance = new Resolve(context);
 167         return instance;
 168     }
 169 
 170     private static Symbol bestOf(Symbol s1,
 171                                  Symbol s2) {

 201                 if (args.contains(mode.opt)) {
 202                     res.add(mode);
 203                 } else if (args.contains("-" + mode.opt)) {
 204                     res.remove(mode);
 205                 }
 206             }
 207             return res;
 208         }
 209     }
 210 
 211     void reportVerboseResolutionDiagnostic(DiagnosticPosition dpos, Name name, Type site,
 212             List<Type> argtypes, List<Type> typeargtypes, Symbol bestSoFar) {
 213         boolean success = !bestSoFar.kind.isResolutionError();
 214 
 215         if (success && !verboseResolutionMode.contains(VerboseResolutionMode.SUCCESS)) {
 216             return;
 217         } else if (!success && !verboseResolutionMode.contains(VerboseResolutionMode.FAILURE)) {
 218             return;
 219         }
 220 
 221         if (bestSoFar.name == names.init &&
 222                 bestSoFar.owner == syms.objectType.tsym &&
 223                 !verboseResolutionMode.contains(VerboseResolutionMode.OBJECT_INIT)) {
 224             return; //skip diags for Object constructor resolution
 225         } else if (site == syms.predefClass.type &&
 226                 !verboseResolutionMode.contains(VerboseResolutionMode.PREDEF)) {
 227             return; //skip spurious diags for predef symbols (i.e. operators)
 228         } else if (currentResolutionContext.internalResolution &&
 229                 !verboseResolutionMode.contains(VerboseResolutionMode.INTERNAL)) {
 230             return;
 231         }
 232 
 233         int pos = 0;
 234         int mostSpecificPos = -1;
 235         ListBuffer<JCDiagnostic> subDiags = new ListBuffer<>();
 236         for (Candidate c : currentResolutionContext.candidates) {
 237             if (currentResolutionContext.step != c.step ||
 238                     (c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.APPLICABLE)) ||
 239                     (!c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.INAPPLICABLE))) {
 240                 continue;
 241             } else {

 274         return diags.fragment(Fragments.NotApplicableMethodFound(pos, sym, subDiag));
 275     }
 276     // </editor-fold>
 277 
 278 /* ************************************************************************
 279  * Identifier resolution
 280  *************************************************************************/
 281 
 282     /** An environment is "static" if its static level is greater than
 283      *  the one of its outer environment
 284      */
 285     protected static boolean isStatic(Env<AttrContext> env) {
 286         return env.outer != null && env.info.staticLevel > env.outer.info.staticLevel;
 287     }
 288 
 289     /** An environment is an "initializer" if it is a constructor or
 290      *  an instance initializer.
 291      */
 292     static boolean isInitializer(Env<AttrContext> env) {
 293         Symbol owner = env.info.scope.owner;
 294         return owner.isConstructor() ||
 295             owner.owner.kind == TYP &&
 296             (owner.kind == VAR ||
 297              owner.kind == MTH && (owner.flags() & BLOCK) != 0) &&
 298             (owner.flags() & STATIC) == 0;
 299     }
 300 
 301     /** Is class accessible in given environment?
 302      *  @param env    The current environment.
 303      *  @param c      The class whose accessibility is checked.
 304      */
 305     public boolean isAccessible(Env<AttrContext> env, TypeSymbol c) {
 306         return isAccessible(env, c, false);
 307     }
 308 
 309     public boolean isAccessible(Env<AttrContext> env, TypeSymbol c, boolean checkInner) {
 310 
 311         /* 15.9.5.1: Note that it is possible for the signature of the anonymous constructor
 312            to refer to an inaccessible type
 313         */
 314         if (env.enclMethod != null && (env.enclMethod.mods.flags & ANONCONSTR) != 0)

 386         if (t.hasTag(ARRAY)) {
 387             return isAccessible(env, types.cvarUpperBound(types.elemtype(t)));
 388         } else if (t.isUnion()) {
 389             return StreamSupport.stream(((UnionClassType) t).getAlternativeTypes().spliterator(), false)
 390                     .allMatch(alternative -> isAccessible(env, alternative.tsym, checkInner));
 391         } else {
 392             return isAccessible(env, t.tsym, checkInner);
 393         }
 394     }
 395 
 396     /** Is symbol accessible as a member of given type in given environment?
 397      *  @param env    The current environment.
 398      *  @param site   The type of which the tested symbol is regarded
 399      *                as a member.
 400      *  @param sym    The symbol.
 401      */
 402     public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym) {
 403         return isAccessible(env, site, sym, false);
 404     }
 405     public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym, boolean checkInner) {
 406         if (sym.name == names.init && sym.owner != site.tsym) return false;
 407 
 408         /* 15.9.5.1: Note that it is possible for the signature of the anonymous constructor
 409            to refer to an inaccessible type
 410         */
 411         if (env.enclMethod != null && (env.enclMethod.mods.flags & ANONCONSTR) != 0)
 412             return true;
 413 
 414         if (env.info.visitingServiceImplementation &&
 415             env.toplevel.modle == sym.packge().modle) {
 416             return true;
 417         }
 418 
 419         switch ((short)(sym.flags() & AccessFlags)) {
 420         case PRIVATE:
 421             return
 422                 (env.enclClass.sym == sym.owner // fast special case
 423                  ||
 424                  env.enclClass.sym.outermostClass() ==
 425                  sym.owner.outermostClass())
 426                 &&
 427                 sym.isInheritedIn(site.tsym, types);
 428         case 0:
 429             return
 430                 (env.toplevel.packge == sym.owner.owner // fast special case
 431                  ||
 432                  env.toplevel.packge == sym.packge())
 433                 &&
 434                 isAccessible(env, site, checkInner)
 435                 &&
 436                 sym.isInheritedIn(site.tsym, types)
 437                 &&
 438                 notOverriddenIn(site, sym);
 439         case PROTECTED:
 440             return
 441                 (env.toplevel.packge == sym.owner.owner // fast special case
 442                  ||
 443                  env.toplevel.packge == sym.packge()
 444                  ||
 445                  isProtectedAccessible(sym, env.enclClass.sym, site)
 446                  ||
 447                  // OK to select instance method or field from 'super' or type name
 448                  // (but type names should be disallowed elsewhere!)
 449                  env.info.selectSuper && (sym.flags() & STATIC) == 0 && sym.kind != TYP)
 450                 &&
 451                 isAccessible(env, site, checkInner)
 452                 &&
 453                 notOverriddenIn(site, sym);
 454         default: // this case includes erroneous combinations as well
 455             return isAccessible(env, site, checkInner) && notOverriddenIn(site, sym);



















 456         }
 457     }
 458     //where
 459     /* `sym' is accessible only if not overridden by
 460      * another symbol which is a member of `site'
 461      * (because, if it is overridden, `sym' is not strictly
 462      * speaking a member of `site'). A polymorphic signature method
 463      * cannot be overridden (e.g. MH.invokeExact(Object[])).
 464      */
 465     private boolean notOverriddenIn(Type site, Symbol sym) {
 466         if (sym.kind != MTH || sym.isConstructor() || sym.isStatic())
 467             return true;
 468         else {
 469             Symbol s2 = ((MethodSymbol)sym).implementation(site.tsym, types, true);
 470             return (s2 == null || s2 == sym || sym.owner == s2.owner || (sym.owner.isInterface() && s2.owner == syms.objectType.tsym) ||
 471                     !types.isSubSignature(types.memberType(site, s2), types.memberType(site, sym)));


 472         }




 473     }
 474     //where
 475         /** Is given protected symbol accessible if it is selected from given site
 476          *  and the selection takes place in given class?
 477          *  @param sym     The symbol with protected access
 478          *  @param c       The class where the access takes place
 479          *  @site          The type of the qualifier
 480          */
 481         private
 482         boolean isProtectedAccessible(Symbol sym, ClassSymbol c, Type site) {
 483             Type newSite = site.hasTag(TYPEVAR) ? site.getUpperBound() : site;
 484             while (c != null &&
 485                    !(c.isSubClass(sym.owner, types) &&
 486                      (c.flags() & INTERFACE) == 0 &&
 487                      // In JLS 2e 6.6.2.1, the subclass restriction applies
 488                      // only to instance fields and methods -- types are excluded
 489                      // regardless of whether they are declared 'static' or not.
 490                      ((sym.flags() & STATIC) != 0 || sym.kind == TYP || newSite.tsym.isSubClass(c, types))))
 491                 c = c.owner.enclClass();
 492             return c != null;

1672 
1673                 // same signature; select (a) the non-bridge method, or
1674                 // (b) the one that overrides the other, or (c) the concrete
1675                 // one, or (d) merge both abstract signatures
1676                 if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE))
1677                     return ((m1.flags() & BRIDGE) != 0) ? m2 : m1;
1678 
1679                 if (m1.baseSymbol() == m2.baseSymbol()) {
1680                     // this is the same imported symbol which has been cloned twice.
1681                     // Return the first one (either will do).
1682                     return m1;
1683                 }
1684 
1685                 // if one overrides or hides the other, use it
1686                 TypeSymbol m1Owner = (TypeSymbol)m1.owner;
1687                 TypeSymbol m2Owner = (TypeSymbol)m2.owner;
1688                 // the two owners can never be the same if the target methods are compiled from source,
1689                 // but we need to protect against cases where the methods are defined in some classfile
1690                 // and make sure we issue an ambiguity error accordingly (by skipping the logic below).
1691                 if (m1Owner != m2Owner) {
1692                     if (types.asSuper(m1Owner.type, m2Owner) != null &&
1693                         ((m1.owner.flags_field & INTERFACE) == 0 ||
1694                          (m2.owner.flags_field & INTERFACE) != 0) &&
1695                         m1.overrides(m2, m1Owner, types, false))
1696                         return m1;
1697                     if (types.asSuper(m2Owner.type, m1Owner) != null &&
1698                         ((m2.owner.flags_field & INTERFACE) == 0 ||
1699                          (m1.owner.flags_field & INTERFACE) != 0) &&
1700                         m2.overrides(m1, m2Owner, types, false))
1701                         return m2;
1702                 }
1703                 boolean m1Abstract = (m1.flags() & ABSTRACT) != 0;
1704                 boolean m2Abstract = (m2.flags() & ABSTRACT) != 0;
1705                 if (m1Abstract && !m2Abstract) return m2;
1706                 if (m2Abstract && !m1Abstract) return m1;
1707                 // both abstract or both concrete
1708                 return ambiguityError(m1, m2);
1709             }
1710             if (m1SignatureMoreSpecific) return m1;
1711             if (m2SignatureMoreSpecific) return m2;
1712             return ambiguityError(m1, m2);
1713         case AMBIGUOUS:
1714             //compare m1 to ambiguous methods in m2
1715             AmbiguityError e = (AmbiguityError)m2.baseSymbol();
1716             boolean m1MoreSpecificThanAnyAmbiguous = true;
1717             boolean allAmbiguousMoreSpecificThanM1 = true;

1844         return bestSoFar;
1845     }
1846     // where
1847     private Symbol findMethod(Env<AttrContext> env,
1848                               Type site,
1849                               Name name,
1850                               List<Type> argtypes,
1851                               List<Type> typeargtypes,
1852                               Type intype,
1853                               Symbol bestSoFar,
1854                               boolean allowBoxing,
1855                               boolean useVarargs) {
1856         @SuppressWarnings({"unchecked","rawtypes"})
1857         List<Type>[] itypes = (List<Type>[])new List[] { List.<Type>nil(), List.<Type>nil() };
1858 
1859         InterfaceLookupPhase iphase = InterfaceLookupPhase.ABSTRACT_OK;
1860         boolean isInterface = site.tsym.isInterface();
1861         for (TypeSymbol s : isInterface ? List.of(intype.tsym) : superclasses(intype)) {
1862             bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
1863                     s.members(), bestSoFar, allowBoxing, useVarargs, true);
1864             if (name == names.init) return bestSoFar;
1865             iphase = (iphase == null) ? null : iphase.update(s, this);
1866             if (iphase != null) {
1867                 for (Type itype : types.interfaces(s.type)) {
1868                     itypes[iphase.ordinal()] = types.union(types.closure(itype), itypes[iphase.ordinal()]);
1869                 }
1870             }
1871         }
1872 
1873         Symbol concrete = bestSoFar.kind.isValid() &&
1874                 (bestSoFar.flags() & ABSTRACT) == 0 ?
1875                 bestSoFar : methodNotFound;
1876 
1877         for (InterfaceLookupPhase iphase2 : InterfaceLookupPhase.values()) {
1878             //keep searching for abstract methods
1879             for (Type itype : itypes[iphase2.ordinal()]) {
1880                 if (!itype.isInterface()) continue; //skip j.l.Object (included by Types.closure())
1881                 if (iphase2 == InterfaceLookupPhase.DEFAULT_OK &&
1882                         (itype.tsym.flags() & DEFAULT) == 0) continue;
1883                 bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
1884                         itype.tsym.members(), bestSoFar, allowBoxing, useVarargs, true);

2279                 bestSoFar = new AmbiguityError(bestSoFar, sym);
2280             else
2281                 bestSoFar = bestOf(bestSoFar, sym);
2282         }
2283         return bestSoFar;
2284     }
2285 
2286     /** Find qualified member type.
2287      *  @param env       The current environment.
2288      *  @param site      The original type from where the selection takes
2289      *                   place.
2290      *  @param name      The type's name.
2291      *  @param c         The class to search for the member type. This is
2292      *                   always a superclass or implemented interface of
2293      *                   site's class.
2294      */
2295     Symbol findMemberType(Env<AttrContext> env,
2296                           Type site,
2297                           Name name,
2298                           TypeSymbol c) {
















2299         Symbol sym = findImmediateMemberType(env, site, name, c);
2300 
2301         if (sym != typeNotFound)
2302             return sym;
2303 
2304         return findInheritedMemberType(env, site, name, c);
2305 
2306     }
2307 
2308     /** Find a global type in given scope and load corresponding class.
2309      *  @param env       The current environment.
2310      *  @param scope     The scope in which to look for the type.
2311      *  @param name      The type's name.
2312      */
2313     Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name, RecoveryLoadClass recoveryLoadClass) {
2314         Symbol bestSoFar = typeNotFound;
2315         for (Symbol s : scope.getSymbolsByName(name)) {
2316             Symbol sym = loadClass(env, s.flatName(), recoveryLoadClass);
2317             if (bestSoFar.kind == TYP && sym.kind == TYP &&
2318                 bestSoFar != sym)

2327         for (Symbol sym : env.info.scope.getSymbolsByName(name)) {
2328             if (sym.kind == TYP) {
2329                 if (sym.type.hasTag(TYPEVAR) &&
2330                         (staticOnly || (isStatic(env) && sym.owner.kind == TYP)))
2331                     // if staticOnly is set, it means that we have recursed through a static declaration,
2332                     // so type variable symbols should not be accessible. If staticOnly is unset, but
2333                     // we are in a static declaration (field or method), we should not allow type-variables
2334                     // defined in the enclosing class to "leak" into this context.
2335                     return new StaticError(sym);
2336                 return sym;
2337             }
2338         }
2339         return typeNotFound;
2340     }
2341 
2342     /** Find an unqualified type symbol.
2343      *  @param env       The current environment.
2344      *  @param name      The type's name.
2345      */
2346     Symbol findType(Env<AttrContext> env, Name name) {








2347         if (name == names.empty)
2348             return typeNotFound; // do not allow inadvertent "lookup" of anonymous types
2349         Symbol bestSoFar = typeNotFound;
2350         Symbol sym;
2351         boolean staticOnly = false;
2352         for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
2353             // First, look for a type variable and the first member type
2354             final Symbol tyvar = findTypeVar(env1, name, staticOnly);
2355             if (isStatic(env1)) staticOnly = true;
2356             sym = findImmediateMemberType(env1, env1.enclClass.sym.type,
2357                                           name, env1.enclClass.sym);
2358 
2359             // Return the type variable if we have it, and have no
2360             // immediate member, OR the type variable is for a method.
2361             if (tyvar != typeNotFound) {
2362                 if (env.baseClause || sym == typeNotFound ||
2363                     (tyvar.kind == TYP && tyvar.exists() &&
2364                      tyvar.owner.kind == MTH)) {
2365                     return tyvar;
2366                 }

2865      *  @param site      The type of class for which a constructor is searched.
2866      *  @param argtypes  The types of the constructor invocation's value
2867      *                   arguments.
2868      *  @param typeargtypes  The types of the constructor invocation's type
2869      *                   arguments.
2870      */
2871     Symbol resolveConstructor(DiagnosticPosition pos,
2872                               Env<AttrContext> env,
2873                               Type site,
2874                               List<Type> argtypes,
2875                               List<Type> typeargtypes) {
2876         return resolveConstructor(new MethodResolutionContext(), pos, env, site, argtypes, typeargtypes);
2877     }
2878 
2879     private Symbol resolveConstructor(MethodResolutionContext resolveContext,
2880                               final DiagnosticPosition pos,
2881                               Env<AttrContext> env,
2882                               Type site,
2883                               List<Type> argtypes,
2884                               List<Type> typeargtypes) {
2885         return lookupMethod(env, pos, site.tsym, resolveContext, new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {

2886             @Override
2887             Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2888                 return findConstructor(pos, env, site, argtypes, typeargtypes,
2889                         phase.isBoxingRequired(),
2890                         phase.isVarargsRequired());
2891             }
2892         });
2893     }
2894 
2895     /** Resolve a constructor, throw a fatal error if not found.
2896      *  @param pos       The position to use for error reporting.
2897      *  @param env       The environment current at the method invocation.
2898      *  @param site      The type to be constructed.
2899      *  @param argtypes  The types of the invocation's value arguments.
2900      *  @param typeargtypes  The types of the invocation's type arguments.
2901      */
2902     public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
2903                                         Type site,
2904                                         List<Type> argtypes,
2905                                         List<Type> typeargtypes) {
2906         MethodResolutionContext resolveContext = new MethodResolutionContext();
2907         resolveContext.internalResolution = true;
2908         Symbol sym = resolveConstructor(resolveContext, pos, env, site, argtypes, typeargtypes);
2909         if (sym.kind == MTH) return (MethodSymbol)sym;
2910         else throw new FatalError(
2911                  diags.fragment(Fragments.FatalErrCantLocateCtor(site)));
2912     }
2913 
2914     Symbol findConstructor(DiagnosticPosition pos, Env<AttrContext> env,
2915                               Type site, List<Type> argtypes,
2916                               List<Type> typeargtypes,
2917                               boolean allowBoxing,
2918                               boolean useVarargs) {

2919         Symbol sym = findMethod(env, site,
2920                                     names.init, argtypes,
2921                                     typeargtypes, allowBoxing,
2922                                     useVarargs);
2923         chk.checkDeprecated(pos, env.info.scope.owner, sym);
2924         chk.checkPreview(pos, env.info.scope.owner, sym);
2925         return sym;
2926     }
2927 
2928     /** Resolve constructor using diamond inference.
2929      *  @param pos       The position to use for error reporting.
2930      *  @param env       The environment current at the constructor invocation.
2931      *  @param site      The type of class for which a constructor is searched.
2932      *                   The scope of this class has been touched in attribution.
2933      *  @param argtypes  The types of the constructor invocation's value
2934      *                   arguments.
2935      *  @param typeargtypes  The types of the constructor invocation's type
2936      *                   arguments.
2937      */
2938     Symbol resolveDiamond(DiagnosticPosition pos,
2939                               Env<AttrContext> env,
2940                               Type site,
2941                               List<Type> argtypes,
2942                               List<Type> typeargtypes) {

2943         return lookupMethod(env, pos, site.tsym, resolveMethodCheck,
2944                 new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
2945                     @Override
2946                     Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2947                         return findDiamond(pos, env, site, argtypes, typeargtypes,
2948                                 phase.isBoxingRequired(),
2949                                 phase.isVarargsRequired());
2950                     }
2951                     @Override
2952                     Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
2953                         if (sym.kind.isResolutionError()) {
2954                             if (sym.kind != WRONG_MTH &&
2955                                 sym.kind != WRONG_MTHS) {
2956                                 sym = super.access(env, pos, location, sym);
2957                             } else {
2958                                 sym = new DiamondError(sym, currentResolutionContext);
2959                                 sym = accessMethod(sym, pos, site, names.init, true, argtypes, typeargtypes);
2960                                 env.info.pendingResolutionPhase = currentResolutionContext.step;
2961                             }
2962                         }
2963                         return sym;
2964                     }});
2965     }
2966 
2967     /** Find the constructor using diamond inference and do some checks(deprecated and preview).
2968      *  @param pos          The position to use for error reporting.
2969      *  @param env          The environment current at the constructor invocation.
2970      *  @param site         The type of class for which a constructor is searched.
2971      *                      The scope of this class has been touched in attribution.
2972      *  @param argtypes     The types of the constructor invocation's value arguments.
2973      *  @param typeargtypes The types of the constructor invocation's type arguments.
2974      *  @param allowBoxing  Allow boxing conversions of arguments.
2975      *  @param useVarargs   Box trailing arguments into an array for varargs.
2976      */
2977     private Symbol findDiamond(DiagnosticPosition pos,
2978                                Env<AttrContext> env,
2979                                Type site,

2986         chk.checkPreview(pos, env.info.scope.owner, sym);
2987         return sym;
2988     }
2989 
2990     /** This method scans all the constructor symbol in a given class scope -
2991      *  assuming that the original scope contains a constructor of the kind:
2992      *  {@code Foo(X x, Y y)}, where X,Y are class type-variables declared in Foo,
2993      *  a method check is executed against the modified constructor type:
2994      *  {@code <X,Y>Foo<X,Y>(X x, Y y)}. This is crucial in order to enable diamond
2995      *  inference. The inferred return type of the synthetic constructor IS
2996      *  the inferred type for the diamond operator.
2997      */
2998     private Symbol findDiamond(Env<AttrContext> env,
2999                               Type site,
3000                               List<Type> argtypes,
3001                               List<Type> typeargtypes,
3002                               boolean allowBoxing,
3003                               boolean useVarargs) {
3004         Symbol bestSoFar = methodNotFound;
3005         TypeSymbol tsym = site.tsym.isInterface() ? syms.objectType.tsym : site.tsym;
3006         for (final Symbol sym : tsym.members().getSymbolsByName(names.init)) {

3007             //- System.out.println(" e " + e.sym);
3008             if (sym.kind == MTH &&
3009                 (sym.flags_field & SYNTHETIC) == 0) {
3010                     List<Type> oldParams = sym.type.hasTag(FORALL) ?
3011                             ((ForAll)sym.type).tvars :
3012                             List.nil();
3013                     Type constrType = new ForAll(site.tsym.type.getTypeArguments().appendList(oldParams),
3014                                                  types.createMethodTypeWithReturn(sym.type.asMethodType(), site));
3015                     MethodSymbol newConstr = new MethodSymbol(sym.flags(), names.init, constrType, site.tsym) {
3016                         @Override
3017                         public Symbol baseSymbol() {
3018                             return sym;
3019                         }
3020                     };
3021                     bestSoFar = selectBest(env, site, argtypes, typeargtypes,
3022                             newConstr,
3023                             bestSoFar,
3024                             allowBoxing,
3025                             useVarargs);
3026             }
3027         }
3028         return bestSoFar;
3029     }
3030 
3031     Symbol getMemberReference(DiagnosticPosition pos,
3032             Env<AttrContext> env,
3033             JCMemberReference referenceTree,
3034             Type site,
3035             Name name) {

3037         site = types.capture(site);
3038 
3039         ReferenceLookupHelper lookupHelper = makeReferenceLookupHelper(
3040                 referenceTree, site, name, List.nil(), null, VARARITY);
3041 
3042         Env<AttrContext> newEnv = env.dup(env.tree, env.info.dup());
3043         Symbol sym = lookupMethod(newEnv, env.tree.pos(), site.tsym,
3044                 nilMethodCheck, lookupHelper);
3045 
3046         env.info.pendingResolutionPhase = newEnv.info.pendingResolutionPhase;
3047 
3048         return sym;
3049     }
3050 
3051     ReferenceLookupHelper makeReferenceLookupHelper(JCMemberReference referenceTree,
3052                                   Type site,
3053                                   Name name,
3054                                   List<Type> argtypes,
3055                                   List<Type> typeargtypes,
3056                                   MethodResolutionPhase maxPhase) {
3057         if (!name.equals(names.init)) {
3058             //method reference
3059             return new MethodReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
3060         } else if (site.hasTag(ARRAY)) {
3061             //array constructor reference
3062             return new ArrayConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase);
3063         } else {
3064             //class constructor reference
3065             return new ConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase);
3066         }
3067     }
3068 
3069     /**
3070      * Resolution of member references is typically done as a single
3071      * overload resolution step, where the argument types A are inferred from
3072      * the target functional descriptor.
3073      *
3074      * If the member reference is a method reference with a type qualifier,
3075      * a two-step lookup process is performed. The first step uses the
3076      * expected argument list A, while the second step discards the first
3077      * type from A (which is treated as a receiver type).

3551         /** The original method reference lookup site. */
3552         Type originalSite;
3553 
3554         MethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
3555                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
3556             super(referenceTree, name, types.skipTypeVars(site, true), argtypes, typeargtypes, maxPhase);
3557             this.originalSite = site;
3558         }
3559 
3560         @Override
3561         final Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
3562             return findMethod(env, site, name, argtypes, typeargtypes,
3563                     phase.isBoxingRequired(), phase.isVarargsRequired());
3564         }
3565 
3566         @Override
3567         ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
3568             if (TreeInfo.isStaticSelector(referenceTree.expr, names)) {
3569                 if (argtypes.nonEmpty() &&
3570                         (argtypes.head.hasTag(NONE) ||
3571                         types.isSubtypeUnchecked(inferenceContext.asUndetVar(argtypes.head), originalSite))) {
3572                     return new UnboundMethodReferenceLookupHelper(referenceTree, name,
3573                             originalSite, argtypes, typeargtypes, maxPhase);
3574                 } else {
3575                     return new ReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase) {
3576                         @Override
3577                         ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
3578                             return this;
3579                         }
3580 
3581                         @Override
3582                         Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
3583                             return methodNotFound;
3584                         }
3585 
3586                         @Override
3587                         ReferenceKind referenceKind(Symbol sym) {
3588                             Assert.error();
3589                             return null;
3590                         }
3591                     };

3604                 return selName != null && selName == names._super ?
3605                         ReferenceKind.SUPER :
3606                         ReferenceKind.BOUND;
3607             }
3608         }
3609     }
3610 
3611     /**
3612      * Helper class for unbound method reference lookup. Essentially the same
3613      * as the basic method reference lookup helper; main difference is that static
3614      * lookup results are thrown away. If qualifier type is raw, an attempt to
3615      * infer a parameterized type is made using the first actual argument (that
3616      * would otherwise be ignored during the lookup).
3617      */
3618     class UnboundMethodReferenceLookupHelper extends MethodReferenceLookupHelper {
3619 
3620         UnboundMethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
3621                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
3622             super(referenceTree, name, site, argtypes.tail, typeargtypes, maxPhase);
3623             if (site.isRaw() && !argtypes.head.hasTag(NONE)) {
3624                 Type asSuperSite = types.asSuper(argtypes.head, site.tsym);
3625                 this.site = types.skipTypeVars(asSuperSite, true);
3626             }
3627         }
3628 
3629         @Override
3630         ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
3631             return this;
3632         }
3633 
3634         @Override
3635         ReferenceKind referenceKind(Symbol sym) {
3636             return ReferenceKind.UNBOUND;
3637         }
3638     }
3639 
3640     /**
3641      * Helper class for array constructor lookup; an array constructor lookup
3642      * is simulated by looking up a method that returns the array type specified
3643      * as qualifier, and that accepts a single int parameter (size of the array).
3644      */
3645     class ArrayConstructorReferenceLookupHelper extends ReferenceLookupHelper {
3646 
3647         ArrayConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
3648                 List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
3649             super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase);

3650         }
3651 
3652         @Override
3653         protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
3654             WriteableScope sc = WriteableScope.create(syms.arrayClass);
3655             MethodSymbol arrayConstr = new MethodSymbol(PUBLIC, name, null, site.tsym);
3656             arrayConstr.type = new MethodType(List.of(syms.intType), site, List.nil(), syms.methodClass);
3657             sc.enter(arrayConstr);
3658             return findMethodInScope(env, site, name, argtypes, typeargtypes, sc, methodNotFound, phase.isBoxingRequired(), phase.isVarargsRequired(), false);
3659         }
3660 
3661         @Override
3662         ReferenceKind referenceKind(Symbol sym) {
3663             return ReferenceKind.ARRAY_CTOR;
3664         }
3665     }
3666 
3667     /**
3668      * Helper class for constructor reference lookup. The lookup logic is based
3669      * upon either Resolve.findMethod or Resolve.findDiamond - depending on
3670      * whether the constructor reference needs diamond inference (this is the case
3671      * if the qualifier type is raw). A special erroneous symbol is returned
3672      * if the lookup returns the constructor of an inner class and there's no
3673      * enclosing instance in scope.
3674      */
3675     class ConstructorReferenceLookupHelper extends ReferenceLookupHelper {
3676 
3677         boolean needsInference;
3678 
3679         ConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
3680                 List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
3681             super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase);
3682             if (site.isRaw()) {
3683                 this.site = new ClassType(site.getEnclosingType(),
3684                         !(site.tsym.isInner() && site.getEnclosingType().isRaw()) ?
3685                                 site.tsym.type.getTypeArguments() : List.nil(), site.tsym, site.getMetadata());
3686                 needsInference = true;
3687             }
3688         }
3689 
3690         @Override
3691         protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
3692             Symbol sym = needsInference ?
3693                 findDiamond(env, site, argtypes, typeargtypes, phase.isBoxingRequired(), phase.isVarargsRequired()) :
3694                 findMethod(env, site, name, argtypes, typeargtypes,
3695                         phase.isBoxingRequired(), phase.isVarargsRequired());
3696             return enclosingInstanceMissing(env, site) ? new BadConstructorReferenceError(sym) : sym;
3697         }
3698 
3699         @Override
3700         ReferenceKind referenceKind(Symbol sym) {
3701             return site.getEnclosingType().hasTag(NONE) ?
3702                     ReferenceKind.TOPLEVEL : ReferenceKind.IMPLICIT_INNER;
3703         }
3704     }
3705 

3755             if (isStatic(env1)) staticOnly = true;
3756             if (env1.enclClass.sym == c) {
3757                 Symbol sym = env1.info.scope.findFirst(name);
3758                 if (sym != null) {
3759                     if (staticOnly) sym = new StaticError(sym);
3760                     return accessBase(sym, pos, env.enclClass.sym.type,
3761                                   name, true);
3762                 }
3763             }
3764             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
3765             env1 = env1.outer;
3766         }
3767         if (c.isInterface() &&
3768             name == names._super && !isStatic(env) &&
3769             types.isDirectSuperInterface(c, env.enclClass.sym)) {
3770             //this might be a default super call if one of the superinterfaces is 'c'
3771             for (Type t : pruneInterfaces(env.enclClass.type)) {
3772                 if (t.tsym == c) {
3773                     env.info.defaultSuperCallSite = t;
3774                     return new VarSymbol(0, names._super,
3775                             types.asSuper(env.enclClass.type, c), env.enclClass.sym);
3776                 }
3777             }
3778             //find a direct supertype that is a subtype of 'c'
3779             for (Type i : types.directSupertypes(env.enclClass.type)) {
3780                 if (i.tsym.isSubClass(c, types) && i.tsym != c) {
3781                     log.error(pos,
3782                               Errors.IllegalDefaultSuperCall(c,
3783                                                              Fragments.RedundantSupertype(c, i)));
3784                     return syms.errSymbol;
3785                 }
3786             }
3787             Assert.error();
3788         }
3789         log.error(pos, Errors.NotEnclClass(c));
3790         return syms.errSymbol;
3791     }
3792     //where
3793     private List<Type> pruneInterfaces(Type t) {
3794         ListBuffer<Type> result = new ListBuffer<>();
3795         for (Type t1 : types.interfaces(t)) {

4068                 Name name,
4069                 List<Type> argtypes,
4070                 List<Type> typeargtypes) {
4071             argtypes = argtypes == null ? List.nil() : argtypes;
4072             typeargtypes = typeargtypes == null ? List.nil() : typeargtypes;
4073             if (name == names.error)
4074                 return null;
4075 
4076             boolean hasLocation = false;
4077             if (location == null) {
4078                 location = site.tsym;
4079             }
4080             if (!location.name.isEmpty()) {
4081                 if (location.kind == PCK && !site.tsym.exists() && location.name != names.java) {
4082                     return diags.create(dkind, log.currentSource(), pos,
4083                         "doesnt.exist", location);
4084                 }
4085                 hasLocation = !location.name.equals(names._this) &&
4086                         !location.name.equals(names._super);
4087             }
4088             boolean isConstructor = name == names.init;
4089             KindName kindname = isConstructor ? KindName.CONSTRUCTOR : kind.absentKind();
4090             Name idname = isConstructor ? site.tsym.name : name;
4091             String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation);
4092             if (hasLocation) {
4093                 return diags.create(dkind, log.currentSource(), pos,
4094                         errKey, kindname, idname, //symbol kindname, name
4095                         typeargtypes, args(argtypes), //type parameters and arguments (if any)
4096                         getLocationDiag(location, site)); //location kindname, type
4097             }
4098             else {
4099                 return diags.create(dkind, log.currentSource(), pos,
4100                         errKey, kindname, idname, //symbol kindname, name
4101                         typeargtypes, args(argtypes)); //type parameters and arguments (if any)
4102             }
4103         }
4104         //where
4105         private Object args(List<Type> args) {
4106             return args.isEmpty() ? args : methodArguments(args);
4107         }
4108 

4160         }
4161 
4162         @Override
4163         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
4164                 DiagnosticPosition pos,
4165                 Symbol location,
4166                 Type site,
4167                 Name name,
4168                 List<Type> argtypes,
4169                 List<Type> typeargtypes) {
4170             if (name == names.error)
4171                 return null;
4172 
4173             Pair<Symbol, JCDiagnostic> c = errCandidate();
4174             Symbol ws = c.fst.asMemberOf(site, types);
4175             return diags.create(dkind, log.currentSource(), pos,
4176                       "cant.apply.symbol",
4177                       compactMethodDiags ?
4178                               d -> MethodResolutionDiagHelper.rewrite(diags, pos, log.currentSource(), dkind, c.snd) : null,
4179                       kindName(ws),
4180                       ws.name == names.init ? ws.owner.name : ws.name,
4181                       methodArguments(ws.type.getParameterTypes()),
4182                       methodArguments(argtypes),
4183                       kindName(ws.owner),
4184                       ws.owner.type,
4185                       c.snd);
4186         }
4187 
4188         @Override
4189         public Symbol access(Name name, TypeSymbol location) {
4190             Pair<Symbol, JCDiagnostic> cand = errCandidate();
4191             TypeSymbol errSymbol = types.createErrorType(name, location, cand != null ? cand.fst.type : syms.errSymbol.type).tsym;
4192             if (cand != null) {
4193                 attrRecover.wrongMethodSymbolCandidate(errSymbol, cand.fst, cand.snd);
4194             }
4195             return errSymbol;
4196         }
4197 
4198         protected Pair<Symbol, JCDiagnostic> errCandidate() {
4199             Candidate bestSoFar = null;
4200             for (Candidate c : resolveContext.candidates) {

4216             super(WRONG_MTHS, "inapplicable symbols", context);
4217         }
4218 
4219         @Override
4220         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
4221                 DiagnosticPosition pos,
4222                 Symbol location,
4223                 Type site,
4224                 Name name,
4225                 List<Type> argtypes,
4226                 List<Type> typeargtypes) {
4227             Map<Symbol, JCDiagnostic> candidatesMap = mapCandidates();
4228             Map<Symbol, JCDiagnostic> filteredCandidates = compactMethodDiags ?
4229                     filterCandidates(candidatesMap) :
4230                     mapCandidates();
4231             if (filteredCandidates.isEmpty()) {
4232                 filteredCandidates = candidatesMap;
4233             }
4234             boolean truncatedDiag = candidatesMap.size() != filteredCandidates.size();
4235             if (filteredCandidates.size() > 1) {

4236                 JCDiagnostic err = diags.create(dkind,
4237                         null,
4238                         truncatedDiag ?
4239                                 EnumSet.of(DiagnosticFlag.COMPRESSED) :
4240                                 EnumSet.noneOf(DiagnosticFlag.class),
4241                         log.currentSource(),
4242                         pos,
4243                         "cant.apply.symbols",
4244                         name == names.init ? KindName.CONSTRUCTOR : kind.absentKind(),
4245                         name == names.init ? site.tsym.name : name,
4246                         methodArguments(argtypes));
4247                 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(filteredCandidates, site));
4248             } else if (filteredCandidates.size() == 1) {
4249                 Map.Entry<Symbol, JCDiagnostic> _e =
4250                                 filteredCandidates.entrySet().iterator().next();
4251                 final Pair<Symbol, JCDiagnostic> p = new Pair<>(_e.getKey(), _e.getValue());
4252                 JCDiagnostic d = new InapplicableSymbolError(resolveContext) {
4253                     @Override
4254                     protected Pair<Symbol, JCDiagnostic> errCandidate() {
4255                         return p;
4256                     }
4257                 }.getDiagnostic(dkind, pos,
4258                     location, site, name, argtypes, typeargtypes);
4259                 if (truncatedDiag) {
4260                     d.setFlag(DiagnosticFlag.COMPRESSED);
4261                 }
4262                 return d;
4263             } else {
4264                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
4265                     location, site, name, argtypes, typeargtypes);

4385 
4386         AccessError(Env<AttrContext> env, Type site, Symbol sym) {
4387             super(HIDDEN, sym, "access error");
4388             this.env = env;
4389             this.site = site;
4390         }
4391 
4392         @Override
4393         public boolean exists() {
4394             return false;
4395         }
4396 
4397         @Override
4398         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
4399                 DiagnosticPosition pos,
4400                 Symbol location,
4401                 Type site,
4402                 Name name,
4403                 List<Type> argtypes,
4404                 List<Type> typeargtypes) {
4405             if (sym.name == names.init && sym.owner != site.tsym) {
4406                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
4407                         pos, location, site, name, argtypes, typeargtypes);
4408             }
4409             else if ((sym.flags() & PUBLIC) != 0
4410                 || (env != null && this.site != null
4411                     && !isAccessible(env, this.site))) {
4412                 if (sym.owner.kind == PCK) {
4413                     return diags.create(dkind, log.currentSource(),
4414                             pos, "not.def.access.package.cant.access",
4415                         sym, sym.location(), inaccessiblePackageReason(env, sym.packge()));
4416                 } else if (   sym.packge() != syms.rootPackage
4417                            && !symbolPackageVisible(env, sym)) {
4418                     return diags.create(dkind, log.currentSource(),
4419                             pos, "not.def.access.class.intf.cant.access.reason",
4420                             sym, sym.location(), sym.location().packge(),
4421                             inaccessiblePackageReason(env, sym.packge()));
4422                 } else {
4423                     return diags.create(dkind, log.currentSource(),
4424                             pos, "not.def.access.class.intf.cant.access",
4425                         sym, sym.location());

4598             }
4599         }
4600 
4601         AmbiguityError addAmbiguousSymbol(Symbol s) {
4602             ambiguousSyms = ambiguousSyms.prepend(s);
4603             return this;
4604         }
4605 
4606         @Override
4607         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
4608                 DiagnosticPosition pos,
4609                 Symbol location,
4610                 Type site,
4611                 Name name,
4612                 List<Type> argtypes,
4613                 List<Type> typeargtypes) {
4614             List<Symbol> diagSyms = ambiguousSyms.reverse();
4615             Symbol s1 = diagSyms.head;
4616             Symbol s2 = diagSyms.tail.head;
4617             Name sname = s1.name;
4618             if (sname == names.init) sname = s1.owner.name;
4619             return diags.create(dkind, log.currentSource(),
4620                     pos, "ref.ambiguous", sname,
4621                     kindName(s1),
4622                     s1,
4623                     s1.location(site, types),
4624                     kindName(s2),
4625                     s2,
4626                     s2.location(site, types));
4627         }
4628 
4629         /**
4630          * If multiple applicable methods are found during overload and none of them
4631          * is more specific than the others, attempt to merge their signatures.
4632          */
4633         Symbol mergeAbstracts(Type site) {
4634             List<Symbol> ambiguousInOrder = ambiguousSyms.reverse();
4635             return types.mergeAbstracts(ambiguousInOrder, site, true).orElse(this);
4636         }
4637 
4638         @Override

  36 import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
  37 import com.sun.tools.javac.comp.DeferredAttr.DeferredAttrContext;
  38 import com.sun.tools.javac.comp.DeferredAttr.DeferredType;
  39 import com.sun.tools.javac.comp.Resolve.MethodResolutionContext.Candidate;
  40 import com.sun.tools.javac.comp.Resolve.MethodResolutionDiagHelper.Template;
  41 import com.sun.tools.javac.comp.Resolve.ReferenceLookupResult.StaticKind;
  42 import com.sun.tools.javac.jvm.*;
  43 import com.sun.tools.javac.main.Option;
  44 import com.sun.tools.javac.resources.CompilerProperties.Errors;
  45 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
  46 import com.sun.tools.javac.resources.CompilerProperties.Warnings;
  47 import com.sun.tools.javac.tree.*;
  48 import com.sun.tools.javac.tree.JCTree.*;
  49 import com.sun.tools.javac.tree.JCTree.JCMemberReference.ReferenceKind;
  50 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
  51 import com.sun.tools.javac.util.*;
  52 import com.sun.tools.javac.util.DefinedBy.Api;
  53 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
  54 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
  55 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType;

  56 
  57 import java.util.Arrays;
  58 import java.util.Collection;
  59 import java.util.EnumSet;
  60 import java.util.HashSet;
  61 import java.util.Iterator;
  62 import java.util.LinkedHashMap;
  63 import java.util.Map;
  64 import java.util.Set;
  65 import java.util.function.BiFunction;
  66 import java.util.function.BiPredicate;

  67 import java.util.function.Function;
  68 import java.util.function.Predicate;
  69 import java.util.function.UnaryOperator;
  70 import java.util.stream.Stream;
  71 import java.util.stream.StreamSupport;
  72 
  73 import javax.lang.model.element.ElementVisitor;
  74 
  75 import static com.sun.tools.javac.code.Flags.*;
  76 import static com.sun.tools.javac.code.Flags.BLOCK;
  77 import static com.sun.tools.javac.code.Flags.STATIC;
  78 import static com.sun.tools.javac.code.Kinds.*;
  79 import static com.sun.tools.javac.code.Kinds.Kind.*;
  80 import static com.sun.tools.javac.code.TypeTag.*;
  81 import static com.sun.tools.javac.comp.Resolve.MethodResolutionPhase.*;
  82 import static com.sun.tools.javac.tree.JCTree.Tag.*;
  83 import static com.sun.tools.javac.util.Iterators.createCompoundIterator;
  84 
  85 /** Helper class for name resolution, used mostly by the attribution phase.
  86  *

  89  *  This code and its internal interfaces are subject to change or
  90  *  deletion without notice.</b>
  91  */
  92 public class Resolve {
  93     protected static final Context.Key<Resolve> resolveKey = new Context.Key<>();
  94 
  95     Names names;
  96     Log log;
  97     Symtab syms;
  98     Attr attr;
  99     AttrRecover attrRecover;
 100     DeferredAttr deferredAttr;
 101     Check chk;
 102     Infer infer;
 103     ClassFinder finder;
 104     ModuleFinder moduleFinder;
 105     Types types;
 106     JCDiagnostic.Factory diags;
 107     public final boolean allowModules;
 108     public final boolean allowRecords;
 109     public final boolean allowValueClasses;
 110     private final boolean compactMethodDiags;
 111     private final boolean allowLocalVariableTypeInference;
 112     private final boolean allowYieldStatement;
 113     final EnumSet<VerboseResolutionMode> verboseResolutionMode;
 114     final boolean dumpMethodReferenceSearchResults;
 115     final boolean allowPrimitiveClasses;
 116 
 117     WriteableScope polymorphicSignatureScope;
 118 
 119     protected Resolve(Context context) {
 120         context.put(resolveKey, this);
 121         syms = Symtab.instance(context);
 122 
 123         varNotFound = new SymbolNotFoundError(ABSENT_VAR);
 124         methodNotFound = new SymbolNotFoundError(ABSENT_MTH);
 125         typeNotFound = new SymbolNotFoundError(ABSENT_TYP);
 126         referenceNotFound = ReferenceLookupResult.error(methodNotFound);
 127 
 128         names = Names.instance(context);
 129         log = Log.instance(context);
 130         attr = Attr.instance(context);
 131         attrRecover = AttrRecover.instance(context);
 132         deferredAttr = DeferredAttr.instance(context);
 133         chk = Check.instance(context);
 134         infer = Infer.instance(context);
 135         finder = ClassFinder.instance(context);
 136         moduleFinder = ModuleFinder.instance(context);
 137         types = Types.instance(context);
 138         diags = JCDiagnostic.Factory.instance(context);
 139         Preview preview = Preview.instance(context);
 140         Source source = Source.instance(context);
 141         Options options = Options.instance(context);
 142         compactMethodDiags = options.isSet(Option.XDIAGS, "compact") ||
 143                 options.isUnset(Option.XDIAGS) && options.isUnset("rawDiagnostics");
 144         verboseResolutionMode = VerboseResolutionMode.getVerboseResolutionMode(options);
 145         Target target = Target.instance(context);
 146         allowLocalVariableTypeInference = Feature.LOCAL_VARIABLE_TYPE_INFERENCE.allowedInSource(source);
 147         allowYieldStatement = Feature.SWITCH_EXPRESSION.allowedInSource(source);
 148         polymorphicSignatureScope = WriteableScope.create(syms.noSymbol);
 149         allowModules = Feature.MODULES.allowedInSource(source);
 150         allowRecords = Feature.RECORDS.allowedInSource(source);
 151         dumpMethodReferenceSearchResults = options.isSet("debug.dumpMethodReferenceSearchResults");
 152         allowValueClasses = Feature.VALUE_CLASSES.allowedInSource(source);
 153         allowPrimitiveClasses = Feature.PRIMITIVE_CLASSES.allowedInSource(source) && options.isSet("enablePrimitiveClasses");
 154     }
 155 
 156     /** error symbols, which are returned when resolution fails
 157      */
 158     private final SymbolNotFoundError varNotFound;
 159     private final SymbolNotFoundError methodNotFound;
 160     private final SymbolNotFoundError typeNotFound;
 161 
 162     /** empty reference lookup result */
 163     private final ReferenceLookupResult referenceNotFound;
 164 
 165     public static Resolve instance(Context context) {
 166         Resolve instance = context.get(resolveKey);
 167         if (instance == null)
 168             instance = new Resolve(context);
 169         return instance;
 170     }
 171 
 172     private static Symbol bestOf(Symbol s1,
 173                                  Symbol s2) {

 203                 if (args.contains(mode.opt)) {
 204                     res.add(mode);
 205                 } else if (args.contains("-" + mode.opt)) {
 206                     res.remove(mode);
 207                 }
 208             }
 209             return res;
 210         }
 211     }
 212 
 213     void reportVerboseResolutionDiagnostic(DiagnosticPosition dpos, Name name, Type site,
 214             List<Type> argtypes, List<Type> typeargtypes, Symbol bestSoFar) {
 215         boolean success = !bestSoFar.kind.isResolutionError();
 216 
 217         if (success && !verboseResolutionMode.contains(VerboseResolutionMode.SUCCESS)) {
 218             return;
 219         } else if (!success && !verboseResolutionMode.contains(VerboseResolutionMode.FAILURE)) {
 220             return;
 221         }
 222 
 223         if (names.isInitOrVNew(bestSoFar.name) &&
 224                 bestSoFar.owner == syms.objectType.tsym &&
 225                 !verboseResolutionMode.contains(VerboseResolutionMode.OBJECT_INIT)) {
 226             return; //skip diags for Object constructor resolution
 227         } else if (site == syms.predefClass.type &&
 228                 !verboseResolutionMode.contains(VerboseResolutionMode.PREDEF)) {
 229             return; //skip spurious diags for predef symbols (i.e. operators)
 230         } else if (currentResolutionContext.internalResolution &&
 231                 !verboseResolutionMode.contains(VerboseResolutionMode.INTERNAL)) {
 232             return;
 233         }
 234 
 235         int pos = 0;
 236         int mostSpecificPos = -1;
 237         ListBuffer<JCDiagnostic> subDiags = new ListBuffer<>();
 238         for (Candidate c : currentResolutionContext.candidates) {
 239             if (currentResolutionContext.step != c.step ||
 240                     (c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.APPLICABLE)) ||
 241                     (!c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.INAPPLICABLE))) {
 242                 continue;
 243             } else {

 276         return diags.fragment(Fragments.NotApplicableMethodFound(pos, sym, subDiag));
 277     }
 278     // </editor-fold>
 279 
 280 /* ************************************************************************
 281  * Identifier resolution
 282  *************************************************************************/
 283 
 284     /** An environment is "static" if its static level is greater than
 285      *  the one of its outer environment
 286      */
 287     protected static boolean isStatic(Env<AttrContext> env) {
 288         return env.outer != null && env.info.staticLevel > env.outer.info.staticLevel;
 289     }
 290 
 291     /** An environment is an "initializer" if it is a constructor or
 292      *  an instance initializer.
 293      */
 294     static boolean isInitializer(Env<AttrContext> env) {
 295         Symbol owner = env.info.scope.owner;
 296         return owner.isInitOrVNew() ||
 297             owner.owner.kind == TYP &&
 298             (owner.kind == VAR ||
 299              owner.kind == MTH && (owner.flags() & BLOCK) != 0) &&
 300             (owner.flags() & STATIC) == 0;
 301     }
 302 
 303     /** Is class accessible in given environment?
 304      *  @param env    The current environment.
 305      *  @param c      The class whose accessibility is checked.
 306      */
 307     public boolean isAccessible(Env<AttrContext> env, TypeSymbol c) {
 308         return isAccessible(env, c, false);
 309     }
 310 
 311     public boolean isAccessible(Env<AttrContext> env, TypeSymbol c, boolean checkInner) {
 312 
 313         /* 15.9.5.1: Note that it is possible for the signature of the anonymous constructor
 314            to refer to an inaccessible type
 315         */
 316         if (env.enclMethod != null && (env.enclMethod.mods.flags & ANONCONSTR) != 0)

 388         if (t.hasTag(ARRAY)) {
 389             return isAccessible(env, types.cvarUpperBound(types.elemtype(t)));
 390         } else if (t.isUnion()) {
 391             return StreamSupport.stream(((UnionClassType) t).getAlternativeTypes().spliterator(), false)
 392                     .allMatch(alternative -> isAccessible(env, alternative.tsym, checkInner));
 393         } else {
 394             return isAccessible(env, t.tsym, checkInner);
 395         }
 396     }
 397 
 398     /** Is symbol accessible as a member of given type in given environment?
 399      *  @param env    The current environment.
 400      *  @param site   The type of which the tested symbol is regarded
 401      *                as a member.
 402      *  @param sym    The symbol.
 403      */
 404     public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym) {
 405         return isAccessible(env, site, sym, false);
 406     }
 407     public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym, boolean checkInner) {
 408         if (names.isInitOrVNew(sym.name) && sym.owner != site.tsym) return false;
 409 
 410         /* 15.9.5.1: Note that it is possible for the signature of the anonymous constructor
 411            to refer to an inaccessible type
 412         */
 413         if (env.enclMethod != null && (env.enclMethod.mods.flags & ANONCONSTR) != 0)
 414             return true;
 415 
 416         if (env.info.visitingServiceImplementation &&
 417             env.toplevel.modle == sym.packge().modle) {
 418             return true;
 419         }
 420 
 421         ClassSymbol enclosingCsym = env.enclClass.sym;
 422         if (allowPrimitiveClasses) {
 423             if (sym.kind == MTH || sym.kind == VAR) {
 424                 /* If any primitive class types are involved, ask the same question in the reference universe,
 425                    where the hierarchy is navigable
 426                 */
 427                 if (site.isPrimitiveClass())
 428                     site = site.referenceProjection();
 429             } else if (sym.kind == TYP) {
 430                 // A type is accessible in a reference projection if it was
 431                 // accessible in the value projection.
 432                 if (site.isReferenceProjection())
 433                     site = site.valueProjection();
 434             }
 435         }
 436         try {
 437             switch ((short)(sym.flags() & AccessFlags)) {
 438                 case PRIVATE:
 439                     return
 440                             (env.enclClass.sym == sym.owner // fast special case
 441                                     ||
 442                                     env.enclClass.sym.outermostClass() ==
 443                                             sym.owner.outermostClass())
 444                                     &&
 445                                     sym.isInheritedIn(site.tsym, types);
 446                 case 0:
 447                     return
 448                             (env.toplevel.packge == sym.owner.owner // fast special case
 449                                     ||
 450                                     env.toplevel.packge == sym.packge())
 451                                     &&
 452                                     isAccessible(env, site, checkInner)
 453                                     &&
 454                                     sym.isInheritedIn(site.tsym, types)
 455                                     &&
 456                                     notOverriddenIn(site, sym);
 457                 case PROTECTED:
 458                     return
 459                             (env.toplevel.packge == sym.owner.owner // fast special case
 460                                     ||
 461                                     env.toplevel.packge == sym.packge()
 462                                     ||
 463                                     isProtectedAccessible(sym, env.enclClass.sym, site)
 464                                     ||
 465                                     // OK to select instance method or field from 'super' or type name
 466                                     // (but type names should be disallowed elsewhere!)
 467                                     env.info.selectSuper && (sym.flags() & STATIC) == 0 && sym.kind != TYP)
 468                                     &&
 469                                     isAccessible(env, site, checkInner)
 470                                     &&
 471                                     notOverriddenIn(site, sym);
 472                 default: // this case includes erroneous combinations as well
 473                     return isAccessible(env, site, checkInner) && notOverriddenIn(site, sym);
 474             }
 475         } finally {
 476             env.enclClass.sym = enclosingCsym;
 477         }
 478     }
 479     //where
 480     /* `sym' is accessible only if not overridden by
 481      * another symbol which is a member of `site'
 482      * (because, if it is overridden, `sym' is not strictly
 483      * speaking a member of `site'). A polymorphic signature method
 484      * cannot be overridden (e.g. MH.invokeExact(Object[])).
 485      */
 486     private boolean notOverriddenIn(Type site, Symbol sym) {
 487         if (sym.kind != MTH || sym.isInitOrVNew() || sym.isStatic())
 488             return true;
 489 
 490         /* If any primitive class types are involved, ask the same question in the reference universe,
 491            where the hierarchy is navigable
 492         */
 493         if (allowPrimitiveClasses && site.isPrimitiveClass()) {
 494             site = site.referenceProjection();
 495         }
 496 
 497         Symbol s2 = ((MethodSymbol)sym).implementation(site.tsym, types, true);
 498         return (s2 == null || s2 == sym || sym.owner == s2.owner || (sym.owner.isInterface() && s2.owner == syms.objectType.tsym) ||
 499                 !types.isSubSignature(types.memberType(site, s2), types.memberType(site, sym)));
 500     }
 501     //where
 502         /** Is given protected symbol accessible if it is selected from given site
 503          *  and the selection takes place in given class?
 504          *  @param sym     The symbol with protected access
 505          *  @param c       The class where the access takes place
 506          *  @site          The type of the qualifier
 507          */
 508         private
 509         boolean isProtectedAccessible(Symbol sym, ClassSymbol c, Type site) {
 510             Type newSite = site.hasTag(TYPEVAR) ? site.getUpperBound() : site;
 511             while (c != null &&
 512                    !(c.isSubClass(sym.owner, types) &&
 513                      (c.flags() & INTERFACE) == 0 &&
 514                      // In JLS 2e 6.6.2.1, the subclass restriction applies
 515                      // only to instance fields and methods -- types are excluded
 516                      // regardless of whether they are declared 'static' or not.
 517                      ((sym.flags() & STATIC) != 0 || sym.kind == TYP || newSite.tsym.isSubClass(c, types))))
 518                 c = c.owner.enclClass();
 519             return c != null;

1699 
1700                 // same signature; select (a) the non-bridge method, or
1701                 // (b) the one that overrides the other, or (c) the concrete
1702                 // one, or (d) merge both abstract signatures
1703                 if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE))
1704                     return ((m1.flags() & BRIDGE) != 0) ? m2 : m1;
1705 
1706                 if (m1.baseSymbol() == m2.baseSymbol()) {
1707                     // this is the same imported symbol which has been cloned twice.
1708                     // Return the first one (either will do).
1709                     return m1;
1710                 }
1711 
1712                 // if one overrides or hides the other, use it
1713                 TypeSymbol m1Owner = (TypeSymbol)m1.owner;
1714                 TypeSymbol m2Owner = (TypeSymbol)m2.owner;
1715                 // the two owners can never be the same if the target methods are compiled from source,
1716                 // but we need to protect against cases where the methods are defined in some classfile
1717                 // and make sure we issue an ambiguity error accordingly (by skipping the logic below).
1718                 if (m1Owner != m2Owner) {
1719                     if (types.asSuper(m1Owner.type.referenceProjectionOrSelf(), m2Owner) != null &&
1720                         ((m1.owner.flags_field & INTERFACE) == 0 ||
1721                          (m2.owner.flags_field & INTERFACE) != 0) &&
1722                         m1.overrides(m2, m1Owner, types, false))
1723                         return m1;
1724                     if (types.asSuper(m2Owner.type.referenceProjectionOrSelf(), m1Owner) != null &&
1725                         ((m2.owner.flags_field & INTERFACE) == 0 ||
1726                          (m1.owner.flags_field & INTERFACE) != 0) &&
1727                         m2.overrides(m1, m2Owner, types, false))
1728                         return m2;
1729                 }
1730                 boolean m1Abstract = (m1.flags() & ABSTRACT) != 0;
1731                 boolean m2Abstract = (m2.flags() & ABSTRACT) != 0;
1732                 if (m1Abstract && !m2Abstract) return m2;
1733                 if (m2Abstract && !m1Abstract) return m1;
1734                 // both abstract or both concrete
1735                 return ambiguityError(m1, m2);
1736             }
1737             if (m1SignatureMoreSpecific) return m1;
1738             if (m2SignatureMoreSpecific) return m2;
1739             return ambiguityError(m1, m2);
1740         case AMBIGUOUS:
1741             //compare m1 to ambiguous methods in m2
1742             AmbiguityError e = (AmbiguityError)m2.baseSymbol();
1743             boolean m1MoreSpecificThanAnyAmbiguous = true;
1744             boolean allAmbiguousMoreSpecificThanM1 = true;

1871         return bestSoFar;
1872     }
1873     // where
1874     private Symbol findMethod(Env<AttrContext> env,
1875                               Type site,
1876                               Name name,
1877                               List<Type> argtypes,
1878                               List<Type> typeargtypes,
1879                               Type intype,
1880                               Symbol bestSoFar,
1881                               boolean allowBoxing,
1882                               boolean useVarargs) {
1883         @SuppressWarnings({"unchecked","rawtypes"})
1884         List<Type>[] itypes = (List<Type>[])new List[] { List.<Type>nil(), List.<Type>nil() };
1885 
1886         InterfaceLookupPhase iphase = InterfaceLookupPhase.ABSTRACT_OK;
1887         boolean isInterface = site.tsym.isInterface();
1888         for (TypeSymbol s : isInterface ? List.of(intype.tsym) : superclasses(intype)) {
1889             bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
1890                     s.members(), bestSoFar, allowBoxing, useVarargs, true);
1891             if (names.isInitOrVNew(name)) return bestSoFar;
1892             iphase = (iphase == null) ? null : iphase.update(s, this);
1893             if (iphase != null) {
1894                 for (Type itype : types.interfaces(s.type)) {
1895                     itypes[iphase.ordinal()] = types.union(types.closure(itype), itypes[iphase.ordinal()]);
1896                 }
1897             }
1898         }
1899 
1900         Symbol concrete = bestSoFar.kind.isValid() &&
1901                 (bestSoFar.flags() & ABSTRACT) == 0 ?
1902                 bestSoFar : methodNotFound;
1903 
1904         for (InterfaceLookupPhase iphase2 : InterfaceLookupPhase.values()) {
1905             //keep searching for abstract methods
1906             for (Type itype : itypes[iphase2.ordinal()]) {
1907                 if (!itype.isInterface()) continue; //skip j.l.Object (included by Types.closure())
1908                 if (iphase2 == InterfaceLookupPhase.DEFAULT_OK &&
1909                         (itype.tsym.flags() & DEFAULT) == 0) continue;
1910                 bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
1911                         itype.tsym.members(), bestSoFar, allowBoxing, useVarargs, true);

2306                 bestSoFar = new AmbiguityError(bestSoFar, sym);
2307             else
2308                 bestSoFar = bestOf(bestSoFar, sym);
2309         }
2310         return bestSoFar;
2311     }
2312 
2313     /** Find qualified member type.
2314      *  @param env       The current environment.
2315      *  @param site      The original type from where the selection takes
2316      *                   place.
2317      *  @param name      The type's name.
2318      *  @param c         The class to search for the member type. This is
2319      *                   always a superclass or implemented interface of
2320      *                   site's class.
2321      */
2322     Symbol findMemberType(Env<AttrContext> env,
2323                           Type site,
2324                           Name name,
2325                           TypeSymbol c) {
2326         return findMemberTypeInternal(env,site, name, c);
2327     }
2328 
2329     /** Find qualified member type.
2330      *  @param env       The current environment.
2331      *  @param site      The original type from where the selection takes
2332      *                   place.
2333      *  @param name      The type's name.
2334      *  @param c         The class to search for the member type. This is
2335      *                   always a superclass or implemented interface of
2336      *                   site's class.
2337      */
2338     Symbol findMemberTypeInternal(Env<AttrContext> env,
2339                           Type site,
2340                           Name name,
2341                           TypeSymbol c) {
2342         Symbol sym = findImmediateMemberType(env, site, name, c);
2343 
2344         if (sym != typeNotFound)
2345             return sym;
2346 
2347         return findInheritedMemberType(env, site, name, c);
2348 
2349     }
2350 
2351     /** Find a global type in given scope and load corresponding class.
2352      *  @param env       The current environment.
2353      *  @param scope     The scope in which to look for the type.
2354      *  @param name      The type's name.
2355      */
2356     Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name, RecoveryLoadClass recoveryLoadClass) {
2357         Symbol bestSoFar = typeNotFound;
2358         for (Symbol s : scope.getSymbolsByName(name)) {
2359             Symbol sym = loadClass(env, s.flatName(), recoveryLoadClass);
2360             if (bestSoFar.kind == TYP && sym.kind == TYP &&
2361                 bestSoFar != sym)

2370         for (Symbol sym : env.info.scope.getSymbolsByName(name)) {
2371             if (sym.kind == TYP) {
2372                 if (sym.type.hasTag(TYPEVAR) &&
2373                         (staticOnly || (isStatic(env) && sym.owner.kind == TYP)))
2374                     // if staticOnly is set, it means that we have recursed through a static declaration,
2375                     // so type variable symbols should not be accessible. If staticOnly is unset, but
2376                     // we are in a static declaration (field or method), we should not allow type-variables
2377                     // defined in the enclosing class to "leak" into this context.
2378                     return new StaticError(sym);
2379                 return sym;
2380             }
2381         }
2382         return typeNotFound;
2383     }
2384 
2385     /** Find an unqualified type symbol.
2386      *  @param env       The current environment.
2387      *  @param name      The type's name.
2388      */
2389     Symbol findType(Env<AttrContext> env, Name name) {
2390         return findTypeInternal(env, name);
2391     }
2392 
2393     /** Find an unqualified type symbol.
2394      *  @param env       The current environment.
2395      *  @param name      The type's name.
2396      */
2397     Symbol findTypeInternal(Env<AttrContext> env, Name name) {
2398         if (name == names.empty)
2399             return typeNotFound; // do not allow inadvertent "lookup" of anonymous types
2400         Symbol bestSoFar = typeNotFound;
2401         Symbol sym;
2402         boolean staticOnly = false;
2403         for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
2404             // First, look for a type variable and the first member type
2405             final Symbol tyvar = findTypeVar(env1, name, staticOnly);
2406             if (isStatic(env1)) staticOnly = true;
2407             sym = findImmediateMemberType(env1, env1.enclClass.sym.type,
2408                                           name, env1.enclClass.sym);
2409 
2410             // Return the type variable if we have it, and have no
2411             // immediate member, OR the type variable is for a method.
2412             if (tyvar != typeNotFound) {
2413                 if (env.baseClause || sym == typeNotFound ||
2414                     (tyvar.kind == TYP && tyvar.exists() &&
2415                      tyvar.owner.kind == MTH)) {
2416                     return tyvar;
2417                 }

2916      *  @param site      The type of class for which a constructor is searched.
2917      *  @param argtypes  The types of the constructor invocation's value
2918      *                   arguments.
2919      *  @param typeargtypes  The types of the constructor invocation's type
2920      *                   arguments.
2921      */
2922     Symbol resolveConstructor(DiagnosticPosition pos,
2923                               Env<AttrContext> env,
2924                               Type site,
2925                               List<Type> argtypes,
2926                               List<Type> typeargtypes) {
2927         return resolveConstructor(new MethodResolutionContext(), pos, env, site, argtypes, typeargtypes);
2928     }
2929 
2930     private Symbol resolveConstructor(MethodResolutionContext resolveContext,
2931                               final DiagnosticPosition pos,
2932                               Env<AttrContext> env,
2933                               Type site,
2934                               List<Type> argtypes,
2935                               List<Type> typeargtypes) {
2936         Name constructorName = site.tsym.isConcreteValueClass() ? names.vnew : names.init;
2937         return lookupMethod(env, pos, site.tsym, resolveContext, new BasicLookupHelper(constructorName, site, argtypes, typeargtypes) {
2938             @Override
2939             Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2940                 return findConstructor(pos, env, site, argtypes, typeargtypes,
2941                         phase.isBoxingRequired(),
2942                         phase.isVarargsRequired());
2943             }
2944         });
2945     }
2946 
2947     /** Resolve a constructor, throw a fatal error if not found.
2948      *  @param pos       The position to use for error reporting.
2949      *  @param env       The environment current at the method invocation.
2950      *  @param site      The type to be constructed.
2951      *  @param argtypes  The types of the invocation's value arguments.
2952      *  @param typeargtypes  The types of the invocation's type arguments.
2953      */
2954     public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
2955                                         Type site,
2956                                         List<Type> argtypes,
2957                                         List<Type> typeargtypes) {
2958         MethodResolutionContext resolveContext = new MethodResolutionContext();
2959         resolveContext.internalResolution = true;
2960         Symbol sym = resolveConstructor(resolveContext, pos, env, site, argtypes, typeargtypes);
2961         if (sym.kind == MTH) return (MethodSymbol)sym;
2962         else throw new FatalError(
2963                  diags.fragment(Fragments.FatalErrCantLocateCtor(site)));
2964     }
2965 
2966     Symbol findConstructor(DiagnosticPosition pos, Env<AttrContext> env,
2967                               Type site, List<Type> argtypes,
2968                               List<Type> typeargtypes,
2969                               boolean allowBoxing,
2970                               boolean useVarargs) {
2971         Name constructorName = site.tsym.isConcreteValueClass() ? names.vnew : names.init;
2972         Symbol sym = findMethod(env, site,
2973                                     constructorName, argtypes,
2974                                     typeargtypes, allowBoxing,
2975                                     useVarargs);
2976         chk.checkDeprecated(pos, env.info.scope.owner, sym);
2977         chk.checkPreview(pos, env.info.scope.owner, sym);
2978         return sym;
2979     }
2980 
2981     /** Resolve constructor using diamond inference.
2982      *  @param pos       The position to use for error reporting.
2983      *  @param env       The environment current at the constructor invocation.
2984      *  @param site      The type of class for which a constructor is searched.
2985      *                   The scope of this class has been touched in attribution.
2986      *  @param argtypes  The types of the constructor invocation's value
2987      *                   arguments.
2988      *  @param typeargtypes  The types of the constructor invocation's type
2989      *                   arguments.
2990      */
2991     Symbol resolveDiamond(DiagnosticPosition pos,
2992                               Env<AttrContext> env,
2993                               Type site,
2994                               List<Type> argtypes,
2995                               List<Type> typeargtypes) {
2996         Name constructorName = allowValueClasses && site.tsym.isConcreteValueClass() ? names.vnew : names.init;
2997         return lookupMethod(env, pos, site.tsym, resolveMethodCheck,
2998                 new BasicLookupHelper(constructorName, site, argtypes, typeargtypes) {
2999                     @Override
3000                     Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
3001                         return findDiamond(pos, env, site, argtypes, typeargtypes,
3002                                 phase.isBoxingRequired(),
3003                                 phase.isVarargsRequired());
3004                     }
3005                     @Override
3006                     Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
3007                         if (sym.kind.isResolutionError()) {
3008                             if (sym.kind != WRONG_MTH &&
3009                                 sym.kind != WRONG_MTHS) {
3010                                 sym = super.access(env, pos, location, sym);
3011                             } else {
3012                                 sym = new DiamondError(sym, currentResolutionContext);
3013                                 sym = accessMethod(sym, pos, site, constructorName, true, argtypes, typeargtypes);
3014                                 env.info.pendingResolutionPhase = currentResolutionContext.step;
3015                             }
3016                         }
3017                         return sym;
3018                     }});
3019     }
3020 
3021     /** Find the constructor using diamond inference and do some checks(deprecated and preview).
3022      *  @param pos          The position to use for error reporting.
3023      *  @param env          The environment current at the constructor invocation.
3024      *  @param site         The type of class for which a constructor is searched.
3025      *                      The scope of this class has been touched in attribution.
3026      *  @param argtypes     The types of the constructor invocation's value arguments.
3027      *  @param typeargtypes The types of the constructor invocation's type arguments.
3028      *  @param allowBoxing  Allow boxing conversions of arguments.
3029      *  @param useVarargs   Box trailing arguments into an array for varargs.
3030      */
3031     private Symbol findDiamond(DiagnosticPosition pos,
3032                                Env<AttrContext> env,
3033                                Type site,

3040         chk.checkPreview(pos, env.info.scope.owner, sym);
3041         return sym;
3042     }
3043 
3044     /** This method scans all the constructor symbol in a given class scope -
3045      *  assuming that the original scope contains a constructor of the kind:
3046      *  {@code Foo(X x, Y y)}, where X,Y are class type-variables declared in Foo,
3047      *  a method check is executed against the modified constructor type:
3048      *  {@code <X,Y>Foo<X,Y>(X x, Y y)}. This is crucial in order to enable diamond
3049      *  inference. The inferred return type of the synthetic constructor IS
3050      *  the inferred type for the diamond operator.
3051      */
3052     private Symbol findDiamond(Env<AttrContext> env,
3053                               Type site,
3054                               List<Type> argtypes,
3055                               List<Type> typeargtypes,
3056                               boolean allowBoxing,
3057                               boolean useVarargs) {
3058         Symbol bestSoFar = methodNotFound;
3059         TypeSymbol tsym = site.tsym.isInterface() ? syms.objectType.tsym : site.tsym;
3060         Name constructorName = site.tsym.isConcreteValueClass() ? names.vnew : names.init;
3061         for (final Symbol sym : tsym.members().getSymbolsByName(constructorName)) {
3062             //- System.out.println(" e " + e.sym);
3063             if (sym.kind == MTH &&
3064                 (sym.flags_field & SYNTHETIC) == 0) {
3065                     List<Type> oldParams = sym.type.hasTag(FORALL) ?
3066                             ((ForAll)sym.type).tvars :
3067                             List.nil();
3068                     Type constrType = new ForAll(site.tsym.type.getTypeArguments().appendList(oldParams),
3069                                                  types.createMethodTypeWithReturn(sym.type.asMethodType(), site));
3070                     MethodSymbol newConstr = new MethodSymbol(sym.flags(), constructorName, constrType, site.tsym) {
3071                         @Override
3072                         public Symbol baseSymbol() {
3073                             return sym;
3074                         }
3075                     };
3076                     bestSoFar = selectBest(env, site, argtypes, typeargtypes,
3077                             newConstr,
3078                             bestSoFar,
3079                             allowBoxing,
3080                             useVarargs);
3081             }
3082         }
3083         return bestSoFar;
3084     }
3085 
3086     Symbol getMemberReference(DiagnosticPosition pos,
3087             Env<AttrContext> env,
3088             JCMemberReference referenceTree,
3089             Type site,
3090             Name name) {

3092         site = types.capture(site);
3093 
3094         ReferenceLookupHelper lookupHelper = makeReferenceLookupHelper(
3095                 referenceTree, site, name, List.nil(), null, VARARITY);
3096 
3097         Env<AttrContext> newEnv = env.dup(env.tree, env.info.dup());
3098         Symbol sym = lookupMethod(newEnv, env.tree.pos(), site.tsym,
3099                 nilMethodCheck, lookupHelper);
3100 
3101         env.info.pendingResolutionPhase = newEnv.info.pendingResolutionPhase;
3102 
3103         return sym;
3104     }
3105 
3106     ReferenceLookupHelper makeReferenceLookupHelper(JCMemberReference referenceTree,
3107                                   Type site,
3108                                   Name name,
3109                                   List<Type> argtypes,
3110                                   List<Type> typeargtypes,
3111                                   MethodResolutionPhase maxPhase) {
3112         if (!names.isInitOrVNew(name)) {
3113             //method reference
3114             return new MethodReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
3115         } else if (site.hasTag(ARRAY)) {
3116             //array constructor reference
3117             return new ArrayConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase);
3118         } else {
3119             //class constructor reference
3120             return new ConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase);
3121         }
3122     }
3123 
3124     /**
3125      * Resolution of member references is typically done as a single
3126      * overload resolution step, where the argument types A are inferred from
3127      * the target functional descriptor.
3128      *
3129      * If the member reference is a method reference with a type qualifier,
3130      * a two-step lookup process is performed. The first step uses the
3131      * expected argument list A, while the second step discards the first
3132      * type from A (which is treated as a receiver type).

3606         /** The original method reference lookup site. */
3607         Type originalSite;
3608 
3609         MethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
3610                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
3611             super(referenceTree, name, types.skipTypeVars(site, true), argtypes, typeargtypes, maxPhase);
3612             this.originalSite = site;
3613         }
3614 
3615         @Override
3616         final Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
3617             return findMethod(env, site, name, argtypes, typeargtypes,
3618                     phase.isBoxingRequired(), phase.isVarargsRequired());
3619         }
3620 
3621         @Override
3622         ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
3623             if (TreeInfo.isStaticSelector(referenceTree.expr, names)) {
3624                 if (argtypes.nonEmpty() &&
3625                         (argtypes.head.hasTag(NONE) ||
3626                         types.isSubtypeUnchecked(inferenceContext.asUndetVar(argtypes.head.referenceProjectionOrSelf()), originalSite))) {
3627                     return new UnboundMethodReferenceLookupHelper(referenceTree, name,
3628                             originalSite, argtypes, typeargtypes, maxPhase);
3629                 } else {
3630                     return new ReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase) {
3631                         @Override
3632                         ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
3633                             return this;
3634                         }
3635 
3636                         @Override
3637                         Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
3638                             return methodNotFound;
3639                         }
3640 
3641                         @Override
3642                         ReferenceKind referenceKind(Symbol sym) {
3643                             Assert.error();
3644                             return null;
3645                         }
3646                     };

3659                 return selName != null && selName == names._super ?
3660                         ReferenceKind.SUPER :
3661                         ReferenceKind.BOUND;
3662             }
3663         }
3664     }
3665 
3666     /**
3667      * Helper class for unbound method reference lookup. Essentially the same
3668      * as the basic method reference lookup helper; main difference is that static
3669      * lookup results are thrown away. If qualifier type is raw, an attempt to
3670      * infer a parameterized type is made using the first actual argument (that
3671      * would otherwise be ignored during the lookup).
3672      */
3673     class UnboundMethodReferenceLookupHelper extends MethodReferenceLookupHelper {
3674 
3675         UnboundMethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
3676                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
3677             super(referenceTree, name, site, argtypes.tail, typeargtypes, maxPhase);
3678             if (site.isRaw() && !argtypes.head.hasTag(NONE)) {
3679                 Type asSuperSite = types.asSuper(argtypes.head.referenceProjectionOrSelf(), site.tsym);
3680                 this.site = types.skipTypeVars(asSuperSite, true);
3681             }
3682         }
3683 
3684         @Override
3685         ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
3686             return this;
3687         }
3688 
3689         @Override
3690         ReferenceKind referenceKind(Symbol sym) {
3691             return ReferenceKind.UNBOUND;
3692         }
3693     }
3694 
3695     /**
3696      * Helper class for array constructor lookup; an array constructor lookup
3697      * is simulated by looking up a method that returns the array type specified
3698      * as qualifier, and that accepts a single int parameter (size of the array).
3699      */
3700     class ArrayConstructorReferenceLookupHelper extends ReferenceLookupHelper {
3701 
3702         ArrayConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
3703                 List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
3704             // TODO - array constructor will be <init>
3705             super(referenceTree, site.tsym.isConcreteValueClass() ? names.vnew : names.init, site, argtypes, typeargtypes, maxPhase);
3706         }
3707 
3708         @Override
3709         protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
3710             WriteableScope sc = WriteableScope.create(syms.arrayClass);
3711             MethodSymbol arrayConstr = new MethodSymbol(PUBLIC, name, null, site.tsym);
3712             arrayConstr.type = new MethodType(List.of(syms.intType), site, List.nil(), syms.methodClass);
3713             sc.enter(arrayConstr);
3714             return findMethodInScope(env, site, name, argtypes, typeargtypes, sc, methodNotFound, phase.isBoxingRequired(), phase.isVarargsRequired(), false);
3715         }
3716 
3717         @Override
3718         ReferenceKind referenceKind(Symbol sym) {
3719             return ReferenceKind.ARRAY_CTOR;
3720         }
3721     }
3722 
3723     /**
3724      * Helper class for constructor reference lookup. The lookup logic is based
3725      * upon either Resolve.findMethod or Resolve.findDiamond - depending on
3726      * whether the constructor reference needs diamond inference (this is the case
3727      * if the qualifier type is raw). A special erroneous symbol is returned
3728      * if the lookup returns the constructor of an inner class and there's no
3729      * enclosing instance in scope.
3730      */
3731     class ConstructorReferenceLookupHelper extends ReferenceLookupHelper {
3732 
3733         boolean needsInference;
3734 
3735         ConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
3736                 List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
3737             super(referenceTree, site.tsym.isConcreteValueClass() ? names.vnew : names.init, site, argtypes, typeargtypes, maxPhase);
3738             if (site.isRaw()) {
3739                 this.site = new ClassType(site.getEnclosingType(),
3740                         !(site.tsym.isInner() && site.getEnclosingType().isRaw()) ?
3741                             site.tsym.type.getTypeArguments() : List.nil(), site.tsym, site.getMetadata(), site.getFlavor());
3742                 needsInference = true;
3743             }
3744         }
3745 
3746         @Override
3747         protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
3748             Symbol sym = needsInference ?
3749                 findDiamond(env, site, argtypes, typeargtypes, phase.isBoxingRequired(), phase.isVarargsRequired()) :
3750                 findMethod(env, site, name, argtypes, typeargtypes,
3751                         phase.isBoxingRequired(), phase.isVarargsRequired());
3752             return enclosingInstanceMissing(env, site) ? new BadConstructorReferenceError(sym) : sym;
3753         }
3754 
3755         @Override
3756         ReferenceKind referenceKind(Symbol sym) {
3757             return site.getEnclosingType().hasTag(NONE) ?
3758                     ReferenceKind.TOPLEVEL : ReferenceKind.IMPLICIT_INNER;
3759         }
3760     }
3761 

3811             if (isStatic(env1)) staticOnly = true;
3812             if (env1.enclClass.sym == c) {
3813                 Symbol sym = env1.info.scope.findFirst(name);
3814                 if (sym != null) {
3815                     if (staticOnly) sym = new StaticError(sym);
3816                     return accessBase(sym, pos, env.enclClass.sym.type,
3817                                   name, true);
3818                 }
3819             }
3820             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
3821             env1 = env1.outer;
3822         }
3823         if (c.isInterface() &&
3824             name == names._super && !isStatic(env) &&
3825             types.isDirectSuperInterface(c, env.enclClass.sym)) {
3826             //this might be a default super call if one of the superinterfaces is 'c'
3827             for (Type t : pruneInterfaces(env.enclClass.type)) {
3828                 if (t.tsym == c) {
3829                     env.info.defaultSuperCallSite = t;
3830                     return new VarSymbol(0, names._super,
3831                             types.asSuper(env.enclClass.type.referenceProjectionOrSelf(), c), env.enclClass.sym);
3832                 }
3833             }
3834             //find a direct supertype that is a subtype of 'c'
3835             for (Type i : types.directSupertypes(env.enclClass.type)) {
3836                 if (i.tsym.isSubClass(c, types) && i.tsym != c) {
3837                     log.error(pos,
3838                               Errors.IllegalDefaultSuperCall(c,
3839                                                              Fragments.RedundantSupertype(c, i)));
3840                     return syms.errSymbol;
3841                 }
3842             }
3843             Assert.error();
3844         }
3845         log.error(pos, Errors.NotEnclClass(c));
3846         return syms.errSymbol;
3847     }
3848     //where
3849     private List<Type> pruneInterfaces(Type t) {
3850         ListBuffer<Type> result = new ListBuffer<>();
3851         for (Type t1 : types.interfaces(t)) {

4124                 Name name,
4125                 List<Type> argtypes,
4126                 List<Type> typeargtypes) {
4127             argtypes = argtypes == null ? List.nil() : argtypes;
4128             typeargtypes = typeargtypes == null ? List.nil() : typeargtypes;
4129             if (name == names.error)
4130                 return null;
4131 
4132             boolean hasLocation = false;
4133             if (location == null) {
4134                 location = site.tsym;
4135             }
4136             if (!location.name.isEmpty()) {
4137                 if (location.kind == PCK && !site.tsym.exists() && location.name != names.java) {
4138                     return diags.create(dkind, log.currentSource(), pos,
4139                         "doesnt.exist", location);
4140                 }
4141                 hasLocation = !location.name.equals(names._this) &&
4142                         !location.name.equals(names._super);
4143             }
4144             boolean isConstructor = names.isInitOrVNew(name);
4145             KindName kindname = isConstructor ? KindName.CONSTRUCTOR : kind.absentKind();
4146             Name idname = isConstructor ? site.tsym.name : name;
4147             String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation);
4148             if (hasLocation) {
4149                 return diags.create(dkind, log.currentSource(), pos,
4150                         errKey, kindname, idname, //symbol kindname, name
4151                         typeargtypes, args(argtypes), //type parameters and arguments (if any)
4152                         getLocationDiag(location, site)); //location kindname, type
4153             }
4154             else {
4155                 return diags.create(dkind, log.currentSource(), pos,
4156                         errKey, kindname, idname, //symbol kindname, name
4157                         typeargtypes, args(argtypes)); //type parameters and arguments (if any)
4158             }
4159         }
4160         //where
4161         private Object args(List<Type> args) {
4162             return args.isEmpty() ? args : methodArguments(args);
4163         }
4164 

4216         }
4217 
4218         @Override
4219         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
4220                 DiagnosticPosition pos,
4221                 Symbol location,
4222                 Type site,
4223                 Name name,
4224                 List<Type> argtypes,
4225                 List<Type> typeargtypes) {
4226             if (name == names.error)
4227                 return null;
4228 
4229             Pair<Symbol, JCDiagnostic> c = errCandidate();
4230             Symbol ws = c.fst.asMemberOf(site, types);
4231             return diags.create(dkind, log.currentSource(), pos,
4232                       "cant.apply.symbol",
4233                       compactMethodDiags ?
4234                               d -> MethodResolutionDiagHelper.rewrite(diags, pos, log.currentSource(), dkind, c.snd) : null,
4235                       kindName(ws),
4236                       names.isInitOrVNew(ws.name) ? ws.owner.name : ws.name,
4237                       methodArguments(ws.type.getParameterTypes()),
4238                       methodArguments(argtypes),
4239                       kindName(ws.owner),
4240                       ws.owner.type,
4241                       c.snd);
4242         }
4243 
4244         @Override
4245         public Symbol access(Name name, TypeSymbol location) {
4246             Pair<Symbol, JCDiagnostic> cand = errCandidate();
4247             TypeSymbol errSymbol = types.createErrorType(name, location, cand != null ? cand.fst.type : syms.errSymbol.type).tsym;
4248             if (cand != null) {
4249                 attrRecover.wrongMethodSymbolCandidate(errSymbol, cand.fst, cand.snd);
4250             }
4251             return errSymbol;
4252         }
4253 
4254         protected Pair<Symbol, JCDiagnostic> errCandidate() {
4255             Candidate bestSoFar = null;
4256             for (Candidate c : resolveContext.candidates) {

4272             super(WRONG_MTHS, "inapplicable symbols", context);
4273         }
4274 
4275         @Override
4276         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
4277                 DiagnosticPosition pos,
4278                 Symbol location,
4279                 Type site,
4280                 Name name,
4281                 List<Type> argtypes,
4282                 List<Type> typeargtypes) {
4283             Map<Symbol, JCDiagnostic> candidatesMap = mapCandidates();
4284             Map<Symbol, JCDiagnostic> filteredCandidates = compactMethodDiags ?
4285                     filterCandidates(candidatesMap) :
4286                     mapCandidates();
4287             if (filteredCandidates.isEmpty()) {
4288                 filteredCandidates = candidatesMap;
4289             }
4290             boolean truncatedDiag = candidatesMap.size() != filteredCandidates.size();
4291             if (filteredCandidates.size() > 1) {
4292                 boolean isConstructor = names.isInitOrVNew(name);
4293                 JCDiagnostic err = diags.create(dkind,
4294                         null,
4295                         truncatedDiag ?
4296                                 EnumSet.of(DiagnosticFlag.COMPRESSED) :
4297                                 EnumSet.noneOf(DiagnosticFlag.class),
4298                         log.currentSource(),
4299                         pos,
4300                         "cant.apply.symbols",
4301                         isConstructor ? KindName.CONSTRUCTOR : kind.absentKind(),
4302                         isConstructor ? site.tsym.name : name,
4303                         methodArguments(argtypes));
4304                 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(filteredCandidates, site));
4305             } else if (filteredCandidates.size() == 1) {
4306                 Map.Entry<Symbol, JCDiagnostic> _e =
4307                                 filteredCandidates.entrySet().iterator().next();
4308                 final Pair<Symbol, JCDiagnostic> p = new Pair<>(_e.getKey(), _e.getValue());
4309                 JCDiagnostic d = new InapplicableSymbolError(resolveContext) {
4310                     @Override
4311                     protected Pair<Symbol, JCDiagnostic> errCandidate() {
4312                         return p;
4313                     }
4314                 }.getDiagnostic(dkind, pos,
4315                     location, site, name, argtypes, typeargtypes);
4316                 if (truncatedDiag) {
4317                     d.setFlag(DiagnosticFlag.COMPRESSED);
4318                 }
4319                 return d;
4320             } else {
4321                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
4322                     location, site, name, argtypes, typeargtypes);

4442 
4443         AccessError(Env<AttrContext> env, Type site, Symbol sym) {
4444             super(HIDDEN, sym, "access error");
4445             this.env = env;
4446             this.site = site;
4447         }
4448 
4449         @Override
4450         public boolean exists() {
4451             return false;
4452         }
4453 
4454         @Override
4455         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
4456                 DiagnosticPosition pos,
4457                 Symbol location,
4458                 Type site,
4459                 Name name,
4460                 List<Type> argtypes,
4461                 List<Type> typeargtypes) {
4462             if (names.isInitOrVNew(sym.name) && sym.owner != site.tsym) {
4463                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
4464                         pos, location, site, name, argtypes, typeargtypes);
4465             }
4466             else if ((sym.flags() & PUBLIC) != 0
4467                 || (env != null && this.site != null
4468                     && !isAccessible(env, this.site))) {
4469                 if (sym.owner.kind == PCK) {
4470                     return diags.create(dkind, log.currentSource(),
4471                             pos, "not.def.access.package.cant.access",
4472                         sym, sym.location(), inaccessiblePackageReason(env, sym.packge()));
4473                 } else if (   sym.packge() != syms.rootPackage
4474                            && !symbolPackageVisible(env, sym)) {
4475                     return diags.create(dkind, log.currentSource(),
4476                             pos, "not.def.access.class.intf.cant.access.reason",
4477                             sym, sym.location(), sym.location().packge(),
4478                             inaccessiblePackageReason(env, sym.packge()));
4479                 } else {
4480                     return diags.create(dkind, log.currentSource(),
4481                             pos, "not.def.access.class.intf.cant.access",
4482                         sym, sym.location());

4655             }
4656         }
4657 
4658         AmbiguityError addAmbiguousSymbol(Symbol s) {
4659             ambiguousSyms = ambiguousSyms.prepend(s);
4660             return this;
4661         }
4662 
4663         @Override
4664         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
4665                 DiagnosticPosition pos,
4666                 Symbol location,
4667                 Type site,
4668                 Name name,
4669                 List<Type> argtypes,
4670                 List<Type> typeargtypes) {
4671             List<Symbol> diagSyms = ambiguousSyms.reverse();
4672             Symbol s1 = diagSyms.head;
4673             Symbol s2 = diagSyms.tail.head;
4674             Name sname = s1.name;
4675             if (names.isInitOrVNew(sname)) sname = s1.owner.name;
4676             return diags.create(dkind, log.currentSource(),
4677                     pos, "ref.ambiguous", sname,
4678                     kindName(s1),
4679                     s1,
4680                     s1.location(site, types),
4681                     kindName(s2),
4682                     s2,
4683                     s2.location(site, types));
4684         }
4685 
4686         /**
4687          * If multiple applicable methods are found during overload and none of them
4688          * is more specific than the others, attempt to merge their signatures.
4689          */
4690         Symbol mergeAbstracts(Type site) {
4691             List<Symbol> ambiguousInOrder = ambiguousSyms.reverse();
4692             return types.mergeAbstracts(ambiguousInOrder, site, true).orElse(this);
4693         }
4694 
4695         @Override
< prev index next >