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