< 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).

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

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

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

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

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

4167                 Type site,
4168                 Name name,
4169                 List<Type> argtypes,
4170                 List<Type> typeargtypes) {
4171             if (name == names.error)
4172                 return null;
4173 
4174             Pair<Symbol, JCDiagnostic> c = errCandidate();
4175             Symbol ws = c.fst.asMemberOf(site, types);
4176 
4177             // If the problem is due to type arguments, then the method parameters aren't relevant,
4178             // so use the error message that omits them to avoid confusion.
4179             switch (c.snd.getCode()) {
4180                 case "compiler.misc.wrong.number.type.args":
4181                 case "compiler.misc.explicit.param.do.not.conform.to.bounds":
4182                     return diags.create(dkind, log.currentSource(), pos,
4183                               "cant.apply.symbol.noargs",
4184                               compactMethodDiags ?
4185                                       d -> MethodResolutionDiagHelper.rewrite(diags, pos, log.currentSource(), dkind, c.snd) : null,
4186                               kindName(ws),
4187                               ws.name == names.init ? ws.owner.name : ws.name,
4188                               kindName(ws.owner),
4189                               ws.owner.type,
4190                               c.snd);
4191                 default:
4192                     return diags.create(dkind, log.currentSource(), pos,
4193                               "cant.apply.symbol",
4194                               compactMethodDiags ?
4195                                       d -> MethodResolutionDiagHelper.rewrite(diags, pos, log.currentSource(), dkind, c.snd) : null,
4196                               kindName(ws),
4197                               ws.name == names.init ? ws.owner.name : ws.name,
4198                               methodArguments(ws.type.getParameterTypes()),
4199                               methodArguments(argtypes),
4200                               kindName(ws.owner),
4201                               ws.owner.type,
4202                               c.snd);
4203             }
4204         }
4205 
4206         @Override
4207         public Symbol access(Name name, TypeSymbol location) {
4208             Pair<Symbol, JCDiagnostic> cand = errCandidate();
4209             TypeSymbol errSymbol = types.createErrorType(name, location, cand != null ? cand.fst.type : syms.errSymbol.type).tsym;
4210             if (cand != null) {
4211                 attrRecover.wrongMethodSymbolCandidate(errSymbol, cand.fst, cand.snd);
4212             }
4213             return errSymbol;
4214         }
4215 
4216         protected Pair<Symbol, JCDiagnostic> errCandidate() {
4217             Candidate bestSoFar = null;

4234             super(WRONG_MTHS, "inapplicable symbols", context);
4235         }
4236 
4237         @Override
4238         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
4239                 DiagnosticPosition pos,
4240                 Symbol location,
4241                 Type site,
4242                 Name name,
4243                 List<Type> argtypes,
4244                 List<Type> typeargtypes) {
4245             Map<Symbol, JCDiagnostic> candidatesMap = mapCandidates();
4246             Map<Symbol, JCDiagnostic> filteredCandidates = compactMethodDiags ?
4247                     filterCandidates(candidatesMap) :
4248                     mapCandidates();
4249             if (filteredCandidates.isEmpty()) {
4250                 filteredCandidates = candidatesMap;
4251             }
4252             boolean truncatedDiag = candidatesMap.size() != filteredCandidates.size();
4253             if (filteredCandidates.size() > 1) {

4254                 JCDiagnostic err = diags.create(dkind,
4255                         null,
4256                         truncatedDiag ?
4257                                 EnumSet.of(DiagnosticFlag.COMPRESSED) :
4258                                 EnumSet.noneOf(DiagnosticFlag.class),
4259                         log.currentSource(),
4260                         pos,
4261                         "cant.apply.symbols",
4262                         name == names.init ? KindName.CONSTRUCTOR : kind.absentKind(),
4263                         name == names.init ? site.tsym.name : name,
4264                         methodArguments(argtypes));
4265                 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(filteredCandidates, site));
4266             } else if (filteredCandidates.size() == 1) {
4267                 Map.Entry<Symbol, JCDiagnostic> _e =
4268                                 filteredCandidates.entrySet().iterator().next();
4269                 final Pair<Symbol, JCDiagnostic> p = new Pair<>(_e.getKey(), _e.getValue());
4270                 JCDiagnostic d = new InapplicableSymbolError(resolveContext) {
4271                     @Override
4272                     protected Pair<Symbol, JCDiagnostic> errCandidate() {
4273                         return p;
4274                     }
4275                 }.getDiagnostic(dkind, pos,
4276                     location, site, name, argtypes, typeargtypes);
4277                 if (truncatedDiag) {
4278                     d.setFlag(DiagnosticFlag.COMPRESSED);
4279                 }
4280                 return d;
4281             } else {
4282                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
4283                     location, site, name, argtypes, typeargtypes);

4403 
4404         AccessError(Env<AttrContext> env, Type site, Symbol sym) {
4405             super(HIDDEN, sym, "access error");
4406             this.env = env;
4407             this.site = site;
4408         }
4409 
4410         @Override
4411         public boolean exists() {
4412             return false;
4413         }
4414 
4415         @Override
4416         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
4417                 DiagnosticPosition pos,
4418                 Symbol location,
4419                 Type site,
4420                 Name name,
4421                 List<Type> argtypes,
4422                 List<Type> typeargtypes) {
4423             if (sym.name == names.init && sym.owner != site.tsym) {
4424                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
4425                         pos, location, site, name, argtypes, typeargtypes);
4426             }
4427             else if ((sym.flags() & PUBLIC) != 0
4428                 || (env != null && this.site != null
4429                     && !isAccessible(env, this.site))) {
4430                 if (sym.owner.kind == PCK) {
4431                     return diags.create(dkind, log.currentSource(),
4432                             pos, "not.def.access.package.cant.access",
4433                         sym, sym.location(), inaccessiblePackageReason(env, sym.packge()));
4434                 } else if (   sym.packge() != syms.rootPackage
4435                            && !symbolPackageVisible(env, sym)) {
4436                     return diags.create(dkind, log.currentSource(),
4437                             pos, "not.def.access.class.intf.cant.access.reason",
4438                             sym, sym.location(), sym.location().packge(),
4439                             inaccessiblePackageReason(env, sym.packge()));
4440                 } else {
4441                     return diags.create(dkind, log.currentSource(),
4442                             pos, "not.def.access.class.intf.cant.access",
4443                         sym, sym.location());

4616             }
4617         }
4618 
4619         AmbiguityError addAmbiguousSymbol(Symbol s) {
4620             ambiguousSyms = ambiguousSyms.prepend(s);
4621             return this;
4622         }
4623 
4624         @Override
4625         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
4626                 DiagnosticPosition pos,
4627                 Symbol location,
4628                 Type site,
4629                 Name name,
4630                 List<Type> argtypes,
4631                 List<Type> typeargtypes) {
4632             List<Symbol> diagSyms = ambiguousSyms.reverse();
4633             Symbol s1 = diagSyms.head;
4634             Symbol s2 = diagSyms.tail.head;
4635             Name sname = s1.name;
4636             if (sname == names.init) sname = s1.owner.name;
4637             return diags.create(dkind, log.currentSource(),
4638                     pos, "ref.ambiguous", sname,
4639                     kindName(s1),
4640                     s1,
4641                     s1.location(site, types),
4642                     kindName(s2),
4643                     s2,
4644                     s2.location(site, types));
4645         }
4646 
4647         /**
4648          * If multiple applicable methods are found during overload and none of them
4649          * is more specific than the others, attempt to merge their signatures.
4650          */
4651         Symbol mergeAbstracts(Type site) {
4652             List<Symbol> ambiguousInOrder = ambiguousSyms.reverse();
4653             return types.mergeAbstracts(ambiguousInOrder, site, true).orElse(this);
4654         }
4655 
4656         @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).

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

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

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

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

4223                 Type site,
4224                 Name name,
4225                 List<Type> argtypes,
4226                 List<Type> typeargtypes) {
4227             if (name == names.error)
4228                 return null;
4229 
4230             Pair<Symbol, JCDiagnostic> c = errCandidate();
4231             Symbol ws = c.fst.asMemberOf(site, types);
4232 
4233             // If the problem is due to type arguments, then the method parameters aren't relevant,
4234             // so use the error message that omits them to avoid confusion.
4235             switch (c.snd.getCode()) {
4236                 case "compiler.misc.wrong.number.type.args":
4237                 case "compiler.misc.explicit.param.do.not.conform.to.bounds":
4238                     return diags.create(dkind, log.currentSource(), pos,
4239                               "cant.apply.symbol.noargs",
4240                               compactMethodDiags ?
4241                                       d -> MethodResolutionDiagHelper.rewrite(diags, pos, log.currentSource(), dkind, c.snd) : null,
4242                               kindName(ws),
4243                               names.isInitOrVNew(ws.name) ? ws.owner.name : ws.name,

4244                               ws.owner.type,
4245                               c.snd);
4246                 default:
4247                     return diags.create(dkind, log.currentSource(), pos,
4248                               "cant.apply.symbol",
4249                               compactMethodDiags ?
4250                                       d -> MethodResolutionDiagHelper.rewrite(diags, pos, log.currentSource(), dkind, c.snd) : null,
4251                               kindName(ws),
4252                               names.isInitOrVNew(ws.name) ? ws.owner.name : ws.name,
4253                               methodArguments(ws.type.getParameterTypes()),
4254                               methodArguments(argtypes),
4255                               kindName(ws.owner),
4256                               ws.owner.type,
4257                               c.snd);
4258             }
4259         }
4260 
4261         @Override
4262         public Symbol access(Name name, TypeSymbol location) {
4263             Pair<Symbol, JCDiagnostic> cand = errCandidate();
4264             TypeSymbol errSymbol = types.createErrorType(name, location, cand != null ? cand.fst.type : syms.errSymbol.type).tsym;
4265             if (cand != null) {
4266                 attrRecover.wrongMethodSymbolCandidate(errSymbol, cand.fst, cand.snd);
4267             }
4268             return errSymbol;
4269         }
4270 
4271         protected Pair<Symbol, JCDiagnostic> errCandidate() {
4272             Candidate bestSoFar = null;

4289             super(WRONG_MTHS, "inapplicable symbols", context);
4290         }
4291 
4292         @Override
4293         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
4294                 DiagnosticPosition pos,
4295                 Symbol location,
4296                 Type site,
4297                 Name name,
4298                 List<Type> argtypes,
4299                 List<Type> typeargtypes) {
4300             Map<Symbol, JCDiagnostic> candidatesMap = mapCandidates();
4301             Map<Symbol, JCDiagnostic> filteredCandidates = compactMethodDiags ?
4302                     filterCandidates(candidatesMap) :
4303                     mapCandidates();
4304             if (filteredCandidates.isEmpty()) {
4305                 filteredCandidates = candidatesMap;
4306             }
4307             boolean truncatedDiag = candidatesMap.size() != filteredCandidates.size();
4308             if (filteredCandidates.size() > 1) {
4309                 boolean isConstructor = names.isInitOrVNew(name);
4310                 JCDiagnostic err = diags.create(dkind,
4311                         null,
4312                         truncatedDiag ?
4313                                 EnumSet.of(DiagnosticFlag.COMPRESSED) :
4314                                 EnumSet.noneOf(DiagnosticFlag.class),
4315                         log.currentSource(),
4316                         pos,
4317                         "cant.apply.symbols",
4318                         isConstructor ? KindName.CONSTRUCTOR : kind.absentKind(),
4319                         isConstructor ? site.tsym.name : name,
4320                         methodArguments(argtypes));
4321                 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(filteredCandidates, site));
4322             } else if (filteredCandidates.size() == 1) {
4323                 Map.Entry<Symbol, JCDiagnostic> _e =
4324                                 filteredCandidates.entrySet().iterator().next();
4325                 final Pair<Symbol, JCDiagnostic> p = new Pair<>(_e.getKey(), _e.getValue());
4326                 JCDiagnostic d = new InapplicableSymbolError(resolveContext) {
4327                     @Override
4328                     protected Pair<Symbol, JCDiagnostic> errCandidate() {
4329                         return p;
4330                     }
4331                 }.getDiagnostic(dkind, pos,
4332                     location, site, name, argtypes, typeargtypes);
4333                 if (truncatedDiag) {
4334                     d.setFlag(DiagnosticFlag.COMPRESSED);
4335                 }
4336                 return d;
4337             } else {
4338                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
4339                     location, site, name, argtypes, typeargtypes);

4459 
4460         AccessError(Env<AttrContext> env, Type site, Symbol sym) {
4461             super(HIDDEN, sym, "access error");
4462             this.env = env;
4463             this.site = site;
4464         }
4465 
4466         @Override
4467         public boolean exists() {
4468             return false;
4469         }
4470 
4471         @Override
4472         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
4473                 DiagnosticPosition pos,
4474                 Symbol location,
4475                 Type site,
4476                 Name name,
4477                 List<Type> argtypes,
4478                 List<Type> typeargtypes) {
4479             if (names.isInitOrVNew(sym.name) && sym.owner != site.tsym) {
4480                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
4481                         pos, location, site, name, argtypes, typeargtypes);
4482             }
4483             else if ((sym.flags() & PUBLIC) != 0
4484                 || (env != null && this.site != null
4485                     && !isAccessible(env, this.site))) {
4486                 if (sym.owner.kind == PCK) {
4487                     return diags.create(dkind, log.currentSource(),
4488                             pos, "not.def.access.package.cant.access",
4489                         sym, sym.location(), inaccessiblePackageReason(env, sym.packge()));
4490                 } else if (   sym.packge() != syms.rootPackage
4491                            && !symbolPackageVisible(env, sym)) {
4492                     return diags.create(dkind, log.currentSource(),
4493                             pos, "not.def.access.class.intf.cant.access.reason",
4494                             sym, sym.location(), sym.location().packge(),
4495                             inaccessiblePackageReason(env, sym.packge()));
4496                 } else {
4497                     return diags.create(dkind, log.currentSource(),
4498                             pos, "not.def.access.class.intf.cant.access",
4499                         sym, sym.location());

4672             }
4673         }
4674 
4675         AmbiguityError addAmbiguousSymbol(Symbol s) {
4676             ambiguousSyms = ambiguousSyms.prepend(s);
4677             return this;
4678         }
4679 
4680         @Override
4681         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
4682                 DiagnosticPosition pos,
4683                 Symbol location,
4684                 Type site,
4685                 Name name,
4686                 List<Type> argtypes,
4687                 List<Type> typeargtypes) {
4688             List<Symbol> diagSyms = ambiguousSyms.reverse();
4689             Symbol s1 = diagSyms.head;
4690             Symbol s2 = diagSyms.tail.head;
4691             Name sname = s1.name;
4692             if (names.isInitOrVNew(sname)) sname = s1.owner.name;
4693             return diags.create(dkind, log.currentSource(),
4694                     pos, "ref.ambiguous", sname,
4695                     kindName(s1),
4696                     s1,
4697                     s1.location(site, types),
4698                     kindName(s2),
4699                     s2,
4700                     s2.location(site, types));
4701         }
4702 
4703         /**
4704          * If multiple applicable methods are found during overload and none of them
4705          * is more specific than the others, attempt to merge their signatures.
4706          */
4707         Symbol mergeAbstracts(Type site) {
4708             List<Symbol> ambiguousInOrder = ambiguousSyms.reverse();
4709             return types.mergeAbstracts(ambiguousInOrder, site, true).orElse(this);
4710         }
4711 
4712         @Override
< prev index next >