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