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