1 /*
   2  * Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package com.sun.tools.javac.comp;
  27 
  28 import com.sun.tools.javac.api.Formattable.LocalizedString;
  29 import com.sun.tools.javac.code.*;
  30 import com.sun.tools.javac.code.Scope.WriteableScope;
  31 import com.sun.tools.javac.code.Source.Feature;
  32 import com.sun.tools.javac.code.Symbol.*;
  33 import com.sun.tools.javac.code.Type.*;
  34 import com.sun.tools.javac.comp.Attr.ResultInfo;
  35 import com.sun.tools.javac.comp.Check.CheckContext;
  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.stream.Stream;
  70 import java.util.stream.StreamSupport;
  71 
  72 import javax.lang.model.element.ElementVisitor;
  73 
  74 import static com.sun.tools.javac.code.Flags.*;
  75 import static com.sun.tools.javac.code.Flags.BLOCK;
  76 import static com.sun.tools.javac.code.Flags.STATIC;
  77 import static com.sun.tools.javac.code.Kinds.*;
  78 import static com.sun.tools.javac.code.Kinds.Kind.*;
  79 import static com.sun.tools.javac.code.TypeTag.*;
  80 import static com.sun.tools.javac.comp.Resolve.MethodResolutionPhase.*;
  81 import static com.sun.tools.javac.tree.JCTree.Tag.*;
  82 import static com.sun.tools.javac.util.Iterators.createCompoundIterator;
  83 
  84 /** Helper class for name resolution, used mostly by the attribution phase.
  85  *
  86  *  <p><b>This is NOT part of any supported API.
  87  *  If you write code that depends on this, you do so at your own risk.
  88  *  This code and its internal interfaces are subject to change or
  89  *  deletion without notice.</b>
  90  */
  91 public class Resolve {
  92     protected static final Context.Key<Resolve> resolveKey = new Context.Key<>();
  93 
  94     Names names;
  95     Log log;
  96     Symtab syms;
  97     Attr attr;
  98     AttrRecover attrRecover;
  99     DeferredAttr deferredAttr;
 100     Check chk;
 101     Infer infer;
 102     ClassFinder finder;
 103     ModuleFinder moduleFinder;
 104     Types types;
 105     JCDiagnostic.Factory diags;
 106     public final boolean allowFunctionalInterfaceMostSpecific;
 107     public final boolean allowModules;
 108     public final boolean allowRecords;
 109     public final boolean checkVarargsAccessAfterResolution;
 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 
 116     WriteableScope polymorphicSignatureScope;
 117 
 118     protected Resolve(Context context) {
 119         context.put(resolveKey, this);
 120         syms = Symtab.instance(context);
 121 
 122         varNotFound = new SymbolNotFoundError(ABSENT_VAR);
 123         methodNotFound = new SymbolNotFoundError(ABSENT_MTH);
 124         typeNotFound = new SymbolNotFoundError(ABSENT_TYP);
 125         referenceNotFound = ReferenceLookupResult.error(methodNotFound);
 126 
 127         names = Names.instance(context);
 128         log = Log.instance(context);
 129         attr = Attr.instance(context);
 130         attrRecover = AttrRecover.instance(context);
 131         deferredAttr = DeferredAttr.instance(context);
 132         chk = Check.instance(context);
 133         infer = Infer.instance(context);
 134         finder = ClassFinder.instance(context);
 135         moduleFinder = ModuleFinder.instance(context);
 136         types = Types.instance(context);
 137         diags = JCDiagnostic.Factory.instance(context);
 138         Preview preview = Preview.instance(context);
 139         Source source = Source.instance(context);
 140         Options options = Options.instance(context);
 141         compactMethodDiags = options.isSet(Option.XDIAGS, "compact") ||
 142                 options.isUnset(Option.XDIAGS) && options.isUnset("rawDiagnostics");
 143         verboseResolutionMode = VerboseResolutionMode.getVerboseResolutionMode(options);
 144         Target target = Target.instance(context);
 145         allowFunctionalInterfaceMostSpecific = Feature.FUNCTIONAL_INTERFACE_MOST_SPECIFIC.allowedInSource(source);
 146         allowLocalVariableTypeInference = Feature.LOCAL_VARIABLE_TYPE_INFERENCE.allowedInSource(source);
 147         allowYieldStatement = Feature.SWITCH_EXPRESSION.allowedInSource(source);
 148         checkVarargsAccessAfterResolution =
 149                 Feature.POST_APPLICABILITY_VARARGS_ACCESS_CHECK.allowedInSource(source);
 150         polymorphicSignatureScope = WriteableScope.create(syms.noSymbol);
 151         allowModules = Feature.MODULES.allowedInSource(source);
 152         allowRecords = Feature.RECORDS.allowedInSource(source);
 153         dumpMethodReferenceSearchResults = options.isSet("debug.dumpMethodReferenceSearchResults");
 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) {
 174         return s1.kind.betterThan(s2.kind) ? s1 : s2;
 175     }
 176 
 177     // <editor-fold defaultstate="collapsed" desc="Verbose resolution diagnostics support">
 178     enum VerboseResolutionMode {
 179         SUCCESS("success"),
 180         FAILURE("failure"),
 181         APPLICABLE("applicable"),
 182         INAPPLICABLE("inapplicable"),
 183         DEFERRED_INST("deferred-inference"),
 184         PREDEF("predef"),
 185         OBJECT_INIT("object-init"),
 186         INTERNAL("internal");
 187 
 188         final String opt;
 189 
 190         private VerboseResolutionMode(String opt) {
 191             this.opt = opt;
 192         }
 193 
 194         static EnumSet<VerboseResolutionMode> getVerboseResolutionMode(Options opts) {
 195             String s = opts.get("debug.verboseResolution");
 196             EnumSet<VerboseResolutionMode> res = EnumSet.noneOf(VerboseResolutionMode.class);
 197             if (s == null) return res;
 198             if (s.contains("all")) {
 199                 res = EnumSet.allOf(VerboseResolutionMode.class);
 200             }
 201             Collection<String> args = Arrays.asList(s.split(","));
 202             for (VerboseResolutionMode mode : values()) {
 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 (bestSoFar.name == names.init &&
 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 {
 244                 subDiags.append(c.isApplicable() ?
 245                         getVerboseApplicableCandidateDiag(pos, c.sym, c.mtype) :
 246                         getVerboseInapplicableCandidateDiag(pos, c.sym, c.details));
 247                 if (c.sym == bestSoFar)
 248                     mostSpecificPos = pos;
 249                 pos++;
 250             }
 251         }
 252         String key = success ? "verbose.resolve.multi" : "verbose.resolve.multi.1";
 253         List<Type> argtypes2 = argtypes.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, bestSoFar, currentResolutionContext.step));
 254         JCDiagnostic main = diags.note(log.currentSource(), dpos, key, name,
 255                 site.tsym, mostSpecificPos, currentResolutionContext.step,
 256                 methodArguments(argtypes2),
 257                 methodArguments(typeargtypes));
 258         JCDiagnostic d = new JCDiagnostic.MultilineDiagnostic(main, subDiags.toList());
 259         log.report(d);
 260     }
 261 
 262     JCDiagnostic getVerboseApplicableCandidateDiag(int pos, Symbol sym, Type inst) {
 263         JCDiagnostic subDiag = null;
 264         if (sym.type.hasTag(FORALL)) {
 265             subDiag = diags.fragment(Fragments.PartialInstSig(inst));
 266         }
 267 
 268         String key = subDiag == null ?
 269                 "applicable.method.found" :
 270                 "applicable.method.found.1";
 271 
 272         return diags.fragment(key, pos, sym, subDiag);
 273     }
 274 
 275     JCDiagnostic getVerboseInapplicableCandidateDiag(int pos, Symbol sym, JCDiagnostic subDiag) {
 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.isConstructor() ||
 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)
 317             return true;
 318 
 319         if (env.info.visitingServiceImplementation &&
 320             env.toplevel.modle == c.packge().modle) {
 321             return true;
 322         }
 323 
 324         boolean isAccessible = false;
 325         switch ((short)(c.flags() & AccessFlags)) {
 326             case PRIVATE:
 327                 isAccessible =
 328                     env.enclClass.sym.outermostClass() ==
 329                     c.owner.outermostClass();
 330                 break;
 331             case 0:
 332                 isAccessible =
 333                     env.toplevel.packge == c.owner // fast special case
 334                     ||
 335                     env.toplevel.packge == c.packge();
 336                 break;
 337             default: // error recovery
 338                 isAccessible = true;
 339                 break;
 340             case PUBLIC:
 341                 if (allowModules) {
 342                     ModuleSymbol currModule = env.toplevel.modle;
 343                     currModule.complete();
 344                     PackageSymbol p = c.packge();
 345                     isAccessible =
 346                         currModule == p.modle ||
 347                         currModule.visiblePackages.get(p.fullname) == p ||
 348                         p == syms.rootPackage ||
 349                         (p.modle == syms.unnamedModule && currModule.readModules.contains(p.modle));
 350                 } else {
 351                     isAccessible = true;
 352                 }
 353                 break;
 354             case PROTECTED:
 355                 isAccessible =
 356                     env.toplevel.packge == c.owner // fast special case
 357                     ||
 358                     env.toplevel.packge == c.packge()
 359                     ||
 360                     isInnerSubClass(env.enclClass.sym, c.owner);
 361                 break;
 362         }
 363         return (checkInner == false || c.type.getEnclosingType() == Type.noType) ?
 364             isAccessible :
 365             isAccessible && isAccessible(env, c.type.getEnclosingType(), checkInner);
 366     }
 367     //where
 368         /** Is given class a subclass of given base class, or an inner class
 369          *  of a subclass?
 370          *  Return null if no such class exists.
 371          *  @param c     The class which is the subclass or is contained in it.
 372          *  @param base  The base class
 373          */
 374         private boolean isInnerSubClass(ClassSymbol c, Symbol base) {
 375             while (c != null && !c.isSubClass(base, types)) {
 376                 c = c.owner.enclClass();
 377             }
 378             return c != null;
 379         }
 380 
 381     boolean isAccessible(Env<AttrContext> env, Type t) {
 382         return isAccessible(env, t, false);
 383     }
 384 
 385     boolean isAccessible(Env<AttrContext> env, Type t, boolean checkInner) {
 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         ClassSymbol enclosingCsym = env.enclClass.sym;
 420         if (sym.kind == MTH || sym.kind == VAR) {
 421             /* If any primitive class types are involved, ask the same question in the reference universe,
 422                where the hierarchy is navigable
 423             */
 424             if (site.isPrimitiveClass())
 425                 site = site.referenceProjection();
 426         } else if (sym.kind == TYP) {
 427             // A type is accessible in a reference projection if it was
 428             // accessible in the value projection.
 429             if (site.isReferenceProjection())
 430                 site = site.asValueType();
 431         }
 432         try {
 433             switch ((short)(sym.flags() & AccessFlags)) {
 434                 case PRIVATE:
 435                     return
 436                             (env.enclClass.sym == sym.owner // fast special case
 437                                     ||
 438                                     env.enclClass.sym.outermostClass() ==
 439                                             sym.owner.outermostClass())
 440                                     &&
 441                                     sym.isInheritedIn(site.tsym, types);
 442                 case 0:
 443                     return
 444                             (env.toplevel.packge == sym.owner.owner // fast special case
 445                                     ||
 446                                     env.toplevel.packge == sym.packge())
 447                                     &&
 448                                     isAccessible(env, site, checkInner)
 449                                     &&
 450                                     sym.isInheritedIn(site.tsym, types)
 451                                     &&
 452                                     notOverriddenIn(site, sym);
 453                 case PROTECTED:
 454                     return
 455                             (env.toplevel.packge == sym.owner.owner // fast special case
 456                                     ||
 457                                     env.toplevel.packge == sym.packge()
 458                                     ||
 459                                     isProtectedAccessible(sym, env.enclClass.sym, site)
 460                                     ||
 461                                     // OK to select instance method or field from 'super' or type name
 462                                     // (but type names should be disallowed elsewhere!)
 463                                     env.info.selectSuper && (sym.flags() & STATIC) == 0 && sym.kind != TYP)
 464                                     &&
 465                                     isAccessible(env, site, checkInner)
 466                                     &&
 467                                     notOverriddenIn(site, sym);
 468                 default: // this case includes erroneous combinations as well
 469                     return isAccessible(env, site, checkInner) && notOverriddenIn(site, sym);
 470             }
 471         } finally {
 472             env.enclClass.sym = enclosingCsym;
 473         }
 474     }
 475     //where
 476     /* `sym' is accessible only if not overridden by
 477      * another symbol which is a member of `site'
 478      * (because, if it is overridden, `sym' is not strictly
 479      * speaking a member of `site'). A polymorphic signature method
 480      * cannot be overridden (e.g. MH.invokeExact(Object[])).
 481      */
 482     private boolean notOverriddenIn(Type site, Symbol sym) {
 483         if (sym.kind != MTH || sym.isConstructor() || sym.isStatic())
 484             return true;
 485 
 486         /* If any primitive class types are involved, ask the same question in the reference universe,
 487            where the hierarchy is navigable
 488         */
 489         if (site.isPrimitiveClass())
 490             site = site.referenceProjection();
 491 
 492         Symbol s2 = ((MethodSymbol)sym).implementation(site.tsym, types, true);
 493         return (s2 == null || s2 == sym || sym.owner == s2.owner || (sym.owner.isInterface() && s2.owner == syms.objectType.tsym) ||
 494                 !types.isSubSignature(types.memberType(site, s2), types.memberType(site, sym)));
 495     }
 496     //where
 497         /** Is given protected symbol accessible if it is selected from given site
 498          *  and the selection takes place in given class?
 499          *  @param sym     The symbol with protected access
 500          *  @param c       The class where the access takes place
 501          *  @site          The type of the qualifier
 502          */
 503         private
 504         boolean isProtectedAccessible(Symbol sym, ClassSymbol c, Type site) {
 505             Type newSite = site.hasTag(TYPEVAR) ? site.getUpperBound() : site;
 506             while (c != null &&
 507                    !(c.isSubClass(sym.owner, types) &&
 508                      (c.flags() & INTERFACE) == 0 &&
 509                      // In JLS 2e 6.6.2.1, the subclass restriction applies
 510                      // only to instance fields and methods -- types are excluded
 511                      // regardless of whether they are declared 'static' or not.
 512                      ((sym.flags() & STATIC) != 0 || sym.kind == TYP || newSite.tsym.isSubClass(c, types))))
 513                 c = c.owner.enclClass();
 514             return c != null;
 515         }
 516 
 517     /**
 518      * Performs a recursive scan of a type looking for accessibility problems
 519      * from current attribution environment
 520      */
 521     void checkAccessibleType(Env<AttrContext> env, Type t) {
 522         accessibilityChecker.visit(t, env);
 523     }
 524 
 525     /**
 526      * Accessibility type-visitor
 527      */
 528     Types.SimpleVisitor<Void, Env<AttrContext>> accessibilityChecker =
 529             new Types.SimpleVisitor<Void, Env<AttrContext>>() {
 530 
 531         void visit(List<Type> ts, Env<AttrContext> env) {
 532             for (Type t : ts) {
 533                 visit(t, env);
 534             }
 535         }
 536 
 537         public Void visitType(Type t, Env<AttrContext> env) {
 538             return null;
 539         }
 540 
 541         @Override
 542         public Void visitArrayType(ArrayType t, Env<AttrContext> env) {
 543             visit(t.elemtype, env);
 544             return null;
 545         }
 546 
 547         @Override
 548         public Void visitClassType(ClassType t, Env<AttrContext> env) {
 549             visit(t.getTypeArguments(), env);
 550             if (!isAccessible(env, t, true)) {
 551                 accessBase(new AccessError(env, null, t.tsym), env.tree.pos(), env.enclClass.sym, t, t.tsym.name, true);
 552             }
 553             return null;
 554         }
 555 
 556         @Override
 557         public Void visitWildcardType(WildcardType t, Env<AttrContext> env) {
 558             visit(t.type, env);
 559             return null;
 560         }
 561 
 562         @Override
 563         public Void visitMethodType(MethodType t, Env<AttrContext> env) {
 564             visit(t.getParameterTypes(), env);
 565             visit(t.getReturnType(), env);
 566             visit(t.getThrownTypes(), env);
 567             return null;
 568         }
 569     };
 570 
 571     /** Try to instantiate the type of a method so that it fits
 572      *  given type arguments and argument types. If successful, return
 573      *  the method's instantiated type, else return null.
 574      *  The instantiation will take into account an additional leading
 575      *  formal parameter if the method is an instance method seen as a member
 576      *  of an under determined site. In this case, we treat site as an additional
 577      *  parameter and the parameters of the class containing the method as
 578      *  additional type variables that get instantiated.
 579      *
 580      *  @param env         The current environment
 581      *  @param site        The type of which the method is a member.
 582      *  @param m           The method symbol.
 583      *  @param argtypes    The invocation's given value arguments.
 584      *  @param typeargtypes    The invocation's given type arguments.
 585      *  @param allowBoxing Allow boxing conversions of arguments.
 586      *  @param useVarargs Box trailing arguments into an array for varargs.
 587      */
 588     Type rawInstantiate(Env<AttrContext> env,
 589                         Type site,
 590                         Symbol m,
 591                         ResultInfo resultInfo,
 592                         List<Type> argtypes,
 593                         List<Type> typeargtypes,
 594                         boolean allowBoxing,
 595                         boolean useVarargs,
 596                         Warner warn) throws Infer.InferenceException {
 597         Type mt = types.memberType(site, m);
 598         // tvars is the list of formal type variables for which type arguments
 599         // need to inferred.
 600         List<Type> tvars = List.nil();
 601         if (typeargtypes == null) typeargtypes = List.nil();
 602         if (!mt.hasTag(FORALL) && typeargtypes.nonEmpty()) {
 603             // This is not a polymorphic method, but typeargs are supplied
 604             // which is fine, see JLS 15.12.2.1
 605         } else if (mt.hasTag(FORALL) && typeargtypes.nonEmpty()) {
 606             ForAll pmt = (ForAll) mt;
 607             if (typeargtypes.length() != pmt.tvars.length())
 608                  // not enough args
 609                 throw new InapplicableMethodException(diags.fragment(Fragments.WrongNumberTypeArgs(Integer.toString(pmt.tvars.length()))));
 610             // Check type arguments are within bounds
 611             List<Type> formals = pmt.tvars;
 612             List<Type> actuals = typeargtypes;
 613             while (formals.nonEmpty() && actuals.nonEmpty()) {
 614                 List<Type> bounds = types.subst(types.getBounds((TypeVar)formals.head),
 615                                                 pmt.tvars, typeargtypes);
 616                 for (; bounds.nonEmpty(); bounds = bounds.tail) {
 617                     if (!types.isSubtypeUnchecked(actuals.head, bounds.head, warn)) {
 618                         throw new InapplicableMethodException(diags.fragment(Fragments.ExplicitParamDoNotConformToBounds(actuals.head, bounds)));
 619                     }
 620                 }
 621                 formals = formals.tail;
 622                 actuals = actuals.tail;
 623             }
 624             mt = types.subst(pmt.qtype, pmt.tvars, typeargtypes);
 625         } else if (mt.hasTag(FORALL)) {
 626             ForAll pmt = (ForAll) mt;
 627             List<Type> tvars1 = types.newInstances(pmt.tvars);
 628             tvars = tvars.appendList(tvars1);
 629             mt = types.subst(pmt.qtype, pmt.tvars, tvars1);
 630         }
 631 
 632         // find out whether we need to go the slow route via infer
 633         boolean instNeeded = tvars.tail != null; /*inlined: tvars.nonEmpty()*/
 634         for (List<Type> l = argtypes;
 635              l.tail != null/*inlined: l.nonEmpty()*/ && !instNeeded;
 636              l = l.tail) {
 637             if (l.head.hasTag(FORALL)) instNeeded = true;
 638         }
 639 
 640         if (instNeeded) {
 641             return infer.instantiateMethod(env,
 642                                     tvars,
 643                                     (MethodType)mt,
 644                                     resultInfo,
 645                                     (MethodSymbol)m,
 646                                     argtypes,
 647                                     allowBoxing,
 648                                     useVarargs,
 649                                     currentResolutionContext,
 650                                     warn);
 651         }
 652 
 653         DeferredAttr.DeferredAttrContext dc = currentResolutionContext.deferredAttrContext(m, infer.emptyContext, resultInfo, warn);
 654         currentResolutionContext.methodCheck.argumentsAcceptable(env, dc,
 655                                 argtypes, mt.getParameterTypes(), warn);
 656         dc.complete();
 657         return mt;
 658     }
 659 
 660     Type checkMethod(Env<AttrContext> env,
 661                      Type site,
 662                      Symbol m,
 663                      ResultInfo resultInfo,
 664                      List<Type> argtypes,
 665                      List<Type> typeargtypes,
 666                      Warner warn) {
 667         MethodResolutionContext prevContext = currentResolutionContext;
 668         try {
 669             currentResolutionContext = new MethodResolutionContext();
 670             currentResolutionContext.attrMode = (resultInfo.pt == Infer.anyPoly) ?
 671                     AttrMode.SPECULATIVE : DeferredAttr.AttrMode.CHECK;
 672             if (env.tree.hasTag(JCTree.Tag.REFERENCE)) {
 673                 //method/constructor references need special check class
 674                 //to handle inference variables in 'argtypes' (might happen
 675                 //during an unsticking round)
 676                 currentResolutionContext.methodCheck =
 677                         new MethodReferenceCheck(resultInfo.checkContext.inferenceContext());
 678             }
 679             MethodResolutionPhase step = currentResolutionContext.step = env.info.pendingResolutionPhase;
 680             return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
 681                     step.isBoxingRequired(), step.isVarargsRequired(), warn);
 682         }
 683         finally {
 684             currentResolutionContext = prevContext;
 685         }
 686     }
 687 
 688     /** Same but returns null instead throwing a NoInstanceException
 689      */
 690     Type instantiate(Env<AttrContext> env,
 691                      Type site,
 692                      Symbol m,
 693                      ResultInfo resultInfo,
 694                      List<Type> argtypes,
 695                      List<Type> typeargtypes,
 696                      boolean allowBoxing,
 697                      boolean useVarargs,
 698                      Warner warn) {
 699         try {
 700             return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
 701                                   allowBoxing, useVarargs, warn);
 702         } catch (InapplicableMethodException ex) {
 703             return null;
 704         }
 705     }
 706 
 707     /**
 708      * This interface defines an entry point that should be used to perform a
 709      * method check. A method check usually consist in determining as to whether
 710      * a set of types (actuals) is compatible with another set of types (formals).
 711      * Since the notion of compatibility can vary depending on the circumstances,
 712      * this interfaces allows to easily add new pluggable method check routines.
 713      */
 714     interface MethodCheck {
 715         /**
 716          * Main method check routine. A method check usually consist in determining
 717          * as to whether a set of types (actuals) is compatible with another set of
 718          * types (formals). If an incompatibility is found, an unchecked exception
 719          * is assumed to be thrown.
 720          */
 721         void argumentsAcceptable(Env<AttrContext> env,
 722                                 DeferredAttrContext deferredAttrContext,
 723                                 List<Type> argtypes,
 724                                 List<Type> formals,
 725                                 Warner warn);
 726 
 727         /**
 728          * Retrieve the method check object that will be used during a
 729          * most specific check.
 730          */
 731         MethodCheck mostSpecificCheck(List<Type> actuals);
 732     }
 733 
 734     /**
 735      * Helper enum defining all method check diagnostics (used by resolveMethodCheck).
 736      */
 737     enum MethodCheckDiag {
 738         /**
 739          * Actuals and formals differs in length.
 740          */
 741         ARITY_MISMATCH("arg.length.mismatch", "infer.arg.length.mismatch"),
 742         /**
 743          * An actual is incompatible with a formal.
 744          */
 745         ARG_MISMATCH("no.conforming.assignment.exists", "infer.no.conforming.assignment.exists"),
 746         /**
 747          * An actual is incompatible with the varargs element type.
 748          */
 749         VARARG_MISMATCH("varargs.argument.mismatch", "infer.varargs.argument.mismatch"),
 750         /**
 751          * The varargs element type is inaccessible.
 752          */
 753         INACCESSIBLE_VARARGS("inaccessible.varargs.type", "inaccessible.varargs.type");
 754 
 755         final String basicKey;
 756         final String inferKey;
 757 
 758         MethodCheckDiag(String basicKey, String inferKey) {
 759             this.basicKey = basicKey;
 760             this.inferKey = inferKey;
 761         }
 762 
 763         String regex() {
 764             return String.format("([a-z]*\\.)*(%s|%s)", basicKey, inferKey);
 765         }
 766     }
 767 
 768     /**
 769      * Dummy method check object. All methods are deemed applicable, regardless
 770      * of their formal parameter types.
 771      */
 772     MethodCheck nilMethodCheck = new MethodCheck() {
 773         public void argumentsAcceptable(Env<AttrContext> env, DeferredAttrContext deferredAttrContext, List<Type> argtypes, List<Type> formals, Warner warn) {
 774             //do nothing - method always applicable regardless of actuals
 775         }
 776 
 777         public MethodCheck mostSpecificCheck(List<Type> actuals) {
 778             return this;
 779         }
 780     };
 781 
 782     /**
 783      * Base class for 'real' method checks. The class defines the logic for
 784      * iterating through formals and actuals and provides and entry point
 785      * that can be used by subclasses in order to define the actual check logic.
 786      */
 787     abstract class AbstractMethodCheck implements MethodCheck {
 788         @Override
 789         public void argumentsAcceptable(final Env<AttrContext> env,
 790                                     DeferredAttrContext deferredAttrContext,
 791                                     List<Type> argtypes,
 792                                     List<Type> formals,
 793                                     Warner warn) {
 794             //should we expand formals?
 795             boolean useVarargs = deferredAttrContext.phase.isVarargsRequired();
 796             JCTree callTree = treeForDiagnostics(env);
 797             List<JCExpression> trees = TreeInfo.args(callTree);
 798 
 799             //inference context used during this method check
 800             InferenceContext inferenceContext = deferredAttrContext.inferenceContext;
 801 
 802             Type varargsFormal = useVarargs ? formals.last() : null;
 803 
 804             if (varargsFormal == null &&
 805                     argtypes.size() != formals.size()) {
 806                 reportMC(callTree, MethodCheckDiag.ARITY_MISMATCH, inferenceContext); // not enough args
 807             }
 808 
 809             while (argtypes.nonEmpty() && formals.head != varargsFormal) {
 810                 DiagnosticPosition pos = trees != null ? trees.head : null;
 811                 checkArg(pos, false, argtypes.head, formals.head, deferredAttrContext, warn);
 812                 argtypes = argtypes.tail;
 813                 formals = formals.tail;
 814                 trees = trees != null ? trees.tail : trees;
 815             }
 816 
 817             if (formals.head != varargsFormal) {
 818                 reportMC(callTree, MethodCheckDiag.ARITY_MISMATCH, inferenceContext); // not enough args
 819             }
 820 
 821             if (useVarargs) {
 822                 //note: if applicability check is triggered by most specific test,
 823                 //the last argument of a varargs is _not_ an array type (see JLS 15.12.2.5)
 824                 final Type elt = types.elemtype(varargsFormal);
 825                 while (argtypes.nonEmpty()) {
 826                     DiagnosticPosition pos = trees != null ? trees.head : null;
 827                     checkArg(pos, true, argtypes.head, elt, deferredAttrContext, warn);
 828                     argtypes = argtypes.tail;
 829                     trees = trees != null ? trees.tail : trees;
 830                 }
 831             }
 832         }
 833 
 834             // where
 835             private JCTree treeForDiagnostics(Env<AttrContext> env) {
 836                 return env.info.preferredTreeForDiagnostics != null ? env.info.preferredTreeForDiagnostics : env.tree;
 837             }
 838 
 839         /**
 840          * Does the actual argument conforms to the corresponding formal?
 841          */
 842         abstract void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn);
 843 
 844         protected void reportMC(DiagnosticPosition pos, MethodCheckDiag diag, InferenceContext inferenceContext, Object... args) {
 845             boolean inferDiag = inferenceContext != infer.emptyContext;
 846             if (inferDiag && (!diag.inferKey.equals(diag.basicKey))) {
 847                 Object[] args2 = new Object[args.length + 1];
 848                 System.arraycopy(args, 0, args2, 1, args.length);
 849                 args2[0] = inferenceContext.inferenceVars();
 850                 args = args2;
 851             }
 852             String key = inferDiag ? diag.inferKey : diag.basicKey;
 853             throw inferDiag ?
 854                 infer.error(diags.create(DiagnosticType.FRAGMENT, log.currentSource(), pos, key, args)) :
 855                 methodCheckFailure.setMessage(diags.create(DiagnosticType.FRAGMENT, log.currentSource(), pos, key, args));
 856         }
 857 
 858         /**
 859          * To eliminate the overhead associated with allocating an exception object in such an
 860          * hot execution path, we use flyweight pattern - and share the same exception instance
 861          * across multiple method check failures.
 862          */
 863         class SharedInapplicableMethodException extends InapplicableMethodException {
 864             private static final long serialVersionUID = 0;
 865 
 866             SharedInapplicableMethodException() {
 867                 super(null);
 868             }
 869 
 870             SharedInapplicableMethodException setMessage(JCDiagnostic details) {
 871                 this.diagnostic = details;
 872                 return this;
 873             }
 874         }
 875 
 876         SharedInapplicableMethodException methodCheckFailure = new SharedInapplicableMethodException();
 877 
 878         public MethodCheck mostSpecificCheck(List<Type> actuals) {
 879             return nilMethodCheck;
 880         }
 881 
 882     }
 883 
 884     /**
 885      * Arity-based method check. A method is applicable if the number of actuals
 886      * supplied conforms to the method signature.
 887      */
 888     MethodCheck arityMethodCheck = new AbstractMethodCheck() {
 889         @Override
 890         void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn) {
 891             //do nothing - actual always compatible to formals
 892         }
 893 
 894         @Override
 895         public String toString() {
 896             return "arityMethodCheck";
 897         }
 898     };
 899 
 900     /**
 901      * Main method applicability routine. Given a list of actual types A,
 902      * a list of formal types F, determines whether the types in A are
 903      * compatible (by method invocation conversion) with the types in F.
 904      *
 905      * Since this routine is shared between overload resolution and method
 906      * type-inference, a (possibly empty) inference context is used to convert
 907      * formal types to the corresponding 'undet' form ahead of a compatibility
 908      * check so that constraints can be propagated and collected.
 909      *
 910      * Moreover, if one or more types in A is a deferred type, this routine uses
 911      * DeferredAttr in order to perform deferred attribution. If one or more actual
 912      * deferred types are stuck, they are placed in a queue and revisited later
 913      * after the remainder of the arguments have been seen. If this is not sufficient
 914      * to 'unstuck' the argument, a cyclic inference error is called out.
 915      *
 916      * A method check handler (see above) is used in order to report errors.
 917      */
 918     MethodCheck resolveMethodCheck = new AbstractMethodCheck() {
 919 
 920         @Override
 921         void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn) {
 922             ResultInfo mresult = methodCheckResult(varargs, formal, deferredAttrContext, warn);
 923             mresult.check(pos, actual);
 924         }
 925 
 926         @Override
 927         public void argumentsAcceptable(final Env<AttrContext> env,
 928                                     DeferredAttrContext deferredAttrContext,
 929                                     List<Type> argtypes,
 930                                     List<Type> formals,
 931                                     Warner warn) {
 932             super.argumentsAcceptable(env, deferredAttrContext, argtypes, formals, warn);
 933             // should we check varargs element type accessibility?
 934             if (deferredAttrContext.phase.isVarargsRequired()) {
 935                 if (deferredAttrContext.mode == AttrMode.CHECK || !checkVarargsAccessAfterResolution) {
 936                     varargsAccessible(env, types.elemtype(formals.last()), deferredAttrContext.inferenceContext);
 937                 }
 938             }
 939         }
 940 
 941         /**
 942          * Test that the runtime array element type corresponding to 't' is accessible.  't' should be the
 943          * varargs element type of either the method invocation type signature (after inference completes)
 944          * or the method declaration signature (before inference completes).
 945          */
 946         private void varargsAccessible(final Env<AttrContext> env, final Type t, final InferenceContext inferenceContext) {
 947             if (inferenceContext.free(t)) {
 948                 inferenceContext.addFreeTypeListener(List.of(t),
 949                         solvedContext -> varargsAccessible(env, solvedContext.asInstType(t), solvedContext));
 950             } else {
 951                 if (!isAccessible(env, types.erasure(t))) {
 952                     Symbol location = env.enclClass.sym;
 953                     reportMC(env.tree, MethodCheckDiag.INACCESSIBLE_VARARGS, inferenceContext, t, Kinds.kindName(location), location);
 954                 }
 955             }
 956         }
 957 
 958         private ResultInfo methodCheckResult(final boolean varargsCheck, Type to,
 959                 final DeferredAttr.DeferredAttrContext deferredAttrContext, Warner rsWarner) {
 960             CheckContext checkContext = new MethodCheckContext(!deferredAttrContext.phase.isBoxingRequired(), deferredAttrContext, rsWarner) {
 961                 MethodCheckDiag methodDiag = varargsCheck ?
 962                                  MethodCheckDiag.VARARG_MISMATCH : MethodCheckDiag.ARG_MISMATCH;
 963 
 964                 @Override
 965                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
 966                     reportMC(pos, methodDiag, deferredAttrContext.inferenceContext, details);
 967                 }
 968             };
 969             return new MethodResultInfo(to, checkContext);
 970         }
 971 
 972         @Override
 973         public MethodCheck mostSpecificCheck(List<Type> actuals) {
 974             return new MostSpecificCheck(actuals);
 975         }
 976 
 977         @Override
 978         public String toString() {
 979             return "resolveMethodCheck";
 980         }
 981     };
 982 
 983     /**
 984      * This class handles method reference applicability checks; since during
 985      * these checks it's sometime possible to have inference variables on
 986      * the actual argument types list, the method applicability check must be
 987      * extended so that inference variables are 'opened' as needed.
 988      */
 989     class MethodReferenceCheck extends AbstractMethodCheck {
 990 
 991         InferenceContext pendingInferenceContext;
 992 
 993         MethodReferenceCheck(InferenceContext pendingInferenceContext) {
 994             this.pendingInferenceContext = pendingInferenceContext;
 995         }
 996 
 997         @Override
 998         void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn) {
 999             ResultInfo mresult = methodCheckResult(varargs, formal, deferredAttrContext, warn);
1000             mresult.check(pos, actual);
1001         }
1002 
1003         private ResultInfo methodCheckResult(final boolean varargsCheck, Type to,
1004                 final DeferredAttr.DeferredAttrContext deferredAttrContext, Warner rsWarner) {
1005             CheckContext checkContext = new MethodCheckContext(!deferredAttrContext.phase.isBoxingRequired(), deferredAttrContext, rsWarner) {
1006                 MethodCheckDiag methodDiag = varargsCheck ?
1007                                  MethodCheckDiag.VARARG_MISMATCH : MethodCheckDiag.ARG_MISMATCH;
1008 
1009                 @Override
1010                 public boolean compatible(Type found, Type req, Warner warn) {
1011                     found = pendingInferenceContext.asUndetVar(found);
1012                     if (found.hasTag(UNDETVAR) && req.isPrimitive()) {
1013                         req = types.boxedClass(req).type;
1014                     }
1015                     return super.compatible(found, req, warn);
1016                 }
1017 
1018                 @Override
1019                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
1020                     reportMC(pos, methodDiag, deferredAttrContext.inferenceContext, details);
1021                 }
1022             };
1023             return new MethodResultInfo(to, checkContext);
1024         }
1025 
1026         @Override
1027         public MethodCheck mostSpecificCheck(List<Type> actuals) {
1028             return new MostSpecificCheck(actuals);
1029         }
1030 
1031         @Override
1032         public String toString() {
1033             return "MethodReferenceCheck";
1034         }
1035     }
1036 
1037     /**
1038      * Check context to be used during method applicability checks. A method check
1039      * context might contain inference variables.
1040      */
1041     abstract class MethodCheckContext implements CheckContext {
1042 
1043         boolean strict;
1044         DeferredAttrContext deferredAttrContext;
1045         Warner rsWarner;
1046 
1047         public MethodCheckContext(boolean strict, DeferredAttrContext deferredAttrContext, Warner rsWarner) {
1048            this.strict = strict;
1049            this.deferredAttrContext = deferredAttrContext;
1050            this.rsWarner = rsWarner;
1051         }
1052 
1053         public boolean compatible(Type found, Type req, Warner warn) {
1054             InferenceContext inferenceContext = deferredAttrContext.inferenceContext;
1055             return strict ?
1056                     types.isSubtypeUnchecked(inferenceContext.asUndetVar(found), inferenceContext.asUndetVar(req), warn) :
1057                     types.isConvertible(inferenceContext.asUndetVar(found), inferenceContext.asUndetVar(req), warn);
1058         }
1059 
1060         public void report(DiagnosticPosition pos, JCDiagnostic details) {
1061             throw new InapplicableMethodException(details);
1062         }
1063 
1064         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
1065             return rsWarner;
1066         }
1067 
1068         public InferenceContext inferenceContext() {
1069             return deferredAttrContext.inferenceContext;
1070         }
1071 
1072         public DeferredAttrContext deferredAttrContext() {
1073             return deferredAttrContext;
1074         }
1075 
1076         @Override
1077         public String toString() {
1078             return "MethodCheckContext";
1079         }
1080     }
1081 
1082     /**
1083      * ResultInfo class to be used during method applicability checks. Check
1084      * for deferred types goes through special path.
1085      */
1086     class MethodResultInfo extends ResultInfo {
1087 
1088         public MethodResultInfo(Type pt, CheckContext checkContext) {
1089             attr.super(KindSelector.VAL, pt, checkContext);
1090         }
1091 
1092         @Override
1093         protected Type check(DiagnosticPosition pos, Type found) {
1094             if (found.hasTag(DEFERRED)) {
1095                 DeferredType dt = (DeferredType)found;
1096                 return dt.check(this);
1097             } else {
1098                 Type uResult = U(found);
1099                 Type capturedType = pos == null || pos.getTree() == null ?
1100                         types.capture(uResult) :
1101                         checkContext.inferenceContext()
1102                             .cachedCapture(pos.getTree(), uResult, true);
1103                 return super.check(pos, chk.checkNonVoid(pos, capturedType));
1104             }
1105         }
1106 
1107         /**
1108          * javac has a long-standing 'simplification' (see 6391995):
1109          * given an actual argument type, the method check is performed
1110          * on its upper bound. This leads to inconsistencies when an
1111          * argument type is checked against itself. For example, given
1112          * a type-variable T, it is not true that {@code U(T) <: T},
1113          * so we need to guard against that.
1114          */
1115         private Type U(Type found) {
1116             return found == pt ?
1117                     found : types.cvarUpperBound(found);
1118         }
1119 
1120         @Override
1121         protected MethodResultInfo dup(Type newPt) {
1122             return new MethodResultInfo(newPt, checkContext);
1123         }
1124 
1125         @Override
1126         protected ResultInfo dup(CheckContext newContext) {
1127             return new MethodResultInfo(pt, newContext);
1128         }
1129 
1130         @Override
1131         protected ResultInfo dup(Type newPt, CheckContext newContext) {
1132             return new MethodResultInfo(newPt, newContext);
1133         }
1134     }
1135 
1136     /**
1137      * Most specific method applicability routine. Given a list of actual types A,
1138      * a list of formal types F1, and a list of formal types F2, the routine determines
1139      * as to whether the types in F1 can be considered more specific than those in F2 w.r.t.
1140      * argument types A.
1141      */
1142     class MostSpecificCheck implements MethodCheck {
1143 
1144         List<Type> actuals;
1145 
1146         MostSpecificCheck(List<Type> actuals) {
1147             this.actuals = actuals;
1148         }
1149 
1150         @Override
1151         public void argumentsAcceptable(final Env<AttrContext> env,
1152                                     DeferredAttrContext deferredAttrContext,
1153                                     List<Type> formals1,
1154                                     List<Type> formals2,
1155                                     Warner warn) {
1156             formals2 = adjustArgs(formals2, deferredAttrContext.msym, formals1.length(), deferredAttrContext.phase.isVarargsRequired());
1157             while (formals2.nonEmpty()) {
1158                 ResultInfo mresult = methodCheckResult(formals2.head, deferredAttrContext, warn, actuals.head);
1159                 mresult.check(null, formals1.head);
1160                 formals1 = formals1.tail;
1161                 formals2 = formals2.tail;
1162                 actuals = actuals.isEmpty() ? actuals : actuals.tail;
1163             }
1164         }
1165 
1166        /**
1167         * Create a method check context to be used during the most specific applicability check
1168         */
1169         ResultInfo methodCheckResult(Type to, DeferredAttr.DeferredAttrContext deferredAttrContext,
1170                Warner rsWarner, Type actual) {
1171             return attr.new ResultInfo(KindSelector.VAL, to,
1172                    new MostSpecificCheckContext(deferredAttrContext, rsWarner, actual));
1173         }
1174 
1175         /**
1176          * Subclass of method check context class that implements most specific
1177          * method conversion. If the actual type under analysis is a deferred type
1178          * a full blown structural analysis is carried out.
1179          */
1180         class MostSpecificCheckContext extends MethodCheckContext {
1181 
1182             Type actual;
1183 
1184             public MostSpecificCheckContext(DeferredAttrContext deferredAttrContext, Warner rsWarner, Type actual) {
1185                 super(true, deferredAttrContext, rsWarner);
1186                 this.actual = actual;
1187             }
1188 
1189             public boolean compatible(Type found, Type req, Warner warn) {
1190                 if (allowFunctionalInterfaceMostSpecific &&
1191                         unrelatedFunctionalInterfaces(found, req) &&
1192                         (actual != null && actual.getTag() == DEFERRED)) {
1193                     DeferredType dt = (DeferredType) actual;
1194                     JCTree speculativeTree = dt.speculativeTree(deferredAttrContext);
1195                     if (speculativeTree != deferredAttr.stuckTree) {
1196                         return functionalInterfaceMostSpecific(found, req, speculativeTree);
1197                     }
1198                 }
1199                 return compatibleBySubtyping(found, req);
1200             }
1201 
1202             private boolean compatibleBySubtyping(Type found, Type req) {
1203                 if (!strict && found.isPrimitive() != req.isPrimitive()) {
1204                     found = found.isPrimitive() ? types.boxedClass(found).type : types.unboxedType(found);
1205                 }
1206                 return types.isSubtypeNoCapture(found, deferredAttrContext.inferenceContext.asUndetVar(req));
1207             }
1208 
1209             /** Whether {@code t} and {@code s} are unrelated functional interface types. */
1210             private boolean unrelatedFunctionalInterfaces(Type t, Type s) {
1211                 return types.isFunctionalInterface(t.tsym) &&
1212                        types.isFunctionalInterface(s.tsym) &&
1213                        unrelatedInterfaces(t, s);
1214             }
1215 
1216             /** Whether {@code t} and {@code s} are unrelated interface types; recurs on intersections. **/
1217             private boolean unrelatedInterfaces(Type t, Type s) {
1218                 if (t.isCompound()) {
1219                     for (Type ti : types.interfaces(t)) {
1220                         if (!unrelatedInterfaces(ti, s)) {
1221                             return false;
1222                         }
1223                     }
1224                     return true;
1225                 } else if (s.isCompound()) {
1226                     for (Type si : types.interfaces(s)) {
1227                         if (!unrelatedInterfaces(t, si)) {
1228                             return false;
1229                         }
1230                     }
1231                     return true;
1232                 } else {
1233                     return types.asSuper(t, s.tsym) == null && types.asSuper(s, t.tsym) == null;
1234                 }
1235             }
1236 
1237             /** Parameters {@code t} and {@code s} are unrelated functional interface types. */
1238             private boolean functionalInterfaceMostSpecific(Type t, Type s, JCTree tree) {
1239                 Type tDesc = types.findDescriptorType(types.capture(t));
1240                 Type tDescNoCapture = types.findDescriptorType(t);
1241                 Type sDesc = types.findDescriptorType(s);
1242                 final List<Type> tTypeParams = tDesc.getTypeArguments();
1243                 final List<Type> tTypeParamsNoCapture = tDescNoCapture.getTypeArguments();
1244                 final List<Type> sTypeParams = sDesc.getTypeArguments();
1245 
1246                 // compare type parameters
1247                 if (tDesc.hasTag(FORALL) && !types.hasSameBounds((ForAll) tDesc, (ForAll) tDescNoCapture)) {
1248                     return false;
1249                 }
1250                 // can't use Types.hasSameBounds on sDesc because bounds may have ivars
1251                 List<Type> tIter = tTypeParams;
1252                 List<Type> sIter = sTypeParams;
1253                 while (tIter.nonEmpty() && sIter.nonEmpty()) {
1254                     Type tBound = tIter.head.getUpperBound();
1255                     Type sBound = types.subst(sIter.head.getUpperBound(), sTypeParams, tTypeParams);
1256                     if (tBound.containsAny(tTypeParams) && inferenceContext().free(sBound)) {
1257                         return false;
1258                     }
1259                     if (!types.isSameType(tBound, inferenceContext().asUndetVar(sBound))) {
1260                         return false;
1261                     }
1262                     tIter = tIter.tail;
1263                     sIter = sIter.tail;
1264                 }
1265                 if (!tIter.isEmpty() || !sIter.isEmpty()) {
1266                     return false;
1267                 }
1268 
1269                 // compare parameters
1270                 List<Type> tParams = tDesc.getParameterTypes();
1271                 List<Type> tParamsNoCapture = tDescNoCapture.getParameterTypes();
1272                 List<Type> sParams = sDesc.getParameterTypes();
1273                 while (tParams.nonEmpty() && tParamsNoCapture.nonEmpty() && sParams.nonEmpty()) {
1274                     Type tParam = tParams.head;
1275                     Type tParamNoCapture = types.subst(tParamsNoCapture.head, tTypeParamsNoCapture, tTypeParams);
1276                     Type sParam = types.subst(sParams.head, sTypeParams, tTypeParams);
1277                     if (tParam.containsAny(tTypeParams) && inferenceContext().free(sParam)) {
1278                         return false;
1279                     }
1280                     if (!types.isSubtype(inferenceContext().asUndetVar(sParam), tParam)) {
1281                         return false;
1282                     }
1283                     if (!types.isSameType(tParamNoCapture, inferenceContext().asUndetVar(sParam))) {
1284                         return false;
1285                     }
1286                     tParams = tParams.tail;
1287                     tParamsNoCapture = tParamsNoCapture.tail;
1288                     sParams = sParams.tail;
1289                 }
1290                 if (!tParams.isEmpty() || !tParamsNoCapture.isEmpty() || !sParams.isEmpty()) {
1291                     return false;
1292                 }
1293 
1294                 // compare returns
1295                 Type tRet = tDesc.getReturnType();
1296                 Type sRet = types.subst(sDesc.getReturnType(), sTypeParams, tTypeParams);
1297                 if (tRet.containsAny(tTypeParams) && inferenceContext().free(sRet)) {
1298                     return false;
1299                 }
1300                 MostSpecificFunctionReturnChecker msc = new MostSpecificFunctionReturnChecker(tRet, sRet);
1301                 msc.scan(tree);
1302                 return msc.result;
1303             }
1304 
1305             /**
1306              * Tests whether one functional interface type can be considered more specific
1307              * than another unrelated functional interface type for the scanned expression.
1308              */
1309             class MostSpecificFunctionReturnChecker extends DeferredAttr.PolyScanner {
1310 
1311                 final Type tRet;
1312                 final Type sRet;
1313                 boolean result;
1314 
1315                 /** Parameters {@code t} and {@code s} are unrelated functional interface types. */
1316                 MostSpecificFunctionReturnChecker(Type tRet, Type sRet) {
1317                     this.tRet = tRet;
1318                     this.sRet = sRet;
1319                     result = true;
1320                 }
1321 
1322                 @Override
1323                 void skip(JCTree tree) {
1324                     result &= false;
1325                 }
1326 
1327                 @Override
1328                 public void visitConditional(JCConditional tree) {
1329                     scan(asExpr(tree.truepart));
1330                     scan(asExpr(tree.falsepart));
1331                 }
1332 
1333                 @Override
1334                 public void visitReference(JCMemberReference tree) {
1335                     if (sRet.hasTag(VOID)) {
1336                         result &= true;
1337                     } else if (tRet.hasTag(VOID)) {
1338                         result &= false;
1339                     } else if (tRet.isPrimitive() != sRet.isPrimitive()) {
1340                         boolean retValIsPrimitive =
1341                                 tree.refPolyKind == PolyKind.STANDALONE &&
1342                                 tree.sym.type.getReturnType().isPrimitive();
1343                         result &= (retValIsPrimitive == tRet.isPrimitive()) &&
1344                                   (retValIsPrimitive != sRet.isPrimitive());
1345                     } else {
1346                         result &= compatibleBySubtyping(tRet, sRet);
1347                     }
1348                 }
1349 
1350                 @Override
1351                 public void visitParens(JCParens tree) {
1352                     scan(asExpr(tree.expr));
1353                 }
1354 
1355                 @Override
1356                 public void visitLambda(JCLambda tree) {
1357                     if (sRet.hasTag(VOID)) {
1358                         result &= true;
1359                     } else if (tRet.hasTag(VOID)) {
1360                         result &= false;
1361                     } else {
1362                         List<JCExpression> lambdaResults = lambdaResults(tree);
1363                         if (!lambdaResults.isEmpty() && unrelatedFunctionalInterfaces(tRet, sRet)) {
1364                             for (JCExpression expr : lambdaResults) {
1365                                 result &= functionalInterfaceMostSpecific(tRet, sRet, expr);
1366                             }
1367                         } else if (!lambdaResults.isEmpty() && tRet.isPrimitive() != sRet.isPrimitive()) {
1368                             for (JCExpression expr : lambdaResults) {
1369                                 boolean retValIsPrimitive = expr.isStandalone() && expr.type.isPrimitive();
1370                                 result &= (retValIsPrimitive == tRet.isPrimitive()) &&
1371                                         (retValIsPrimitive != sRet.isPrimitive());
1372                             }
1373                         } else {
1374                             result &= compatibleBySubtyping(tRet, sRet);
1375                         }
1376                     }
1377                 }
1378                 //where
1379 
1380                 private List<JCExpression> lambdaResults(JCLambda lambda) {
1381                     if (lambda.getBodyKind() == JCTree.JCLambda.BodyKind.EXPRESSION) {
1382                         return List.of(asExpr((JCExpression) lambda.body));
1383                     } else {
1384                         final ListBuffer<JCExpression> buffer = new ListBuffer<>();
1385                         DeferredAttr.LambdaReturnScanner lambdaScanner =
1386                                 new DeferredAttr.LambdaReturnScanner() {
1387                                     @Override
1388                                     public void visitReturn(JCReturn tree) {
1389                                         if (tree.expr != null) {
1390                                             buffer.append(asExpr(tree.expr));
1391                                         }
1392                                     }
1393                                 };
1394                         lambdaScanner.scan(lambda.body);
1395                         return buffer.toList();
1396                     }
1397                 }
1398 
1399                 private JCExpression asExpr(JCExpression expr) {
1400                     if (expr.type.hasTag(DEFERRED)) {
1401                         JCTree speculativeTree = ((DeferredType)expr.type).speculativeTree(deferredAttrContext);
1402                         if (speculativeTree != deferredAttr.stuckTree) {
1403                             expr = (JCExpression)speculativeTree;
1404                         }
1405                     }
1406                     return expr;
1407                 }
1408             }
1409 
1410         }
1411 
1412         public MethodCheck mostSpecificCheck(List<Type> actuals) {
1413             Assert.error("Cannot get here!");
1414             return null;
1415         }
1416     }
1417 
1418     public static class InapplicableMethodException extends RuntimeException {
1419         private static final long serialVersionUID = 0;
1420 
1421         transient JCDiagnostic diagnostic;
1422 
1423         InapplicableMethodException(JCDiagnostic diag) {
1424             this.diagnostic = diag;
1425         }
1426 
1427         public JCDiagnostic getDiagnostic() {
1428             return diagnostic;
1429         }
1430     }
1431 
1432 /* ***************************************************************************
1433  *  Symbol lookup
1434  *  the following naming conventions for arguments are used
1435  *
1436  *       env      is the environment where the symbol was mentioned
1437  *       site     is the type of which the symbol is a member
1438  *       name     is the symbol's name
1439  *                if no arguments are given
1440  *       argtypes are the value arguments, if we search for a method
1441  *
1442  *  If no symbol was found, a ResolveError detailing the problem is returned.
1443  ****************************************************************************/
1444 
1445     /** Find field. Synthetic fields are always skipped.
1446      *  @param env     The current environment.
1447      *  @param site    The original type from where the selection takes place.
1448      *  @param name    The name of the field.
1449      *  @param c       The class to search for the field. This is always
1450      *                 a superclass or implemented interface of site's class.
1451      */
1452     Symbol findField(Env<AttrContext> env,
1453                      Type site,
1454                      Name name,
1455                      TypeSymbol c) {
1456         while (c.type.hasTag(TYPEVAR))
1457             c = c.type.getUpperBound().tsym;
1458         Symbol bestSoFar = varNotFound;
1459         Symbol sym;
1460         for (Symbol s : c.members().getSymbolsByName(name)) {
1461             if (s.kind == VAR && (s.flags_field & SYNTHETIC) == 0) {
1462                 return isAccessible(env, site, s)
1463                     ? s : new AccessError(env, site, s);
1464             }
1465         }
1466         Type st = types.supertype(c.type);
1467         if (st != null && (st.hasTag(CLASS) || st.hasTag(TYPEVAR))) {
1468             sym = findField(env, site, name, st.tsym);
1469             bestSoFar = bestOf(bestSoFar, sym);
1470         }
1471         for (List<Type> l = types.interfaces(c.type);
1472              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
1473              l = l.tail) {
1474             sym = findField(env, site, name, l.head.tsym);
1475             if (bestSoFar.exists() && sym.exists() &&
1476                 sym.owner != bestSoFar.owner)
1477                 bestSoFar = new AmbiguityError(bestSoFar, sym);
1478             else
1479                 bestSoFar = bestOf(bestSoFar, sym);
1480         }
1481         return bestSoFar;
1482     }
1483 
1484     /** Resolve a field identifier, throw a fatal error if not found.
1485      *  @param pos       The position to use for error reporting.
1486      *  @param env       The environment current at the method invocation.
1487      *  @param site      The type of the qualifying expression, in which
1488      *                   identifier is searched.
1489      *  @param name      The identifier's name.
1490      */
1491     public VarSymbol resolveInternalField(DiagnosticPosition pos, Env<AttrContext> env,
1492                                           Type site, Name name) {
1493         Symbol sym = findField(env, site, name, site.tsym);
1494         if (sym.kind == VAR) return (VarSymbol)sym;
1495         else throw new FatalError(
1496                  diags.fragment(Fragments.FatalErrCantLocateField(name)));
1497     }
1498 
1499     /** Find unqualified variable or field with given name.
1500      *  Synthetic fields always skipped.
1501      *  @param env     The current environment.
1502      *  @param name    The name of the variable or field.
1503      */
1504     Symbol findVar(Env<AttrContext> env, Name name) {
1505         Symbol bestSoFar = varNotFound;
1506         Env<AttrContext> env1 = env;
1507         boolean staticOnly = false;
1508         while (env1.outer != null) {
1509             Symbol sym = null;
1510             for (Symbol s : env1.info.scope.getSymbolsByName(name)) {
1511                 if (s.kind == VAR && (s.flags_field & SYNTHETIC) == 0) {
1512                     sym = s;
1513                     if (staticOnly) {
1514                         return new StaticError(sym);
1515                     }
1516                     break;
1517                 }
1518             }
1519             if (isStatic(env1)) staticOnly = true;
1520             if (sym == null) {
1521                 sym = findField(env1, env1.enclClass.sym.type, name, env1.enclClass.sym);
1522             }
1523             if (sym.exists()) {
1524                 if (staticOnly &&
1525                         sym.kind == VAR &&
1526                         sym.owner.kind == TYP &&
1527                         (sym.flags() & STATIC) == 0)
1528                     return new StaticError(sym);
1529                 else
1530                     return sym;
1531             } else {
1532                 bestSoFar = bestOf(bestSoFar, sym);
1533             }
1534 
1535             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
1536             env1 = env1.outer;
1537         }
1538 
1539         Symbol sym = findField(env, syms.predefClass.type, name, syms.predefClass);
1540         if (sym.exists())
1541             return sym;
1542         if (bestSoFar.exists())
1543             return bestSoFar;
1544 
1545         Symbol origin = null;
1546         for (Scope sc : new Scope[] { env.toplevel.namedImportScope, env.toplevel.starImportScope }) {
1547             for (Symbol currentSymbol : sc.getSymbolsByName(name)) {
1548                 if (currentSymbol.kind != VAR)
1549                     continue;
1550                 // invariant: sym.kind == Symbol.Kind.VAR
1551                 if (!bestSoFar.kind.isResolutionError() &&
1552                     currentSymbol.owner != bestSoFar.owner)
1553                     return new AmbiguityError(bestSoFar, currentSymbol);
1554                 else if (!bestSoFar.kind.betterThan(VAR)) {
1555                     origin = sc.getOrigin(currentSymbol).owner;
1556                     bestSoFar = isAccessible(env, origin.type, currentSymbol)
1557                         ? currentSymbol : new AccessError(env, origin.type, currentSymbol);
1558                 }
1559             }
1560             if (bestSoFar.exists()) break;
1561         }
1562         if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type)
1563             return bestSoFar.clone(origin);
1564         else
1565             return bestSoFar;
1566     }
1567 
1568     Warner noteWarner = new Warner();
1569 
1570     /** Select the best method for a call site among two choices.
1571      *  @param env              The current environment.
1572      *  @param site             The original type from where the
1573      *                          selection takes place.
1574      *  @param argtypes         The invocation's value arguments,
1575      *  @param typeargtypes     The invocation's type arguments,
1576      *  @param sym              Proposed new best match.
1577      *  @param bestSoFar        Previously found best match.
1578      *  @param allowBoxing Allow boxing conversions of arguments.
1579      *  @param useVarargs Box trailing arguments into an array for varargs.
1580      */
1581     @SuppressWarnings("fallthrough")
1582     Symbol selectBest(Env<AttrContext> env,
1583                       Type site,
1584                       List<Type> argtypes,
1585                       List<Type> typeargtypes,
1586                       Symbol sym,
1587                       Symbol bestSoFar,
1588                       boolean allowBoxing,
1589                       boolean useVarargs) {
1590         if (sym.kind == ERR ||
1591                 (site.tsym != sym.owner && !sym.isInheritedIn(site.tsym, types)) ||
1592                 !notOverriddenIn(site, sym)) {
1593             return bestSoFar;
1594         } else if (useVarargs && (sym.flags() & VARARGS) == 0) {
1595             return bestSoFar.kind.isResolutionError() ?
1596                     new BadVarargsMethod((ResolveError)bestSoFar.baseSymbol()) :
1597                     bestSoFar;
1598         }
1599         Assert.check(!sym.kind.isResolutionError());
1600         try {
1601             types.noWarnings.clear();
1602             Type mt = rawInstantiate(env, site, sym, null, argtypes, typeargtypes,
1603                                allowBoxing, useVarargs, types.noWarnings);
1604             currentResolutionContext.addApplicableCandidate(sym, mt);
1605         } catch (InapplicableMethodException ex) {
1606             currentResolutionContext.addInapplicableCandidate(sym, ex.getDiagnostic());
1607             // Currently, an InapplicableMethodException occurs.
1608             // If bestSoFar.kind was ABSENT_MTH, return an InapplicableSymbolError(kind is WRONG_MTH).
1609             // If bestSoFar.kind was HIDDEN(AccessError)/WRONG_MTH/WRONG_MTHS, return an InapplicableSymbolsError(kind is WRONG_MTHS).
1610             // See JDK-8255968 for more information.
1611             switch (bestSoFar.kind) {
1612                 case ABSENT_MTH:
1613                     return new InapplicableSymbolError(currentResolutionContext);
1614                 case HIDDEN:
1615                     if (bestSoFar instanceof AccessError accessError) {
1616                         // Add the JCDiagnostic of previous AccessError to the currentResolutionContext
1617                         // and construct InapplicableSymbolsError.
1618                         // Intentionally fallthrough.
1619                         currentResolutionContext.addInapplicableCandidate(accessError.sym,
1620                                 accessError.getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT, null, null, site, null, argtypes, typeargtypes));
1621                     } else {
1622                         return bestSoFar;
1623                     }
1624                 case WRONG_MTH:
1625                     bestSoFar = new InapplicableSymbolsError(currentResolutionContext);
1626                 default:
1627                     return bestSoFar;
1628             }
1629         }
1630         if (!isAccessible(env, site, sym)) {
1631             AccessError curAccessError = new AccessError(env, site, sym);
1632             JCDiagnostic curDiagnostic = curAccessError.getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT, null, null, site, null, argtypes, typeargtypes);
1633             // Currently, an AccessError occurs.
1634             // If bestSoFar.kind was ABSENT_MTH, return an AccessError(kind is HIDDEN).
1635             // If bestSoFar.kind was HIDDEN(AccessError), WRONG_MTH, WRONG_MTHS, return an InapplicableSymbolsError(kind is WRONG_MTHS).
1636             // See JDK-8255968 for more information.
1637             if (bestSoFar.kind == ABSENT_MTH) {
1638                 bestSoFar = curAccessError;
1639             } else if (bestSoFar.kind == WRONG_MTH) {
1640                 // Add the JCDiagnostic of current AccessError to the currentResolutionContext
1641                 // and construct InapplicableSymbolsError.
1642                 currentResolutionContext.addInapplicableCandidate(sym, curDiagnostic);
1643                 bestSoFar = new InapplicableSymbolsError(currentResolutionContext);
1644             } else if (bestSoFar.kind == WRONG_MTHS) {
1645                 // Add the JCDiagnostic of current AccessError to the currentResolutionContext
1646                 currentResolutionContext.addInapplicableCandidate(sym, curDiagnostic);
1647             } else if (bestSoFar.kind == HIDDEN && bestSoFar instanceof AccessError accessError) {
1648                 // Add the JCDiagnostics of previous and current AccessError to the currentResolutionContext
1649                 // and construct InapplicableSymbolsError.
1650                 currentResolutionContext.addInapplicableCandidate(accessError.sym,
1651                         accessError.getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT, null, null, site, null, argtypes, typeargtypes));
1652                 currentResolutionContext.addInapplicableCandidate(sym, curDiagnostic);
1653                 bestSoFar = new InapplicableSymbolsError(currentResolutionContext);
1654             }
1655             return bestSoFar;
1656         }
1657         return (bestSoFar.kind.isResolutionError() && bestSoFar.kind != AMBIGUOUS)
1658             ? sym
1659             : mostSpecific(argtypes, sym, bestSoFar, env, site, useVarargs);
1660     }
1661 
1662     /* Return the most specific of the two methods for a call,
1663      *  given that both are accessible and applicable.
1664      *  @param m1               A new candidate for most specific.
1665      *  @param m2               The previous most specific candidate.
1666      *  @param env              The current environment.
1667      *  @param site             The original type from where the selection
1668      *                          takes place.
1669      *  @param allowBoxing Allow boxing conversions of arguments.
1670      *  @param useVarargs Box trailing arguments into an array for varargs.
1671      */
1672     Symbol mostSpecific(List<Type> argtypes, Symbol m1,
1673                         Symbol m2,
1674                         Env<AttrContext> env,
1675                         final Type site,
1676                         boolean useVarargs) {
1677         switch (m2.kind) {
1678         case MTH:
1679             if (m1 == m2) return m1;
1680             boolean m1SignatureMoreSpecific =
1681                     signatureMoreSpecific(argtypes, env, site, m1, m2, useVarargs);
1682             boolean m2SignatureMoreSpecific =
1683                     signatureMoreSpecific(argtypes, env, site, m2, m1, useVarargs);
1684             if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) {
1685                 Type mt1 = types.memberType(site, m1);
1686                 Type mt2 = types.memberType(site, m2);
1687                 if (!types.overrideEquivalent(mt1, mt2))
1688                     return ambiguityError(m1, m2);
1689 
1690                 // same signature; select (a) the non-bridge method, or
1691                 // (b) the one that overrides the other, or (c) the concrete
1692                 // one, or (d) merge both abstract signatures
1693                 if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE))
1694                     return ((m1.flags() & BRIDGE) != 0) ? m2 : m1;
1695 
1696                 if (m1.baseSymbol() == m2.baseSymbol()) {
1697                     // this is the same imported symbol which has been cloned twice.
1698                     // Return the first one (either will do).
1699                     return m1;
1700                 }
1701 
1702                 // if one overrides or hides the other, use it
1703                 TypeSymbol m1Owner = (TypeSymbol)m1.owner;
1704                 TypeSymbol m2Owner = (TypeSymbol)m2.owner;
1705                 // the two owners can never be the same if the target methods are compiled from source,
1706                 // but we need to protect against cases where the methods are defined in some classfile
1707                 // and make sure we issue an ambiguity error accordingly (by skipping the logic below).
1708                 if (m1Owner != m2Owner) {
1709                     if (types.asSuper(m1Owner.type.referenceProjectionOrSelf(), m2Owner) != null &&
1710                         ((m1.owner.flags_field & INTERFACE) == 0 ||
1711                          (m2.owner.flags_field & INTERFACE) != 0) &&
1712                         m1.overrides(m2, m1Owner, types, false))
1713                         return m1;
1714                     if (types.asSuper(m2Owner.type.referenceProjectionOrSelf(), m1Owner) != null &&
1715                         ((m2.owner.flags_field & INTERFACE) == 0 ||
1716                          (m1.owner.flags_field & INTERFACE) != 0) &&
1717                         m2.overrides(m1, m2Owner, types, false))
1718                         return m2;
1719                 }
1720                 boolean m1Abstract = (m1.flags() & ABSTRACT) != 0;
1721                 boolean m2Abstract = (m2.flags() & ABSTRACT) != 0;
1722                 if (m1Abstract && !m2Abstract) return m2;
1723                 if (m2Abstract && !m1Abstract) return m1;
1724                 // both abstract or both concrete
1725                 return ambiguityError(m1, m2);
1726             }
1727             if (m1SignatureMoreSpecific) return m1;
1728             if (m2SignatureMoreSpecific) return m2;
1729             return ambiguityError(m1, m2);
1730         case AMBIGUOUS:
1731             //compare m1 to ambiguous methods in m2
1732             AmbiguityError e = (AmbiguityError)m2.baseSymbol();
1733             boolean m1MoreSpecificThanAnyAmbiguous = true;
1734             boolean allAmbiguousMoreSpecificThanM1 = true;
1735             for (Symbol s : e.ambiguousSyms) {
1736                 Symbol moreSpecific = mostSpecific(argtypes, m1, s, env, site, useVarargs);
1737                 m1MoreSpecificThanAnyAmbiguous &= moreSpecific == m1;
1738                 allAmbiguousMoreSpecificThanM1 &= moreSpecific == s;
1739             }
1740             if (m1MoreSpecificThanAnyAmbiguous)
1741                 return m1;
1742             //if m1 is more specific than some ambiguous methods, but other ambiguous methods are
1743             //more specific than m1, add it as a new ambiguous method:
1744             if (!allAmbiguousMoreSpecificThanM1)
1745                 e.addAmbiguousSymbol(m1);
1746             return e;
1747         default:
1748             throw new AssertionError();
1749         }
1750     }
1751     //where
1752     private boolean signatureMoreSpecific(List<Type> actuals, Env<AttrContext> env, Type site, Symbol m1, Symbol m2, boolean useVarargs) {
1753         noteWarner.clear();
1754         int maxLength = Math.max(
1755                             Math.max(m1.type.getParameterTypes().length(), actuals.length()),
1756                             m2.type.getParameterTypes().length());
1757         MethodResolutionContext prevResolutionContext = currentResolutionContext;
1758         try {
1759             currentResolutionContext = new MethodResolutionContext();
1760             currentResolutionContext.step = prevResolutionContext.step;
1761             currentResolutionContext.methodCheck =
1762                     prevResolutionContext.methodCheck.mostSpecificCheck(actuals);
1763             Type mst = instantiate(env, site, m2, null,
1764                     adjustArgs(types.cvarLowerBounds(types.memberType(site, m1).getParameterTypes()), m1, maxLength, useVarargs), null,
1765                     false, useVarargs, noteWarner);
1766             return mst != null &&
1767                     !noteWarner.hasLint(Lint.LintCategory.UNCHECKED);
1768         } finally {
1769             currentResolutionContext = prevResolutionContext;
1770         }
1771     }
1772 
1773     List<Type> adjustArgs(List<Type> args, Symbol msym, int length, boolean allowVarargs) {
1774         if ((msym.flags() & VARARGS) != 0 && allowVarargs) {
1775             Type varargsElem = types.elemtype(args.last());
1776             if (varargsElem == null) {
1777                 Assert.error("Bad varargs = " + args.last() + " " + msym);
1778             }
1779             List<Type> newArgs = args.reverse().tail.prepend(varargsElem).reverse();
1780             while (newArgs.length() < length) {
1781                 newArgs = newArgs.append(newArgs.last());
1782             }
1783             return newArgs;
1784         } else {
1785             return args;
1786         }
1787     }
1788     //where
1789     Symbol ambiguityError(Symbol m1, Symbol m2) {
1790         if (((m1.flags() | m2.flags()) & CLASH) != 0) {
1791             return (m1.flags() & CLASH) == 0 ? m1 : m2;
1792         } else {
1793             return new AmbiguityError(m1, m2);
1794         }
1795     }
1796 
1797     Symbol findMethodInScope(Env<AttrContext> env,
1798             Type site,
1799             Name name,
1800             List<Type> argtypes,
1801             List<Type> typeargtypes,
1802             Scope sc,
1803             Symbol bestSoFar,
1804             boolean allowBoxing,
1805             boolean useVarargs,
1806             boolean abstractok) {
1807         for (Symbol s : sc.getSymbolsByName(name, new LookupFilter(abstractok))) {
1808             bestSoFar = selectBest(env, site, argtypes, typeargtypes, s,
1809                     bestSoFar, allowBoxing, useVarargs);
1810         }
1811         return bestSoFar;
1812     }
1813     //where
1814         class LookupFilter implements Predicate<Symbol> {
1815 
1816             boolean abstractOk;
1817 
1818             LookupFilter(boolean abstractOk) {
1819                 this.abstractOk = abstractOk;
1820             }
1821 
1822             @Override
1823             public boolean test(Symbol s) {
1824                 long flags = s.flags();
1825                 return s.kind == MTH &&
1826                         (flags & SYNTHETIC) == 0 &&
1827                         (abstractOk ||
1828                         (flags & DEFAULT) != 0 ||
1829                         (flags & ABSTRACT) == 0);
1830             }
1831         }
1832 
1833     /** Find best qualified method matching given name, type and value
1834      *  arguments.
1835      *  @param env       The current environment.
1836      *  @param site      The original type from where the selection
1837      *                   takes place.
1838      *  @param name      The method's name.
1839      *  @param argtypes  The method's value arguments.
1840      *  @param typeargtypes The method's type arguments
1841      *  @param allowBoxing Allow boxing conversions of arguments.
1842      *  @param useVarargs Box trailing arguments into an array for varargs.
1843      */
1844     Symbol findMethod(Env<AttrContext> env,
1845                       Type site,
1846                       Name name,
1847                       List<Type> argtypes,
1848                       List<Type> typeargtypes,
1849                       boolean allowBoxing,
1850                       boolean useVarargs) {
1851         Symbol bestSoFar = methodNotFound;
1852         bestSoFar = findMethod(env,
1853                           site,
1854                           name,
1855                           argtypes,
1856                           typeargtypes,
1857                           site.tsym.type,
1858                           bestSoFar,
1859                           allowBoxing,
1860                           useVarargs);
1861         return bestSoFar;
1862     }
1863     // where
1864     private Symbol findMethod(Env<AttrContext> env,
1865                               Type site,
1866                               Name name,
1867                               List<Type> argtypes,
1868                               List<Type> typeargtypes,
1869                               Type intype,
1870                               Symbol bestSoFar,
1871                               boolean allowBoxing,
1872                               boolean useVarargs) {
1873         @SuppressWarnings({"unchecked","rawtypes"})
1874         List<Type>[] itypes = (List<Type>[])new List[] { List.<Type>nil(), List.<Type>nil() };
1875 
1876         InterfaceLookupPhase iphase = InterfaceLookupPhase.ABSTRACT_OK;
1877         boolean isInterface = site.tsym.isInterface();
1878         for (TypeSymbol s : isInterface ? List.of(intype.tsym) : superclasses(intype)) {
1879             bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
1880                     s.members(), bestSoFar, allowBoxing, useVarargs, true);
1881             if (name == names.init) return bestSoFar;
1882             iphase = (iphase == null) ? null : iphase.update(s, this);
1883             if (iphase != null) {
1884                 for (Type itype : types.interfaces(s.type)) {
1885                     itypes[iphase.ordinal()] = types.union(types.closure(itype), itypes[iphase.ordinal()]);
1886                 }
1887             }
1888         }
1889 
1890         Symbol concrete = bestSoFar.kind.isValid() &&
1891                 (bestSoFar.flags() & ABSTRACT) == 0 ?
1892                 bestSoFar : methodNotFound;
1893 
1894         for (InterfaceLookupPhase iphase2 : InterfaceLookupPhase.values()) {
1895             //keep searching for abstract methods
1896             for (Type itype : itypes[iphase2.ordinal()]) {
1897                 if (!itype.isInterface()) continue; //skip j.l.Object (included by Types.closure())
1898                 if (iphase2 == InterfaceLookupPhase.DEFAULT_OK &&
1899                         (itype.tsym.flags() & DEFAULT) == 0) continue;
1900                 bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
1901                         itype.tsym.members(), bestSoFar, allowBoxing, useVarargs, true);
1902                 if (concrete != bestSoFar &&
1903                     concrete.kind.isValid() &&
1904                     bestSoFar.kind.isValid() &&
1905                         types.isSubSignature(concrete.type, bestSoFar.type)) {
1906                     //this is an hack - as javac does not do full membership checks
1907                     //most specific ends up comparing abstract methods that might have
1908                     //been implemented by some concrete method in a subclass and,
1909                     //because of raw override, it is possible for an abstract method
1910                     //to be more specific than the concrete method - so we need
1911                     //to explicitly call that out (see CR 6178365)
1912                     bestSoFar = concrete;
1913                 }
1914             }
1915         }
1916         if (isInterface && bestSoFar.kind.isResolutionError()) {
1917             bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
1918                     syms.objectType.tsym.members(), bestSoFar, allowBoxing, useVarargs, true);
1919             if (bestSoFar.kind.isValid()) {
1920                 Symbol baseSymbol = bestSoFar;
1921                 bestSoFar = new MethodSymbol(bestSoFar.flags_field, bestSoFar.name, bestSoFar.type, intype.tsym) {
1922                     @Override
1923                     public Symbol baseSymbol() {
1924                         return baseSymbol;
1925                     }
1926                 };
1927             }
1928         }
1929         return bestSoFar;
1930     }
1931 
1932     enum InterfaceLookupPhase {
1933         ABSTRACT_OK() {
1934             @Override
1935             InterfaceLookupPhase update(Symbol s, Resolve rs) {
1936                 //We should not look for abstract methods if receiver is a concrete class
1937                 //(as concrete classes are expected to implement all abstracts coming
1938                 //from superinterfaces)
1939                 if ((s.flags() & (ABSTRACT | INTERFACE | ENUM)) != 0) {
1940                     return this;
1941                 } else {
1942                     return DEFAULT_OK;
1943                 }
1944             }
1945         },
1946         DEFAULT_OK() {
1947             @Override
1948             InterfaceLookupPhase update(Symbol s, Resolve rs) {
1949                 return this;
1950             }
1951         };
1952 
1953         abstract InterfaceLookupPhase update(Symbol s, Resolve rs);
1954     }
1955 
1956     /**
1957      * Return an Iterable object to scan the superclasses of a given type.
1958      * It's crucial that the scan is done lazily, as we don't want to accidentally
1959      * access more supertypes than strictly needed (as this could trigger completion
1960      * errors if some of the not-needed supertypes are missing/ill-formed).
1961      */
1962     Iterable<TypeSymbol> superclasses(final Type intype) {
1963         return () -> new Iterator<TypeSymbol>() {
1964 
1965             List<TypeSymbol> seen = List.nil();
1966             TypeSymbol currentSym = symbolFor(intype);
1967             TypeSymbol prevSym = null;
1968 
1969             public boolean hasNext() {
1970                 if (currentSym == syms.noSymbol) {
1971                     currentSym = symbolFor(types.supertype(prevSym.type));
1972                 }
1973                 return currentSym != null;
1974             }
1975 
1976             public TypeSymbol next() {
1977                 prevSym = currentSym;
1978                 currentSym = syms.noSymbol;
1979                 Assert.check(prevSym != null || prevSym != syms.noSymbol);
1980                 return prevSym;
1981             }
1982 
1983             public void remove() {
1984                 throw new UnsupportedOperationException();
1985             }
1986 
1987             TypeSymbol symbolFor(Type t) {
1988                 if (!t.hasTag(CLASS) &&
1989                         !t.hasTag(TYPEVAR)) {
1990                     return null;
1991                 }
1992                 t = types.skipTypeVars(t, false);
1993                 if (seen.contains(t.tsym)) {
1994                     //degenerate case in which we have a circular
1995                     //class hierarchy - because of ill-formed classfiles
1996                     return null;
1997                 }
1998                 seen = seen.prepend(t.tsym);
1999                 return t.tsym;
2000             }
2001         };
2002     }
2003 
2004     /** Find unqualified method matching given name, type and value arguments.
2005      *  @param env       The current environment.
2006      *  @param name      The method's name.
2007      *  @param argtypes  The method's value arguments.
2008      *  @param typeargtypes  The method's type arguments.
2009      *  @param allowBoxing Allow boxing conversions of arguments.
2010      *  @param useVarargs Box trailing arguments into an array for varargs.
2011      */
2012     Symbol findFun(Env<AttrContext> env, Name name,
2013                    List<Type> argtypes, List<Type> typeargtypes,
2014                    boolean allowBoxing, boolean useVarargs) {
2015         Symbol bestSoFar = methodNotFound;
2016         Env<AttrContext> env1 = env;
2017         boolean staticOnly = false;
2018         while (env1.outer != null) {
2019             if (isStatic(env1)) staticOnly = true;
2020             Assert.check(env1.info.preferredTreeForDiagnostics == null);
2021             env1.info.preferredTreeForDiagnostics = env.tree;
2022             try {
2023                 Symbol sym = findMethod(
2024                     env1, env1.enclClass.sym.type, name, argtypes, typeargtypes,
2025                     allowBoxing, useVarargs);
2026                 if (sym.exists()) {
2027                     if (staticOnly &&
2028                         sym.kind == MTH &&
2029                         sym.owner.kind == TYP &&
2030                         (sym.flags() & STATIC) == 0) return new StaticError(sym);
2031                     else return sym;
2032                 } else {
2033                     bestSoFar = bestOf(bestSoFar, sym);
2034                 }
2035             } finally {
2036                 env1.info.preferredTreeForDiagnostics = null;
2037             }
2038             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
2039             env1 = env1.outer;
2040         }
2041 
2042         Symbol sym = findMethod(env, syms.predefClass.type, name, argtypes,
2043                                 typeargtypes, allowBoxing, useVarargs);
2044         if (sym.exists())
2045             return sym;
2046 
2047         for (Symbol currentSym : env.toplevel.namedImportScope.getSymbolsByName(name)) {
2048             Symbol origin = env.toplevel.namedImportScope.getOrigin(currentSym).owner;
2049             if (currentSym.kind == MTH) {
2050                 if (currentSym.owner.type != origin.type)
2051                     currentSym = currentSym.clone(origin);
2052                 if (!isAccessible(env, origin.type, currentSym))
2053                     currentSym = new AccessError(env, origin.type, currentSym);
2054                 bestSoFar = selectBest(env, origin.type,
2055                                        argtypes, typeargtypes,
2056                                        currentSym, bestSoFar,
2057                                        allowBoxing, useVarargs);
2058             }
2059         }
2060         if (bestSoFar.exists())
2061             return bestSoFar;
2062 
2063         for (Symbol currentSym : env.toplevel.starImportScope.getSymbolsByName(name)) {
2064             Symbol origin = env.toplevel.starImportScope.getOrigin(currentSym).owner;
2065             if (currentSym.kind == MTH) {
2066                 if (currentSym.owner.type != origin.type)
2067                     currentSym = currentSym.clone(origin);
2068                 if (!isAccessible(env, origin.type, currentSym))
2069                     currentSym = new AccessError(env, origin.type, currentSym);
2070                 bestSoFar = selectBest(env, origin.type,
2071                                        argtypes, typeargtypes,
2072                                        currentSym, bestSoFar,
2073                                        allowBoxing, useVarargs);
2074             }
2075         }
2076         return bestSoFar;
2077     }
2078 
2079     /** Load toplevel or member class with given fully qualified name and
2080      *  verify that it is accessible.
2081      *  @param env       The current environment.
2082      *  @param name      The fully qualified name of the class to be loaded.
2083      */
2084     Symbol loadClass(Env<AttrContext> env, Name name, RecoveryLoadClass recoveryLoadClass) {
2085         try {
2086             ClassSymbol c = finder.loadClass(env.toplevel.modle, name);
2087             return isAccessible(env, c) ? c : new AccessError(env, null, c);
2088         } catch (ClassFinder.BadClassFile err) {
2089             return new BadClassFileError(err);
2090         } catch (CompletionFailure ex) {
2091             Symbol candidate = recoveryLoadClass.loadClass(env, name);
2092 
2093             if (candidate != null) {
2094                 return candidate;
2095             }
2096 
2097             return typeNotFound;
2098         }
2099     }
2100 
2101     public interface RecoveryLoadClass {
2102         Symbol loadClass(Env<AttrContext> env, Name name);
2103     }
2104 
2105     private final RecoveryLoadClass noRecovery = (env, name) -> null;
2106 
2107     private final RecoveryLoadClass doRecoveryLoadClass = new RecoveryLoadClass() {
2108         @Override public Symbol loadClass(Env<AttrContext> env, Name name) {
2109             List<Name> candidates = Convert.classCandidates(name);
2110             return lookupInvisibleSymbol(env, name,
2111                                          n -> () -> createCompoundIterator(candidates,
2112                                                                            c -> syms.getClassesForName(c)
2113                                                                                     .iterator()),
2114                                          (ms, n) -> {
2115                 for (Name candidate : candidates) {
2116                     try {
2117                         return finder.loadClass(ms, candidate);
2118                     } catch (CompletionFailure cf) {
2119                         //ignore
2120                     }
2121                 }
2122                 return null;
2123             }, sym -> sym.kind == Kind.TYP, typeNotFound);
2124         }
2125     };
2126 
2127     private final RecoveryLoadClass namedImportScopeRecovery = (env, name) -> {
2128         Scope importScope = env.toplevel.namedImportScope;
2129         Symbol existing = importScope.findFirst(Convert.shortName(name),
2130                                                 sym -> sym.kind == TYP && sym.flatName() == name);
2131 
2132         if (existing != null) {
2133             return new InvisibleSymbolError(env, true, existing);
2134         }
2135         return null;
2136     };
2137 
2138     private final RecoveryLoadClass starImportScopeRecovery = (env, name) -> {
2139         Scope importScope = env.toplevel.starImportScope;
2140         Symbol existing = importScope.findFirst(Convert.shortName(name),
2141                                                 sym -> sym.kind == TYP && sym.flatName() == name);
2142 
2143         if (existing != null) {
2144             try {
2145                 existing = finder.loadClass(existing.packge().modle, name);
2146 
2147                 return new InvisibleSymbolError(env, true, existing);
2148             } catch (CompletionFailure cf) {
2149                 //ignore
2150             }
2151         }
2152 
2153         return null;
2154     };
2155 
2156     Symbol lookupPackage(Env<AttrContext> env, Name name) {
2157         PackageSymbol pack = syms.lookupPackage(env.toplevel.modle, name);
2158 
2159         if (allowModules && isImportOnDemand(env, name)) {
2160             if (pack.members().isEmpty()) {
2161                 return lookupInvisibleSymbol(env, name, syms::getPackagesForName, syms::enterPackage, sym -> {
2162                     sym.complete();
2163                     return !sym.members().isEmpty();
2164                 }, pack);
2165             }
2166         }
2167 
2168         return pack;
2169     }
2170 
2171     private boolean isImportOnDemand(Env<AttrContext> env, Name name) {
2172         if (!env.tree.hasTag(IMPORT))
2173             return false;
2174 
2175         JCTree qualid = ((JCImport) env.tree).qualid;
2176 
2177         if (!qualid.hasTag(SELECT))
2178             return false;
2179 
2180         if (TreeInfo.name(qualid) != names.asterisk)
2181             return false;
2182 
2183         return TreeInfo.fullName(((JCFieldAccess) qualid).selected) == name;
2184     }
2185 
2186     private <S extends Symbol> Symbol lookupInvisibleSymbol(Env<AttrContext> env,
2187                                                             Name name,
2188                                                             Function<Name, Iterable<S>> get,
2189                                                             BiFunction<ModuleSymbol, Name, S> load,
2190                                                             Predicate<S> validate,
2191                                                             Symbol defaultResult) {
2192         //even if a class/package cannot be found in the current module and among packages in modules
2193         //it depends on that are exported for any or this module, the class/package may exist internally
2194         //in some of these modules, or may exist in a module on which this module does not depend.
2195         //Provide better diagnostic in such cases by looking for the class in any module:
2196         Iterable<? extends S> candidates = get.apply(name);
2197 
2198         for (S sym : candidates) {
2199             if (validate.test(sym))
2200                 return createInvisibleSymbolError(env, sym);
2201         }
2202 
2203         Set<ModuleSymbol> recoverableModules = new HashSet<>(syms.getAllModules());
2204 
2205         recoverableModules.add(syms.unnamedModule);
2206         recoverableModules.remove(env.toplevel.modle);
2207 
2208         for (ModuleSymbol ms : recoverableModules) {
2209             //avoid overly eager completing classes from source-based modules, as those
2210             //may not be completable with the current compiler settings:
2211             if (ms.sourceLocation == null) {
2212                 if (ms.classLocation == null) {
2213                     ms = moduleFinder.findModule(ms);
2214                 }
2215 
2216                 if (ms.kind != ERR) {
2217                     S sym = load.apply(ms, name);
2218 
2219                     if (sym != null && validate.test(sym)) {
2220                         return createInvisibleSymbolError(env, sym);
2221                     }
2222                 }
2223             }
2224         }
2225 
2226         return defaultResult;
2227     }
2228 
2229     private Symbol createInvisibleSymbolError(Env<AttrContext> env, Symbol sym) {
2230         if (symbolPackageVisible(env, sym)) {
2231             return new AccessError(env, null, sym);
2232         } else {
2233             return new InvisibleSymbolError(env, false, sym);
2234         }
2235     }
2236 
2237     private boolean symbolPackageVisible(Env<AttrContext> env, Symbol sym) {
2238         ModuleSymbol envMod = env.toplevel.modle;
2239         PackageSymbol symPack = sym.packge();
2240         return envMod == symPack.modle ||
2241                envMod.visiblePackages.containsKey(symPack.fullname);
2242     }
2243 
2244     /**
2245      * Find a type declared in a scope (not inherited).  Return null
2246      * if none is found.
2247      *  @param env       The current environment.
2248      *  @param site      The original type from where the selection takes
2249      *                   place.
2250      *  @param name      The type's name.
2251      *  @param c         The class to search for the member type. This is
2252      *                   always a superclass or implemented interface of
2253      *                   site's class.
2254      */
2255     Symbol findImmediateMemberType(Env<AttrContext> env,
2256                                    Type site,
2257                                    Name name,
2258                                    TypeSymbol c) {
2259         for (Symbol sym : c.members().getSymbolsByName(name)) {
2260             if (sym.kind == TYP) {
2261                 return isAccessible(env, site, sym)
2262                     ? sym
2263                     : new AccessError(env, site, sym);
2264             }
2265         }
2266         return typeNotFound;
2267     }
2268 
2269     /** Find a member type inherited from a superclass or interface.
2270      *  @param env       The current environment.
2271      *  @param site      The original type from where the selection takes
2272      *                   place.
2273      *  @param name      The type's name.
2274      *  @param c         The class to search for the member type. This is
2275      *                   always a superclass or implemented interface of
2276      *                   site's class.
2277      */
2278     Symbol findInheritedMemberType(Env<AttrContext> env,
2279                                    Type site,
2280                                    Name name,
2281                                    TypeSymbol c) {
2282         Symbol bestSoFar = typeNotFound;
2283         Symbol sym;
2284         Type st = types.supertype(c.type);
2285         if (st != null && st.hasTag(CLASS)) {
2286             sym = findMemberType(env, site, name, st.tsym);
2287             bestSoFar = bestOf(bestSoFar, sym);
2288         }
2289         for (List<Type> l = types.interfaces(c.type);
2290              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
2291              l = l.tail) {
2292             sym = findMemberType(env, site, name, l.head.tsym);
2293             if (!bestSoFar.kind.isResolutionError() &&
2294                 !sym.kind.isResolutionError() &&
2295                 sym.owner != bestSoFar.owner)
2296                 bestSoFar = new AmbiguityError(bestSoFar, sym);
2297             else
2298                 bestSoFar = bestOf(bestSoFar, sym);
2299         }
2300         return bestSoFar;
2301     }
2302 
2303     /** Find qualified member type.
2304      *  @param env       The current environment.
2305      *  @param site      The original type from where the selection takes
2306      *                   place.
2307      *  @param name      The type's name.
2308      *  @param c         The class to search for the member type. This is
2309      *                   always a superclass or implemented interface of
2310      *                   site's class.
2311      */
2312     Symbol findMemberType(Env<AttrContext> env,
2313                           Type site,
2314                           Name name,
2315                           TypeSymbol c) {
2316         return findMemberTypeInternal(env,site, name, c);
2317     }
2318 
2319     /** Find qualified member type.
2320      *  @param env       The current environment.
2321      *  @param site      The original type from where the selection takes
2322      *                   place.
2323      *  @param name      The type's name.
2324      *  @param c         The class to search for the member type. This is
2325      *                   always a superclass or implemented interface of
2326      *                   site's class.
2327      */
2328     Symbol findMemberTypeInternal(Env<AttrContext> env,
2329                           Type site,
2330                           Name name,
2331                           TypeSymbol c) {
2332         Symbol sym = findImmediateMemberType(env, site, name, c);
2333 
2334         if (sym != typeNotFound)
2335             return sym;
2336 
2337         return findInheritedMemberType(env, site, name, c);
2338 
2339     }
2340 
2341     /** Find a global type in given scope and load corresponding class.
2342      *  @param env       The current environment.
2343      *  @param scope     The scope in which to look for the type.
2344      *  @param name      The type's name.
2345      */
2346     Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name, RecoveryLoadClass recoveryLoadClass) {
2347         Symbol bestSoFar = typeNotFound;
2348         for (Symbol s : scope.getSymbolsByName(name)) {
2349             Symbol sym = loadClass(env, s.flatName(), recoveryLoadClass);
2350             if (bestSoFar.kind == TYP && sym.kind == TYP &&
2351                 bestSoFar != sym)
2352                 return new AmbiguityError(bestSoFar, sym);
2353             else
2354                 bestSoFar = bestOf(bestSoFar, sym);
2355         }
2356         return bestSoFar;
2357     }
2358 
2359     Symbol findTypeVar(Env<AttrContext> env, Name name, boolean staticOnly) {
2360         for (Symbol sym : env.info.scope.getSymbolsByName(name)) {
2361             if (sym.kind == TYP) {
2362                 if (sym.type.hasTag(TYPEVAR) &&
2363                         (staticOnly || (isStatic(env) && sym.owner.kind == TYP)))
2364                     // if staticOnly is set, it means that we have recursed through a static declaration,
2365                     // so type variable symbols should not be accessible. If staticOnly is unset, but
2366                     // we are in a static declaration (field or method), we should not allow type-variables
2367                     // defined in the enclosing class to "leak" into this context.
2368                     return new StaticError(sym);
2369                 return sym;
2370             }
2371         }
2372         return typeNotFound;
2373     }
2374 
2375     /** Find an unqualified type symbol.
2376      *  @param env       The current environment.
2377      *  @param name      The type's name.
2378      */
2379     Symbol findType(Env<AttrContext> env, Name name) {
2380         return findTypeInternal(env, name);
2381     }
2382 
2383     /** Find an unqualified type symbol.
2384      *  @param env       The current environment.
2385      *  @param name      The type's name.
2386      */
2387     Symbol findTypeInternal(Env<AttrContext> env, Name name) {
2388         if (name == names.empty)
2389             return typeNotFound; // do not allow inadvertent "lookup" of anonymous types
2390         Symbol bestSoFar = typeNotFound;
2391         Symbol sym;
2392         boolean staticOnly = false;
2393         for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
2394             // First, look for a type variable and the first member type
2395             final Symbol tyvar = findTypeVar(env1, name, staticOnly);
2396             if (isStatic(env1)) staticOnly = true;
2397             sym = findImmediateMemberType(env1, env1.enclClass.sym.type,
2398                                           name, env1.enclClass.sym);
2399 
2400             // Return the type variable if we have it, and have no
2401             // immediate member, OR the type variable is for a method.
2402             if (tyvar != typeNotFound) {
2403                 if (env.baseClause || sym == typeNotFound ||
2404                     (tyvar.kind == TYP && tyvar.exists() &&
2405                      tyvar.owner.kind == MTH)) {
2406                     return tyvar;
2407                 }
2408             }
2409 
2410             // If the environment is a class def, finish up,
2411             // otherwise, do the entire findMemberType
2412             if (sym == typeNotFound)
2413                 sym = findInheritedMemberType(env1, env1.enclClass.sym.type,
2414                                               name, env1.enclClass.sym);
2415 
2416             if (staticOnly && sym.kind == TYP &&
2417                 sym.type.hasTag(CLASS) &&
2418                 sym.type.getEnclosingType().hasTag(CLASS) &&
2419                 env1.enclClass.sym.type.isParameterized() &&
2420                 sym.type.getEnclosingType().isParameterized())
2421                 return new StaticError(sym);
2422             else if (sym.exists()) return sym;
2423             else bestSoFar = bestOf(bestSoFar, sym);
2424 
2425             JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass;
2426             if ((encl.sym.flags() & STATIC) != 0)
2427                 staticOnly = true;
2428         }
2429 
2430         if (!env.tree.hasTag(IMPORT)) {
2431             sym = findGlobalType(env, env.toplevel.namedImportScope, name, namedImportScopeRecovery);
2432             if (sym.exists()) return sym;
2433             else bestSoFar = bestOf(bestSoFar, sym);
2434 
2435             sym = findGlobalType(env, env.toplevel.toplevelScope, name, noRecovery);
2436             if (sym.exists()) return sym;
2437             else bestSoFar = bestOf(bestSoFar, sym);
2438 
2439             sym = findGlobalType(env, env.toplevel.packge.members(), name, noRecovery);
2440             if (sym.exists()) return sym;
2441             else bestSoFar = bestOf(bestSoFar, sym);
2442 
2443             sym = findGlobalType(env, env.toplevel.starImportScope, name, starImportScopeRecovery);
2444             if (sym.exists()) return sym;
2445             else bestSoFar = bestOf(bestSoFar, sym);
2446         }
2447 
2448         return bestSoFar;
2449     }
2450 
2451     /** Find an unqualified identifier which matches a specified kind set.
2452      *  @param pos       position on which report warnings, if any;
2453      *                   null warnings should not be reported
2454      *  @param env       The current environment.
2455      *  @param name      The identifier's name.
2456      *  @param kind      Indicates the possible symbol kinds
2457      *                   (a subset of VAL, TYP, PCK).
2458      */
2459     Symbol findIdent(DiagnosticPosition pos, Env<AttrContext> env, Name name, KindSelector kind) {
2460         return checkRestrictedType(pos, findIdentInternal(env, name, kind), name);
2461     }
2462 
2463     Symbol findIdentInternal(Env<AttrContext> env, Name name, KindSelector kind) {
2464         Symbol bestSoFar = typeNotFound;
2465         Symbol sym;
2466 
2467         if (kind.contains(KindSelector.VAL)) {
2468             sym = findVar(env, name);
2469             if (sym.exists()) return sym;
2470             else bestSoFar = bestOf(bestSoFar, sym);
2471         }
2472 
2473         if (kind.contains(KindSelector.TYP)) {
2474             sym = findType(env, name);
2475 
2476             if (sym.exists()) return sym;
2477             else bestSoFar = bestOf(bestSoFar, sym);
2478         }
2479 
2480         if (kind.contains(KindSelector.PCK))
2481             return lookupPackage(env, name);
2482         else return bestSoFar;
2483     }
2484 
2485     /** Find an identifier in a package which matches a specified kind set.
2486      *  @param pos       position on which report warnings, if any;
2487      *                   null warnings should not be reported
2488      *  @param env       The current environment.
2489      *  @param name      The identifier's name.
2490      *  @param kind      Indicates the possible symbol kinds
2491      *                   (a nonempty subset of TYP, PCK).
2492      */
2493     Symbol findIdentInPackage(DiagnosticPosition pos,
2494                               Env<AttrContext> env, TypeSymbol pck,
2495                               Name name, KindSelector kind) {
2496         return checkRestrictedType(pos, findIdentInPackageInternal(env, pck, name, kind), name);
2497     }
2498 
2499     Symbol findIdentInPackageInternal(Env<AttrContext> env, TypeSymbol pck,
2500                               Name name, KindSelector kind) {
2501         Name fullname = TypeSymbol.formFullName(name, pck);
2502         Symbol bestSoFar = typeNotFound;
2503         if (kind.contains(KindSelector.TYP)) {
2504             RecoveryLoadClass recoveryLoadClass =
2505                     allowModules && !kind.contains(KindSelector.PCK) &&
2506                     !pck.exists() && !env.info.attributionMode.isSpeculative ?
2507                         doRecoveryLoadClass : noRecovery;
2508             Symbol sym = loadClass(env, fullname, recoveryLoadClass);
2509             if (sym.exists()) {
2510                 // don't allow programs to use flatnames
2511                 if (name == sym.name) return sym;
2512             }
2513             else bestSoFar = bestOf(bestSoFar, sym);
2514         }
2515         if (kind.contains(KindSelector.PCK)) {
2516             return lookupPackage(env, fullname);
2517         }
2518         return bestSoFar;
2519     }
2520 
2521     /** Find an identifier among the members of a given type `site'.
2522      *  @param pos       position on which report warnings, if any;
2523      *                   null warnings should not be reported
2524      *  @param env       The current environment.
2525      *  @param site      The type containing the symbol to be found.
2526      *  @param name      The identifier's name.
2527      *  @param kind      Indicates the possible symbol kinds
2528      *                   (a subset of VAL, TYP).
2529      */
2530     Symbol findIdentInType(DiagnosticPosition pos,
2531                            Env<AttrContext> env, Type site,
2532                            Name name, KindSelector kind) {
2533         return checkRestrictedType(pos, findIdentInTypeInternal(env, site, name, kind), name);
2534     }
2535 
2536     Symbol findIdentInTypeInternal(Env<AttrContext> env, Type site,
2537                            Name name, KindSelector kind) {
2538         Symbol bestSoFar = typeNotFound;
2539         Symbol sym;
2540         if (kind.contains(KindSelector.VAL)) {
2541             sym = findField(env, site, name, site.tsym);
2542             if (sym.exists()) return sym;
2543             else bestSoFar = bestOf(bestSoFar, sym);
2544         }
2545 
2546         if (kind.contains(KindSelector.TYP)) {
2547             sym = findMemberType(env, site, name, site.tsym);
2548             if (sym.exists()) return sym;
2549             else bestSoFar = bestOf(bestSoFar, sym);
2550         }
2551         return bestSoFar;
2552     }
2553 
2554     private Symbol checkRestrictedType(DiagnosticPosition pos, Symbol bestSoFar, Name name) {
2555         if (bestSoFar.kind == TYP || bestSoFar.kind == ABSENT_TYP) {
2556             if (allowLocalVariableTypeInference && name.equals(names.var)) {
2557                 bestSoFar = new BadRestrictedTypeError(names.var);
2558             } else if (name.equals(names.yield)) {
2559                 if (allowYieldStatement) {
2560                     bestSoFar = new BadRestrictedTypeError(names.yield);
2561                 } else if (pos != null) {
2562                     log.warning(pos, Warnings.IllegalRefToRestrictedType(names.yield));
2563                 }
2564             }
2565         }
2566         return bestSoFar;
2567     }
2568 
2569 /* ***************************************************************************
2570  *  Access checking
2571  *  The following methods convert ResolveErrors to ErrorSymbols, issuing
2572  *  an error message in the process
2573  ****************************************************************************/
2574 
2575     /** If `sym' is a bad symbol: report error and return errSymbol
2576      *  else pass through unchanged,
2577      *  additional arguments duplicate what has been used in trying to find the
2578      *  symbol {@literal (--> flyweight pattern)}. This improves performance since we
2579      *  expect misses to happen frequently.
2580      *
2581      *  @param sym       The symbol that was found, or a ResolveError.
2582      *  @param pos       The position to use for error reporting.
2583      *  @param location  The symbol the served as a context for this lookup
2584      *  @param site      The original type from where the selection took place.
2585      *  @param name      The symbol's name.
2586      *  @param qualified Did we get here through a qualified expression resolution?
2587      *  @param argtypes  The invocation's value arguments,
2588      *                   if we looked for a method.
2589      *  @param typeargtypes  The invocation's type arguments,
2590      *                   if we looked for a method.
2591      *  @param logResolveHelper helper class used to log resolve errors
2592      */
2593     Symbol accessInternal(Symbol sym,
2594                   DiagnosticPosition pos,
2595                   Symbol location,
2596                   Type site,
2597                   Name name,
2598                   boolean qualified,
2599                   List<Type> argtypes,
2600                   List<Type> typeargtypes,
2601                   LogResolveHelper logResolveHelper) {
2602         if (sym.kind.isResolutionError()) {
2603             ResolveError errSym = (ResolveError)sym.baseSymbol();
2604             sym = errSym.access(name, qualified ? site.tsym : syms.noSymbol);
2605             argtypes = logResolveHelper.getArgumentTypes(errSym, sym, name, argtypes);
2606             if (logResolveHelper.resolveDiagnosticNeeded(site, argtypes, typeargtypes)) {
2607                 logResolveError(errSym, pos, location, site, name, argtypes, typeargtypes);
2608             }
2609         }
2610         return sym;
2611     }
2612 
2613     /**
2614      * Variant of the generalized access routine, to be used for generating method
2615      * resolution diagnostics
2616      */
2617     Symbol accessMethod(Symbol sym,
2618                   DiagnosticPosition pos,
2619                   Symbol location,
2620                   Type site,
2621                   Name name,
2622                   boolean qualified,
2623                   List<Type> argtypes,
2624                   List<Type> typeargtypes) {
2625         return accessInternal(sym, pos, location, site, name, qualified, argtypes, typeargtypes, methodLogResolveHelper);
2626     }
2627 
2628     /** Same as original accessMethod(), but without location.
2629      */
2630     Symbol accessMethod(Symbol sym,
2631                   DiagnosticPosition pos,
2632                   Type site,
2633                   Name name,
2634                   boolean qualified,
2635                   List<Type> argtypes,
2636                   List<Type> typeargtypes) {
2637         return accessMethod(sym, pos, site.tsym, site, name, qualified, argtypes, typeargtypes);
2638     }
2639 
2640     /**
2641      * Variant of the generalized access routine, to be used for generating variable,
2642      * type resolution diagnostics
2643      */
2644     Symbol accessBase(Symbol sym,
2645                   DiagnosticPosition pos,
2646                   Symbol location,
2647                   Type site,
2648                   Name name,
2649                   boolean qualified) {
2650         return accessInternal(sym, pos, location, site, name, qualified, List.nil(), null, basicLogResolveHelper);
2651     }
2652 
2653     /** Same as original accessBase(), but without location.
2654      */
2655     Symbol accessBase(Symbol sym,
2656                   DiagnosticPosition pos,
2657                   Type site,
2658                   Name name,
2659                   boolean qualified) {
2660         return accessBase(sym, pos, site.tsym, site, name, qualified);
2661     }
2662 
2663     interface LogResolveHelper {
2664         boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes);
2665         List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes);
2666     }
2667 
2668     LogResolveHelper basicLogResolveHelper = new LogResolveHelper() {
2669         public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
2670             return !site.isErroneous();
2671         }
2672         public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
2673             return argtypes;
2674         }
2675     };
2676 
2677     LogResolveHelper silentLogResolveHelper = new LogResolveHelper() {
2678         public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
2679             return false;
2680         }
2681         public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
2682             return argtypes;
2683         }
2684     };
2685 
2686     LogResolveHelper methodLogResolveHelper = new LogResolveHelper() {
2687         public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
2688             return !site.isErroneous() &&
2689                         !Type.isErroneous(argtypes) &&
2690                         (typeargtypes == null || !Type.isErroneous(typeargtypes));
2691         }
2692         public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
2693             return argtypes.map(new ResolveDeferredRecoveryMap(AttrMode.SPECULATIVE, accessedSym, currentResolutionContext.step));
2694         }
2695     };
2696 
2697     class ResolveDeferredRecoveryMap extends DeferredAttr.RecoveryDeferredTypeMap {
2698 
2699         public ResolveDeferredRecoveryMap(AttrMode mode, Symbol msym, MethodResolutionPhase step) {
2700             deferredAttr.super(mode, msym, step);
2701         }
2702 
2703         @Override
2704         protected Type typeOf(DeferredType dt, Type pt) {
2705             Type res = super.typeOf(dt, pt);
2706             if (!res.isErroneous()) {
2707                 switch (TreeInfo.skipParens(dt.tree).getTag()) {
2708                     case LAMBDA:
2709                     case REFERENCE:
2710                         return dt;
2711                     case CONDEXPR:
2712                         return res == Type.recoveryType ?
2713                                 dt : res;
2714                 }
2715             }
2716             return res;
2717         }
2718     }
2719 
2720     /** Check that sym is not an abstract method.
2721      */
2722     void checkNonAbstract(DiagnosticPosition pos, Symbol sym) {
2723         if ((sym.flags() & ABSTRACT) != 0 && (sym.flags() & DEFAULT) == 0)
2724             log.error(pos,
2725                       Errors.AbstractCantBeAccessedDirectly(kindName(sym),sym, sym.location()));
2726     }
2727 
2728 /* ***************************************************************************
2729  *  Name resolution
2730  *  Naming conventions are as for symbol lookup
2731  *  Unlike the find... methods these methods will report access errors
2732  ****************************************************************************/
2733 
2734     /** Resolve an unqualified (non-method) identifier.
2735      *  @param pos       The position to use for error reporting.
2736      *  @param env       The environment current at the identifier use.
2737      *  @param name      The identifier's name.
2738      *  @param kind      The set of admissible symbol kinds for the identifier.
2739      */
2740     Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env,
2741                         Name name, KindSelector kind) {
2742         return accessBase(
2743             findIdent(pos, env, name, kind),
2744             pos, env.enclClass.sym.type, name, false);
2745     }
2746 
2747     /** Resolve an unqualified method identifier.
2748      *  @param pos       The position to use for error reporting.
2749      *  @param env       The environment current at the method invocation.
2750      *  @param name      The identifier's name.
2751      *  @param argtypes  The types of the invocation's value arguments.
2752      *  @param typeargtypes  The types of the invocation's type arguments.
2753      */
2754     Symbol resolveMethod(DiagnosticPosition pos,
2755                          Env<AttrContext> env,
2756                          Name name,
2757                          List<Type> argtypes,
2758                          List<Type> typeargtypes) {
2759         return lookupMethod(env, pos, env.enclClass.sym, resolveMethodCheck,
2760                 new BasicLookupHelper(name, env.enclClass.sym.type, argtypes, typeargtypes) {
2761                     @Override
2762                     Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2763                         return findFun(env, name, argtypes, typeargtypes,
2764                                 phase.isBoxingRequired(),
2765                                 phase.isVarargsRequired());
2766                     }});
2767     }
2768 
2769     /** Resolve a qualified method identifier
2770      *  @param pos       The position to use for error reporting.
2771      *  @param env       The environment current at the method invocation.
2772      *  @param site      The type of the qualifying expression, in which
2773      *                   identifier is searched.
2774      *  @param name      The identifier's name.
2775      *  @param argtypes  The types of the invocation's value arguments.
2776      *  @param typeargtypes  The types of the invocation's type arguments.
2777      */
2778     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
2779                                   Type site, Name name, List<Type> argtypes,
2780                                   List<Type> typeargtypes) {
2781         return resolveQualifiedMethod(pos, env, site.tsym, site, name, argtypes, typeargtypes);
2782     }
2783     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
2784                                   Symbol location, Type site, Name name, List<Type> argtypes,
2785                                   List<Type> typeargtypes) {
2786         return resolveQualifiedMethod(new MethodResolutionContext(), pos, env, location, site, name, argtypes, typeargtypes);
2787     }
2788     private Symbol resolveQualifiedMethod(MethodResolutionContext resolveContext,
2789                                   DiagnosticPosition pos, Env<AttrContext> env,
2790                                   Symbol location, Type site, Name name, List<Type> argtypes,
2791                                   List<Type> typeargtypes) {
2792         return lookupMethod(env, pos, location, resolveContext, new BasicLookupHelper(name, site, argtypes, typeargtypes) {
2793             @Override
2794             Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2795                 return findMethod(env, site, name, argtypes, typeargtypes,
2796                         phase.isBoxingRequired(),
2797                         phase.isVarargsRequired());
2798             }
2799             @Override
2800             Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
2801                 if (sym.kind.isResolutionError()) {
2802                     sym = super.access(env, pos, location, sym);
2803                 } else {
2804                     MethodSymbol msym = (MethodSymbol)sym;
2805                     if ((msym.flags() & SIGNATURE_POLYMORPHIC) != 0) {
2806                         env.info.pendingResolutionPhase = BASIC;
2807                         return findPolymorphicSignatureInstance(env, sym, argtypes);
2808                     }
2809                 }
2810                 return sym;
2811             }
2812         });
2813     }
2814 
2815     /** Find or create an implicit method of exactly the given type (after erasure).
2816      *  Searches in a side table, not the main scope of the site.
2817      *  This emulates the lookup process required by JSR 292 in JVM.
2818      *  @param env       Attribution environment
2819      *  @param spMethod  signature polymorphic method - i.e. MH.invokeExact
2820      *  @param argtypes  The required argument types
2821      */
2822     Symbol findPolymorphicSignatureInstance(Env<AttrContext> env,
2823                                             final Symbol spMethod,
2824                                             List<Type> argtypes) {
2825         Type mtype = infer.instantiatePolymorphicSignatureInstance(env,
2826                 (MethodSymbol)spMethod, currentResolutionContext, argtypes);
2827         return findPolymorphicSignatureInstance(spMethod, mtype);
2828     }
2829 
2830     Symbol findPolymorphicSignatureInstance(final Symbol spMethod,
2831                                             Type mtype) {
2832         for (Symbol sym : polymorphicSignatureScope.getSymbolsByName(spMethod.name)) {
2833             // Check that there is already a method symbol for the method
2834             // type and owner
2835             if (types.isSameType(mtype, sym.type) &&
2836                 spMethod.owner == sym.owner) {
2837                 return sym;
2838             }
2839         }
2840 
2841         Type spReturnType = spMethod.asType().getReturnType();
2842         if (types.isSameType(spReturnType, syms.objectType)) {
2843             // Polymorphic return, pass through mtype
2844         } else if (!types.isSameType(spReturnType, mtype.getReturnType())) {
2845             // Retain the sig poly method's return type, which differs from that of mtype
2846             // Will result in an incompatible return type error
2847             mtype = new MethodType(mtype.getParameterTypes(),
2848                     spReturnType,
2849                     mtype.getThrownTypes(),
2850                     syms.methodClass);
2851         }
2852 
2853         // Create the desired method
2854         // Retain static modifier is to support invocations to
2855         // MethodHandle.linkTo* methods
2856         long flags = ABSTRACT | HYPOTHETICAL |
2857                      spMethod.flags() & (Flags.AccessFlags | Flags.STATIC);
2858         Symbol msym = new MethodSymbol(flags, spMethod.name, mtype, spMethod.owner) {
2859             @Override
2860             public Symbol baseSymbol() {
2861                 return spMethod;
2862             }
2863         };
2864         if (!mtype.isErroneous()) { // Cache only if kosher.
2865             polymorphicSignatureScope.enter(msym);
2866         }
2867         return msym;
2868     }
2869 
2870     /** Resolve a qualified method identifier, throw a fatal error if not
2871      *  found.
2872      *  @param pos       The position to use for error reporting.
2873      *  @param env       The environment current at the method invocation.
2874      *  @param site      The type of the qualifying expression, in which
2875      *                   identifier is searched.
2876      *  @param name      The identifier's name.
2877      *  @param argtypes  The types of the invocation's value arguments.
2878      *  @param typeargtypes  The types of the invocation's type arguments.
2879      */
2880     public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env,
2881                                         Type site, Name name,
2882                                         List<Type> argtypes,
2883                                         List<Type> typeargtypes) {
2884         MethodResolutionContext resolveContext = new MethodResolutionContext();
2885         resolveContext.internalResolution = true;
2886         Symbol sym = resolveQualifiedMethod(resolveContext, pos, env, site.tsym,
2887                 site, name, argtypes, typeargtypes);
2888         if (sym.kind == MTH) return (MethodSymbol)sym;
2889         else throw new FatalError(
2890                  diags.fragment(Fragments.FatalErrCantLocateMeth(name)));
2891     }
2892 
2893     /** Resolve constructor.
2894      *  @param pos       The position to use for error reporting.
2895      *  @param env       The environment current at the constructor invocation.
2896      *  @param site      The type of class for which a constructor is searched.
2897      *  @param argtypes  The types of the constructor invocation's value
2898      *                   arguments.
2899      *  @param typeargtypes  The types of the constructor invocation's type
2900      *                   arguments.
2901      */
2902     Symbol resolveConstructor(DiagnosticPosition pos,
2903                               Env<AttrContext> env,
2904                               Type site,
2905                               List<Type> argtypes,
2906                               List<Type> typeargtypes) {
2907         return resolveConstructor(new MethodResolutionContext(), pos, env, site, argtypes, typeargtypes);
2908     }
2909 
2910     private Symbol resolveConstructor(MethodResolutionContext resolveContext,
2911                               final DiagnosticPosition pos,
2912                               Env<AttrContext> env,
2913                               Type site,
2914                               List<Type> argtypes,
2915                               List<Type> typeargtypes) {
2916         return lookupMethod(env, pos, site.tsym, resolveContext, new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
2917             @Override
2918             Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2919                 return findConstructor(pos, env, site, argtypes, typeargtypes,
2920                         phase.isBoxingRequired(),
2921                         phase.isVarargsRequired());
2922             }
2923         });
2924     }
2925 
2926     /** Resolve a constructor, throw a fatal error if not found.
2927      *  @param pos       The position to use for error reporting.
2928      *  @param env       The environment current at the method invocation.
2929      *  @param site      The type to be constructed.
2930      *  @param argtypes  The types of the invocation's value arguments.
2931      *  @param typeargtypes  The types of the invocation's type arguments.
2932      */
2933     public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
2934                                         Type site,
2935                                         List<Type> argtypes,
2936                                         List<Type> typeargtypes) {
2937         MethodResolutionContext resolveContext = new MethodResolutionContext();
2938         resolveContext.internalResolution = true;
2939         Symbol sym = resolveConstructor(resolveContext, pos, env, site, argtypes, typeargtypes);
2940         if (sym.kind == MTH) return (MethodSymbol)sym;
2941         else throw new FatalError(
2942                  diags.fragment(Fragments.FatalErrCantLocateCtor(site)));
2943     }
2944 
2945     Symbol findConstructor(DiagnosticPosition pos, Env<AttrContext> env,
2946                               Type site, List<Type> argtypes,
2947                               List<Type> typeargtypes,
2948                               boolean allowBoxing,
2949                               boolean useVarargs) {
2950         Symbol sym = findMethod(env, site,
2951                                     names.init, argtypes,
2952                                     typeargtypes, allowBoxing,
2953                                     useVarargs);
2954         chk.checkDeprecated(pos, env.info.scope.owner, sym);
2955         chk.checkPreview(pos, env.info.scope.owner, sym);
2956         return sym;
2957     }
2958 
2959     /** Resolve constructor using diamond inference.
2960      *  @param pos       The position to use for error reporting.
2961      *  @param env       The environment current at the constructor invocation.
2962      *  @param site      The type of class for which a constructor is searched.
2963      *                   The scope of this class has been touched in attribution.
2964      *  @param argtypes  The types of the constructor invocation's value
2965      *                   arguments.
2966      *  @param typeargtypes  The types of the constructor invocation's type
2967      *                   arguments.
2968      */
2969     Symbol resolveDiamond(DiagnosticPosition pos,
2970                               Env<AttrContext> env,
2971                               Type site,
2972                               List<Type> argtypes,
2973                               List<Type> typeargtypes) {
2974         return lookupMethod(env, pos, site.tsym, resolveMethodCheck,
2975                 new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
2976                     @Override
2977                     Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2978                         return findDiamond(pos, env, site, argtypes, typeargtypes,
2979                                 phase.isBoxingRequired(),
2980                                 phase.isVarargsRequired());
2981                     }
2982                     @Override
2983                     Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
2984                         if (sym.kind.isResolutionError()) {
2985                             if (sym.kind != WRONG_MTH &&
2986                                 sym.kind != WRONG_MTHS) {
2987                                 sym = super.access(env, pos, location, sym);
2988                             } else {
2989                                 final JCDiagnostic details = sym.kind == WRONG_MTH ?
2990                                                 ((InapplicableSymbolError)sym.baseSymbol()).errCandidate().snd :
2991                                                 null;
2992                                 sym = new DiamondError(sym, currentResolutionContext);
2993                                 sym = accessMethod(sym, pos, site, names.init, true, argtypes, typeargtypes);
2994                                 env.info.pendingResolutionPhase = currentResolutionContext.step;
2995                             }
2996                         }
2997                         return sym;
2998                     }});
2999     }
3000 
3001     /** Find the constructor using diamond inference and do some checks(deprecated and preview).
3002      *  @param pos          The position to use for error reporting.
3003      *  @param env          The environment current at the constructor invocation.
3004      *  @param site         The type of class for which a constructor is searched.
3005      *                      The scope of this class has been touched in attribution.
3006      *  @param argtypes     The types of the constructor invocation's value arguments.
3007      *  @param typeargtypes The types of the constructor invocation's type arguments.
3008      *  @param allowBoxing  Allow boxing conversions of arguments.
3009      *  @param useVarargs   Box trailing arguments into an array for varargs.
3010      */
3011     private Symbol findDiamond(DiagnosticPosition pos,
3012                                Env<AttrContext> env,
3013                                Type site,
3014                                List<Type> argtypes,
3015                                List<Type> typeargtypes,
3016                                boolean allowBoxing,
3017                                boolean useVarargs) {
3018         Symbol sym = findDiamond(env, site, argtypes, typeargtypes, allowBoxing, useVarargs);
3019         chk.checkDeprecated(pos, env.info.scope.owner, sym);
3020         chk.checkPreview(pos, env.info.scope.owner, sym);
3021         return sym;
3022     }
3023 
3024     /** This method scans all the constructor symbol in a given class scope -
3025      *  assuming that the original scope contains a constructor of the kind:
3026      *  {@code Foo(X x, Y y)}, where X,Y are class type-variables declared in Foo,
3027      *  a method check is executed against the modified constructor type:
3028      *  {@code <X,Y>Foo<X,Y>(X x, Y y)}. This is crucial in order to enable diamond
3029      *  inference. The inferred return type of the synthetic constructor IS
3030      *  the inferred type for the diamond operator.
3031      */
3032     private Symbol findDiamond(Env<AttrContext> env,
3033                               Type site,
3034                               List<Type> argtypes,
3035                               List<Type> typeargtypes,
3036                               boolean allowBoxing,
3037                               boolean useVarargs) {
3038         Symbol bestSoFar = methodNotFound;
3039         TypeSymbol tsym = site.tsym.isInterface() ? syms.objectType.tsym : site.tsym;
3040         for (final Symbol sym : tsym.members().getSymbolsByName(names.init)) {
3041             //- System.out.println(" e " + e.sym);
3042             if (sym.kind == MTH &&
3043                 (sym.flags_field & SYNTHETIC) == 0) {
3044                     List<Type> oldParams = sym.type.hasTag(FORALL) ?
3045                             ((ForAll)sym.type).tvars :
3046                             List.nil();
3047                     Type constrType = new ForAll(site.tsym.type.getTypeArguments().appendList(oldParams),
3048                                                  types.createMethodTypeWithReturn(sym.type.asMethodType(), site));
3049                     MethodSymbol newConstr = new MethodSymbol(sym.flags(), names.init, constrType, site.tsym) {
3050                         @Override
3051                         public Symbol baseSymbol() {
3052                             return sym;
3053                         }
3054                     };
3055                     bestSoFar = selectBest(env, site, argtypes, typeargtypes,
3056                             newConstr,
3057                             bestSoFar,
3058                             allowBoxing,
3059                             useVarargs);
3060             }
3061         }
3062         return bestSoFar;
3063     }
3064 
3065     Symbol getMemberReference(DiagnosticPosition pos,
3066             Env<AttrContext> env,
3067             JCMemberReference referenceTree,
3068             Type site,
3069             Name name) {
3070 
3071         site = types.capture(site);
3072 
3073         ReferenceLookupHelper lookupHelper = makeReferenceLookupHelper(
3074                 referenceTree, site, name, List.nil(), null, VARARITY);
3075 
3076         Env<AttrContext> newEnv = env.dup(env.tree, env.info.dup());
3077         Symbol sym = lookupMethod(newEnv, env.tree.pos(), site.tsym,
3078                 nilMethodCheck, lookupHelper);
3079 
3080         env.info.pendingResolutionPhase = newEnv.info.pendingResolutionPhase;
3081 
3082         return sym;
3083     }
3084 
3085     ReferenceLookupHelper makeReferenceLookupHelper(JCMemberReference referenceTree,
3086                                   Type site,
3087                                   Name name,
3088                                   List<Type> argtypes,
3089                                   List<Type> typeargtypes,
3090                                   MethodResolutionPhase maxPhase) {
3091         if (!name.equals(names.init)) {
3092             //method reference
3093             return new MethodReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
3094         } else if (site.hasTag(ARRAY)) {
3095             //array constructor reference
3096             return new ArrayConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase);
3097         } else {
3098             //class constructor reference
3099             return new ConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase);
3100         }
3101     }
3102 
3103     /**
3104      * Resolution of member references is typically done as a single
3105      * overload resolution step, where the argument types A are inferred from
3106      * the target functional descriptor.
3107      *
3108      * If the member reference is a method reference with a type qualifier,
3109      * a two-step lookup process is performed. The first step uses the
3110      * expected argument list A, while the second step discards the first
3111      * type from A (which is treated as a receiver type).
3112      *
3113      * There are two cases in which inference is performed: (i) if the member
3114      * reference is a constructor reference and the qualifier type is raw - in
3115      * which case diamond inference is used to infer a parameterization for the
3116      * type qualifier; (ii) if the member reference is an unbound reference
3117      * where the type qualifier is raw - in that case, during the unbound lookup
3118      * the receiver argument type is used to infer an instantiation for the raw
3119      * qualifier type.
3120      *
3121      * When a multi-step resolution process is exploited, the process of picking
3122      * the resulting symbol is delegated to an helper class {@link com.sun.tools.javac.comp.Resolve.ReferenceChooser}.
3123      *
3124      * This routine returns a pair (T,S), where S is the member reference symbol,
3125      * and T is the type of the class in which S is defined. This is necessary as
3126      * the type T might be dynamically inferred (i.e. if constructor reference
3127      * has a raw qualifier).
3128      */
3129     Pair<Symbol, ReferenceLookupHelper> resolveMemberReference(Env<AttrContext> env,
3130                                   JCMemberReference referenceTree,
3131                                   Type site,
3132                                   Name name,
3133                                   List<Type> argtypes,
3134                                   List<Type> typeargtypes,
3135                                   Type descriptor,
3136                                   MethodCheck methodCheck,
3137                                   InferenceContext inferenceContext,
3138                                   ReferenceChooser referenceChooser) {
3139 
3140         //step 1 - bound lookup
3141         ReferenceLookupHelper boundLookupHelper = makeReferenceLookupHelper(
3142                 referenceTree, site, name, argtypes, typeargtypes, VARARITY);
3143         Env<AttrContext> boundEnv = env.dup(env.tree, env.info.dup());
3144         MethodResolutionContext boundSearchResolveContext = new MethodResolutionContext();
3145         boundSearchResolveContext.methodCheck = methodCheck;
3146         Symbol boundSym = lookupMethod(boundEnv, env.tree.pos(),
3147                 site.tsym, boundSearchResolveContext, boundLookupHelper);
3148         ReferenceLookupResult boundRes = new ReferenceLookupResult(boundSym, boundSearchResolveContext);
3149         if (dumpMethodReferenceSearchResults) {
3150             dumpMethodReferenceSearchResults(referenceTree, boundSearchResolveContext, boundSym, true);
3151         }
3152 
3153         //step 2 - unbound lookup
3154         Symbol unboundSym = methodNotFound;
3155         Env<AttrContext> unboundEnv = env.dup(env.tree, env.info.dup());
3156         ReferenceLookupHelper unboundLookupHelper = boundLookupHelper.unboundLookup(inferenceContext);
3157         ReferenceLookupResult unboundRes = referenceNotFound;
3158         if (unboundLookupHelper != null) {
3159             MethodResolutionContext unboundSearchResolveContext =
3160                     new MethodResolutionContext();
3161             unboundSearchResolveContext.methodCheck = methodCheck;
3162             unboundSym = lookupMethod(unboundEnv, env.tree.pos(),
3163                     site.tsym, unboundSearchResolveContext, unboundLookupHelper);
3164             unboundRes = new ReferenceLookupResult(unboundSym, unboundSearchResolveContext);
3165             if (dumpMethodReferenceSearchResults) {
3166                 dumpMethodReferenceSearchResults(referenceTree, unboundSearchResolveContext, unboundSym, false);
3167             }
3168         }
3169 
3170         //merge results
3171         Pair<Symbol, ReferenceLookupHelper> res;
3172         ReferenceLookupResult bestRes = referenceChooser.result(boundRes, unboundRes);
3173         res = new Pair<>(bestRes.sym,
3174                 bestRes == unboundRes ? unboundLookupHelper : boundLookupHelper);
3175         env.info.pendingResolutionPhase = bestRes == unboundRes ?
3176                 unboundEnv.info.pendingResolutionPhase :
3177                 boundEnv.info.pendingResolutionPhase;
3178 
3179         if (!res.fst.kind.isResolutionError()) {
3180             //handle sigpoly method references
3181             MethodSymbol msym = (MethodSymbol)res.fst;
3182             if ((msym.flags() & SIGNATURE_POLYMORPHIC) != 0) {
3183                 env.info.pendingResolutionPhase = BASIC;
3184                 res = new Pair<>(findPolymorphicSignatureInstance(msym, descriptor), res.snd);
3185             }
3186         }
3187 
3188         return res;
3189     }
3190 
3191     private void dumpMethodReferenceSearchResults(JCMemberReference referenceTree,
3192                                                   MethodResolutionContext resolutionContext,
3193                                                   Symbol bestSoFar,
3194                                                   boolean bound) {
3195         ListBuffer<JCDiagnostic> subDiags = new ListBuffer<>();
3196         int pos = 0;
3197         int mostSpecificPos = -1;
3198         for (Candidate c : resolutionContext.candidates) {
3199             if (resolutionContext.step != c.step || !c.isApplicable()) {
3200                 continue;
3201             } else {
3202                 JCDiagnostic subDiag = null;
3203                 if (c.sym.type.hasTag(FORALL)) {
3204                     subDiag = diags.fragment(Fragments.PartialInstSig(c.mtype));
3205                 }
3206 
3207                 String key = subDiag == null ?
3208                         "applicable.method.found.2" :
3209                         "applicable.method.found.3";
3210                 subDiags.append(diags.fragment(key, pos,
3211                         c.sym.isStatic() ? Fragments.Static : Fragments.NonStatic, c.sym, subDiag));
3212                 if (c.sym == bestSoFar)
3213                     mostSpecificPos = pos;
3214                 pos++;
3215             }
3216         }
3217         JCDiagnostic main = diags.note(
3218                 log.currentSource(),
3219                 referenceTree,
3220                 "method.ref.search.results.multi",
3221                 bound ? Fragments.Bound : Fragments.Unbound,
3222                 referenceTree.toString(), mostSpecificPos);
3223         JCDiagnostic d = new JCDiagnostic.MultilineDiagnostic(main, subDiags.toList());
3224         log.report(d);
3225     }
3226 
3227     /**
3228      * This class is used to represent a method reference lookup result. It keeps track of two
3229      * things: (i) the symbol found during a method reference lookup and (ii) the static kind
3230      * of the lookup (see {@link com.sun.tools.javac.comp.Resolve.ReferenceLookupResult.StaticKind}).
3231      */
3232     static class ReferenceLookupResult {
3233 
3234         /**
3235          * Static kind associated with a method reference lookup. Erroneous lookups end up with
3236          * the UNDEFINED kind; successful lookups will end up with either STATIC, NON_STATIC,
3237          * depending on whether all applicable candidates are static or non-static methods,
3238          * respectively. If a successful lookup has both static and non-static applicable methods,
3239          * its kind is set to BOTH.
3240          */
3241         enum StaticKind {
3242             STATIC,
3243             NON_STATIC,
3244             BOTH,
3245             UNDEFINED;
3246 
3247             /**
3248              * Retrieve the static kind associated with a given (method) symbol.
3249              */
3250             static StaticKind from(Symbol s) {
3251                 return s.isStatic() ?
3252                         STATIC : NON_STATIC;
3253             }
3254 
3255             /**
3256              * Merge two static kinds together.
3257              */
3258             static StaticKind reduce(StaticKind sk1, StaticKind sk2) {
3259                 if (sk1 == UNDEFINED) {
3260                     return sk2;
3261                 } else if (sk2 == UNDEFINED) {
3262                     return sk1;
3263                 } else {
3264                     return sk1 == sk2 ? sk1 : BOTH;
3265                 }
3266             }
3267         }
3268 
3269         /** The static kind. */
3270         StaticKind staticKind;
3271 
3272         /** The lookup result. */
3273         Symbol sym;
3274 
3275         ReferenceLookupResult(Symbol sym, MethodResolutionContext resolutionContext) {
3276             this(sym, staticKind(sym, resolutionContext));
3277         }
3278 
3279         private ReferenceLookupResult(Symbol sym, StaticKind staticKind) {
3280             this.staticKind = staticKind;
3281             this.sym = sym;
3282         }
3283 
3284         private static StaticKind staticKind(Symbol sym, MethodResolutionContext resolutionContext) {
3285             switch (sym.kind) {
3286                 case MTH:
3287                 case AMBIGUOUS:
3288                     return resolutionContext.candidates.stream()
3289                             .filter(c -> c.isApplicable() && c.step == resolutionContext.step)
3290                             .map(c -> StaticKind.from(c.sym))
3291                             .reduce(StaticKind::reduce)
3292                             .orElse(StaticKind.UNDEFINED);
3293                 default:
3294                     return StaticKind.UNDEFINED;
3295             }
3296         }
3297 
3298         /**
3299          * Does this result corresponds to a successful lookup (i.e. one where a method has been found?)
3300          */
3301         boolean isSuccess() {
3302             return staticKind != StaticKind.UNDEFINED;
3303         }
3304 
3305         /**
3306          * Does this result have given static kind?
3307          */
3308         boolean hasKind(StaticKind sk) {
3309             return this.staticKind == sk;
3310         }
3311 
3312         /**
3313          * Error recovery helper: can this lookup result be ignored (for the purpose of returning
3314          * some 'better' result) ?
3315          */
3316         boolean canIgnore() {
3317             switch (sym.kind) {
3318                 case ABSENT_MTH:
3319                     return true;
3320                 case WRONG_MTH:
3321                     InapplicableSymbolError errSym =
3322                             (InapplicableSymbolError)sym.baseSymbol();
3323                     return new Template(MethodCheckDiag.ARITY_MISMATCH.regex())
3324                             .matches(errSym.errCandidate().snd);
3325                 case WRONG_MTHS:
3326                     InapplicableSymbolsError errSyms =
3327                             (InapplicableSymbolsError)sym.baseSymbol();
3328                     return errSyms.filterCandidates(errSyms.mapCandidates()).isEmpty();
3329                 default:
3330                     return false;
3331             }
3332         }
3333 
3334         static ReferenceLookupResult error(Symbol sym) {
3335             return new ReferenceLookupResult(sym, StaticKind.UNDEFINED);
3336         }
3337     }
3338 
3339     /**
3340      * This abstract class embodies the logic that converts one (bound lookup) or two (unbound lookup)
3341      * {@code ReferenceLookupResult} objects into a (@code Symbol), which is then regarded as the
3342      * result of method reference resolution.
3343      */
3344     abstract class ReferenceChooser {
3345         /**
3346          * Generate a result from a pair of lookup result objects. This method delegates to the
3347          * appropriate result generation routine.
3348          */
3349         ReferenceLookupResult result(ReferenceLookupResult boundRes, ReferenceLookupResult unboundRes) {
3350             return unboundRes != referenceNotFound ?
3351                     unboundResult(boundRes, unboundRes) :
3352                     boundResult(boundRes);
3353         }
3354 
3355         /**
3356          * Generate a symbol from a given bound lookup result.
3357          */
3358         abstract ReferenceLookupResult boundResult(ReferenceLookupResult boundRes);
3359 
3360         /**
3361          * Generate a symbol from a pair of bound/unbound lookup results.
3362          */
3363         abstract ReferenceLookupResult unboundResult(ReferenceLookupResult boundRes, ReferenceLookupResult unboundRes);
3364     }
3365 
3366     /**
3367      * This chooser implements the selection strategy used during a full lookup; this logic
3368      * is described in JLS SE 8 (15.3.2).
3369      */
3370     ReferenceChooser basicReferenceChooser = new ReferenceChooser() {
3371 
3372         @Override
3373         ReferenceLookupResult boundResult(ReferenceLookupResult boundRes) {
3374             return !boundRes.isSuccess() || boundRes.hasKind(StaticKind.NON_STATIC) ?
3375                     boundRes : //the search produces a non-static method
3376                     ReferenceLookupResult.error(new BadMethodReferenceError(boundRes.sym, false));
3377         }
3378 
3379         @Override
3380         ReferenceLookupResult unboundResult(ReferenceLookupResult boundRes, ReferenceLookupResult unboundRes) {
3381             if (boundRes.isSuccess() && boundRes.sym.isStatic() &&
3382                     (!unboundRes.isSuccess() || unboundRes.hasKind(StaticKind.STATIC))) {
3383                 //the first search produces a static method and no non-static method is applicable
3384                 //during the second search
3385                 return boundRes;
3386             } else if (unboundRes.isSuccess() && !unboundRes.sym.isStatic() &&
3387                     (!boundRes.isSuccess() || boundRes.hasKind(StaticKind.NON_STATIC))) {
3388                 //the second search produces a non-static method and no static method is applicable
3389                 //during the first search
3390                 return unboundRes;
3391             } else if (boundRes.isSuccess() && unboundRes.isSuccess()) {
3392                 //both searches produce some result; ambiguity (error recovery)
3393                 return ReferenceLookupResult.error(ambiguityError(boundRes.sym, unboundRes.sym));
3394             } else if (boundRes.isSuccess() || unboundRes.isSuccess()) {
3395                 //Both searches failed to produce a result with correct staticness (i.e. first search
3396                 //produces an non-static method). Alternatively, a given search produced a result
3397                 //with the right staticness, but the other search has applicable methods with wrong
3398                 //staticness (error recovery)
3399                 return ReferenceLookupResult.error(new BadMethodReferenceError(boundRes.isSuccess() ?
3400                         boundRes.sym : unboundRes.sym, true));
3401             } else {
3402                 //both searches fail to produce a result - pick 'better' error using heuristics (error recovery)
3403                 return (boundRes.canIgnore() && !unboundRes.canIgnore()) ?
3404                         unboundRes : boundRes;
3405             }
3406         }
3407     };
3408 
3409     /**
3410      * This chooser implements the selection strategy used during an arity-based lookup; this logic
3411      * is described in JLS SE 8 (15.12.2.1).
3412      */
3413     ReferenceChooser structuralReferenceChooser = new ReferenceChooser() {
3414 
3415         @Override
3416         ReferenceLookupResult boundResult(ReferenceLookupResult boundRes) {
3417             return (!boundRes.isSuccess() || !boundRes.hasKind(StaticKind.STATIC)) ?
3418                     boundRes : //the search has at least one applicable non-static method
3419                     ReferenceLookupResult.error(new BadMethodReferenceError(boundRes.sym, false));
3420         }
3421 
3422         @Override
3423         ReferenceLookupResult unboundResult(ReferenceLookupResult boundRes, ReferenceLookupResult unboundRes) {
3424             if (boundRes.isSuccess() && !boundRes.hasKind(StaticKind.NON_STATIC)) {
3425                 //the first search has at least one applicable static method
3426                 return boundRes;
3427             } else if (unboundRes.isSuccess() && !unboundRes.hasKind(StaticKind.STATIC)) {
3428                 //the second search has at least one applicable non-static method
3429                 return unboundRes;
3430             } else if (boundRes.isSuccess() || unboundRes.isSuccess()) {
3431                 //either the first search produces a non-static method, or second search produces
3432                 //a non-static method (error recovery)
3433                 return ReferenceLookupResult.error(new BadMethodReferenceError(boundRes.isSuccess() ?
3434                         boundRes.sym : unboundRes.sym, true));
3435             } else {
3436                 //both searches fail to produce a result - pick 'better' error using heuristics (error recovery)
3437                 return (boundRes.canIgnore() && !unboundRes.canIgnore()) ?
3438                         unboundRes : boundRes;
3439             }
3440         }
3441     };
3442 
3443     /**
3444      * Helper for defining custom method-like lookup logic; a lookup helper
3445      * provides hooks for (i) the actual lookup logic and (ii) accessing the
3446      * lookup result (this step might result in compiler diagnostics to be generated)
3447      */
3448     abstract class LookupHelper {
3449 
3450         /** name of the symbol to lookup */
3451         Name name;
3452 
3453         /** location in which the lookup takes place */
3454         Type site;
3455 
3456         /** actual types used during the lookup */
3457         List<Type> argtypes;
3458 
3459         /** type arguments used during the lookup */
3460         List<Type> typeargtypes;
3461 
3462         /** Max overload resolution phase handled by this helper */
3463         MethodResolutionPhase maxPhase;
3464 
3465         LookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
3466             this.name = name;
3467             this.site = site;
3468             this.argtypes = argtypes;
3469             this.typeargtypes = typeargtypes;
3470             this.maxPhase = maxPhase;
3471         }
3472 
3473         /**
3474          * Should lookup stop at given phase with given result
3475          */
3476         final boolean shouldStop(Symbol sym, MethodResolutionPhase phase) {
3477             return phase.ordinal() > maxPhase.ordinal() ||
3478                  !sym.kind.isResolutionError() || sym.kind == AMBIGUOUS || sym.kind == STATICERR;
3479         }
3480 
3481         /**
3482          * Search for a symbol under a given overload resolution phase - this method
3483          * is usually called several times, once per each overload resolution phase
3484          */
3485         abstract Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase);
3486 
3487         /**
3488          * Dump overload resolution info
3489          */
3490         void debug(DiagnosticPosition pos, Symbol sym) {
3491             //do nothing
3492         }
3493 
3494         /**
3495          * Validate the result of the lookup
3496          */
3497         abstract Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym);
3498     }
3499 
3500     abstract class BasicLookupHelper extends LookupHelper {
3501 
3502         BasicLookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes) {
3503             this(name, site, argtypes, typeargtypes, MethodResolutionPhase.VARARITY);
3504         }
3505 
3506         BasicLookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
3507             super(name, site, argtypes, typeargtypes, maxPhase);
3508         }
3509 
3510         @Override
3511         final Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
3512             Symbol sym = doLookup(env, phase);
3513             if (sym.kind == AMBIGUOUS) {
3514                 AmbiguityError a_err = (AmbiguityError)sym.baseSymbol();
3515                 sym = a_err.mergeAbstracts(site);
3516             }
3517             return sym;
3518         }
3519 
3520         abstract Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase);
3521 
3522         @Override
3523         Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
3524             if (sym.kind.isResolutionError()) {
3525                 //if nothing is found return the 'first' error
3526                 sym = accessMethod(sym, pos, location, site, name, true, argtypes, typeargtypes);
3527             }
3528             return sym;
3529         }
3530 
3531         @Override
3532         void debug(DiagnosticPosition pos, Symbol sym) {
3533             reportVerboseResolutionDiagnostic(pos, name, site, argtypes, typeargtypes, sym);
3534         }
3535     }
3536 
3537     /**
3538      * Helper class for member reference lookup. A reference lookup helper
3539      * defines the basic logic for member reference lookup; a method gives
3540      * access to an 'unbound' helper used to perform an unbound member
3541      * reference lookup.
3542      */
3543     abstract class ReferenceLookupHelper extends LookupHelper {
3544 
3545         /** The member reference tree */
3546         JCMemberReference referenceTree;
3547 
3548         ReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
3549                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
3550             super(name, site, argtypes, typeargtypes, maxPhase);
3551             this.referenceTree = referenceTree;
3552         }
3553 
3554         /**
3555          * Returns an unbound version of this lookup helper. By default, this
3556          * method returns an dummy lookup helper.
3557          */
3558         ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
3559             return null;
3560         }
3561 
3562         /**
3563          * Get the kind of the member reference
3564          */
3565         abstract JCMemberReference.ReferenceKind referenceKind(Symbol sym);
3566 
3567         Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
3568             if (sym.kind == AMBIGUOUS) {
3569                 AmbiguityError a_err = (AmbiguityError)sym.baseSymbol();
3570                 sym = a_err.mergeAbstracts(site);
3571             }
3572             //skip error reporting
3573             return sym;
3574         }
3575     }
3576 
3577     /**
3578      * Helper class for method reference lookup. The lookup logic is based
3579      * upon Resolve.findMethod; in certain cases, this helper class has a
3580      * corresponding unbound helper class (see UnboundMethodReferenceLookupHelper).
3581      * In such cases, non-static lookup results are thrown away.
3582      */
3583     class MethodReferenceLookupHelper extends ReferenceLookupHelper {
3584 
3585         /** The original method reference lookup site. */
3586         Type originalSite;
3587 
3588         MethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
3589                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
3590             super(referenceTree, name, types.skipTypeVars(site, true), argtypes, typeargtypes, maxPhase);
3591             this.originalSite = site;
3592         }
3593 
3594         @Override
3595         final Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
3596             return findMethod(env, site, name, argtypes, typeargtypes,
3597                     phase.isBoxingRequired(), phase.isVarargsRequired());
3598         }
3599 
3600         @Override
3601         ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
3602             if (TreeInfo.isStaticSelector(referenceTree.expr, names)) {
3603                 if (argtypes.nonEmpty() &&
3604                         (argtypes.head.hasTag(NONE) ||
3605                         types.isSubtypeUnchecked(inferenceContext.asUndetVar(argtypes.head.referenceProjectionOrSelf()), originalSite))) {
3606                     return new UnboundMethodReferenceLookupHelper(referenceTree, name,
3607                             originalSite, argtypes, typeargtypes, maxPhase);
3608                 } else {
3609                     return new ReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase) {
3610                         @Override
3611                         ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
3612                             return this;
3613                         }
3614 
3615                         @Override
3616                         Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
3617                             return methodNotFound;
3618                         }
3619 
3620                         @Override
3621                         ReferenceKind referenceKind(Symbol sym) {
3622                             Assert.error();
3623                             return null;
3624                         }
3625                     };
3626                 }
3627             } else {
3628                 return super.unboundLookup(inferenceContext);
3629             }
3630         }
3631 
3632         @Override
3633         ReferenceKind referenceKind(Symbol sym) {
3634             if (sym.isStatic()) {
3635                 return ReferenceKind.STATIC;
3636             } else {
3637                 Name selName = TreeInfo.name(referenceTree.getQualifierExpression());
3638                 return selName != null && selName == names._super ?
3639                         ReferenceKind.SUPER :
3640                         ReferenceKind.BOUND;
3641             }
3642         }
3643     }
3644 
3645     /**
3646      * Helper class for unbound method reference lookup. Essentially the same
3647      * as the basic method reference lookup helper; main difference is that static
3648      * lookup results are thrown away. If qualifier type is raw, an attempt to
3649      * infer a parameterized type is made using the first actual argument (that
3650      * would otherwise be ignored during the lookup).
3651      */
3652     class UnboundMethodReferenceLookupHelper extends MethodReferenceLookupHelper {
3653 
3654         UnboundMethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
3655                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
3656             super(referenceTree, name, site, argtypes.tail, typeargtypes, maxPhase);
3657             if (site.isRaw() && !argtypes.head.hasTag(NONE)) {
3658                 Type asSuperSite = types.asSuper(argtypes.head.referenceProjectionOrSelf(), site.tsym);
3659                 this.site = types.skipTypeVars(asSuperSite, true);
3660             }
3661         }
3662 
3663         @Override
3664         ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
3665             return this;
3666         }
3667 
3668         @Override
3669         ReferenceKind referenceKind(Symbol sym) {
3670             return ReferenceKind.UNBOUND;
3671         }
3672     }
3673 
3674     /**
3675      * Helper class for array constructor lookup; an array constructor lookup
3676      * is simulated by looking up a method that returns the array type specified
3677      * as qualifier, and that accepts a single int parameter (size of the array).
3678      */
3679     class ArrayConstructorReferenceLookupHelper extends ReferenceLookupHelper {
3680 
3681         ArrayConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
3682                 List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
3683             super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase);
3684         }
3685 
3686         @Override
3687         protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
3688             WriteableScope sc = WriteableScope.create(syms.arrayClass);
3689             MethodSymbol arrayConstr = new MethodSymbol(PUBLIC, name, null, site.tsym);
3690             arrayConstr.type = new MethodType(List.of(syms.intType), site, List.nil(), syms.methodClass);
3691             sc.enter(arrayConstr);
3692             return findMethodInScope(env, site, name, argtypes, typeargtypes, sc, methodNotFound, phase.isBoxingRequired(), phase.isVarargsRequired(), false);
3693         }
3694 
3695         @Override
3696         ReferenceKind referenceKind(Symbol sym) {
3697             return ReferenceKind.ARRAY_CTOR;
3698         }
3699     }
3700 
3701     /**
3702      * Helper class for constructor reference lookup. The lookup logic is based
3703      * upon either Resolve.findMethod or Resolve.findDiamond - depending on
3704      * whether the constructor reference needs diamond inference (this is the case
3705      * if the qualifier type is raw). A special erroneous symbol is returned
3706      * if the lookup returns the constructor of an inner class and there's no
3707      * enclosing instance in scope.
3708      */
3709     class ConstructorReferenceLookupHelper extends ReferenceLookupHelper {
3710 
3711         boolean needsInference;
3712 
3713         ConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
3714                 List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
3715             super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase);
3716             if (site.isRaw()) {
3717                 this.site = new ClassType(site.getEnclosingType(), site.tsym.type.getTypeArguments(), site.tsym, site.getMetadata(), site.getFlavor());
3718                 needsInference = true;
3719             }
3720         }
3721 
3722         @Override
3723         protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
3724             Symbol sym = needsInference ?
3725                 findDiamond(env, site, argtypes, typeargtypes, phase.isBoxingRequired(), phase.isVarargsRequired()) :
3726                 findMethod(env, site, name, argtypes, typeargtypes,
3727                         phase.isBoxingRequired(), phase.isVarargsRequired());
3728             return enclosingInstanceMissing(env, site) ? new BadConstructorReferenceError(sym) : sym;
3729         }
3730 
3731         @Override
3732         ReferenceKind referenceKind(Symbol sym) {
3733             return site.getEnclosingType().hasTag(NONE) ?
3734                     ReferenceKind.TOPLEVEL : ReferenceKind.IMPLICIT_INNER;
3735         }
3736     }
3737 
3738     /**
3739      * Main overload resolution routine. On each overload resolution step, a
3740      * lookup helper class is used to perform the method/constructor lookup;
3741      * at the end of the lookup, the helper is used to validate the results
3742      * (this last step might trigger overload resolution diagnostics).
3743      */
3744     Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, MethodCheck methodCheck, LookupHelper lookupHelper) {
3745         MethodResolutionContext resolveContext = new MethodResolutionContext();
3746         resolveContext.methodCheck = methodCheck;
3747         return lookupMethod(env, pos, location, resolveContext, lookupHelper);
3748     }
3749 
3750     Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location,
3751             MethodResolutionContext resolveContext, LookupHelper lookupHelper) {
3752         MethodResolutionContext prevResolutionContext = currentResolutionContext;
3753         try {
3754             Symbol bestSoFar = methodNotFound;
3755             currentResolutionContext = resolveContext;
3756             for (MethodResolutionPhase phase : methodResolutionSteps) {
3757                 if (lookupHelper.shouldStop(bestSoFar, phase))
3758                     break;
3759                 MethodResolutionPhase prevPhase = currentResolutionContext.step;
3760                 Symbol prevBest = bestSoFar;
3761                 currentResolutionContext.step = phase;
3762                 Symbol sym = lookupHelper.lookup(env, phase);
3763                 lookupHelper.debug(pos, sym);
3764                 bestSoFar = phase.mergeResults(bestSoFar, sym);
3765                 env.info.pendingResolutionPhase = (prevBest == bestSoFar) ? prevPhase : phase;
3766             }
3767             return lookupHelper.access(env, pos, location, bestSoFar);
3768         } finally {
3769             currentResolutionContext = prevResolutionContext;
3770         }
3771     }
3772 
3773     /**
3774      * Resolve `c.name' where name == this or name == super.
3775      * @param pos           The position to use for error reporting.
3776      * @param env           The environment current at the expression.
3777      * @param c             The qualifier.
3778      * @param name          The identifier's name.
3779      */
3780     Symbol resolveSelf(DiagnosticPosition pos,
3781                        Env<AttrContext> env,
3782                        TypeSymbol c,
3783                        Name name) {
3784         Env<AttrContext> env1 = env;
3785         boolean staticOnly = false;
3786         while (env1.outer != null) {
3787             if (isStatic(env1)) staticOnly = true;
3788             if (env1.enclClass.sym == c) {
3789                 Symbol sym = env1.info.scope.findFirst(name);
3790                 if (sym != null) {
3791                     if (staticOnly) sym = new StaticError(sym);
3792                     return accessBase(sym, pos, env.enclClass.sym.type,
3793                                   name, true);
3794                 }
3795             }
3796             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
3797             env1 = env1.outer;
3798         }
3799         if (c.isInterface() &&
3800             name == names._super && !isStatic(env) &&
3801             types.isDirectSuperInterface(c, env.enclClass.sym)) {
3802             //this might be a default super call if one of the superinterfaces is 'c'
3803             for (Type t : pruneInterfaces(env.enclClass.type)) {
3804                 if (t.tsym == c) {
3805                     env.info.defaultSuperCallSite = t;
3806                     return new VarSymbol(0, names._super,
3807                             types.asSuper(env.enclClass.type.referenceProjectionOrSelf(), c), env.enclClass.sym);
3808                 }
3809             }
3810             //find a direct super type that is a subtype of 'c'
3811             for (Type i : types.directSupertypes(env.enclClass.type)) {
3812                 if (i.tsym.isSubClass(c, types) && i.tsym != c) {
3813                     log.error(pos,
3814                               Errors.IllegalDefaultSuperCall(c,
3815                                                              Fragments.RedundantSupertype(c, i)));
3816                     return syms.errSymbol;
3817                 }
3818             }
3819             Assert.error();
3820         }
3821         log.error(pos, Errors.NotEnclClass(c));
3822         return syms.errSymbol;
3823     }
3824     //where
3825     private List<Type> pruneInterfaces(Type t) {
3826         ListBuffer<Type> result = new ListBuffer<>();
3827         for (Type t1 : types.interfaces(t)) {
3828             boolean shouldAdd = true;
3829             for (Type t2 : types.directSupertypes(t)) {
3830                 if (t1 != t2 && !t2.hasTag(ERROR) && types.isSubtypeNoCapture(t2, t1)) {
3831                     shouldAdd = false;
3832                 }
3833             }
3834             if (shouldAdd) {
3835                 result.append(t1);
3836             }
3837         }
3838         return result.toList();
3839     }
3840 
3841 
3842     /**
3843      * Resolve `c.this' for an enclosing class c that contains the
3844      * named member.
3845      * @param pos           The position to use for error reporting.
3846      * @param env           The environment current at the expression.
3847      * @param member        The member that must be contained in the result.
3848      */
3849     Symbol resolveSelfContaining(DiagnosticPosition pos,
3850                                  Env<AttrContext> env,
3851                                  Symbol member,
3852                                  boolean isSuperCall) {
3853         Symbol sym = resolveSelfContainingInternal(env, member, isSuperCall);
3854         if (sym == null) {
3855             log.error(pos, Errors.EnclClassRequired(member));
3856             return syms.errSymbol;
3857         } else {
3858             return accessBase(sym, pos, env.enclClass.sym.type, sym.name, true);
3859         }
3860     }
3861 
3862     boolean enclosingInstanceMissing(Env<AttrContext> env, Type type) {
3863         if (type.hasTag(CLASS) && type.getEnclosingType().hasTag(CLASS)) {
3864             Symbol encl = resolveSelfContainingInternal(env, type.tsym, false);
3865             return encl == null || encl.kind.isResolutionError();
3866         }
3867         return false;
3868     }
3869 
3870     private Symbol resolveSelfContainingInternal(Env<AttrContext> env,
3871                                  Symbol member,
3872                                  boolean isSuperCall) {
3873         Name name = names._this;
3874         Env<AttrContext> env1 = isSuperCall ? env.outer : env;
3875         boolean staticOnly = false;
3876         if (env1 != null) {
3877             while (env1 != null && env1.outer != null) {
3878                 if (isStatic(env1)) staticOnly = true;
3879                 if (env1.enclClass.sym.isSubClass(member.owner.enclClass(), types)) {
3880                     Symbol sym = env1.info.scope.findFirst(name);
3881                     if (sym != null) {
3882                         if (staticOnly) sym = new StaticError(sym);
3883                         return sym;
3884                     }
3885                 }
3886                 if ((env1.enclClass.sym.flags() & STATIC) != 0)
3887                     staticOnly = true;
3888                 env1 = env1.outer;
3889             }
3890         }
3891         return null;
3892     }
3893 
3894     /**
3895      * Resolve an appropriate implicit this instance for t's container.
3896      * JLS 8.8.5.1 and 15.9.2
3897      */
3898     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
3899         return resolveImplicitThis(pos, env, t, false);
3900     }
3901 
3902     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t, boolean isSuperCall) {
3903         Type thisType = (t.tsym.owner.kind.matches(KindSelector.VAL_MTH)
3904                          ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
3905                          : resolveSelfContaining(pos, env, t.tsym, isSuperCall)).type;
3906         if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym) {
3907             log.error(pos, Errors.CantRefBeforeCtorCalled("this"));
3908         }
3909         return thisType;
3910     }
3911 
3912 /* ***************************************************************************
3913  *  ResolveError classes, indicating error situations when accessing symbols
3914  ****************************************************************************/
3915 
3916     //used by TransTypes when checking target type of synthetic cast
3917     public void logAccessErrorInternal(Env<AttrContext> env, JCTree tree, Type type) {
3918         AccessError error = new AccessError(env, env.enclClass.type, type.tsym);
3919         logResolveError(error, tree.pos(), env.enclClass.sym, env.enclClass.type, null, null, null);
3920     }
3921     //where
3922     private void logResolveError(ResolveError error,
3923             DiagnosticPosition pos,
3924             Symbol location,
3925             Type site,
3926             Name name,
3927             List<Type> argtypes,
3928             List<Type> typeargtypes) {
3929         JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
3930                 pos, location, site, name, argtypes, typeargtypes);
3931         if (d != null) {
3932             d.setFlag(DiagnosticFlag.RESOLVE_ERROR);
3933             log.report(d);
3934         }
3935     }
3936 
3937     private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
3938 
3939     public Object methodArguments(List<Type> argtypes) {
3940         if (argtypes == null || argtypes.isEmpty()) {
3941             return noArgs;
3942         } else {
3943             ListBuffer<Object> diagArgs = new ListBuffer<>();
3944             for (Type t : argtypes) {
3945                 if (t.hasTag(DEFERRED)) {
3946                     diagArgs.append(((DeferredAttr.DeferredType)t).tree);
3947                 } else {
3948                     diagArgs.append(t);
3949                 }
3950             }
3951             return diagArgs;
3952         }
3953     }
3954 
3955     /**
3956      * Root class for resolution errors. Subclass of ResolveError
3957      * represent a different kinds of resolution error - as such they must
3958      * specify how they map into concrete compiler diagnostics.
3959      */
3960     abstract class ResolveError extends Symbol {
3961 
3962         /** The name of the kind of error, for debugging only. */
3963         final String debugName;
3964 
3965         ResolveError(Kind kind, String debugName) {
3966             super(kind, 0, null, null, null);
3967             this.debugName = debugName;
3968         }
3969 
3970         @Override @DefinedBy(Api.LANGUAGE_MODEL)
3971         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
3972             throw new AssertionError();
3973         }
3974 
3975         @Override
3976         public String toString() {
3977             return debugName;
3978         }
3979 
3980         @Override
3981         public boolean exists() {
3982             return false;
3983         }
3984 
3985         @Override
3986         public boolean isStatic() {
3987             return false;
3988         }
3989 
3990         /**
3991          * Create an external representation for this erroneous symbol to be
3992          * used during attribution - by default this returns the symbol of a
3993          * brand new error type which stores the original type found
3994          * during resolution.
3995          *
3996          * @param name     the name used during resolution
3997          * @param location the location from which the symbol is accessed
3998          */
3999         protected Symbol access(Name name, TypeSymbol location) {
4000             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
4001         }
4002 
4003         /**
4004          * Create a diagnostic representing this resolution error.
4005          *
4006          * @param dkind     The kind of the diagnostic to be created (e.g error).
4007          * @param pos       The position to be used for error reporting.
4008          * @param site      The original type from where the selection took place.
4009          * @param name      The name of the symbol to be resolved.
4010          * @param argtypes  The invocation's value arguments,
4011          *                  if we looked for a method.
4012          * @param typeargtypes  The invocation's type arguments,
4013          *                      if we looked for a method.
4014          */
4015         abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
4016                 DiagnosticPosition pos,
4017                 Symbol location,
4018                 Type site,
4019                 Name name,
4020                 List<Type> argtypes,
4021                 List<Type> typeargtypes);
4022     }
4023 
4024     /**
4025      * This class is the root class of all resolution errors caused by
4026      * an invalid symbol being found during resolution.
4027      */
4028     abstract class InvalidSymbolError extends ResolveError {
4029 
4030         /** The invalid symbol found during resolution */
4031         Symbol sym;
4032 
4033         InvalidSymbolError(Kind kind, Symbol sym, String debugName) {
4034             super(kind, debugName);
4035             this.sym = sym;
4036         }
4037 
4038         @Override
4039         public boolean exists() {
4040             return true;
4041         }
4042 
4043         @Override
4044         public String toString() {
4045              return super.toString() + " wrongSym=" + sym;
4046         }
4047 
4048         @Override
4049         public Symbol access(Name name, TypeSymbol location) {
4050             if (!sym.kind.isResolutionError() && sym.kind.matches(KindSelector.TYP))
4051                 return types.createErrorType(name, location, sym.type).tsym;
4052             else
4053                 return sym;
4054         }
4055     }
4056 
4057     class BadRestrictedTypeError extends ResolveError {
4058         private final Name typeName;
4059         BadRestrictedTypeError(Name typeName) {
4060             super(Kind.BAD_RESTRICTED_TYPE, "bad var use");
4061             this.typeName = typeName;
4062         }
4063 
4064         @Override
4065         JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
4066             return diags.create(dkind, log.currentSource(), pos, "illegal.ref.to.restricted.type", typeName);
4067         }
4068     }
4069 
4070     /**
4071      * InvalidSymbolError error class indicating that a symbol matching a
4072      * given name does not exists in a given site.
4073      */
4074     class SymbolNotFoundError extends ResolveError {
4075 
4076         SymbolNotFoundError(Kind kind) {
4077             this(kind, "symbol not found error");
4078         }
4079 
4080         SymbolNotFoundError(Kind kind, String debugName) {
4081             super(kind, debugName);
4082         }
4083 
4084         @Override
4085         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
4086                 DiagnosticPosition pos,
4087                 Symbol location,
4088                 Type site,
4089                 Name name,
4090                 List<Type> argtypes,
4091                 List<Type> typeargtypes) {
4092             argtypes = argtypes == null ? List.nil() : argtypes;
4093             typeargtypes = typeargtypes == null ? List.nil() : typeargtypes;
4094             if (name == names.error)
4095                 return null;
4096 
4097             boolean hasLocation = false;
4098             if (location == null) {
4099                 location = site.tsym;
4100             }
4101             if (!location.name.isEmpty()) {
4102                 if (location.kind == PCK && !site.tsym.exists() && location.name != names.java) {
4103                     return diags.create(dkind, log.currentSource(), pos,
4104                         "doesnt.exist", location);
4105                 }
4106                 hasLocation = !location.name.equals(names._this) &&
4107                         !location.name.equals(names._super);
4108             }
4109             boolean isConstructor = name == names.init;
4110             KindName kindname = isConstructor ? KindName.CONSTRUCTOR : kind.absentKind();
4111             Name idname = isConstructor ? site.tsym.name : name;
4112             String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation);
4113             if (hasLocation) {
4114                 return diags.create(dkind, log.currentSource(), pos,
4115                         errKey, kindname, idname, //symbol kindname, name
4116                         typeargtypes, args(argtypes), //type parameters and arguments (if any)
4117                         getLocationDiag(location, site)); //location kindname, type
4118             }
4119             else {
4120                 return diags.create(dkind, log.currentSource(), pos,
4121                         errKey, kindname, idname, //symbol kindname, name
4122                         typeargtypes, args(argtypes)); //type parameters and arguments (if any)
4123             }
4124         }
4125         //where
4126         private Object args(List<Type> args) {
4127             return args.isEmpty() ? args : methodArguments(args);
4128         }
4129 
4130         private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) {
4131             String key = "cant.resolve";
4132             String suffix = hasLocation ? ".location" : "";
4133             switch (kindname) {
4134                 case METHOD:
4135                 case CONSTRUCTOR: {
4136                     suffix += ".args";
4137                     suffix += hasTypeArgs ? ".params" : "";
4138                 }
4139             }
4140             return key + suffix;
4141         }
4142         private JCDiagnostic getLocationDiag(Symbol location, Type site) {
4143             if (location.kind == VAR) {
4144                 return diags.fragment(Fragments.Location1(kindName(location),
4145                                                           location,
4146                                                           location.type));
4147             } else {
4148                 return diags.fragment(Fragments.Location(typeKindName(site),
4149                                       site,
4150                                       null));
4151             }
4152         }
4153     }
4154 
4155     /**
4156      * InvalidSymbolError error class indicating that a given symbol
4157      * (either a method, a constructor or an operand) is not applicable
4158      * given an actual arguments/type argument list.
4159      */
4160     class InapplicableSymbolError extends ResolveError {
4161 
4162         protected MethodResolutionContext resolveContext;
4163 
4164         InapplicableSymbolError(MethodResolutionContext context) {
4165             this(WRONG_MTH, "inapplicable symbol error", context);
4166         }
4167 
4168         protected InapplicableSymbolError(Kind kind, String debugName, MethodResolutionContext context) {
4169             super(kind, debugName);
4170             this.resolveContext = context;
4171         }
4172 
4173         @Override
4174         public String toString() {
4175             return super.toString();
4176         }
4177 
4178         @Override
4179         public boolean exists() {
4180             return true;
4181         }
4182 
4183         @Override
4184         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
4185                 DiagnosticPosition pos,
4186                 Symbol location,
4187                 Type site,
4188                 Name name,
4189                 List<Type> argtypes,
4190                 List<Type> typeargtypes) {
4191             if (name == names.error)
4192                 return null;
4193 
4194             Pair<Symbol, JCDiagnostic> c = errCandidate();
4195             if (compactMethodDiags) {
4196                 JCDiagnostic simpleDiag =
4197                     MethodResolutionDiagHelper.rewrite(diags, pos, log.currentSource(), dkind, c.snd);
4198                 if (simpleDiag != null) {
4199                     return simpleDiag;
4200                 }
4201             }
4202             Symbol ws = c.fst.asMemberOf(site, types);
4203             return diags.create(dkind, log.currentSource(), pos,
4204                       "cant.apply.symbol",
4205                       kindName(ws),
4206                       ws.name == names.init ? ws.owner.name : ws.name,
4207                       methodArguments(ws.type.getParameterTypes()),
4208                       methodArguments(argtypes),
4209                       kindName(ws.owner),
4210                       ws.owner.type,
4211                       c.snd);
4212         }
4213 
4214         @Override
4215         public Symbol access(Name name, TypeSymbol location) {
4216             Pair<Symbol, JCDiagnostic> cand = errCandidate();
4217             TypeSymbol errSymbol = types.createErrorType(name, location, cand != null ? cand.fst.type : syms.errSymbol.type).tsym;
4218             if (cand != null) {
4219                 attrRecover.wrongMethodSymbolCandidate(errSymbol, cand.fst, cand.snd);
4220             }
4221             return errSymbol;
4222         }
4223 
4224         protected Pair<Symbol, JCDiagnostic> errCandidate() {
4225             Candidate bestSoFar = null;
4226             for (Candidate c : resolveContext.candidates) {
4227                 if (c.isApplicable()) continue;
4228                 bestSoFar = c;
4229             }
4230             Assert.checkNonNull(bestSoFar);
4231             return new Pair<>(bestSoFar.sym, bestSoFar.details);
4232         }
4233     }
4234 
4235     /**
4236      * ResolveError error class indicating that a symbol (either methods, constructors or operand)
4237      * is not applicable given an actual arguments/type argument list.
4238      */
4239     class InapplicableSymbolsError extends InapplicableSymbolError {
4240 
4241         InapplicableSymbolsError(MethodResolutionContext context) {
4242             super(WRONG_MTHS, "inapplicable symbols", context);
4243         }
4244 
4245         @Override
4246         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
4247                 DiagnosticPosition pos,
4248                 Symbol location,
4249                 Type site,
4250                 Name name,
4251                 List<Type> argtypes,
4252                 List<Type> typeargtypes) {
4253             Map<Symbol, JCDiagnostic> candidatesMap = mapCandidates();
4254             Map<Symbol, JCDiagnostic> filteredCandidates = compactMethodDiags ?
4255                     filterCandidates(candidatesMap) :
4256                     mapCandidates();
4257             if (filteredCandidates.isEmpty()) {
4258                 filteredCandidates = candidatesMap;
4259             }
4260             boolean truncatedDiag = candidatesMap.size() != filteredCandidates.size();
4261             if (filteredCandidates.size() > 1) {
4262                 JCDiagnostic err = diags.create(dkind,
4263                         null,
4264                         truncatedDiag ?
4265                             EnumSet.of(DiagnosticFlag.COMPRESSED) :
4266                             EnumSet.noneOf(DiagnosticFlag.class),
4267                         log.currentSource(),
4268                         pos,
4269                         "cant.apply.symbols",
4270                         name == names.init ? KindName.CONSTRUCTOR : kind.absentKind(),
4271                         name == names.init ? site.tsym.name : name,
4272                         methodArguments(argtypes));
4273                 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(filteredCandidates, site));
4274             } else if (filteredCandidates.size() == 1) {
4275                 Map.Entry<Symbol, JCDiagnostic> _e =
4276                                 filteredCandidates.entrySet().iterator().next();
4277                 final Pair<Symbol, JCDiagnostic> p = new Pair<>(_e.getKey(), _e.getValue());
4278                 JCDiagnostic d = new InapplicableSymbolError(resolveContext) {
4279                     @Override
4280                     protected Pair<Symbol, JCDiagnostic> errCandidate() {
4281                         return p;
4282                     }
4283                 }.getDiagnostic(dkind, pos,
4284                     location, site, name, argtypes, typeargtypes);
4285                 if (truncatedDiag) {
4286                     d.setFlag(DiagnosticFlag.COMPRESSED);
4287                 }
4288                 return d;
4289             } else {
4290                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
4291                     location, site, name, argtypes, typeargtypes);
4292             }
4293         }
4294         //where
4295             private Map<Symbol, JCDiagnostic> mapCandidates() {
4296                 MostSpecificMap candidates = new MostSpecificMap();
4297                 for (Candidate c : resolveContext.candidates) {
4298                     if (c.isApplicable()) continue;
4299                     candidates.put(c);
4300                 }
4301                 return candidates;
4302             }
4303 
4304             @SuppressWarnings("serial")
4305             private class MostSpecificMap extends LinkedHashMap<Symbol, JCDiagnostic> {
4306                 private void put(Candidate c) {
4307                     ListBuffer<Symbol> overridden = new ListBuffer<>();
4308                     for (Symbol s : keySet()) {
4309                         if (s == c.sym) {
4310                             continue;
4311                         }
4312                         if (c.sym.overrides(s, (TypeSymbol)s.owner, types, false)) {
4313                             overridden.add(s);
4314                         } else if (s.overrides(c.sym, (TypeSymbol)c.sym.owner, types, false)) {
4315                             return;
4316                         }
4317                     }
4318                     for (Symbol s : overridden) {
4319                         remove(s);
4320                     }
4321                     put(c.sym, c.details);
4322                 }
4323             }
4324 
4325             Map<Symbol, JCDiagnostic> filterCandidates(Map<Symbol, JCDiagnostic> candidatesMap) {
4326                 Map<Symbol, JCDiagnostic> candidates = new LinkedHashMap<>();
4327                 for (Map.Entry<Symbol, JCDiagnostic> _entry : candidatesMap.entrySet()) {
4328                     JCDiagnostic d = _entry.getValue();
4329                     if (!new Template(MethodCheckDiag.ARITY_MISMATCH.regex()).matches(d)) {
4330                         candidates.put(_entry.getKey(), d);
4331                     }
4332                 }
4333                 return candidates;
4334             }
4335 
4336             private List<JCDiagnostic> candidateDetails(Map<Symbol, JCDiagnostic> candidatesMap, Type site) {
4337                 List<JCDiagnostic> details = List.nil();
4338                 for (Map.Entry<Symbol, JCDiagnostic> _entry : candidatesMap.entrySet()) {
4339                     Symbol sym = _entry.getKey();
4340                     JCDiagnostic detailDiag =
4341                             diags.fragment(Fragments.InapplicableMethod(Kinds.kindName(sym),
4342                                                                         sym.location(site, types),
4343                                                                         sym.asMemberOf(site, types),
4344                                                                         _entry.getValue()));
4345                     details = details.prepend(detailDiag);
4346                 }
4347                 //typically members are visited in reverse order (see Scope)
4348                 //so we need to reverse the candidate list so that candidates
4349                 //conform to source order
4350                 return details;
4351             }
4352 
4353         @Override
4354         protected Pair<Symbol, JCDiagnostic> errCandidate() {
4355             Map<Symbol, JCDiagnostic> candidatesMap = mapCandidates();
4356             Map<Symbol, JCDiagnostic> filteredCandidates = filterCandidates(candidatesMap);
4357             if (filteredCandidates.size() == 1) {
4358                 return Pair.of(filteredCandidates.keySet().iterator().next(),
4359                                filteredCandidates.values().iterator().next());
4360             }
4361             return null;
4362         }
4363     }
4364 
4365     /**
4366      * DiamondError error class indicating that a constructor symbol is not applicable
4367      * given an actual arguments/type argument list using diamond inference.
4368      */
4369     class DiamondError extends InapplicableSymbolError {
4370 
4371         Symbol sym;
4372 
4373         public DiamondError(Symbol sym, MethodResolutionContext context) {
4374             super(sym.kind, "diamondError", context);
4375             this.sym = sym;
4376         }
4377 
4378         JCDiagnostic getDetails() {
4379             return (sym.kind == WRONG_MTH) ?
4380                     ((InapplicableSymbolError)sym.baseSymbol()).errCandidate().snd :
4381                     null;
4382         }
4383 
4384         @Override
4385         JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos,
4386                 Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
4387             JCDiagnostic details = getDetails();
4388             if (details != null && compactMethodDiags) {
4389                 JCDiagnostic simpleDiag =
4390                         MethodResolutionDiagHelper.rewrite(diags, pos, log.currentSource(), dkind, details);
4391                 if (simpleDiag != null) {
4392                     return simpleDiag;
4393                 }
4394             }
4395             String key = details == null ?
4396                 "cant.apply.diamond" :
4397                 "cant.apply.diamond.1";
4398             return diags.create(dkind, log.currentSource(), pos, key,
4399                     Fragments.Diamond(site.tsym), details);
4400         }
4401     }
4402 
4403     /**
4404      * An InvalidSymbolError error class indicating that a symbol is not
4405      * accessible from a given site
4406      */
4407     class AccessError extends InvalidSymbolError {
4408 
4409         private Env<AttrContext> env;
4410         private Type site;
4411 
4412         AccessError(Env<AttrContext> env, Type site, Symbol sym) {
4413             super(HIDDEN, sym, "access error");
4414             this.env = env;
4415             this.site = site;
4416         }
4417 
4418         @Override
4419         public boolean exists() {
4420             return false;
4421         }
4422 
4423         @Override
4424         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
4425                 DiagnosticPosition pos,
4426                 Symbol location,
4427                 Type site,
4428                 Name name,
4429                 List<Type> argtypes,
4430                 List<Type> typeargtypes) {
4431             if (sym.name == names.init && sym.owner != site.tsym) {
4432                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
4433                         pos, location, site, name, argtypes, typeargtypes);
4434             }
4435             else if ((sym.flags() & PUBLIC) != 0
4436                 || (env != null && this.site != null
4437                     && !isAccessible(env, this.site))) {
4438                 if (sym.owner.kind == PCK) {
4439                     return diags.create(dkind, log.currentSource(),
4440                             pos, "not.def.access.package.cant.access",
4441                         sym, sym.location(), inaccessiblePackageReason(env, sym.packge()));
4442                 } else if (   sym.packge() != syms.rootPackage
4443                            && !symbolPackageVisible(env, sym)) {
4444                     return diags.create(dkind, log.currentSource(),
4445                             pos, "not.def.access.class.intf.cant.access.reason",
4446                             sym, sym.location(), sym.location().packge(),
4447                             inaccessiblePackageReason(env, sym.packge()));
4448                 } else {
4449                     return diags.create(dkind, log.currentSource(),
4450                             pos, "not.def.access.class.intf.cant.access",
4451                         sym, sym.location());
4452                 }
4453             }
4454             else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) {
4455                 return diags.create(dkind, log.currentSource(),
4456                         pos, "report.access", sym,
4457                         asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
4458                         sym.location());
4459             }
4460             else {
4461                 return diags.create(dkind, log.currentSource(),
4462                         pos, "not.def.public.cant.access", sym, sym.location());
4463             }
4464         }
4465 
4466         private String toString(Type type) {
4467             StringBuilder sb = new StringBuilder();
4468             sb.append(type);
4469             if (type != null) {
4470                 sb.append("[tsym:").append(type.tsym);
4471                 if (type.tsym != null)
4472                     sb.append("packge:").append(type.tsym.packge());
4473                 sb.append("]");
4474             }
4475             return sb.toString();
4476         }
4477     }
4478 
4479     class InvisibleSymbolError extends InvalidSymbolError {
4480 
4481         private final Env<AttrContext> env;
4482         private final boolean suppressError;
4483 
4484         InvisibleSymbolError(Env<AttrContext> env, boolean suppressError, Symbol sym) {
4485             super(HIDDEN, sym, "invisible class error");
4486             this.env = env;
4487             this.suppressError = suppressError;
4488             this.name = sym.name;
4489         }
4490 
4491         @Override
4492         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
4493                 DiagnosticPosition pos,
4494                 Symbol location,
4495                 Type site,
4496                 Name name,
4497                 List<Type> argtypes,
4498                 List<Type> typeargtypes) {
4499             if (suppressError)
4500                 return null;
4501 
4502             if (sym.kind == PCK) {
4503                 JCDiagnostic details = inaccessiblePackageReason(env, sym.packge());
4504                 return diags.create(dkind, log.currentSource(),
4505                         pos, "package.not.visible", sym, details);
4506             }
4507 
4508             JCDiagnostic details = inaccessiblePackageReason(env, sym.packge());
4509 
4510             if (pos.getTree() != null) {
4511                 Symbol o = sym;
4512                 JCTree tree = pos.getTree();
4513 
4514                 while (o.kind != PCK && tree.hasTag(SELECT)) {
4515                     o = o.owner;
4516                     tree = ((JCFieldAccess) tree).selected;
4517                 }
4518 
4519                 if (o.kind == PCK) {
4520                     pos = tree.pos();
4521 
4522                     return diags.create(dkind, log.currentSource(),
4523                             pos, "package.not.visible", o, details);
4524                 }
4525             }
4526 
4527             return diags.create(dkind, log.currentSource(),
4528                     pos, "not.def.access.package.cant.access", sym, sym.packge(), details);
4529         }
4530     }
4531 
4532     JCDiagnostic inaccessiblePackageReason(Env<AttrContext> env, PackageSymbol sym) {
4533         //no dependency:
4534         if (!env.toplevel.modle.readModules.contains(sym.modle)) {
4535             //does not read:
4536             if (sym.modle != syms.unnamedModule) {
4537                 if (env.toplevel.modle != syms.unnamedModule) {
4538                     return diags.fragment(Fragments.NotDefAccessDoesNotRead(env.toplevel.modle,
4539                                                                             sym,
4540                                                                             sym.modle));
4541                 } else {
4542                     return diags.fragment(Fragments.NotDefAccessDoesNotReadFromUnnamed(sym,
4543                                                                                        sym.modle));
4544                 }
4545             } else {
4546                 return diags.fragment(Fragments.NotDefAccessDoesNotReadUnnamed(sym,
4547                                                                                env.toplevel.modle));
4548             }
4549         } else {
4550             if (sym.packge().modle.exports.stream().anyMatch(e -> e.packge == sym)) {
4551                 //not exported to this module:
4552                 if (env.toplevel.modle != syms.unnamedModule) {
4553                     return diags.fragment(Fragments.NotDefAccessNotExportedToModule(sym,
4554                                                                                     sym.modle,
4555                                                                                     env.toplevel.modle));
4556                 } else {
4557                     return diags.fragment(Fragments.NotDefAccessNotExportedToModuleFromUnnamed(sym,
4558                                                                                                sym.modle));
4559                 }
4560             } else {
4561                 //not exported:
4562                 if (env.toplevel.modle != syms.unnamedModule) {
4563                     return diags.fragment(Fragments.NotDefAccessNotExported(sym,
4564                                                                             sym.modle));
4565                 } else {
4566                     return diags.fragment(Fragments.NotDefAccessNotExportedFromUnnamed(sym,
4567                                                                                        sym.modle));
4568                 }
4569             }
4570         }
4571     }
4572 
4573     /**
4574      * InvalidSymbolError error class indicating that an instance member
4575      * has erroneously been accessed from a static context.
4576      */
4577     class StaticError extends InvalidSymbolError {
4578 
4579         StaticError(Symbol sym) {
4580             super(STATICERR, sym, "static error");
4581         }
4582 
4583         @Override
4584         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
4585                 DiagnosticPosition pos,
4586                 Symbol location,
4587                 Type site,
4588                 Name name,
4589                 List<Type> argtypes,
4590                 List<Type> typeargtypes) {
4591             Symbol errSym = ((sym.kind == TYP && sym.type.hasTag(CLASS))
4592                 ? types.erasure(sym.type).tsym
4593                 : sym);
4594             return diags.create(dkind, log.currentSource(), pos,
4595                     "non-static.cant.be.ref", kindName(sym), errSym);
4596         }
4597     }
4598 
4599     /**
4600      * InvalidSymbolError error class indicating that a pair of symbols
4601      * (either methods, constructors or operands) are ambiguous
4602      * given an actual arguments/type argument list.
4603      */
4604     class AmbiguityError extends ResolveError {
4605 
4606         /** The other maximally specific symbol */
4607         List<Symbol> ambiguousSyms = List.nil();
4608 
4609         @Override
4610         public boolean exists() {
4611             return true;
4612         }
4613 
4614         AmbiguityError(Symbol sym1, Symbol sym2) {
4615             super(AMBIGUOUS, "ambiguity error");
4616             ambiguousSyms = flatten(sym2).appendList(flatten(sym1));
4617         }
4618 
4619         private List<Symbol> flatten(Symbol sym) {
4620             if (sym.kind == AMBIGUOUS) {
4621                 return ((AmbiguityError)sym.baseSymbol()).ambiguousSyms;
4622             } else {
4623                 return List.of(sym);
4624             }
4625         }
4626 
4627         AmbiguityError addAmbiguousSymbol(Symbol s) {
4628             ambiguousSyms = ambiguousSyms.prepend(s);
4629             return this;
4630         }
4631 
4632         @Override
4633         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
4634                 DiagnosticPosition pos,
4635                 Symbol location,
4636                 Type site,
4637                 Name name,
4638                 List<Type> argtypes,
4639                 List<Type> typeargtypes) {
4640             List<Symbol> diagSyms = ambiguousSyms.reverse();
4641             Symbol s1 = diagSyms.head;
4642             Symbol s2 = diagSyms.tail.head;
4643             Name sname = s1.name;
4644             if (sname == names.init) sname = s1.owner.name;
4645             return diags.create(dkind, log.currentSource(),
4646                     pos, "ref.ambiguous", sname,
4647                     kindName(s1),
4648                     s1,
4649                     s1.location(site, types),
4650                     kindName(s2),
4651                     s2,
4652                     s2.location(site, types));
4653         }
4654 
4655         /**
4656          * If multiple applicable methods are found during overload and none of them
4657          * is more specific than the others, attempt to merge their signatures.
4658          */
4659         Symbol mergeAbstracts(Type site) {
4660             List<Symbol> ambiguousInOrder = ambiguousSyms.reverse();
4661             return types.mergeAbstracts(ambiguousInOrder, site, true).orElse(this);
4662         }
4663 
4664         @Override
4665         protected Symbol access(Name name, TypeSymbol location) {
4666             Symbol firstAmbiguity = ambiguousSyms.last();
4667             return firstAmbiguity.kind == TYP ?
4668                     types.createErrorType(name, location, firstAmbiguity.type).tsym :
4669                     firstAmbiguity;
4670         }
4671     }
4672 
4673     class BadVarargsMethod extends ResolveError {
4674 
4675         ResolveError delegatedError;
4676 
4677         BadVarargsMethod(ResolveError delegatedError) {
4678             super(delegatedError.kind, "badVarargs");
4679             this.delegatedError = delegatedError;
4680         }
4681 
4682         @Override
4683         public Symbol baseSymbol() {
4684             return delegatedError.baseSymbol();
4685         }
4686 
4687         @Override
4688         protected Symbol access(Name name, TypeSymbol location) {
4689             return delegatedError.access(name, location);
4690         }
4691 
4692         @Override
4693         public boolean exists() {
4694             return true;
4695         }
4696 
4697         @Override
4698         JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
4699             return delegatedError.getDiagnostic(dkind, pos, location, site, name, argtypes, typeargtypes);
4700         }
4701     }
4702 
4703     /**
4704      * BadMethodReferenceError error class indicating that a method reference symbol has been found,
4705      * but with the wrong staticness.
4706      */
4707     class BadMethodReferenceError extends StaticError {
4708 
4709         boolean unboundLookup;
4710 
4711         public BadMethodReferenceError(Symbol sym, boolean unboundLookup) {
4712             super(sym);
4713             this.unboundLookup = unboundLookup;
4714         }
4715 
4716         @Override
4717         JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
4718             final String key;
4719             if (!unboundLookup) {
4720                 key = "bad.static.method.in.bound.lookup";
4721             } else if (sym.isStatic()) {
4722                 key = "bad.static.method.in.unbound.lookup";
4723             } else {
4724                 key = "bad.instance.method.in.unbound.lookup";
4725             }
4726             return sym.kind.isResolutionError() ?
4727                     ((ResolveError)sym).getDiagnostic(dkind, pos, location, site, name, argtypes, typeargtypes) :
4728                     diags.create(dkind, log.currentSource(), pos, key, Kinds.kindName(sym), sym);
4729         }
4730     }
4731 
4732     /**
4733      * BadConstructorReferenceError error class indicating that a constructor reference symbol has been found,
4734      * but pointing to a class for which an enclosing instance is not available.
4735      */
4736     class BadConstructorReferenceError extends InvalidSymbolError {
4737 
4738         public BadConstructorReferenceError(Symbol sym) {
4739             super(MISSING_ENCL, sym, "BadConstructorReferenceError");
4740         }
4741 
4742         @Override
4743         JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
4744            return diags.create(dkind, log.currentSource(), pos,
4745                 "cant.access.inner.cls.constr", site.tsym.name, argtypes, site.getEnclosingType());
4746         }
4747     }
4748 
4749     class BadClassFileError extends InvalidSymbolError {
4750 
4751         private final CompletionFailure ex;
4752 
4753         public BadClassFileError(CompletionFailure ex) {
4754             super(HIDDEN, ex.sym, "BadClassFileError");
4755             this.name = sym.name;
4756             this.ex = ex;
4757         }
4758 
4759         @Override
4760         JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
4761             JCDiagnostic d = diags.create(dkind, log.currentSource(), pos,
4762                 "cant.access", ex.sym, ex.getDetailValue());
4763 
4764             d.setFlag(DiagnosticFlag.NON_DEFERRABLE);
4765             return d;
4766         }
4767 
4768     }
4769 
4770     /**
4771      * Helper class for method resolution diagnostic simplification.
4772      * Certain resolution diagnostic are rewritten as simpler diagnostic
4773      * where the enclosing resolution diagnostic (i.e. 'inapplicable method')
4774      * is stripped away, as it doesn't carry additional info. The logic
4775      * for matching a given diagnostic is given in terms of a template
4776      * hierarchy: a diagnostic template can be specified programmatically,
4777      * so that only certain diagnostics are matched. Each templete is then
4778      * associated with a rewriter object that carries out the task of rewtiting
4779      * the diagnostic to a simpler one.
4780      */
4781     static class MethodResolutionDiagHelper {
4782 
4783         /**
4784          * A diagnostic rewriter transforms a method resolution diagnostic
4785          * into a simpler one
4786          */
4787         interface DiagnosticRewriter {
4788             JCDiagnostic rewriteDiagnostic(JCDiagnostic.Factory diags,
4789                     DiagnosticPosition preferredPos, DiagnosticSource preferredSource,
4790                     DiagnosticType preferredKind, JCDiagnostic d);
4791         }
4792 
4793         /**
4794          * A diagnostic template is made up of two ingredients: (i) a regular
4795          * expression for matching a diagnostic key and (ii) a list of sub-templates
4796          * for matching diagnostic arguments.
4797          */
4798         static class Template {
4799 
4800             /** regex used to match diag key */
4801             String regex;
4802 
4803             /** templates used to match diagnostic args */
4804             Template[] subTemplates;
4805 
4806             Template(String key, Template... subTemplates) {
4807                 this.regex = key;
4808                 this.subTemplates = subTemplates;
4809             }
4810 
4811             /**
4812              * Returns true if the regex matches the diagnostic key and if
4813              * all diagnostic arguments are matches by corresponding sub-templates.
4814              */
4815             boolean matches(Object o) {
4816                 JCDiagnostic d = (JCDiagnostic)o;
4817                 Object[] args = d.getArgs();
4818                 if (!d.getCode().matches(regex) ||
4819                         subTemplates.length != d.getArgs().length) {
4820                     return false;
4821                 }
4822                 for (int i = 0; i < args.length ; i++) {
4823                     if (!subTemplates[i].matches(args[i])) {
4824                         return false;
4825                     }
4826                 }
4827                 return true;
4828             }
4829         }
4830 
4831         /**
4832          * Common rewriter for all argument mismatch simplifications.
4833          */
4834         static class ArgMismatchRewriter implements DiagnosticRewriter {
4835 
4836             /** the index of the subdiagnostic to be used as primary. */
4837             int causeIndex;
4838 
4839             public ArgMismatchRewriter(int causeIndex) {
4840                 this.causeIndex = causeIndex;
4841             }
4842 
4843             @Override
4844             public JCDiagnostic rewriteDiagnostic(JCDiagnostic.Factory diags,
4845                     DiagnosticPosition preferredPos, DiagnosticSource preferredSource,
4846                     DiagnosticType preferredKind, JCDiagnostic d) {
4847                 JCDiagnostic cause = (JCDiagnostic)d.getArgs()[causeIndex];
4848                 DiagnosticPosition pos = d.getDiagnosticPosition();
4849                 if (pos == null) {
4850                     pos = preferredPos;
4851                 }
4852                 return diags.create(preferredKind, preferredSource, pos,
4853                         "prob.found.req", cause);
4854             }
4855         }
4856 
4857         /** a dummy template that match any diagnostic argument */
4858         static final Template skip = new Template("") {
4859             @Override
4860             boolean matches(Object d) {
4861                 return true;
4862             }
4863         };
4864 
4865         /** template for matching inference-free arguments mismatch failures */
4866         static final Template argMismatchTemplate = new Template(MethodCheckDiag.ARG_MISMATCH.regex(), skip);
4867 
4868         /** template for matching inference related arguments mismatch failures */
4869         static final Template inferArgMismatchTemplate = new Template(MethodCheckDiag.ARG_MISMATCH.regex(), skip, skip) {
4870             @Override
4871             boolean matches(Object o) {
4872                 if (!super.matches(o)) {
4873                     return false;
4874                 }
4875                 JCDiagnostic d = (JCDiagnostic)o;
4876                 @SuppressWarnings("unchecked")
4877                 List<Type> tvars = (List<Type>)d.getArgs()[0];
4878                 return !containsAny(d, tvars);
4879             }
4880 
4881             BiPredicate<Object, List<Type>> containsPredicate = (o, ts) -> {
4882                 if (o instanceof Type type) {
4883                     return type.containsAny(ts);
4884                 } else if (o instanceof JCDiagnostic diagnostic) {
4885                     return containsAny(diagnostic, ts);
4886                 } else {
4887                     return false;
4888                 }
4889             };
4890 
4891             boolean containsAny(JCDiagnostic d, List<Type> ts) {
4892                 return Stream.of(d.getArgs())
4893                         .anyMatch(o -> containsPredicate.test(o, ts));
4894             }
4895         };
4896 
4897         /** rewriter map used for method resolution simplification */
4898         static final Map<Template, DiagnosticRewriter> rewriters = new LinkedHashMap<>();
4899 
4900         static {
4901             rewriters.put(argMismatchTemplate, new ArgMismatchRewriter(0));
4902             rewriters.put(inferArgMismatchTemplate, new ArgMismatchRewriter(1));
4903         }
4904 
4905         /**
4906          * Main entry point for diagnostic rewriting - given a diagnostic, see if any templates matches it,
4907          * and rewrite it accordingly.
4908          */
4909         static JCDiagnostic rewrite(JCDiagnostic.Factory diags, DiagnosticPosition pos, DiagnosticSource source,
4910                                     DiagnosticType dkind, JCDiagnostic d) {
4911             for (Map.Entry<Template, DiagnosticRewriter> _entry : rewriters.entrySet()) {
4912                 if (_entry.getKey().matches(d)) {
4913                     JCDiagnostic simpleDiag =
4914                             _entry.getValue().rewriteDiagnostic(diags, pos, source, dkind, d);
4915                     simpleDiag.setFlag(DiagnosticFlag.COMPRESSED);
4916                     return simpleDiag;
4917                 }
4918             }
4919             return null;
4920         }
4921     }
4922 
4923     enum MethodResolutionPhase {
4924         BASIC(false, false),
4925         BOX(true, false),
4926         VARARITY(true, true) {
4927             @Override
4928             public Symbol mergeResults(Symbol bestSoFar, Symbol sym) {
4929                 //Check invariants (see {@code LookupHelper.shouldStop})
4930                 Assert.check(bestSoFar.kind.isResolutionError() && bestSoFar.kind != AMBIGUOUS);
4931                 if (!sym.kind.isResolutionError()) {
4932                     //varargs resolution successful
4933                     return sym;
4934                 } else {
4935                     //pick best error
4936                     switch (bestSoFar.kind) {
4937                         case WRONG_MTH:
4938                         case WRONG_MTHS:
4939                             //Override previous errors if they were caused by argument mismatch.
4940                             //This generally means preferring current symbols - but we need to pay
4941                             //attention to the fact that the varargs lookup returns 'less' candidates
4942                             //than the previous rounds, and adjust that accordingly.
4943                             switch (sym.kind) {
4944                                 case WRONG_MTH:
4945                                     //if the previous round matched more than one method, return that
4946                                     //result instead
4947                                     return bestSoFar.kind == WRONG_MTHS ?
4948                                             bestSoFar : sym;
4949                                 case ABSENT_MTH:
4950                                     //do not override erroneous symbol if the arity lookup did not
4951                                     //match any method
4952                                     return bestSoFar;
4953                                 case WRONG_MTHS:
4954                                 default:
4955                                     //safe to override
4956                                     return sym;
4957                             }
4958                         default:
4959                             //otherwise, return first error
4960                             return bestSoFar;
4961                     }
4962                 }
4963             }
4964         };
4965 
4966         final boolean isBoxingRequired;
4967         final boolean isVarargsRequired;
4968 
4969         MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) {
4970            this.isBoxingRequired = isBoxingRequired;
4971            this.isVarargsRequired = isVarargsRequired;
4972         }
4973 
4974         public boolean isBoxingRequired() {
4975             return isBoxingRequired;
4976         }
4977 
4978         public boolean isVarargsRequired() {
4979             return isVarargsRequired;
4980         }
4981 
4982         public Symbol mergeResults(Symbol prev, Symbol sym) {
4983             return sym;
4984         }
4985     }
4986 
4987     final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
4988 
4989     /**
4990      * A resolution context is used to keep track of intermediate results of
4991      * overload resolution, such as list of method that are not applicable
4992      * (used to generate more precise diagnostics) and so on. Resolution contexts
4993      * can be nested - this means that when each overload resolution routine should
4994      * work within the resolution context it created.
4995      */
4996     class MethodResolutionContext {
4997 
4998         private List<Candidate> candidates = List.nil();
4999 
5000         MethodResolutionPhase step = null;
5001 
5002         MethodCheck methodCheck = resolveMethodCheck;
5003 
5004         private boolean internalResolution = false;
5005         private DeferredAttr.AttrMode attrMode = DeferredAttr.AttrMode.SPECULATIVE;
5006 
5007         void addInapplicableCandidate(Symbol sym, JCDiagnostic details) {
5008             Candidate c = new Candidate(currentResolutionContext.step, sym, details, null);
5009             candidates = candidates.append(c);
5010         }
5011 
5012         void addApplicableCandidate(Symbol sym, Type mtype) {
5013             Candidate c = new Candidate(currentResolutionContext.step, sym, null, mtype);
5014             candidates = candidates.append(c);
5015         }
5016 
5017         DeferredAttrContext deferredAttrContext(Symbol sym, InferenceContext inferenceContext, ResultInfo pendingResult, Warner warn) {
5018             DeferredAttrContext parent = (pendingResult == null)
5019                 ? deferredAttr.emptyDeferredAttrContext
5020                 : pendingResult.checkContext.deferredAttrContext();
5021             return deferredAttr.new DeferredAttrContext(attrMode, sym, step,
5022                     inferenceContext, parent, warn);
5023         }
5024 
5025         /**
5026          * This class represents an overload resolution candidate. There are two
5027          * kinds of candidates: applicable methods and inapplicable methods;
5028          * applicable methods have a pointer to the instantiated method type,
5029          * while inapplicable candidates contain further details about the
5030          * reason why the method has been considered inapplicable.
5031          */
5032         @SuppressWarnings("overrides")
5033         class Candidate {
5034 
5035             final MethodResolutionPhase step;
5036             final Symbol sym;
5037             final JCDiagnostic details;
5038             final Type mtype;
5039 
5040             private Candidate(MethodResolutionPhase step, Symbol sym, JCDiagnostic details, Type mtype) {
5041                 this.step = step;
5042                 this.sym = sym;
5043                 this.details = details;
5044                 this.mtype = mtype;
5045             }
5046 
5047             boolean isApplicable() {
5048                 return mtype != null;
5049             }
5050         }
5051 
5052         DeferredAttr.AttrMode attrMode() {
5053             return attrMode;
5054         }
5055 
5056         boolean internal() {
5057             return internalResolution;
5058         }
5059     }
5060 
5061     MethodResolutionContext currentResolutionContext = null;
5062 }