src/share/classes/com/sun/tools/javac/comp/Resolve.java

Fri, 10 Jan 2014 12:47:15 +0100

author
alundblad
date
Fri, 10 Jan 2014 12:47:15 +0100
changeset 2814
380f6c17ea01
parent 2794
7c25c29a7544
child 2893
ca5783d9a597
child 3005
0353cf89ea96
permissions
-rw-r--r--

8028389: NullPointerException compiling annotation values that have bodies
Summary: Made sure anonymous class declarations inside class- and package-level annotations are properly entered.
Reviewed-by: jfranck

     1 /*
     2  * Copyright (c) 1999, 2014, 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  */
    26 package com.sun.tools.javac.comp;
    28 import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
    29 import com.sun.tools.javac.api.Formattable.LocalizedString;
    30 import com.sun.tools.javac.code.*;
    31 import com.sun.tools.javac.code.Symbol.*;
    32 import com.sun.tools.javac.code.Type.*;
    33 import com.sun.tools.javac.comp.Attr.ResultInfo;
    34 import com.sun.tools.javac.comp.Check.CheckContext;
    35 import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
    36 import com.sun.tools.javac.comp.DeferredAttr.DeferredAttrContext;
    37 import com.sun.tools.javac.comp.DeferredAttr.DeferredType;
    38 import com.sun.tools.javac.comp.Infer.InferenceContext;
    39 import com.sun.tools.javac.comp.Infer.FreeTypeListener;
    40 import com.sun.tools.javac.comp.Resolve.MethodResolutionContext.Candidate;
    41 import com.sun.tools.javac.comp.Resolve.MethodResolutionDiagHelper.DiagnosticRewriter;
    42 import com.sun.tools.javac.comp.Resolve.MethodResolutionDiagHelper.Template;
    43 import com.sun.tools.javac.jvm.*;
    44 import com.sun.tools.javac.main.Option;
    45 import com.sun.tools.javac.tree.*;
    46 import com.sun.tools.javac.tree.JCTree.*;
    47 import com.sun.tools.javac.tree.JCTree.JCMemberReference.ReferenceKind;
    48 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
    49 import com.sun.tools.javac.util.*;
    50 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
    51 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    52 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType;
    54 import java.util.Arrays;
    55 import java.util.Collection;
    56 import java.util.EnumMap;
    57 import java.util.EnumSet;
    58 import java.util.Iterator;
    59 import java.util.LinkedHashMap;
    60 import java.util.LinkedHashSet;
    61 import java.util.Map;
    63 import javax.lang.model.element.ElementVisitor;
    65 import static com.sun.tools.javac.code.Flags.*;
    66 import static com.sun.tools.javac.code.Flags.BLOCK;
    67 import static com.sun.tools.javac.code.Kinds.*;
    68 import static com.sun.tools.javac.code.Kinds.ERRONEOUS;
    69 import static com.sun.tools.javac.code.TypeTag.*;
    70 import static com.sun.tools.javac.comp.Resolve.MethodResolutionPhase.*;
    71 import static com.sun.tools.javac.tree.JCTree.Tag.*;
    73 /** Helper class for name resolution, used mostly by the attribution phase.
    74  *
    75  *  <p><b>This is NOT part of any supported API.
    76  *  If you write code that depends on this, you do so at your own risk.
    77  *  This code and its internal interfaces are subject to change or
    78  *  deletion without notice.</b>
    79  */
    80 public class Resolve {
    81     protected static final Context.Key<Resolve> resolveKey =
    82         new Context.Key<Resolve>();
    84     Names names;
    85     Log log;
    86     Symtab syms;
    87     Attr attr;
    88     DeferredAttr deferredAttr;
    89     Check chk;
    90     Infer infer;
    91     ClassReader reader;
    92     TreeInfo treeinfo;
    93     Types types;
    94     JCDiagnostic.Factory diags;
    95     public final boolean boxingEnabled;
    96     public final boolean varargsEnabled;
    97     public final boolean allowMethodHandles;
    98     public final boolean allowFunctionalInterfaceMostSpecific;
    99     public final boolean checkVarargsAccessAfterResolution;
   100     private final boolean debugResolve;
   101     private final boolean compactMethodDiags;
   102     final EnumSet<VerboseResolutionMode> verboseResolutionMode;
   104     Scope polymorphicSignatureScope;
   106     protected Resolve(Context context) {
   107         context.put(resolveKey, this);
   108         syms = Symtab.instance(context);
   110         varNotFound = new
   111             SymbolNotFoundError(ABSENT_VAR);
   112         methodNotFound = new
   113             SymbolNotFoundError(ABSENT_MTH);
   114         methodWithCorrectStaticnessNotFound = new
   115             SymbolNotFoundError(WRONG_STATICNESS,
   116                 "method found has incorrect staticness");
   117         typeNotFound = new
   118             SymbolNotFoundError(ABSENT_TYP);
   120         names = Names.instance(context);
   121         log = Log.instance(context);
   122         attr = Attr.instance(context);
   123         deferredAttr = DeferredAttr.instance(context);
   124         chk = Check.instance(context);
   125         infer = Infer.instance(context);
   126         reader = ClassReader.instance(context);
   127         treeinfo = TreeInfo.instance(context);
   128         types = Types.instance(context);
   129         diags = JCDiagnostic.Factory.instance(context);
   130         Source source = Source.instance(context);
   131         boxingEnabled = source.allowBoxing();
   132         varargsEnabled = source.allowVarargs();
   133         Options options = Options.instance(context);
   134         debugResolve = options.isSet("debugresolve");
   135         compactMethodDiags = options.isSet(Option.XDIAGS, "compact") ||
   136                 options.isUnset(Option.XDIAGS) && options.isUnset("rawDiagnostics");
   137         verboseResolutionMode = VerboseResolutionMode.getVerboseResolutionMode(options);
   138         Target target = Target.instance(context);
   139         allowMethodHandles = target.hasMethodHandles();
   140         allowFunctionalInterfaceMostSpecific = source.allowFunctionalInterfaceMostSpecific();
   141         checkVarargsAccessAfterResolution =
   142                 source.allowPostApplicabilityVarargsAccessCheck();
   143         polymorphicSignatureScope = new Scope(syms.noSymbol);
   145         inapplicableMethodException = new InapplicableMethodException(diags);
   146     }
   148     /** error symbols, which are returned when resolution fails
   149      */
   150     private final SymbolNotFoundError varNotFound;
   151     private final SymbolNotFoundError methodNotFound;
   152     private final SymbolNotFoundError methodWithCorrectStaticnessNotFound;
   153     private final SymbolNotFoundError typeNotFound;
   155     public static Resolve instance(Context context) {
   156         Resolve instance = context.get(resolveKey);
   157         if (instance == null)
   158             instance = new Resolve(context);
   159         return instance;
   160     }
   162     // <editor-fold defaultstate="collapsed" desc="Verbose resolution diagnostics support">
   163     enum VerboseResolutionMode {
   164         SUCCESS("success"),
   165         FAILURE("failure"),
   166         APPLICABLE("applicable"),
   167         INAPPLICABLE("inapplicable"),
   168         DEFERRED_INST("deferred-inference"),
   169         PREDEF("predef"),
   170         OBJECT_INIT("object-init"),
   171         INTERNAL("internal");
   173         final String opt;
   175         private VerboseResolutionMode(String opt) {
   176             this.opt = opt;
   177         }
   179         static EnumSet<VerboseResolutionMode> getVerboseResolutionMode(Options opts) {
   180             String s = opts.get("verboseResolution");
   181             EnumSet<VerboseResolutionMode> res = EnumSet.noneOf(VerboseResolutionMode.class);
   182             if (s == null) return res;
   183             if (s.contains("all")) {
   184                 res = EnumSet.allOf(VerboseResolutionMode.class);
   185             }
   186             Collection<String> args = Arrays.asList(s.split(","));
   187             for (VerboseResolutionMode mode : values()) {
   188                 if (args.contains(mode.opt)) {
   189                     res.add(mode);
   190                 } else if (args.contains("-" + mode.opt)) {
   191                     res.remove(mode);
   192                 }
   193             }
   194             return res;
   195         }
   196     }
   198     void reportVerboseResolutionDiagnostic(DiagnosticPosition dpos, Name name, Type site,
   199             List<Type> argtypes, List<Type> typeargtypes, Symbol bestSoFar) {
   200         boolean success = bestSoFar.kind < ERRONEOUS;
   202         if (success && !verboseResolutionMode.contains(VerboseResolutionMode.SUCCESS)) {
   203             return;
   204         } else if (!success && !verboseResolutionMode.contains(VerboseResolutionMode.FAILURE)) {
   205             return;
   206         }
   208         if (bestSoFar.name == names.init &&
   209                 bestSoFar.owner == syms.objectType.tsym &&
   210                 !verboseResolutionMode.contains(VerboseResolutionMode.OBJECT_INIT)) {
   211             return; //skip diags for Object constructor resolution
   212         } else if (site == syms.predefClass.type &&
   213                 !verboseResolutionMode.contains(VerboseResolutionMode.PREDEF)) {
   214             return; //skip spurious diags for predef symbols (i.e. operators)
   215         } else if (currentResolutionContext.internalResolution &&
   216                 !verboseResolutionMode.contains(VerboseResolutionMode.INTERNAL)) {
   217             return;
   218         }
   220         int pos = 0;
   221         int mostSpecificPos = -1;
   222         ListBuffer<JCDiagnostic> subDiags = new ListBuffer<>();
   223         for (Candidate c : currentResolutionContext.candidates) {
   224             if (currentResolutionContext.step != c.step ||
   225                     (c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.APPLICABLE)) ||
   226                     (!c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.INAPPLICABLE))) {
   227                 continue;
   228             } else {
   229                 subDiags.append(c.isApplicable() ?
   230                         getVerboseApplicableCandidateDiag(pos, c.sym, c.mtype) :
   231                         getVerboseInapplicableCandidateDiag(pos, c.sym, c.details));
   232                 if (c.sym == bestSoFar)
   233                     mostSpecificPos = pos;
   234                 pos++;
   235             }
   236         }
   237         String key = success ? "verbose.resolve.multi" : "verbose.resolve.multi.1";
   238         List<Type> argtypes2 = Type.map(argtypes,
   239                     deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, bestSoFar, currentResolutionContext.step));
   240         JCDiagnostic main = diags.note(log.currentSource(), dpos, key, name,
   241                 site.tsym, mostSpecificPos, currentResolutionContext.step,
   242                 methodArguments(argtypes2),
   243                 methodArguments(typeargtypes));
   244         JCDiagnostic d = new JCDiagnostic.MultilineDiagnostic(main, subDiags.toList());
   245         log.report(d);
   246     }
   248     JCDiagnostic getVerboseApplicableCandidateDiag(int pos, Symbol sym, Type inst) {
   249         JCDiagnostic subDiag = null;
   250         if (sym.type.hasTag(FORALL)) {
   251             subDiag = diags.fragment("partial.inst.sig", inst);
   252         }
   254         String key = subDiag == null ?
   255                 "applicable.method.found" :
   256                 "applicable.method.found.1";
   258         return diags.fragment(key, pos, sym, subDiag);
   259     }
   261     JCDiagnostic getVerboseInapplicableCandidateDiag(int pos, Symbol sym, JCDiagnostic subDiag) {
   262         return diags.fragment("not.applicable.method.found", pos, sym, subDiag);
   263     }
   264     // </editor-fold>
   266 /* ************************************************************************
   267  * Identifier resolution
   268  *************************************************************************/
   270     /** An environment is "static" if its static level is greater than
   271      *  the one of its outer environment
   272      */
   273     protected static boolean isStatic(Env<AttrContext> env) {
   274         return env.outer != null && env.info.staticLevel > env.outer.info.staticLevel;
   275     }
   277     /** An environment is an "initializer" if it is a constructor or
   278      *  an instance initializer.
   279      */
   280     static boolean isInitializer(Env<AttrContext> env) {
   281         Symbol owner = env.info.scope.owner;
   282         return owner.isConstructor() ||
   283             owner.owner.kind == TYP &&
   284             (owner.kind == VAR ||
   285              owner.kind == MTH && (owner.flags() & BLOCK) != 0) &&
   286             (owner.flags() & STATIC) == 0;
   287     }
   289     /** Is class accessible in given evironment?
   290      *  @param env    The current environment.
   291      *  @param c      The class whose accessibility is checked.
   292      */
   293     public boolean isAccessible(Env<AttrContext> env, TypeSymbol c) {
   294         return isAccessible(env, c, false);
   295     }
   297     public boolean isAccessible(Env<AttrContext> env, TypeSymbol c, boolean checkInner) {
   298         boolean isAccessible = false;
   299         switch ((short)(c.flags() & AccessFlags)) {
   300             case PRIVATE:
   301                 isAccessible =
   302                     env.enclClass.sym.outermostClass() ==
   303                     c.owner.outermostClass();
   304                 break;
   305             case 0:
   306                 isAccessible =
   307                     env.toplevel.packge == c.owner // fast special case
   308                     ||
   309                     env.toplevel.packge == c.packge()
   310                     ||
   311                     // Hack: this case is added since synthesized default constructors
   312                     // of anonymous classes should be allowed to access
   313                     // classes which would be inaccessible otherwise.
   314                     env.enclMethod != null &&
   315                     (env.enclMethod.mods.flags & ANONCONSTR) != 0;
   316                 break;
   317             default: // error recovery
   318             case PUBLIC:
   319                 isAccessible = true;
   320                 break;
   321             case PROTECTED:
   322                 isAccessible =
   323                     env.toplevel.packge == c.owner // fast special case
   324                     ||
   325                     env.toplevel.packge == c.packge()
   326                     ||
   327                     isInnerSubClass(env.enclClass.sym, c.owner);
   328                 break;
   329         }
   330         return (checkInner == false || c.type.getEnclosingType() == Type.noType) ?
   331             isAccessible :
   332             isAccessible && isAccessible(env, c.type.getEnclosingType(), checkInner);
   333     }
   334     //where
   335         /** Is given class a subclass of given base class, or an inner class
   336          *  of a subclass?
   337          *  Return null if no such class exists.
   338          *  @param c     The class which is the subclass or is contained in it.
   339          *  @param base  The base class
   340          */
   341         private boolean isInnerSubClass(ClassSymbol c, Symbol base) {
   342             while (c != null && !c.isSubClass(base, types)) {
   343                 c = c.owner.enclClass();
   344             }
   345             return c != null;
   346         }
   348     boolean isAccessible(Env<AttrContext> env, Type t) {
   349         return isAccessible(env, t, false);
   350     }
   352     boolean isAccessible(Env<AttrContext> env, Type t, boolean checkInner) {
   353         return (t.hasTag(ARRAY))
   354             ? isAccessible(env, types.cvarUpperBound(types.elemtype(t)))
   355             : isAccessible(env, t.tsym, checkInner);
   356     }
   358     /** Is symbol accessible as a member of given type in given environment?
   359      *  @param env    The current environment.
   360      *  @param site   The type of which the tested symbol is regarded
   361      *                as a member.
   362      *  @param sym    The symbol.
   363      */
   364     public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym) {
   365         return isAccessible(env, site, sym, false);
   366     }
   367     public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym, boolean checkInner) {
   368         if (sym.name == names.init && sym.owner != site.tsym) return false;
   369         switch ((short)(sym.flags() & AccessFlags)) {
   370         case PRIVATE:
   371             return
   372                 (env.enclClass.sym == sym.owner // fast special case
   373                  ||
   374                  env.enclClass.sym.outermostClass() ==
   375                  sym.owner.outermostClass())
   376                 &&
   377                 sym.isInheritedIn(site.tsym, types);
   378         case 0:
   379             return
   380                 (env.toplevel.packge == sym.owner.owner // fast special case
   381                  ||
   382                  env.toplevel.packge == sym.packge())
   383                 &&
   384                 isAccessible(env, site, checkInner)
   385                 &&
   386                 sym.isInheritedIn(site.tsym, types)
   387                 &&
   388                 notOverriddenIn(site, sym);
   389         case PROTECTED:
   390             return
   391                 (env.toplevel.packge == sym.owner.owner // fast special case
   392                  ||
   393                  env.toplevel.packge == sym.packge()
   394                  ||
   395                  isProtectedAccessible(sym, env.enclClass.sym, site)
   396                  ||
   397                  // OK to select instance method or field from 'super' or type name
   398                  // (but type names should be disallowed elsewhere!)
   399                  env.info.selectSuper && (sym.flags() & STATIC) == 0 && sym.kind != TYP)
   400                 &&
   401                 isAccessible(env, site, checkInner)
   402                 &&
   403                 notOverriddenIn(site, sym);
   404         default: // this case includes erroneous combinations as well
   405             return isAccessible(env, site, checkInner) && notOverriddenIn(site, sym);
   406         }
   407     }
   408     //where
   409     /* `sym' is accessible only if not overridden by
   410      * another symbol which is a member of `site'
   411      * (because, if it is overridden, `sym' is not strictly
   412      * speaking a member of `site'). A polymorphic signature method
   413      * cannot be overridden (e.g. MH.invokeExact(Object[])).
   414      */
   415     private boolean notOverriddenIn(Type site, Symbol sym) {
   416         if (sym.kind != MTH || sym.isConstructor() || sym.isStatic())
   417             return true;
   418         else {
   419             Symbol s2 = ((MethodSymbol)sym).implementation(site.tsym, types, true);
   420             return (s2 == null || s2 == sym || sym.owner == s2.owner ||
   421                     !types.isSubSignature(types.memberType(site, s2), types.memberType(site, sym)));
   422         }
   423     }
   424     //where
   425         /** Is given protected symbol accessible if it is selected from given site
   426          *  and the selection takes place in given class?
   427          *  @param sym     The symbol with protected access
   428          *  @param c       The class where the access takes place
   429          *  @site          The type of the qualifier
   430          */
   431         private
   432         boolean isProtectedAccessible(Symbol sym, ClassSymbol c, Type site) {
   433             Type newSite = site.hasTag(TYPEVAR) ? site.getUpperBound() : site;
   434             while (c != null &&
   435                    !(c.isSubClass(sym.owner, types) &&
   436                      (c.flags() & INTERFACE) == 0 &&
   437                      // In JLS 2e 6.6.2.1, the subclass restriction applies
   438                      // only to instance fields and methods -- types are excluded
   439                      // regardless of whether they are declared 'static' or not.
   440                      ((sym.flags() & STATIC) != 0 || sym.kind == TYP || newSite.tsym.isSubClass(c, types))))
   441                 c = c.owner.enclClass();
   442             return c != null;
   443         }
   445     /**
   446      * Performs a recursive scan of a type looking for accessibility problems
   447      * from current attribution environment
   448      */
   449     void checkAccessibleType(Env<AttrContext> env, Type t) {
   450         accessibilityChecker.visit(t, env);
   451     }
   453     /**
   454      * Accessibility type-visitor
   455      */
   456     Types.SimpleVisitor<Void, Env<AttrContext>> accessibilityChecker =
   457             new Types.SimpleVisitor<Void, Env<AttrContext>>() {
   459         void visit(List<Type> ts, Env<AttrContext> env) {
   460             for (Type t : ts) {
   461                 visit(t, env);
   462             }
   463         }
   465         public Void visitType(Type t, Env<AttrContext> env) {
   466             return null;
   467         }
   469         @Override
   470         public Void visitArrayType(ArrayType t, Env<AttrContext> env) {
   471             visit(t.elemtype, env);
   472             return null;
   473         }
   475         @Override
   476         public Void visitClassType(ClassType t, Env<AttrContext> env) {
   477             visit(t.getTypeArguments(), env);
   478             if (!isAccessible(env, t, true)) {
   479                 accessBase(new AccessError(t.tsym), env.tree.pos(), env.enclClass.sym, t, t.tsym.name, true);
   480             }
   481             return null;
   482         }
   484         @Override
   485         public Void visitWildcardType(WildcardType t, Env<AttrContext> env) {
   486             visit(t.type, env);
   487             return null;
   488         }
   490         @Override
   491         public Void visitMethodType(MethodType t, Env<AttrContext> env) {
   492             visit(t.getParameterTypes(), env);
   493             visit(t.getReturnType(), env);
   494             visit(t.getThrownTypes(), env);
   495             return null;
   496         }
   497     };
   499     /** Try to instantiate the type of a method so that it fits
   500      *  given type arguments and argument types. If successful, return
   501      *  the method's instantiated type, else return null.
   502      *  The instantiation will take into account an additional leading
   503      *  formal parameter if the method is an instance method seen as a member
   504      *  of an under determined site. In this case, we treat site as an additional
   505      *  parameter and the parameters of the class containing the method as
   506      *  additional type variables that get instantiated.
   507      *
   508      *  @param env         The current environment
   509      *  @param site        The type of which the method is a member.
   510      *  @param m           The method symbol.
   511      *  @param argtypes    The invocation's given value arguments.
   512      *  @param typeargtypes    The invocation's given type arguments.
   513      *  @param allowBoxing Allow boxing conversions of arguments.
   514      *  @param useVarargs Box trailing arguments into an array for varargs.
   515      */
   516     Type rawInstantiate(Env<AttrContext> env,
   517                         Type site,
   518                         Symbol m,
   519                         ResultInfo resultInfo,
   520                         List<Type> argtypes,
   521                         List<Type> typeargtypes,
   522                         boolean allowBoxing,
   523                         boolean useVarargs,
   524                         Warner warn) throws Infer.InferenceException {
   526         Type mt = types.memberType(site, m);
   527         // tvars is the list of formal type variables for which type arguments
   528         // need to inferred.
   529         List<Type> tvars = List.nil();
   530         if (typeargtypes == null) typeargtypes = List.nil();
   531         if (!mt.hasTag(FORALL) && typeargtypes.nonEmpty()) {
   532             // This is not a polymorphic method, but typeargs are supplied
   533             // which is fine, see JLS 15.12.2.1
   534         } else if (mt.hasTag(FORALL) && typeargtypes.nonEmpty()) {
   535             ForAll pmt = (ForAll) mt;
   536             if (typeargtypes.length() != pmt.tvars.length())
   537                 throw inapplicableMethodException.setMessage("arg.length.mismatch"); // not enough args
   538             // Check type arguments are within bounds
   539             List<Type> formals = pmt.tvars;
   540             List<Type> actuals = typeargtypes;
   541             while (formals.nonEmpty() && actuals.nonEmpty()) {
   542                 List<Type> bounds = types.subst(types.getBounds((TypeVar)formals.head),
   543                                                 pmt.tvars, typeargtypes);
   544                 for (; bounds.nonEmpty(); bounds = bounds.tail)
   545                     if (!types.isSubtypeUnchecked(actuals.head, bounds.head, warn))
   546                         throw inapplicableMethodException.setMessage("explicit.param.do.not.conform.to.bounds",actuals.head, bounds);
   547                 formals = formals.tail;
   548                 actuals = actuals.tail;
   549             }
   550             mt = types.subst(pmt.qtype, pmt.tvars, typeargtypes);
   551         } else if (mt.hasTag(FORALL)) {
   552             ForAll pmt = (ForAll) mt;
   553             List<Type> tvars1 = types.newInstances(pmt.tvars);
   554             tvars = tvars.appendList(tvars1);
   555             mt = types.subst(pmt.qtype, pmt.tvars, tvars1);
   556         }
   558         // find out whether we need to go the slow route via infer
   559         boolean instNeeded = tvars.tail != null; /*inlined: tvars.nonEmpty()*/
   560         for (List<Type> l = argtypes;
   561              l.tail != null/*inlined: l.nonEmpty()*/ && !instNeeded;
   562              l = l.tail) {
   563             if (l.head.hasTag(FORALL)) instNeeded = true;
   564         }
   566         if (instNeeded)
   567             return infer.instantiateMethod(env,
   568                                     tvars,
   569                                     (MethodType)mt,
   570                                     resultInfo,
   571                                     (MethodSymbol)m,
   572                                     argtypes,
   573                                     allowBoxing,
   574                                     useVarargs,
   575                                     currentResolutionContext,
   576                                     warn);
   578         DeferredAttr.DeferredAttrContext dc = currentResolutionContext.deferredAttrContext(m, infer.emptyContext, resultInfo, warn);
   579         currentResolutionContext.methodCheck.argumentsAcceptable(env, dc,
   580                                 argtypes, mt.getParameterTypes(), warn);
   581         dc.complete();
   582         return mt;
   583     }
   585     Type checkMethod(Env<AttrContext> env,
   586                      Type site,
   587                      Symbol m,
   588                      ResultInfo resultInfo,
   589                      List<Type> argtypes,
   590                      List<Type> typeargtypes,
   591                      Warner warn) {
   592         MethodResolutionContext prevContext = currentResolutionContext;
   593         try {
   594             currentResolutionContext = new MethodResolutionContext();
   595             currentResolutionContext.attrMode = DeferredAttr.AttrMode.CHECK;
   596             if (env.tree.hasTag(JCTree.Tag.REFERENCE)) {
   597                 //method/constructor references need special check class
   598                 //to handle inference variables in 'argtypes' (might happen
   599                 //during an unsticking round)
   600                 currentResolutionContext.methodCheck =
   601                         new MethodReferenceCheck(resultInfo.checkContext.inferenceContext());
   602             }
   603             MethodResolutionPhase step = currentResolutionContext.step = env.info.pendingResolutionPhase;
   604             return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
   605                     step.isBoxingRequired(), step.isVarargsRequired(), warn);
   606         }
   607         finally {
   608             currentResolutionContext = prevContext;
   609         }
   610     }
   612     /** Same but returns null instead throwing a NoInstanceException
   613      */
   614     Type instantiate(Env<AttrContext> env,
   615                      Type site,
   616                      Symbol m,
   617                      ResultInfo resultInfo,
   618                      List<Type> argtypes,
   619                      List<Type> typeargtypes,
   620                      boolean allowBoxing,
   621                      boolean useVarargs,
   622                      Warner warn) {
   623         try {
   624             return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
   625                                   allowBoxing, useVarargs, warn);
   626         } catch (InapplicableMethodException ex) {
   627             return null;
   628         }
   629     }
   631     /**
   632      * This interface defines an entry point that should be used to perform a
   633      * method check. A method check usually consist in determining as to whether
   634      * a set of types (actuals) is compatible with another set of types (formals).
   635      * Since the notion of compatibility can vary depending on the circumstances,
   636      * this interfaces allows to easily add new pluggable method check routines.
   637      */
   638     interface MethodCheck {
   639         /**
   640          * Main method check routine. A method check usually consist in determining
   641          * as to whether a set of types (actuals) is compatible with another set of
   642          * types (formals). If an incompatibility is found, an unchecked exception
   643          * is assumed to be thrown.
   644          */
   645         void argumentsAcceptable(Env<AttrContext> env,
   646                                 DeferredAttrContext deferredAttrContext,
   647                                 List<Type> argtypes,
   648                                 List<Type> formals,
   649                                 Warner warn);
   651         /**
   652          * Retrieve the method check object that will be used during a
   653          * most specific check.
   654          */
   655         MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict);
   656     }
   658     /**
   659      * Helper enum defining all method check diagnostics (used by resolveMethodCheck).
   660      */
   661     enum MethodCheckDiag {
   662         /**
   663          * Actuals and formals differs in length.
   664          */
   665         ARITY_MISMATCH("arg.length.mismatch", "infer.arg.length.mismatch"),
   666         /**
   667          * An actual is incompatible with a formal.
   668          */
   669         ARG_MISMATCH("no.conforming.assignment.exists", "infer.no.conforming.assignment.exists"),
   670         /**
   671          * An actual is incompatible with the varargs element type.
   672          */
   673         VARARG_MISMATCH("varargs.argument.mismatch", "infer.varargs.argument.mismatch"),
   674         /**
   675          * The varargs element type is inaccessible.
   676          */
   677         INACCESSIBLE_VARARGS("inaccessible.varargs.type", "inaccessible.varargs.type");
   679         final String basicKey;
   680         final String inferKey;
   682         MethodCheckDiag(String basicKey, String inferKey) {
   683             this.basicKey = basicKey;
   684             this.inferKey = inferKey;
   685         }
   687         String regex() {
   688             return String.format("([a-z]*\\.)*(%s|%s)", basicKey, inferKey);
   689         }
   690     }
   692     /**
   693      * Dummy method check object. All methods are deemed applicable, regardless
   694      * of their formal parameter types.
   695      */
   696     MethodCheck nilMethodCheck = new MethodCheck() {
   697         public void argumentsAcceptable(Env<AttrContext> env, DeferredAttrContext deferredAttrContext, List<Type> argtypes, List<Type> formals, Warner warn) {
   698             //do nothing - method always applicable regardless of actuals
   699         }
   701         public MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict) {
   702             return this;
   703         }
   704     };
   706     /**
   707      * Base class for 'real' method checks. The class defines the logic for
   708      * iterating through formals and actuals and provides and entry point
   709      * that can be used by subclasses in order to define the actual check logic.
   710      */
   711     abstract class AbstractMethodCheck implements MethodCheck {
   712         @Override
   713         public void argumentsAcceptable(final Env<AttrContext> env,
   714                                     DeferredAttrContext deferredAttrContext,
   715                                     List<Type> argtypes,
   716                                     List<Type> formals,
   717                                     Warner warn) {
   718             //should we expand formals?
   719             boolean useVarargs = deferredAttrContext.phase.isVarargsRequired();
   720             List<JCExpression> trees = TreeInfo.args(env.tree);
   722             //inference context used during this method check
   723             InferenceContext inferenceContext = deferredAttrContext.inferenceContext;
   725             Type varargsFormal = useVarargs ? formals.last() : null;
   727             if (varargsFormal == null &&
   728                     argtypes.size() != formals.size()) {
   729                 reportMC(env.tree, MethodCheckDiag.ARITY_MISMATCH, inferenceContext); // not enough args
   730             }
   732             while (argtypes.nonEmpty() && formals.head != varargsFormal) {
   733                 DiagnosticPosition pos = trees != null ? trees.head : null;
   734                 checkArg(pos, false, argtypes.head, formals.head, deferredAttrContext, warn);
   735                 argtypes = argtypes.tail;
   736                 formals = formals.tail;
   737                 trees = trees != null ? trees.tail : trees;
   738             }
   740             if (formals.head != varargsFormal) {
   741                 reportMC(env.tree, MethodCheckDiag.ARITY_MISMATCH, inferenceContext); // not enough args
   742             }
   744             if (useVarargs) {
   745                 //note: if applicability check is triggered by most specific test,
   746                 //the last argument of a varargs is _not_ an array type (see JLS 15.12.2.5)
   747                 final Type elt = types.elemtype(varargsFormal);
   748                 while (argtypes.nonEmpty()) {
   749                     DiagnosticPosition pos = trees != null ? trees.head : null;
   750                     checkArg(pos, true, argtypes.head, elt, deferredAttrContext, warn);
   751                     argtypes = argtypes.tail;
   752                     trees = trees != null ? trees.tail : trees;
   753                 }
   754             }
   755         }
   757         /**
   758          * Does the actual argument conforms to the corresponding formal?
   759          */
   760         abstract void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn);
   762         protected void reportMC(DiagnosticPosition pos, MethodCheckDiag diag, InferenceContext inferenceContext, Object... args) {
   763             boolean inferDiag = inferenceContext != infer.emptyContext;
   764             InapplicableMethodException ex = inferDiag ?
   765                     infer.inferenceException : inapplicableMethodException;
   766             if (inferDiag && (!diag.inferKey.equals(diag.basicKey))) {
   767                 Object[] args2 = new Object[args.length + 1];
   768                 System.arraycopy(args, 0, args2, 1, args.length);
   769                 args2[0] = inferenceContext.inferenceVars();
   770                 args = args2;
   771             }
   772             String key = inferDiag ? diag.inferKey : diag.basicKey;
   773             throw ex.setMessage(diags.create(DiagnosticType.FRAGMENT, log.currentSource(), pos, key, args));
   774         }
   776         public MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict) {
   777             return nilMethodCheck;
   778         }
   780     }
   782     /**
   783      * Arity-based method check. A method is applicable if the number of actuals
   784      * supplied conforms to the method signature.
   785      */
   786     MethodCheck arityMethodCheck = new AbstractMethodCheck() {
   787         @Override
   788         void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn) {
   789             //do nothing - actual always compatible to formals
   790         }
   792         @Override
   793         public String toString() {
   794             return "arityMethodCheck";
   795         }
   796     };
   798     List<Type> dummyArgs(int length) {
   799         ListBuffer<Type> buf = new ListBuffer<>();
   800         for (int i = 0 ; i < length ; i++) {
   801             buf.append(Type.noType);
   802         }
   803         return buf.toList();
   804     }
   806     /**
   807      * Main method applicability routine. Given a list of actual types A,
   808      * a list of formal types F, determines whether the types in A are
   809      * compatible (by method invocation conversion) with the types in F.
   810      *
   811      * Since this routine is shared between overload resolution and method
   812      * type-inference, a (possibly empty) inference context is used to convert
   813      * formal types to the corresponding 'undet' form ahead of a compatibility
   814      * check so that constraints can be propagated and collected.
   815      *
   816      * Moreover, if one or more types in A is a deferred type, this routine uses
   817      * DeferredAttr in order to perform deferred attribution. If one or more actual
   818      * deferred types are stuck, they are placed in a queue and revisited later
   819      * after the remainder of the arguments have been seen. If this is not sufficient
   820      * to 'unstuck' the argument, a cyclic inference error is called out.
   821      *
   822      * A method check handler (see above) is used in order to report errors.
   823      */
   824     MethodCheck resolveMethodCheck = new AbstractMethodCheck() {
   826         @Override
   827         void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn) {
   828             ResultInfo mresult = methodCheckResult(varargs, formal, deferredAttrContext, warn);
   829             mresult.check(pos, actual);
   830         }
   832         @Override
   833         public void argumentsAcceptable(final Env<AttrContext> env,
   834                                     DeferredAttrContext deferredAttrContext,
   835                                     List<Type> argtypes,
   836                                     List<Type> formals,
   837                                     Warner warn) {
   838             super.argumentsAcceptable(env, deferredAttrContext, argtypes, formals, warn);
   839             // should we check varargs element type accessibility?
   840             if (deferredAttrContext.phase.isVarargsRequired()) {
   841                 if (deferredAttrContext.mode == AttrMode.CHECK || !checkVarargsAccessAfterResolution) {
   842                     varargsAccessible(env, types.elemtype(formals.last()), deferredAttrContext.inferenceContext);
   843                 }
   844             }
   845         }
   847         /**
   848          * Test that the runtime array element type corresponding to 't' is accessible.  't' should be the
   849          * varargs element type of either the method invocation type signature (after inference completes)
   850          * or the method declaration signature (before inference completes).
   851          */
   852         private void varargsAccessible(final Env<AttrContext> env, final Type t, final InferenceContext inferenceContext) {
   853             if (inferenceContext.free(t)) {
   854                 inferenceContext.addFreeTypeListener(List.of(t), new FreeTypeListener() {
   855                     @Override
   856                     public void typesInferred(InferenceContext inferenceContext) {
   857                         varargsAccessible(env, inferenceContext.asInstType(t), inferenceContext);
   858                     }
   859                 });
   860             } else {
   861                 if (!isAccessible(env, types.erasure(t))) {
   862                     Symbol location = env.enclClass.sym;
   863                     reportMC(env.tree, MethodCheckDiag.INACCESSIBLE_VARARGS, inferenceContext, t, Kinds.kindName(location), location);
   864                 }
   865             }
   866         }
   868         private ResultInfo methodCheckResult(final boolean varargsCheck, Type to,
   869                 final DeferredAttr.DeferredAttrContext deferredAttrContext, Warner rsWarner) {
   870             CheckContext checkContext = new MethodCheckContext(!deferredAttrContext.phase.isBoxingRequired(), deferredAttrContext, rsWarner) {
   871                 MethodCheckDiag methodDiag = varargsCheck ?
   872                                  MethodCheckDiag.VARARG_MISMATCH : MethodCheckDiag.ARG_MISMATCH;
   874                 @Override
   875                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
   876                     reportMC(pos, methodDiag, deferredAttrContext.inferenceContext, details);
   877                 }
   878             };
   879             return new MethodResultInfo(to, checkContext);
   880         }
   882         @Override
   883         public MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict) {
   884             return new MostSpecificCheck(strict, actuals);
   885         }
   887         @Override
   888         public String toString() {
   889             return "resolveMethodCheck";
   890         }
   891     };
   893     /**
   894      * This class handles method reference applicability checks; since during
   895      * these checks it's sometime possible to have inference variables on
   896      * the actual argument types list, the method applicability check must be
   897      * extended so that inference variables are 'opened' as needed.
   898      */
   899     class MethodReferenceCheck extends AbstractMethodCheck {
   901         InferenceContext pendingInferenceContext;
   903         MethodReferenceCheck(InferenceContext pendingInferenceContext) {
   904             this.pendingInferenceContext = pendingInferenceContext;
   905         }
   907         @Override
   908         void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn) {
   909             ResultInfo mresult = methodCheckResult(varargs, formal, deferredAttrContext, warn);
   910             mresult.check(pos, actual);
   911         }
   913         private ResultInfo methodCheckResult(final boolean varargsCheck, Type to,
   914                 final DeferredAttr.DeferredAttrContext deferredAttrContext, Warner rsWarner) {
   915             CheckContext checkContext = new MethodCheckContext(!deferredAttrContext.phase.isBoxingRequired(), deferredAttrContext, rsWarner) {
   916                 MethodCheckDiag methodDiag = varargsCheck ?
   917                                  MethodCheckDiag.VARARG_MISMATCH : MethodCheckDiag.ARG_MISMATCH;
   919                 @Override
   920                 public boolean compatible(Type found, Type req, Warner warn) {
   921                     found = pendingInferenceContext.asUndetVar(found);
   922                     if (found.hasTag(UNDETVAR) && req.isPrimitive()) {
   923                         req = types.boxedClass(req).type;
   924                     }
   925                     return super.compatible(found, req, warn);
   926                 }
   928                 @Override
   929                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
   930                     reportMC(pos, methodDiag, deferredAttrContext.inferenceContext, details);
   931                 }
   932             };
   933             return new MethodResultInfo(to, checkContext);
   934         }
   936         @Override
   937         public MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict) {
   938             return new MostSpecificCheck(strict, actuals);
   939         }
   940     };
   942     /**
   943      * Check context to be used during method applicability checks. A method check
   944      * context might contain inference variables.
   945      */
   946     abstract class MethodCheckContext implements CheckContext {
   948         boolean strict;
   949         DeferredAttrContext deferredAttrContext;
   950         Warner rsWarner;
   952         public MethodCheckContext(boolean strict, DeferredAttrContext deferredAttrContext, Warner rsWarner) {
   953            this.strict = strict;
   954            this.deferredAttrContext = deferredAttrContext;
   955            this.rsWarner = rsWarner;
   956         }
   958         public boolean compatible(Type found, Type req, Warner warn) {
   959             InferenceContext inferenceContext = deferredAttrContext.inferenceContext;
   960             return strict ?
   961                     types.isSubtypeUnchecked(inferenceContext.asUndetVar(found), inferenceContext.asUndetVar(req), warn) :
   962                     types.isConvertible(inferenceContext.asUndetVar(found), inferenceContext.asUndetVar(req), warn);
   963         }
   965         public void report(DiagnosticPosition pos, JCDiagnostic details) {
   966             throw inapplicableMethodException.setMessage(details);
   967         }
   969         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
   970             return rsWarner;
   971         }
   973         public InferenceContext inferenceContext() {
   974             return deferredAttrContext.inferenceContext;
   975         }
   977         public DeferredAttrContext deferredAttrContext() {
   978             return deferredAttrContext;
   979         }
   981         @Override
   982         public String toString() {
   983             return "MethodReferenceCheck";
   984         }
   986     }
   988     /**
   989      * ResultInfo class to be used during method applicability checks. Check
   990      * for deferred types goes through special path.
   991      */
   992     class MethodResultInfo extends ResultInfo {
   994         public MethodResultInfo(Type pt, CheckContext checkContext) {
   995             attr.super(VAL, pt, checkContext);
   996         }
   998         @Override
   999         protected Type check(DiagnosticPosition pos, Type found) {
  1000             if (found.hasTag(DEFERRED)) {
  1001                 DeferredType dt = (DeferredType)found;
  1002                 return dt.check(this);
  1003             } else {
  1004                 Type uResult = U(found.baseType());
  1005                 Type capturedType = pos == null || pos.getTree() == null ?
  1006                         types.capture(uResult) :
  1007                         checkContext.inferenceContext()
  1008                             .cachedCapture(pos.getTree(), uResult, true);
  1009                 return super.check(pos, chk.checkNonVoid(pos, capturedType));
  1013         /**
  1014          * javac has a long-standing 'simplification' (see 6391995):
  1015          * given an actual argument type, the method check is performed
  1016          * on its upper bound. This leads to inconsistencies when an
  1017          * argument type is checked against itself. For example, given
  1018          * a type-variable T, it is not true that {@code U(T) <: T},
  1019          * so we need to guard against that.
  1020          */
  1021         private Type U(Type found) {
  1022             return found == pt ?
  1023                     found : types.cvarUpperBound(found);
  1026         @Override
  1027         protected MethodResultInfo dup(Type newPt) {
  1028             return new MethodResultInfo(newPt, checkContext);
  1031         @Override
  1032         protected ResultInfo dup(CheckContext newContext) {
  1033             return new MethodResultInfo(pt, newContext);
  1037     /**
  1038      * Most specific method applicability routine. Given a list of actual types A,
  1039      * a list of formal types F1, and a list of formal types F2, the routine determines
  1040      * as to whether the types in F1 can be considered more specific than those in F2 w.r.t.
  1041      * argument types A.
  1042      */
  1043     class MostSpecificCheck implements MethodCheck {
  1045         boolean strict;
  1046         List<Type> actuals;
  1048         MostSpecificCheck(boolean strict, List<Type> actuals) {
  1049             this.strict = strict;
  1050             this.actuals = actuals;
  1053         @Override
  1054         public void argumentsAcceptable(final Env<AttrContext> env,
  1055                                     DeferredAttrContext deferredAttrContext,
  1056                                     List<Type> formals1,
  1057                                     List<Type> formals2,
  1058                                     Warner warn) {
  1059             formals2 = adjustArgs(formals2, deferredAttrContext.msym, formals1.length(), deferredAttrContext.phase.isVarargsRequired());
  1060             while (formals2.nonEmpty()) {
  1061                 ResultInfo mresult = methodCheckResult(formals2.head, deferredAttrContext, warn, actuals.head);
  1062                 mresult.check(null, formals1.head);
  1063                 formals1 = formals1.tail;
  1064                 formals2 = formals2.tail;
  1065                 actuals = actuals.isEmpty() ? actuals : actuals.tail;
  1069        /**
  1070         * Create a method check context to be used during the most specific applicability check
  1071         */
  1072         ResultInfo methodCheckResult(Type to, DeferredAttr.DeferredAttrContext deferredAttrContext,
  1073                Warner rsWarner, Type actual) {
  1074            return attr.new ResultInfo(Kinds.VAL, to,
  1075                    new MostSpecificCheckContext(strict, deferredAttrContext, rsWarner, actual));
  1078         /**
  1079          * Subclass of method check context class that implements most specific
  1080          * method conversion. If the actual type under analysis is a deferred type
  1081          * a full blown structural analysis is carried out.
  1082          */
  1083         class MostSpecificCheckContext extends MethodCheckContext {
  1085             Type actual;
  1087             public MostSpecificCheckContext(boolean strict, DeferredAttrContext deferredAttrContext, Warner rsWarner, Type actual) {
  1088                 super(strict, deferredAttrContext, rsWarner);
  1089                 this.actual = actual;
  1092             public boolean compatible(Type found, Type req, Warner warn) {
  1093                 if (allowFunctionalInterfaceMostSpecific &&
  1094                         unrelatedFunctionalInterfaces(found, req) &&
  1095                         (actual != null && actual.getTag() == DEFERRED)) {
  1096                     DeferredType dt = (DeferredType) actual;
  1097                     DeferredType.SpeculativeCache.Entry e =
  1098                             dt.speculativeCache.get(deferredAttrContext.msym, deferredAttrContext.phase);
  1099                     if (e != null && e.speculativeTree != deferredAttr.stuckTree) {
  1100                         return functionalInterfaceMostSpecific(found, req, e.speculativeTree, warn);
  1103                 return super.compatible(found, req, warn);
  1106             /** Whether {@code t} and {@code s} are unrelated functional interface types. */
  1107             private boolean unrelatedFunctionalInterfaces(Type t, Type s) {
  1108                 return types.isFunctionalInterface(t.tsym) &&
  1109                        types.isFunctionalInterface(s.tsym) &&
  1110                        types.asSuper(t, s.tsym) == null &&
  1111                        types.asSuper(s, t.tsym) == null;
  1114             /** Parameters {@code t} and {@code s} are unrelated functional interface types. */
  1115             private boolean functionalInterfaceMostSpecific(Type t, Type s, JCTree tree, Warner warn) {
  1116                 FunctionalInterfaceMostSpecificChecker msc = new FunctionalInterfaceMostSpecificChecker(t, s, warn);
  1117                 msc.scan(tree);
  1118                 return msc.result;
  1121             /**
  1122              * Tests whether one functional interface type can be considered more specific
  1123              * than another unrelated functional interface type for the scanned expression.
  1124              */
  1125             class FunctionalInterfaceMostSpecificChecker extends DeferredAttr.PolyScanner {
  1127                 final Type t;
  1128                 final Type s;
  1129                 final Warner warn;
  1130                 boolean result;
  1132                 /** Parameters {@code t} and {@code s} are unrelated functional interface types. */
  1133                 FunctionalInterfaceMostSpecificChecker(Type t, Type s, Warner warn) {
  1134                     this.t = t;
  1135                     this.s = s;
  1136                     this.warn = warn;
  1137                     result = true;
  1140                 @Override
  1141                 void skip(JCTree tree) {
  1142                     result &= false;
  1145                 @Override
  1146                 public void visitConditional(JCConditional tree) {
  1147                     scan(tree.truepart);
  1148                     scan(tree.falsepart);
  1151                 @Override
  1152                 public void visitReference(JCMemberReference tree) {
  1153                     Type desc_t = types.findDescriptorType(t);
  1154                     Type desc_s = types.findDescriptorType(s);
  1155                     // use inference variables here for more-specific inference (18.5.4)
  1156                     if (!types.isSameTypes(desc_t.getParameterTypes(),
  1157                             inferenceContext().asUndetVars(desc_s.getParameterTypes()))) {
  1158                         result &= false;
  1159                     } else {
  1160                         // compare return types
  1161                         Type ret_t = desc_t.getReturnType();
  1162                         Type ret_s = desc_s.getReturnType();
  1163                         if (ret_s.hasTag(VOID)) {
  1164                             result &= true;
  1165                         } else if (ret_t.hasTag(VOID)) {
  1166                             result &= false;
  1167                         } else if (ret_t.isPrimitive() != ret_s.isPrimitive()) {
  1168                             boolean retValIsPrimitive =
  1169                                     tree.refPolyKind == PolyKind.STANDALONE &&
  1170                                     tree.sym.type.getReturnType().isPrimitive();
  1171                             result &= (retValIsPrimitive == ret_t.isPrimitive()) &&
  1172                                       (retValIsPrimitive != ret_s.isPrimitive());
  1173                         } else {
  1174                             result &= MostSpecificCheckContext.super.compatible(ret_t, ret_s, warn);
  1179                 @Override
  1180                 public void visitLambda(JCLambda tree) {
  1181                     Type desc_t = types.findDescriptorType(t);
  1182                     Type desc_s = types.findDescriptorType(s);
  1183                     // use inference variables here for more-specific inference (18.5.4)
  1184                     if (!types.isSameTypes(desc_t.getParameterTypes(),
  1185                             inferenceContext().asUndetVars(desc_s.getParameterTypes()))) {
  1186                         result &= false;
  1187                     } else {
  1188                         // compare return types
  1189                         Type ret_t = desc_t.getReturnType();
  1190                         Type ret_s = desc_s.getReturnType();
  1191                         if (ret_s.hasTag(VOID)) {
  1192                             result &= true;
  1193                         } else if (ret_t.hasTag(VOID)) {
  1194                             result &= false;
  1195                         } else if (unrelatedFunctionalInterfaces(ret_t, ret_s)) {
  1196                             for (JCExpression expr : lambdaResults(tree)) {
  1197                                 result &= functionalInterfaceMostSpecific(ret_t, ret_s, expr, warn);
  1199                         } else if (ret_t.isPrimitive() != ret_s.isPrimitive()) {
  1200                             for (JCExpression expr : lambdaResults(tree)) {
  1201                                 boolean retValIsPrimitive = expr.isStandalone() && expr.type.isPrimitive();
  1202                                 result &= (retValIsPrimitive == ret_t.isPrimitive()) &&
  1203                                           (retValIsPrimitive != ret_s.isPrimitive());
  1205                         } else {
  1206                             result &= MostSpecificCheckContext.super.compatible(ret_t, ret_s, warn);
  1210                 //where
  1212                 private List<JCExpression> lambdaResults(JCLambda lambda) {
  1213                     if (lambda.getBodyKind() == JCTree.JCLambda.BodyKind.EXPRESSION) {
  1214                         return List.of((JCExpression) lambda.body);
  1215                     } else {
  1216                         final ListBuffer<JCExpression> buffer = new ListBuffer<>();
  1217                         DeferredAttr.LambdaReturnScanner lambdaScanner =
  1218                                 new DeferredAttr.LambdaReturnScanner() {
  1219                                     @Override
  1220                                     public void visitReturn(JCReturn tree) {
  1221                                         if (tree.expr != null) {
  1222                                             buffer.append(tree.expr);
  1225                                 };
  1226                         lambdaScanner.scan(lambda.body);
  1227                         return buffer.toList();
  1234         public MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict) {
  1235             Assert.error("Cannot get here!");
  1236             return null;
  1240     public static class InapplicableMethodException extends RuntimeException {
  1241         private static final long serialVersionUID = 0;
  1243         JCDiagnostic diagnostic;
  1244         JCDiagnostic.Factory diags;
  1246         InapplicableMethodException(JCDiagnostic.Factory diags) {
  1247             this.diagnostic = null;
  1248             this.diags = diags;
  1250         InapplicableMethodException setMessage() {
  1251             return setMessage((JCDiagnostic)null);
  1253         InapplicableMethodException setMessage(String key) {
  1254             return setMessage(key != null ? diags.fragment(key) : null);
  1256         InapplicableMethodException setMessage(String key, Object... args) {
  1257             return setMessage(key != null ? diags.fragment(key, args) : null);
  1259         InapplicableMethodException setMessage(JCDiagnostic diag) {
  1260             this.diagnostic = diag;
  1261             return this;
  1264         public JCDiagnostic getDiagnostic() {
  1265             return diagnostic;
  1268     private final InapplicableMethodException inapplicableMethodException;
  1270 /* ***************************************************************************
  1271  *  Symbol lookup
  1272  *  the following naming conventions for arguments are used
  1274  *       env      is the environment where the symbol was mentioned
  1275  *       site     is the type of which the symbol is a member
  1276  *       name     is the symbol's name
  1277  *                if no arguments are given
  1278  *       argtypes are the value arguments, if we search for a method
  1280  *  If no symbol was found, a ResolveError detailing the problem is returned.
  1281  ****************************************************************************/
  1283     /** Find field. Synthetic fields are always skipped.
  1284      *  @param env     The current environment.
  1285      *  @param site    The original type from where the selection takes place.
  1286      *  @param name    The name of the field.
  1287      *  @param c       The class to search for the field. This is always
  1288      *                 a superclass or implemented interface of site's class.
  1289      */
  1290     Symbol findField(Env<AttrContext> env,
  1291                      Type site,
  1292                      Name name,
  1293                      TypeSymbol c) {
  1294         while (c.type.hasTag(TYPEVAR))
  1295             c = c.type.getUpperBound().tsym;
  1296         Symbol bestSoFar = varNotFound;
  1297         Symbol sym;
  1298         Scope.Entry e = c.members().lookup(name);
  1299         while (e.scope != null) {
  1300             if (e.sym.kind == VAR && (e.sym.flags_field & SYNTHETIC) == 0) {
  1301                 return isAccessible(env, site, e.sym)
  1302                     ? e.sym : new AccessError(env, site, e.sym);
  1304             e = e.next();
  1306         Type st = types.supertype(c.type);
  1307         if (st != null && (st.hasTag(CLASS) || st.hasTag(TYPEVAR))) {
  1308             sym = findField(env, site, name, st.tsym);
  1309             if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1311         for (List<Type> l = types.interfaces(c.type);
  1312              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
  1313              l = l.tail) {
  1314             sym = findField(env, site, name, l.head.tsym);
  1315             if (bestSoFar.exists() && sym.exists() &&
  1316                 sym.owner != bestSoFar.owner)
  1317                 bestSoFar = new AmbiguityError(bestSoFar, sym);
  1318             else if (sym.kind < bestSoFar.kind)
  1319                 bestSoFar = sym;
  1321         return bestSoFar;
  1324     /** Resolve a field identifier, throw a fatal error if not found.
  1325      *  @param pos       The position to use for error reporting.
  1326      *  @param env       The environment current at the method invocation.
  1327      *  @param site      The type of the qualifying expression, in which
  1328      *                   identifier is searched.
  1329      *  @param name      The identifier's name.
  1330      */
  1331     public VarSymbol resolveInternalField(DiagnosticPosition pos, Env<AttrContext> env,
  1332                                           Type site, Name name) {
  1333         Symbol sym = findField(env, site, name, site.tsym);
  1334         if (sym.kind == VAR) return (VarSymbol)sym;
  1335         else throw new FatalError(
  1336                  diags.fragment("fatal.err.cant.locate.field",
  1337                                 name));
  1340     /** Find unqualified variable or field with given name.
  1341      *  Synthetic fields always skipped.
  1342      *  @param env     The current environment.
  1343      *  @param name    The name of the variable or field.
  1344      */
  1345     Symbol findVar(Env<AttrContext> env, Name name) {
  1346         Symbol bestSoFar = varNotFound;
  1347         Symbol sym;
  1348         Env<AttrContext> env1 = env;
  1349         boolean staticOnly = false;
  1350         while (env1.outer != null) {
  1351             if (isStatic(env1)) staticOnly = true;
  1352             Scope.Entry e = env1.info.scope.lookup(name);
  1353             while (e.scope != null &&
  1354                    (e.sym.kind != VAR ||
  1355                     (e.sym.flags_field & SYNTHETIC) != 0))
  1356                 e = e.next();
  1357             sym = (e.scope != null)
  1358                 ? e.sym
  1359                 : findField(
  1360                     env1, env1.enclClass.sym.type, name, env1.enclClass.sym);
  1361             if (sym.exists()) {
  1362                 if (staticOnly &&
  1363                     sym.kind == VAR &&
  1364                     sym.owner.kind == TYP &&
  1365                     (sym.flags() & STATIC) == 0)
  1366                     return new StaticError(sym);
  1367                 else
  1368                     return sym;
  1369             } else if (sym.kind < bestSoFar.kind) {
  1370                 bestSoFar = sym;
  1373             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  1374             env1 = env1.outer;
  1377         sym = findField(env, syms.predefClass.type, name, syms.predefClass);
  1378         if (sym.exists())
  1379             return sym;
  1380         if (bestSoFar.exists())
  1381             return bestSoFar;
  1383         Symbol origin = null;
  1384         for (Scope sc : new Scope[] { env.toplevel.namedImportScope, env.toplevel.starImportScope }) {
  1385             Scope.Entry e = sc.lookup(name);
  1386             for (; e.scope != null; e = e.next()) {
  1387                 sym = e.sym;
  1388                 if (sym.kind != VAR)
  1389                     continue;
  1390                 // invariant: sym.kind == VAR
  1391                 if (bestSoFar.kind < AMBIGUOUS && sym.owner != bestSoFar.owner)
  1392                     return new AmbiguityError(bestSoFar, sym);
  1393                 else if (bestSoFar.kind >= VAR) {
  1394                     origin = e.getOrigin().owner;
  1395                     bestSoFar = isAccessible(env, origin.type, sym)
  1396                         ? sym : new AccessError(env, origin.type, sym);
  1399             if (bestSoFar.exists()) break;
  1401         if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type)
  1402             return bestSoFar.clone(origin);
  1403         else
  1404             return bestSoFar;
  1407     Warner noteWarner = new Warner();
  1409     /** Select the best method for a call site among two choices.
  1410      *  @param env              The current environment.
  1411      *  @param site             The original type from where the
  1412      *                          selection takes place.
  1413      *  @param argtypes         The invocation's value arguments,
  1414      *  @param typeargtypes     The invocation's type arguments,
  1415      *  @param sym              Proposed new best match.
  1416      *  @param bestSoFar        Previously found best match.
  1417      *  @param allowBoxing Allow boxing conversions of arguments.
  1418      *  @param useVarargs Box trailing arguments into an array for varargs.
  1419      */
  1420     @SuppressWarnings("fallthrough")
  1421     Symbol selectBest(Env<AttrContext> env,
  1422                       Type site,
  1423                       List<Type> argtypes,
  1424                       List<Type> typeargtypes,
  1425                       Symbol sym,
  1426                       Symbol bestSoFar,
  1427                       boolean allowBoxing,
  1428                       boolean useVarargs,
  1429                       boolean operator) {
  1430         if (sym.kind == ERR ||
  1431                 !sym.isInheritedIn(site.tsym, types)) {
  1432             return bestSoFar;
  1433         } else if (useVarargs && (sym.flags() & VARARGS) == 0) {
  1434             return bestSoFar.kind >= ERRONEOUS ?
  1435                     new BadVarargsMethod((ResolveError)bestSoFar.baseSymbol()) :
  1436                     bestSoFar;
  1438         Assert.check(sym.kind < AMBIGUOUS);
  1439         try {
  1440             Type mt = rawInstantiate(env, site, sym, null, argtypes, typeargtypes,
  1441                                allowBoxing, useVarargs, types.noWarnings);
  1442             if (!operator || verboseResolutionMode.contains(VerboseResolutionMode.PREDEF))
  1443                 currentResolutionContext.addApplicableCandidate(sym, mt);
  1444         } catch (InapplicableMethodException ex) {
  1445             if (!operator)
  1446                 currentResolutionContext.addInapplicableCandidate(sym, ex.getDiagnostic());
  1447             switch (bestSoFar.kind) {
  1448                 case ABSENT_MTH:
  1449                     return new InapplicableSymbolError(currentResolutionContext);
  1450                 case WRONG_MTH:
  1451                     if (operator) return bestSoFar;
  1452                     bestSoFar = new InapplicableSymbolsError(currentResolutionContext);
  1453                 default:
  1454                     return bestSoFar;
  1457         if (!isAccessible(env, site, sym)) {
  1458             return (bestSoFar.kind == ABSENT_MTH)
  1459                 ? new AccessError(env, site, sym)
  1460                 : bestSoFar;
  1462         return (bestSoFar.kind > AMBIGUOUS)
  1463             ? sym
  1464             : mostSpecific(argtypes, sym, bestSoFar, env, site,
  1465                            allowBoxing && operator, useVarargs);
  1468     /* Return the most specific of the two methods for a call,
  1469      *  given that both are accessible and applicable.
  1470      *  @param m1               A new candidate for most specific.
  1471      *  @param m2               The previous most specific candidate.
  1472      *  @param env              The current environment.
  1473      *  @param site             The original type from where the selection
  1474      *                          takes place.
  1475      *  @param allowBoxing Allow boxing conversions of arguments.
  1476      *  @param useVarargs Box trailing arguments into an array for varargs.
  1477      */
  1478     Symbol mostSpecific(List<Type> argtypes, Symbol m1,
  1479                         Symbol m2,
  1480                         Env<AttrContext> env,
  1481                         final Type site,
  1482                         boolean allowBoxing,
  1483                         boolean useVarargs) {
  1484         switch (m2.kind) {
  1485         case MTH:
  1486             if (m1 == m2) return m1;
  1487             boolean m1SignatureMoreSpecific =
  1488                     signatureMoreSpecific(argtypes, env, site, m1, m2, allowBoxing, useVarargs);
  1489             boolean m2SignatureMoreSpecific =
  1490                     signatureMoreSpecific(argtypes, env, site, m2, m1, allowBoxing, useVarargs);
  1491             if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) {
  1492                 Type mt1 = types.memberType(site, m1);
  1493                 Type mt2 = types.memberType(site, m2);
  1494                 if (!types.overrideEquivalent(mt1, mt2))
  1495                     return ambiguityError(m1, m2);
  1497                 // same signature; select (a) the non-bridge method, or
  1498                 // (b) the one that overrides the other, or (c) the concrete
  1499                 // one, or (d) merge both abstract signatures
  1500                 if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE))
  1501                     return ((m1.flags() & BRIDGE) != 0) ? m2 : m1;
  1503                 // if one overrides or hides the other, use it
  1504                 TypeSymbol m1Owner = (TypeSymbol)m1.owner;
  1505                 TypeSymbol m2Owner = (TypeSymbol)m2.owner;
  1506                 if (types.asSuper(m1Owner.type, m2Owner) != null &&
  1507                     ((m1.owner.flags_field & INTERFACE) == 0 ||
  1508                      (m2.owner.flags_field & INTERFACE) != 0) &&
  1509                     m1.overrides(m2, m1Owner, types, false))
  1510                     return m1;
  1511                 if (types.asSuper(m2Owner.type, m1Owner) != null &&
  1512                     ((m2.owner.flags_field & INTERFACE) == 0 ||
  1513                      (m1.owner.flags_field & INTERFACE) != 0) &&
  1514                     m2.overrides(m1, m2Owner, types, false))
  1515                     return m2;
  1516                 boolean m1Abstract = (m1.flags() & ABSTRACT) != 0;
  1517                 boolean m2Abstract = (m2.flags() & ABSTRACT) != 0;
  1518                 if (m1Abstract && !m2Abstract) return m2;
  1519                 if (m2Abstract && !m1Abstract) return m1;
  1520                 // both abstract or both concrete
  1521                 return ambiguityError(m1, m2);
  1523             if (m1SignatureMoreSpecific) return m1;
  1524             if (m2SignatureMoreSpecific) return m2;
  1525             return ambiguityError(m1, m2);
  1526         case AMBIGUOUS:
  1527             //compare m1 to ambiguous methods in m2
  1528             AmbiguityError e = (AmbiguityError)m2.baseSymbol();
  1529             boolean m1MoreSpecificThanAnyAmbiguous = true;
  1530             boolean allAmbiguousMoreSpecificThanM1 = true;
  1531             for (Symbol s : e.ambiguousSyms) {
  1532                 Symbol moreSpecific = mostSpecific(argtypes, m1, s, env, site, allowBoxing, useVarargs);
  1533                 m1MoreSpecificThanAnyAmbiguous &= moreSpecific == m1;
  1534                 allAmbiguousMoreSpecificThanM1 &= moreSpecific == s;
  1536             if (m1MoreSpecificThanAnyAmbiguous)
  1537                 return m1;
  1538             //if m1 is more specific than some ambiguous methods, but other ambiguous methods are
  1539             //more specific than m1, add it as a new ambiguous method:
  1540             if (!allAmbiguousMoreSpecificThanM1)
  1541                 e.addAmbiguousSymbol(m1);
  1542             return e;
  1543         default:
  1544             throw new AssertionError();
  1547     //where
  1548     private boolean signatureMoreSpecific(List<Type> actuals, Env<AttrContext> env, Type site, Symbol m1, Symbol m2, boolean allowBoxing, boolean useVarargs) {
  1549         noteWarner.clear();
  1550         int maxLength = Math.max(
  1551                             Math.max(m1.type.getParameterTypes().length(), actuals.length()),
  1552                             m2.type.getParameterTypes().length());
  1553         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  1554         try {
  1555             currentResolutionContext = new MethodResolutionContext();
  1556             currentResolutionContext.step = prevResolutionContext.step;
  1557             currentResolutionContext.methodCheck =
  1558                     prevResolutionContext.methodCheck.mostSpecificCheck(actuals, !allowBoxing);
  1559             Type mst = instantiate(env, site, m2, null,
  1560                     adjustArgs(types.cvarLowerBounds(types.memberType(site, m1).getParameterTypes()), m1, maxLength, useVarargs), null,
  1561                     allowBoxing, useVarargs, noteWarner);
  1562             return mst != null &&
  1563                     !noteWarner.hasLint(Lint.LintCategory.UNCHECKED);
  1564         } finally {
  1565             currentResolutionContext = prevResolutionContext;
  1569     List<Type> adjustArgs(List<Type> args, Symbol msym, int length, boolean allowVarargs) {
  1570         if ((msym.flags() & VARARGS) != 0 && allowVarargs) {
  1571             Type varargsElem = types.elemtype(args.last());
  1572             if (varargsElem == null) {
  1573                 Assert.error("Bad varargs = " + args.last() + " " + msym);
  1575             List<Type> newArgs = args.reverse().tail.prepend(varargsElem).reverse();
  1576             while (newArgs.length() < length) {
  1577                 newArgs = newArgs.append(newArgs.last());
  1579             return newArgs;
  1580         } else {
  1581             return args;
  1584     //where
  1585     Type mostSpecificReturnType(Type mt1, Type mt2) {
  1586         Type rt1 = mt1.getReturnType();
  1587         Type rt2 = mt2.getReturnType();
  1589         if (mt1.hasTag(FORALL) && mt2.hasTag(FORALL)) {
  1590             //if both are generic methods, adjust return type ahead of subtyping check
  1591             rt1 = types.subst(rt1, mt1.getTypeArguments(), mt2.getTypeArguments());
  1593         //first use subtyping, then return type substitutability
  1594         if (types.isSubtype(rt1, rt2)) {
  1595             return mt1;
  1596         } else if (types.isSubtype(rt2, rt1)) {
  1597             return mt2;
  1598         } else if (types.returnTypeSubstitutable(mt1, mt2)) {
  1599             return mt1;
  1600         } else if (types.returnTypeSubstitutable(mt2, mt1)) {
  1601             return mt2;
  1602         } else {
  1603             return null;
  1606     //where
  1607     Symbol ambiguityError(Symbol m1, Symbol m2) {
  1608         if (((m1.flags() | m2.flags()) & CLASH) != 0) {
  1609             return (m1.flags() & CLASH) == 0 ? m1 : m2;
  1610         } else {
  1611             return new AmbiguityError(m1, m2);
  1615     Symbol findMethodInScope(Env<AttrContext> env,
  1616             Type site,
  1617             Name name,
  1618             List<Type> argtypes,
  1619             List<Type> typeargtypes,
  1620             Scope sc,
  1621             Symbol bestSoFar,
  1622             boolean allowBoxing,
  1623             boolean useVarargs,
  1624             boolean operator,
  1625             boolean abstractok) {
  1626         for (Symbol s : sc.getElementsByName(name, new LookupFilter(abstractok))) {
  1627             bestSoFar = selectBest(env, site, argtypes, typeargtypes, s,
  1628                     bestSoFar, allowBoxing, useVarargs, operator);
  1630         return bestSoFar;
  1632     //where
  1633         class LookupFilter implements Filter<Symbol> {
  1635             boolean abstractOk;
  1637             LookupFilter(boolean abstractOk) {
  1638                 this.abstractOk = abstractOk;
  1641             public boolean accepts(Symbol s) {
  1642                 long flags = s.flags();
  1643                 return s.kind == MTH &&
  1644                         (flags & SYNTHETIC) == 0 &&
  1645                         (abstractOk ||
  1646                         (flags & DEFAULT) != 0 ||
  1647                         (flags & ABSTRACT) == 0);
  1649         };
  1651     /** Find best qualified method matching given name, type and value
  1652      *  arguments.
  1653      *  @param env       The current environment.
  1654      *  @param site      The original type from where the selection
  1655      *                   takes place.
  1656      *  @param name      The method's name.
  1657      *  @param argtypes  The method's value arguments.
  1658      *  @param typeargtypes The method's type arguments
  1659      *  @param allowBoxing Allow boxing conversions of arguments.
  1660      *  @param useVarargs Box trailing arguments into an array for varargs.
  1661      */
  1662     Symbol findMethod(Env<AttrContext> env,
  1663                       Type site,
  1664                       Name name,
  1665                       List<Type> argtypes,
  1666                       List<Type> typeargtypes,
  1667                       boolean allowBoxing,
  1668                       boolean useVarargs,
  1669                       boolean operator) {
  1670         Symbol bestSoFar = methodNotFound;
  1671         bestSoFar = findMethod(env,
  1672                           site,
  1673                           name,
  1674                           argtypes,
  1675                           typeargtypes,
  1676                           site.tsym.type,
  1677                           bestSoFar,
  1678                           allowBoxing,
  1679                           useVarargs,
  1680                           operator);
  1681         return bestSoFar;
  1683     // where
  1684     private Symbol findMethod(Env<AttrContext> env,
  1685                               Type site,
  1686                               Name name,
  1687                               List<Type> argtypes,
  1688                               List<Type> typeargtypes,
  1689                               Type intype,
  1690                               Symbol bestSoFar,
  1691                               boolean allowBoxing,
  1692                               boolean useVarargs,
  1693                               boolean operator) {
  1694         @SuppressWarnings({"unchecked","rawtypes"})
  1695         List<Type>[] itypes = (List<Type>[])new List[] { List.<Type>nil(), List.<Type>nil() };
  1696         InterfaceLookupPhase iphase = InterfaceLookupPhase.ABSTRACT_OK;
  1697         for (TypeSymbol s : superclasses(intype)) {
  1698             bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
  1699                     s.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
  1700             if (name == names.init) return bestSoFar;
  1701             iphase = (iphase == null) ? null : iphase.update(s, this);
  1702             if (iphase != null) {
  1703                 for (Type itype : types.interfaces(s.type)) {
  1704                     itypes[iphase.ordinal()] = types.union(types.closure(itype), itypes[iphase.ordinal()]);
  1709         Symbol concrete = bestSoFar.kind < ERR &&
  1710                 (bestSoFar.flags() & ABSTRACT) == 0 ?
  1711                 bestSoFar : methodNotFound;
  1713         for (InterfaceLookupPhase iphase2 : InterfaceLookupPhase.values()) {
  1714             //keep searching for abstract methods
  1715             for (Type itype : itypes[iphase2.ordinal()]) {
  1716                 if (!itype.isInterface()) continue; //skip j.l.Object (included by Types.closure())
  1717                 if (iphase2 == InterfaceLookupPhase.DEFAULT_OK &&
  1718                         (itype.tsym.flags() & DEFAULT) == 0) continue;
  1719                 bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
  1720                         itype.tsym.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
  1721                 if (concrete != bestSoFar &&
  1722                         concrete.kind < ERR  && bestSoFar.kind < ERR &&
  1723                         types.isSubSignature(concrete.type, bestSoFar.type)) {
  1724                     //this is an hack - as javac does not do full membership checks
  1725                     //most specific ends up comparing abstract methods that might have
  1726                     //been implemented by some concrete method in a subclass and,
  1727                     //because of raw override, it is possible for an abstract method
  1728                     //to be more specific than the concrete method - so we need
  1729                     //to explicitly call that out (see CR 6178365)
  1730                     bestSoFar = concrete;
  1734         return bestSoFar;
  1737     enum InterfaceLookupPhase {
  1738         ABSTRACT_OK() {
  1739             @Override
  1740             InterfaceLookupPhase update(Symbol s, Resolve rs) {
  1741                 //We should not look for abstract methods if receiver is a concrete class
  1742                 //(as concrete classes are expected to implement all abstracts coming
  1743                 //from superinterfaces)
  1744                 if ((s.flags() & (ABSTRACT | INTERFACE | ENUM)) != 0) {
  1745                     return this;
  1746                 } else {
  1747                     return DEFAULT_OK;
  1750         },
  1751         DEFAULT_OK() {
  1752             @Override
  1753             InterfaceLookupPhase update(Symbol s, Resolve rs) {
  1754                 return this;
  1756         };
  1758         abstract InterfaceLookupPhase update(Symbol s, Resolve rs);
  1761     /**
  1762      * Return an Iterable object to scan the superclasses of a given type.
  1763      * It's crucial that the scan is done lazily, as we don't want to accidentally
  1764      * access more supertypes than strictly needed (as this could trigger completion
  1765      * errors if some of the not-needed supertypes are missing/ill-formed).
  1766      */
  1767     Iterable<TypeSymbol> superclasses(final Type intype) {
  1768         return new Iterable<TypeSymbol>() {
  1769             public Iterator<TypeSymbol> iterator() {
  1770                 return new Iterator<TypeSymbol>() {
  1772                     List<TypeSymbol> seen = List.nil();
  1773                     TypeSymbol currentSym = symbolFor(intype);
  1774                     TypeSymbol prevSym = null;
  1776                     public boolean hasNext() {
  1777                         if (currentSym == syms.noSymbol) {
  1778                             currentSym = symbolFor(types.supertype(prevSym.type));
  1780                         return currentSym != null;
  1783                     public TypeSymbol next() {
  1784                         prevSym = currentSym;
  1785                         currentSym = syms.noSymbol;
  1786                         Assert.check(prevSym != null || prevSym != syms.noSymbol);
  1787                         return prevSym;
  1790                     public void remove() {
  1791                         throw new UnsupportedOperationException();
  1794                     TypeSymbol symbolFor(Type t) {
  1795                         if (!t.hasTag(CLASS) &&
  1796                                 !t.hasTag(TYPEVAR)) {
  1797                             return null;
  1799                         while (t.hasTag(TYPEVAR))
  1800                             t = t.getUpperBound();
  1801                         if (seen.contains(t.tsym)) {
  1802                             //degenerate case in which we have a circular
  1803                             //class hierarchy - because of ill-formed classfiles
  1804                             return null;
  1806                         seen = seen.prepend(t.tsym);
  1807                         return t.tsym;
  1809                 };
  1811         };
  1814     /** Find unqualified method matching given name, type and value arguments.
  1815      *  @param env       The current environment.
  1816      *  @param name      The method's name.
  1817      *  @param argtypes  The method's value arguments.
  1818      *  @param typeargtypes  The method's type arguments.
  1819      *  @param allowBoxing Allow boxing conversions of arguments.
  1820      *  @param useVarargs Box trailing arguments into an array for varargs.
  1821      */
  1822     Symbol findFun(Env<AttrContext> env, Name name,
  1823                    List<Type> argtypes, List<Type> typeargtypes,
  1824                    boolean allowBoxing, boolean useVarargs) {
  1825         Symbol bestSoFar = methodNotFound;
  1826         Symbol sym;
  1827         Env<AttrContext> env1 = env;
  1828         boolean staticOnly = false;
  1829         while (env1.outer != null) {
  1830             if (isStatic(env1)) staticOnly = true;
  1831             sym = findMethod(
  1832                 env1, env1.enclClass.sym.type, name, argtypes, typeargtypes,
  1833                 allowBoxing, useVarargs, false);
  1834             if (sym.exists()) {
  1835                 if (staticOnly &&
  1836                     sym.kind == MTH &&
  1837                     sym.owner.kind == TYP &&
  1838                     (sym.flags() & STATIC) == 0) return new StaticError(sym);
  1839                 else return sym;
  1840             } else if (sym.kind < bestSoFar.kind) {
  1841                 bestSoFar = sym;
  1843             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  1844             env1 = env1.outer;
  1847         sym = findMethod(env, syms.predefClass.type, name, argtypes,
  1848                          typeargtypes, allowBoxing, useVarargs, false);
  1849         if (sym.exists())
  1850             return sym;
  1852         Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
  1853         for (; e.scope != null; e = e.next()) {
  1854             sym = e.sym;
  1855             Type origin = e.getOrigin().owner.type;
  1856             if (sym.kind == MTH) {
  1857                 if (e.sym.owner.type != origin)
  1858                     sym = sym.clone(e.getOrigin().owner);
  1859                 if (!isAccessible(env, origin, sym))
  1860                     sym = new AccessError(env, origin, sym);
  1861                 bestSoFar = selectBest(env, origin,
  1862                                        argtypes, typeargtypes,
  1863                                        sym, bestSoFar,
  1864                                        allowBoxing, useVarargs, false);
  1867         if (bestSoFar.exists())
  1868             return bestSoFar;
  1870         e = env.toplevel.starImportScope.lookup(name);
  1871         for (; e.scope != null; e = e.next()) {
  1872             sym = e.sym;
  1873             Type origin = e.getOrigin().owner.type;
  1874             if (sym.kind == MTH) {
  1875                 if (e.sym.owner.type != origin)
  1876                     sym = sym.clone(e.getOrigin().owner);
  1877                 if (!isAccessible(env, origin, sym))
  1878                     sym = new AccessError(env, origin, sym);
  1879                 bestSoFar = selectBest(env, origin,
  1880                                        argtypes, typeargtypes,
  1881                                        sym, bestSoFar,
  1882                                        allowBoxing, useVarargs, false);
  1885         return bestSoFar;
  1888     /** Load toplevel or member class with given fully qualified name and
  1889      *  verify that it is accessible.
  1890      *  @param env       The current environment.
  1891      *  @param name      The fully qualified name of the class to be loaded.
  1892      */
  1893     Symbol loadClass(Env<AttrContext> env, Name name) {
  1894         try {
  1895             ClassSymbol c = reader.loadClass(name);
  1896             return isAccessible(env, c) ? c : new AccessError(c);
  1897         } catch (ClassReader.BadClassFile err) {
  1898             throw err;
  1899         } catch (CompletionFailure ex) {
  1900             return typeNotFound;
  1905     /**
  1906      * Find a type declared in a scope (not inherited).  Return null
  1907      * if none is found.
  1908      *  @param env       The current environment.
  1909      *  @param site      The original type from where the selection takes
  1910      *                   place.
  1911      *  @param name      The type's name.
  1912      *  @param c         The class to search for the member type. This is
  1913      *                   always a superclass or implemented interface of
  1914      *                   site's class.
  1915      */
  1916     Symbol findImmediateMemberType(Env<AttrContext> env,
  1917                                    Type site,
  1918                                    Name name,
  1919                                    TypeSymbol c) {
  1920         Scope.Entry e = c.members().lookup(name);
  1921         while (e.scope != null) {
  1922             if (e.sym.kind == TYP) {
  1923                 return isAccessible(env, site, e.sym)
  1924                     ? e.sym
  1925                     : new AccessError(env, site, e.sym);
  1927             e = e.next();
  1929         return typeNotFound;
  1932     /** Find a member type inherited from a superclass or interface.
  1933      *  @param env       The current environment.
  1934      *  @param site      The original type from where the selection takes
  1935      *                   place.
  1936      *  @param name      The type's name.
  1937      *  @param c         The class to search for the member type. This is
  1938      *                   always a superclass or implemented interface of
  1939      *                   site's class.
  1940      */
  1941     Symbol findInheritedMemberType(Env<AttrContext> env,
  1942                                    Type site,
  1943                                    Name name,
  1944                                    TypeSymbol c) {
  1945         Symbol bestSoFar = typeNotFound;
  1946         Symbol sym;
  1947         Type st = types.supertype(c.type);
  1948         if (st != null && st.hasTag(CLASS)) {
  1949             sym = findMemberType(env, site, name, st.tsym);
  1950             if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1952         for (List<Type> l = types.interfaces(c.type);
  1953              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
  1954              l = l.tail) {
  1955             sym = findMemberType(env, site, name, l.head.tsym);
  1956             if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
  1957                 sym.owner != bestSoFar.owner)
  1958                 bestSoFar = new AmbiguityError(bestSoFar, sym);
  1959             else if (sym.kind < bestSoFar.kind)
  1960                 bestSoFar = sym;
  1962         return bestSoFar;
  1965     /** Find qualified member type.
  1966      *  @param env       The current environment.
  1967      *  @param site      The original type from where the selection takes
  1968      *                   place.
  1969      *  @param name      The type's name.
  1970      *  @param c         The class to search for the member type. This is
  1971      *                   always a superclass or implemented interface of
  1972      *                   site's class.
  1973      */
  1974     Symbol findMemberType(Env<AttrContext> env,
  1975                           Type site,
  1976                           Name name,
  1977                           TypeSymbol c) {
  1978         Symbol sym = findImmediateMemberType(env, site, name, c);
  1980         if (sym != typeNotFound)
  1981             return sym;
  1983         return findInheritedMemberType(env, site, name, c);
  1987     /** Find a global type in given scope and load corresponding class.
  1988      *  @param env       The current environment.
  1989      *  @param scope     The scope in which to look for the type.
  1990      *  @param name      The type's name.
  1991      */
  1992     Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name) {
  1993         Symbol bestSoFar = typeNotFound;
  1994         for (Scope.Entry e = scope.lookup(name); e.scope != null; e = e.next()) {
  1995             Symbol sym = loadClass(env, e.sym.flatName());
  1996             if (bestSoFar.kind == TYP && sym.kind == TYP &&
  1997                 bestSoFar != sym)
  1998                 return new AmbiguityError(bestSoFar, sym);
  1999             else if (sym.kind < bestSoFar.kind)
  2000                 bestSoFar = sym;
  2002         return bestSoFar;
  2005     Symbol findTypeVar(Env<AttrContext> env, Name name, boolean staticOnly) {
  2006         for (Scope.Entry e = env.info.scope.lookup(name);
  2007              e.scope != null;
  2008              e = e.next()) {
  2009             if (e.sym.kind == TYP) {
  2010                 if (staticOnly &&
  2011                     e.sym.type.hasTag(TYPEVAR) &&
  2012                     e.sym.owner.kind == TYP)
  2013                     return new StaticError(e.sym);
  2014                 return e.sym;
  2017         return typeNotFound;
  2020     /** Find an unqualified type symbol.
  2021      *  @param env       The current environment.
  2022      *  @param name      The type's name.
  2023      */
  2024     Symbol findType(Env<AttrContext> env, Name name) {
  2025         Symbol bestSoFar = typeNotFound;
  2026         Symbol sym;
  2027         boolean staticOnly = false;
  2028         for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
  2029             if (isStatic(env1)) staticOnly = true;
  2030             // First, look for a type variable and the first member type
  2031             final Symbol tyvar = findTypeVar(env1, name, staticOnly);
  2032             sym = findImmediateMemberType(env1, env1.enclClass.sym.type,
  2033                                           name, env1.enclClass.sym);
  2035             // Return the type variable if we have it, and have no
  2036             // immediate member, OR the type variable is for a method.
  2037             if (tyvar != typeNotFound) {
  2038                 if (sym == typeNotFound ||
  2039                     (tyvar.kind == TYP && tyvar.exists() &&
  2040                      tyvar.owner.kind == MTH))
  2041                     return tyvar;
  2044             // If the environment is a class def, finish up,
  2045             // otherwise, do the entire findMemberType
  2046             if (sym == typeNotFound)
  2047                 sym = findInheritedMemberType(env1, env1.enclClass.sym.type,
  2048                                               name, env1.enclClass.sym);
  2050             if (staticOnly && sym.kind == TYP &&
  2051                 sym.type.hasTag(CLASS) &&
  2052                 sym.type.getEnclosingType().hasTag(CLASS) &&
  2053                 env1.enclClass.sym.type.isParameterized() &&
  2054                 sym.type.getEnclosingType().isParameterized())
  2055                 return new StaticError(sym);
  2056             else if (sym.exists()) return sym;
  2057             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  2059             JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass;
  2060             if ((encl.sym.flags() & STATIC) != 0)
  2061                 staticOnly = true;
  2064         if (!env.tree.hasTag(IMPORT)) {
  2065             sym = findGlobalType(env, env.toplevel.namedImportScope, name);
  2066             if (sym.exists()) return sym;
  2067             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  2069             sym = findGlobalType(env, env.toplevel.packge.members(), name);
  2070             if (sym.exists()) return sym;
  2071             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  2073             sym = findGlobalType(env, env.toplevel.starImportScope, name);
  2074             if (sym.exists()) return sym;
  2075             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  2078         return bestSoFar;
  2081     /** Find an unqualified identifier which matches a specified kind set.
  2082      *  @param env       The current environment.
  2083      *  @param name      The identifier's name.
  2084      *  @param kind      Indicates the possible symbol kinds
  2085      *                   (a subset of VAL, TYP, PCK).
  2086      */
  2087     Symbol findIdent(Env<AttrContext> env, Name name, int kind) {
  2088         Symbol bestSoFar = typeNotFound;
  2089         Symbol sym;
  2091         if ((kind & VAR) != 0) {
  2092             sym = findVar(env, name);
  2093             if (sym.exists()) return sym;
  2094             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  2097         if ((kind & TYP) != 0) {
  2098             sym = findType(env, name);
  2099             if (sym.kind==TYP) {
  2100                  reportDependence(env.enclClass.sym, sym);
  2102             if (sym.exists()) return sym;
  2103             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  2106         if ((kind & PCK) != 0) return reader.enterPackage(name);
  2107         else return bestSoFar;
  2110     /** Report dependencies.
  2111      * @param from The enclosing class sym
  2112      * @param to   The found identifier that the class depends on.
  2113      */
  2114     public void reportDependence(Symbol from, Symbol to) {
  2115         // Override if you want to collect the reported dependencies.
  2118     /** Find an identifier in a package which matches a specified kind set.
  2119      *  @param env       The current environment.
  2120      *  @param name      The identifier's name.
  2121      *  @param kind      Indicates the possible symbol kinds
  2122      *                   (a nonempty subset of TYP, PCK).
  2123      */
  2124     Symbol findIdentInPackage(Env<AttrContext> env, TypeSymbol pck,
  2125                               Name name, int kind) {
  2126         Name fullname = TypeSymbol.formFullName(name, pck);
  2127         Symbol bestSoFar = typeNotFound;
  2128         PackageSymbol pack = null;
  2129         if ((kind & PCK) != 0) {
  2130             pack = reader.enterPackage(fullname);
  2131             if (pack.exists()) return pack;
  2133         if ((kind & TYP) != 0) {
  2134             Symbol sym = loadClass(env, fullname);
  2135             if (sym.exists()) {
  2136                 // don't allow programs to use flatnames
  2137                 if (name == sym.name) return sym;
  2139             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  2141         return (pack != null) ? pack : bestSoFar;
  2144     /** Find an identifier among the members of a given type `site'.
  2145      *  @param env       The current environment.
  2146      *  @param site      The type containing the symbol to be found.
  2147      *  @param name      The identifier's name.
  2148      *  @param kind      Indicates the possible symbol kinds
  2149      *                   (a subset of VAL, TYP).
  2150      */
  2151     Symbol findIdentInType(Env<AttrContext> env, Type site,
  2152                            Name name, int kind) {
  2153         Symbol bestSoFar = typeNotFound;
  2154         Symbol sym;
  2155         if ((kind & VAR) != 0) {
  2156             sym = findField(env, site, name, site.tsym);
  2157             if (sym.exists()) return sym;
  2158             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  2161         if ((kind & TYP) != 0) {
  2162             sym = findMemberType(env, site, name, site.tsym);
  2163             if (sym.exists()) return sym;
  2164             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  2166         return bestSoFar;
  2169 /* ***************************************************************************
  2170  *  Access checking
  2171  *  The following methods convert ResolveErrors to ErrorSymbols, issuing
  2172  *  an error message in the process
  2173  ****************************************************************************/
  2175     /** If `sym' is a bad symbol: report error and return errSymbol
  2176      *  else pass through unchanged,
  2177      *  additional arguments duplicate what has been used in trying to find the
  2178      *  symbol {@literal (--> flyweight pattern)}. This improves performance since we
  2179      *  expect misses to happen frequently.
  2181      *  @param sym       The symbol that was found, or a ResolveError.
  2182      *  @param pos       The position to use for error reporting.
  2183      *  @param location  The symbol the served as a context for this lookup
  2184      *  @param site      The original type from where the selection took place.
  2185      *  @param name      The symbol's name.
  2186      *  @param qualified Did we get here through a qualified expression resolution?
  2187      *  @param argtypes  The invocation's value arguments,
  2188      *                   if we looked for a method.
  2189      *  @param typeargtypes  The invocation's type arguments,
  2190      *                   if we looked for a method.
  2191      *  @param logResolveHelper helper class used to log resolve errors
  2192      */
  2193     Symbol accessInternal(Symbol sym,
  2194                   DiagnosticPosition pos,
  2195                   Symbol location,
  2196                   Type site,
  2197                   Name name,
  2198                   boolean qualified,
  2199                   List<Type> argtypes,
  2200                   List<Type> typeargtypes,
  2201                   LogResolveHelper logResolveHelper) {
  2202         if (sym.kind >= AMBIGUOUS) {
  2203             ResolveError errSym = (ResolveError)sym.baseSymbol();
  2204             sym = errSym.access(name, qualified ? site.tsym : syms.noSymbol);
  2205             argtypes = logResolveHelper.getArgumentTypes(errSym, sym, name, argtypes);
  2206             if (logResolveHelper.resolveDiagnosticNeeded(site, argtypes, typeargtypes)) {
  2207                 logResolveError(errSym, pos, location, site, name, argtypes, typeargtypes);
  2210         return sym;
  2213     /**
  2214      * Variant of the generalized access routine, to be used for generating method
  2215      * resolution diagnostics
  2216      */
  2217     Symbol accessMethod(Symbol sym,
  2218                   DiagnosticPosition pos,
  2219                   Symbol location,
  2220                   Type site,
  2221                   Name name,
  2222                   boolean qualified,
  2223                   List<Type> argtypes,
  2224                   List<Type> typeargtypes) {
  2225         return accessInternal(sym, pos, location, site, name, qualified, argtypes, typeargtypes, methodLogResolveHelper);
  2228     /** Same as original accessMethod(), but without location.
  2229      */
  2230     Symbol accessMethod(Symbol sym,
  2231                   DiagnosticPosition pos,
  2232                   Type site,
  2233                   Name name,
  2234                   boolean qualified,
  2235                   List<Type> argtypes,
  2236                   List<Type> typeargtypes) {
  2237         return accessMethod(sym, pos, site.tsym, site, name, qualified, argtypes, typeargtypes);
  2240     /**
  2241      * Variant of the generalized access routine, to be used for generating variable,
  2242      * type resolution diagnostics
  2243      */
  2244     Symbol accessBase(Symbol sym,
  2245                   DiagnosticPosition pos,
  2246                   Symbol location,
  2247                   Type site,
  2248                   Name name,
  2249                   boolean qualified) {
  2250         return accessInternal(sym, pos, location, site, name, qualified, List.<Type>nil(), null, basicLogResolveHelper);
  2253     /** Same as original accessBase(), but without location.
  2254      */
  2255     Symbol accessBase(Symbol sym,
  2256                   DiagnosticPosition pos,
  2257                   Type site,
  2258                   Name name,
  2259                   boolean qualified) {
  2260         return accessBase(sym, pos, site.tsym, site, name, qualified);
  2263     interface LogResolveHelper {
  2264         boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes);
  2265         List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes);
  2268     LogResolveHelper basicLogResolveHelper = new LogResolveHelper() {
  2269         public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
  2270             return !site.isErroneous();
  2272         public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
  2273             return argtypes;
  2275     };
  2277     LogResolveHelper methodLogResolveHelper = new LogResolveHelper() {
  2278         public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
  2279             return !site.isErroneous() &&
  2280                         !Type.isErroneous(argtypes) &&
  2281                         (typeargtypes == null || !Type.isErroneous(typeargtypes));
  2283         public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
  2284             return (syms.operatorNames.contains(name)) ?
  2285                     argtypes :
  2286                     Type.map(argtypes, new ResolveDeferredRecoveryMap(AttrMode.SPECULATIVE, accessedSym, currentResolutionContext.step));
  2288     };
  2290     class ResolveDeferredRecoveryMap extends DeferredAttr.RecoveryDeferredTypeMap {
  2292         public ResolveDeferredRecoveryMap(AttrMode mode, Symbol msym, MethodResolutionPhase step) {
  2293             deferredAttr.super(mode, msym, step);
  2296         @Override
  2297         protected Type typeOf(DeferredType dt) {
  2298             Type res = super.typeOf(dt);
  2299             if (!res.isErroneous()) {
  2300                 switch (TreeInfo.skipParens(dt.tree).getTag()) {
  2301                     case LAMBDA:
  2302                     case REFERENCE:
  2303                         return dt;
  2304                     case CONDEXPR:
  2305                         return res == Type.recoveryType ?
  2306                                 dt : res;
  2309             return res;
  2313     /** Check that sym is not an abstract method.
  2314      */
  2315     void checkNonAbstract(DiagnosticPosition pos, Symbol sym) {
  2316         if ((sym.flags() & ABSTRACT) != 0 && (sym.flags() & DEFAULT) == 0)
  2317             log.error(pos, "abstract.cant.be.accessed.directly",
  2318                       kindName(sym), sym, sym.location());
  2321 /* ***************************************************************************
  2322  *  Debugging
  2323  ****************************************************************************/
  2325     /** print all scopes starting with scope s and proceeding outwards.
  2326      *  used for debugging.
  2327      */
  2328     public void printscopes(Scope s) {
  2329         while (s != null) {
  2330             if (s.owner != null)
  2331                 System.err.print(s.owner + ": ");
  2332             for (Scope.Entry e = s.elems; e != null; e = e.sibling) {
  2333                 if ((e.sym.flags() & ABSTRACT) != 0)
  2334                     System.err.print("abstract ");
  2335                 System.err.print(e.sym + " ");
  2337             System.err.println();
  2338             s = s.next;
  2342     void printscopes(Env<AttrContext> env) {
  2343         while (env.outer != null) {
  2344             System.err.println("------------------------------");
  2345             printscopes(env.info.scope);
  2346             env = env.outer;
  2350     public void printscopes(Type t) {
  2351         while (t.hasTag(CLASS)) {
  2352             printscopes(t.tsym.members());
  2353             t = types.supertype(t);
  2357 /* ***************************************************************************
  2358  *  Name resolution
  2359  *  Naming conventions are as for symbol lookup
  2360  *  Unlike the find... methods these methods will report access errors
  2361  ****************************************************************************/
  2363     /** Resolve an unqualified (non-method) identifier.
  2364      *  @param pos       The position to use for error reporting.
  2365      *  @param env       The environment current at the identifier use.
  2366      *  @param name      The identifier's name.
  2367      *  @param kind      The set of admissible symbol kinds for the identifier.
  2368      */
  2369     Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env,
  2370                         Name name, int kind) {
  2371         return accessBase(
  2372             findIdent(env, name, kind),
  2373             pos, env.enclClass.sym.type, name, false);
  2376     /** Resolve an unqualified method identifier.
  2377      *  @param pos       The position to use for error reporting.
  2378      *  @param env       The environment current at the method invocation.
  2379      *  @param name      The identifier's name.
  2380      *  @param argtypes  The types of the invocation's value arguments.
  2381      *  @param typeargtypes  The types of the invocation's type arguments.
  2382      */
  2383     Symbol resolveMethod(DiagnosticPosition pos,
  2384                          Env<AttrContext> env,
  2385                          Name name,
  2386                          List<Type> argtypes,
  2387                          List<Type> typeargtypes) {
  2388         return lookupMethod(env, pos, env.enclClass.sym, resolveMethodCheck,
  2389                 new BasicLookupHelper(name, env.enclClass.sym.type, argtypes, typeargtypes) {
  2390                     @Override
  2391                     Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2392                         return findFun(env, name, argtypes, typeargtypes,
  2393                                 phase.isBoxingRequired(),
  2394                                 phase.isVarargsRequired());
  2395                     }});
  2398     /** Resolve a qualified method identifier
  2399      *  @param pos       The position to use for error reporting.
  2400      *  @param env       The environment current at the method invocation.
  2401      *  @param site      The type of the qualifying expression, in which
  2402      *                   identifier is searched.
  2403      *  @param name      The identifier's name.
  2404      *  @param argtypes  The types of the invocation's value arguments.
  2405      *  @param typeargtypes  The types of the invocation's type arguments.
  2406      */
  2407     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
  2408                                   Type site, Name name, List<Type> argtypes,
  2409                                   List<Type> typeargtypes) {
  2410         return resolveQualifiedMethod(pos, env, site.tsym, site, name, argtypes, typeargtypes);
  2412     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
  2413                                   Symbol location, Type site, Name name, List<Type> argtypes,
  2414                                   List<Type> typeargtypes) {
  2415         return resolveQualifiedMethod(new MethodResolutionContext(), pos, env, location, site, name, argtypes, typeargtypes);
  2417     private Symbol resolveQualifiedMethod(MethodResolutionContext resolveContext,
  2418                                   DiagnosticPosition pos, Env<AttrContext> env,
  2419                                   Symbol location, Type site, Name name, List<Type> argtypes,
  2420                                   List<Type> typeargtypes) {
  2421         return lookupMethod(env, pos, location, resolveContext, new BasicLookupHelper(name, site, argtypes, typeargtypes) {
  2422             @Override
  2423             Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2424                 return findMethod(env, site, name, argtypes, typeargtypes,
  2425                         phase.isBoxingRequired(),
  2426                         phase.isVarargsRequired(), false);
  2428             @Override
  2429             Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2430                 if (sym.kind >= AMBIGUOUS) {
  2431                     sym = super.access(env, pos, location, sym);
  2432                 } else if (allowMethodHandles) {
  2433                     MethodSymbol msym = (MethodSymbol)sym;
  2434                     if ((msym.flags() & SIGNATURE_POLYMORPHIC) != 0) {
  2435                         return findPolymorphicSignatureInstance(env, sym, argtypes);
  2438                 return sym;
  2440         });
  2443     /** Find or create an implicit method of exactly the given type (after erasure).
  2444      *  Searches in a side table, not the main scope of the site.
  2445      *  This emulates the lookup process required by JSR 292 in JVM.
  2446      *  @param env       Attribution environment
  2447      *  @param spMethod  signature polymorphic method - i.e. MH.invokeExact
  2448      *  @param argtypes  The required argument types
  2449      */
  2450     Symbol findPolymorphicSignatureInstance(Env<AttrContext> env,
  2451                                             final Symbol spMethod,
  2452                                             List<Type> argtypes) {
  2453         Type mtype = infer.instantiatePolymorphicSignatureInstance(env,
  2454                 (MethodSymbol)spMethod, currentResolutionContext, argtypes);
  2455         for (Symbol sym : polymorphicSignatureScope.getElementsByName(spMethod.name)) {
  2456             if (types.isSameType(mtype, sym.type)) {
  2457                return sym;
  2461         // create the desired method
  2462         long flags = ABSTRACT | HYPOTHETICAL | spMethod.flags() & Flags.AccessFlags;
  2463         Symbol msym = new MethodSymbol(flags, spMethod.name, mtype, spMethod.owner) {
  2464             @Override
  2465             public Symbol baseSymbol() {
  2466                 return spMethod;
  2468         };
  2469         polymorphicSignatureScope.enter(msym);
  2470         return msym;
  2473     /** Resolve a qualified method identifier, throw a fatal error if not
  2474      *  found.
  2475      *  @param pos       The position to use for error reporting.
  2476      *  @param env       The environment current at the method invocation.
  2477      *  @param site      The type of the qualifying expression, in which
  2478      *                   identifier is searched.
  2479      *  @param name      The identifier's name.
  2480      *  @param argtypes  The types of the invocation's value arguments.
  2481      *  @param typeargtypes  The types of the invocation's type arguments.
  2482      */
  2483     public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env,
  2484                                         Type site, Name name,
  2485                                         List<Type> argtypes,
  2486                                         List<Type> typeargtypes) {
  2487         MethodResolutionContext resolveContext = new MethodResolutionContext();
  2488         resolveContext.internalResolution = true;
  2489         Symbol sym = resolveQualifiedMethod(resolveContext, pos, env, site.tsym,
  2490                 site, name, argtypes, typeargtypes);
  2491         if (sym.kind == MTH) return (MethodSymbol)sym;
  2492         else throw new FatalError(
  2493                  diags.fragment("fatal.err.cant.locate.meth",
  2494                                 name));
  2497     /** Resolve constructor.
  2498      *  @param pos       The position to use for error reporting.
  2499      *  @param env       The environment current at the constructor invocation.
  2500      *  @param site      The type of class for which a constructor is searched.
  2501      *  @param argtypes  The types of the constructor invocation's value
  2502      *                   arguments.
  2503      *  @param typeargtypes  The types of the constructor invocation's type
  2504      *                   arguments.
  2505      */
  2506     Symbol resolveConstructor(DiagnosticPosition pos,
  2507                               Env<AttrContext> env,
  2508                               Type site,
  2509                               List<Type> argtypes,
  2510                               List<Type> typeargtypes) {
  2511         return resolveConstructor(new MethodResolutionContext(), pos, env, site, argtypes, typeargtypes);
  2514     private Symbol resolveConstructor(MethodResolutionContext resolveContext,
  2515                               final DiagnosticPosition pos,
  2516                               Env<AttrContext> env,
  2517                               Type site,
  2518                               List<Type> argtypes,
  2519                               List<Type> typeargtypes) {
  2520         return lookupMethod(env, pos, site.tsym, resolveContext, new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
  2521             @Override
  2522             Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2523                 return findConstructor(pos, env, site, argtypes, typeargtypes,
  2524                         phase.isBoxingRequired(),
  2525                         phase.isVarargsRequired());
  2527         });
  2530     /** Resolve a constructor, throw a fatal error if not found.
  2531      *  @param pos       The position to use for error reporting.
  2532      *  @param env       The environment current at the method invocation.
  2533      *  @param site      The type to be constructed.
  2534      *  @param argtypes  The types of the invocation's value arguments.
  2535      *  @param typeargtypes  The types of the invocation's type arguments.
  2536      */
  2537     public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  2538                                         Type site,
  2539                                         List<Type> argtypes,
  2540                                         List<Type> typeargtypes) {
  2541         MethodResolutionContext resolveContext = new MethodResolutionContext();
  2542         resolveContext.internalResolution = true;
  2543         Symbol sym = resolveConstructor(resolveContext, pos, env, site, argtypes, typeargtypes);
  2544         if (sym.kind == MTH) return (MethodSymbol)sym;
  2545         else throw new FatalError(
  2546                  diags.fragment("fatal.err.cant.locate.ctor", site));
  2549     Symbol findConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  2550                               Type site, List<Type> argtypes,
  2551                               List<Type> typeargtypes,
  2552                               boolean allowBoxing,
  2553                               boolean useVarargs) {
  2554         Symbol sym = findMethod(env, site,
  2555                                     names.init, argtypes,
  2556                                     typeargtypes, allowBoxing,
  2557                                     useVarargs, false);
  2558         chk.checkDeprecated(pos, env.info.scope.owner, sym);
  2559         return sym;
  2562     /** Resolve constructor using diamond inference.
  2563      *  @param pos       The position to use for error reporting.
  2564      *  @param env       The environment current at the constructor invocation.
  2565      *  @param site      The type of class for which a constructor is searched.
  2566      *                   The scope of this class has been touched in attribution.
  2567      *  @param argtypes  The types of the constructor invocation's value
  2568      *                   arguments.
  2569      *  @param typeargtypes  The types of the constructor invocation's type
  2570      *                   arguments.
  2571      */
  2572     Symbol resolveDiamond(DiagnosticPosition pos,
  2573                               Env<AttrContext> env,
  2574                               Type site,
  2575                               List<Type> argtypes,
  2576                               List<Type> typeargtypes) {
  2577         return lookupMethod(env, pos, site.tsym, resolveMethodCheck,
  2578                 new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
  2579                     @Override
  2580                     Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2581                         return findDiamond(env, site, argtypes, typeargtypes,
  2582                                 phase.isBoxingRequired(),
  2583                                 phase.isVarargsRequired());
  2585                     @Override
  2586                     Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2587                         if (sym.kind >= AMBIGUOUS) {
  2588                             if (sym.kind != WRONG_MTH && sym.kind != WRONG_MTHS) {
  2589                                 sym = super.access(env, pos, location, sym);
  2590                             } else {
  2591                                 final JCDiagnostic details = sym.kind == WRONG_MTH ?
  2592                                                 ((InapplicableSymbolError)sym.baseSymbol()).errCandidate().snd :
  2593                                                 null;
  2594                                 sym = new InapplicableSymbolError(sym.kind, "diamondError", currentResolutionContext) {
  2595                                     @Override
  2596                                     JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos,
  2597                                             Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
  2598                                         String key = details == null ?
  2599                                             "cant.apply.diamond" :
  2600                                             "cant.apply.diamond.1";
  2601                                         return diags.create(dkind, log.currentSource(), pos, key,
  2602                                                 diags.fragment("diamond", site.tsym), details);
  2604                                 };
  2605                                 sym = accessMethod(sym, pos, site, names.init, true, argtypes, typeargtypes);
  2606                                 env.info.pendingResolutionPhase = currentResolutionContext.step;
  2609                         return sym;
  2610                     }});
  2613     /** This method scans all the constructor symbol in a given class scope -
  2614      *  assuming that the original scope contains a constructor of the kind:
  2615      *  {@code Foo(X x, Y y)}, where X,Y are class type-variables declared in Foo,
  2616      *  a method check is executed against the modified constructor type:
  2617      *  {@code <X,Y>Foo<X,Y>(X x, Y y)}. This is crucial in order to enable diamond
  2618      *  inference. The inferred return type of the synthetic constructor IS
  2619      *  the inferred type for the diamond operator.
  2620      */
  2621     private Symbol findDiamond(Env<AttrContext> env,
  2622                               Type site,
  2623                               List<Type> argtypes,
  2624                               List<Type> typeargtypes,
  2625                               boolean allowBoxing,
  2626                               boolean useVarargs) {
  2627         Symbol bestSoFar = methodNotFound;
  2628         for (Scope.Entry e = site.tsym.members().lookup(names.init);
  2629              e.scope != null;
  2630              e = e.next()) {
  2631             final Symbol sym = e.sym;
  2632             //- System.out.println(" e " + e.sym);
  2633             if (sym.kind == MTH &&
  2634                 (sym.flags_field & SYNTHETIC) == 0) {
  2635                     List<Type> oldParams = e.sym.type.hasTag(FORALL) ?
  2636                             ((ForAll)sym.type).tvars :
  2637                             List.<Type>nil();
  2638                     Type constrType = new ForAll(site.tsym.type.getTypeArguments().appendList(oldParams),
  2639                             types.createMethodTypeWithReturn(sym.type.asMethodType(), site));
  2640                     MethodSymbol newConstr = new MethodSymbol(sym.flags(), names.init, constrType, site.tsym) {
  2641                         @Override
  2642                         public Symbol baseSymbol() {
  2643                             return sym;
  2645                     };
  2646                     bestSoFar = selectBest(env, site, argtypes, typeargtypes,
  2647                             newConstr,
  2648                             bestSoFar,
  2649                             allowBoxing,
  2650                             useVarargs,
  2651                             false);
  2654         return bestSoFar;
  2659     /** Resolve operator.
  2660      *  @param pos       The position to use for error reporting.
  2661      *  @param optag     The tag of the operation tree.
  2662      *  @param env       The environment current at the operation.
  2663      *  @param argtypes  The types of the operands.
  2664      */
  2665     Symbol resolveOperator(DiagnosticPosition pos, JCTree.Tag optag,
  2666                            Env<AttrContext> env, List<Type> argtypes) {
  2667         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  2668         try {
  2669             currentResolutionContext = new MethodResolutionContext();
  2670             Name name = treeinfo.operatorName(optag);
  2671             return lookupMethod(env, pos, syms.predefClass, currentResolutionContext,
  2672                     new BasicLookupHelper(name, syms.predefClass.type, argtypes, null, BOX) {
  2673                 @Override
  2674                 Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2675                     return findMethod(env, site, name, argtypes, typeargtypes,
  2676                             phase.isBoxingRequired(),
  2677                             phase.isVarargsRequired(), true);
  2679                 @Override
  2680                 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2681                     return accessMethod(sym, pos, env.enclClass.sym.type, name,
  2682                           false, argtypes, null);
  2684             });
  2685         } finally {
  2686             currentResolutionContext = prevResolutionContext;
  2690     /** Resolve operator.
  2691      *  @param pos       The position to use for error reporting.
  2692      *  @param optag     The tag of the operation tree.
  2693      *  @param env       The environment current at the operation.
  2694      *  @param arg       The type of the operand.
  2695      */
  2696     Symbol resolveUnaryOperator(DiagnosticPosition pos, JCTree.Tag optag, Env<AttrContext> env, Type arg) {
  2697         return resolveOperator(pos, optag, env, List.of(arg));
  2700     /** Resolve binary operator.
  2701      *  @param pos       The position to use for error reporting.
  2702      *  @param optag     The tag of the operation tree.
  2703      *  @param env       The environment current at the operation.
  2704      *  @param left      The types of the left operand.
  2705      *  @param right     The types of the right operand.
  2706      */
  2707     Symbol resolveBinaryOperator(DiagnosticPosition pos,
  2708                                  JCTree.Tag optag,
  2709                                  Env<AttrContext> env,
  2710                                  Type left,
  2711                                  Type right) {
  2712         return resolveOperator(pos, optag, env, List.of(left, right));
  2715     Symbol getMemberReference(DiagnosticPosition pos,
  2716             Env<AttrContext> env,
  2717             JCMemberReference referenceTree,
  2718             Type site,
  2719             Name name) {
  2721         site = types.capture(site);
  2723         ReferenceLookupHelper lookupHelper = makeReferenceLookupHelper(
  2724                 referenceTree, site, name, List.<Type>nil(), null, VARARITY);
  2726         Env<AttrContext> newEnv = env.dup(env.tree, env.info.dup());
  2727         Symbol sym = lookupMethod(newEnv, env.tree.pos(), site.tsym,
  2728                 nilMethodCheck, lookupHelper);
  2730         env.info.pendingResolutionPhase = newEnv.info.pendingResolutionPhase;
  2732         return sym;
  2735     ReferenceLookupHelper makeReferenceLookupHelper(JCMemberReference referenceTree,
  2736                                   Type site,
  2737                                   Name name,
  2738                                   List<Type> argtypes,
  2739                                   List<Type> typeargtypes,
  2740                                   MethodResolutionPhase maxPhase) {
  2741         ReferenceLookupHelper result;
  2742         if (!name.equals(names.init)) {
  2743             //method reference
  2744             result =
  2745                     new MethodReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
  2746         } else {
  2747             if (site.hasTag(ARRAY)) {
  2748                 //array constructor reference
  2749                 result =
  2750                         new ArrayConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase);
  2751             } else {
  2752                 //class constructor reference
  2753                 result =
  2754                         new ConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase);
  2757         return result;
  2760     Symbol resolveMemberReferenceByArity(Env<AttrContext> env,
  2761                                   JCMemberReference referenceTree,
  2762                                   Type site,
  2763                                   Name name,
  2764                                   List<Type> argtypes,
  2765                                   InferenceContext inferenceContext) {
  2767         boolean isStaticSelector = TreeInfo.isStaticSelector(referenceTree.expr, names);
  2768         site = types.capture(site);
  2770         ReferenceLookupHelper boundLookupHelper = makeReferenceLookupHelper(
  2771                 referenceTree, site, name, argtypes, null, VARARITY);
  2772         //step 1 - bound lookup
  2773         Env<AttrContext> boundEnv = env.dup(env.tree, env.info.dup());
  2774         Symbol boundSym = lookupMethod(boundEnv, env.tree.pos(), site.tsym,
  2775                 arityMethodCheck, boundLookupHelper);
  2776         if (isStaticSelector &&
  2777             !name.equals(names.init) &&
  2778             !boundSym.isStatic() &&
  2779             boundSym.kind < ERRONEOUS) {
  2780             boundSym = methodNotFound;
  2783         //step 2 - unbound lookup
  2784         Symbol unboundSym = methodNotFound;
  2785         ReferenceLookupHelper unboundLookupHelper = null;
  2786         Env<AttrContext> unboundEnv = env.dup(env.tree, env.info.dup());
  2787         if (isStaticSelector) {
  2788             unboundLookupHelper = boundLookupHelper.unboundLookup(inferenceContext);
  2789             unboundSym = lookupMethod(unboundEnv, env.tree.pos(), site.tsym,
  2790                     arityMethodCheck, unboundLookupHelper);
  2791             if (unboundSym.isStatic() &&
  2792                 unboundSym.kind < ERRONEOUS) {
  2793                 unboundSym = methodNotFound;
  2797         //merge results
  2798         Symbol bestSym = choose(boundSym, unboundSym);
  2799         env.info.pendingResolutionPhase = bestSym == unboundSym ?
  2800                 unboundEnv.info.pendingResolutionPhase :
  2801                 boundEnv.info.pendingResolutionPhase;
  2803         return bestSym;
  2806     /**
  2807      * Resolution of member references is typically done as a single
  2808      * overload resolution step, where the argument types A are inferred from
  2809      * the target functional descriptor.
  2811      * If the member reference is a method reference with a type qualifier,
  2812      * a two-step lookup process is performed. The first step uses the
  2813      * expected argument list A, while the second step discards the first
  2814      * type from A (which is treated as a receiver type).
  2816      * There are two cases in which inference is performed: (i) if the member
  2817      * reference is a constructor reference and the qualifier type is raw - in
  2818      * which case diamond inference is used to infer a parameterization for the
  2819      * type qualifier; (ii) if the member reference is an unbound reference
  2820      * where the type qualifier is raw - in that case, during the unbound lookup
  2821      * the receiver argument type is used to infer an instantiation for the raw
  2822      * qualifier type.
  2824      * When a multi-step resolution process is exploited, it is an error
  2825      * if two candidates are found (ambiguity).
  2827      * This routine returns a pair (T,S), where S is the member reference symbol,
  2828      * and T is the type of the class in which S is defined. This is necessary as
  2829      * the type T might be dynamically inferred (i.e. if constructor reference
  2830      * has a raw qualifier).
  2831      */
  2832     Pair<Symbol, ReferenceLookupHelper> resolveMemberReference(Env<AttrContext> env,
  2833                                   JCMemberReference referenceTree,
  2834                                   Type site,
  2835                                   Name name,
  2836                                   List<Type> argtypes,
  2837                                   List<Type> typeargtypes,
  2838                                   MethodCheck methodCheck,
  2839                                   InferenceContext inferenceContext,
  2840                                   AttrMode mode) {
  2842         site = types.capture(site);
  2843         ReferenceLookupHelper boundLookupHelper = makeReferenceLookupHelper(
  2844                 referenceTree, site, name, argtypes, typeargtypes, VARARITY);
  2846         //step 1 - bound lookup
  2847         Env<AttrContext> boundEnv = env.dup(env.tree, env.info.dup());
  2848         Symbol origBoundSym;
  2849         boolean staticErrorForBound = false;
  2850         MethodResolutionContext boundSearchResolveContext = new MethodResolutionContext();
  2851         boundSearchResolveContext.methodCheck = methodCheck;
  2852         Symbol boundSym = origBoundSym = lookupMethod(boundEnv, env.tree.pos(),
  2853                 site.tsym, boundSearchResolveContext, boundLookupHelper);
  2854         SearchResultKind boundSearchResultKind = SearchResultKind.NOT_APPLICABLE_MATCH;
  2855         boolean isStaticSelector = TreeInfo.isStaticSelector(referenceTree.expr, names);
  2856         boolean shouldCheckForStaticness = isStaticSelector &&
  2857                 referenceTree.getMode() == ReferenceMode.INVOKE;
  2858         if (boundSym.kind != WRONG_MTHS && boundSym.kind != WRONG_MTH) {
  2859             if (shouldCheckForStaticness) {
  2860                 if (!boundSym.isStatic()) {
  2861                     staticErrorForBound = true;
  2862                     if (hasAnotherApplicableMethod(
  2863                             boundSearchResolveContext, boundSym, true)) {
  2864                         boundSearchResultKind = SearchResultKind.BAD_MATCH_MORE_SPECIFIC;
  2865                     } else {
  2866                         boundSearchResultKind = SearchResultKind.BAD_MATCH;
  2867                         if (boundSym.kind < ERRONEOUS) {
  2868                             boundSym = methodWithCorrectStaticnessNotFound;
  2871                 } else if (boundSym.kind < ERRONEOUS) {
  2872                     boundSearchResultKind = SearchResultKind.GOOD_MATCH;
  2877         //step 2 - unbound lookup
  2878         Symbol origUnboundSym = null;
  2879         Symbol unboundSym = methodNotFound;
  2880         ReferenceLookupHelper unboundLookupHelper = null;
  2881         Env<AttrContext> unboundEnv = env.dup(env.tree, env.info.dup());
  2882         SearchResultKind unboundSearchResultKind = SearchResultKind.NOT_APPLICABLE_MATCH;
  2883         boolean staticErrorForUnbound = false;
  2884         if (isStaticSelector) {
  2885             unboundLookupHelper = boundLookupHelper.unboundLookup(inferenceContext);
  2886             MethodResolutionContext unboundSearchResolveContext =
  2887                     new MethodResolutionContext();
  2888             unboundSearchResolveContext.methodCheck = methodCheck;
  2889             unboundSym = origUnboundSym = lookupMethod(unboundEnv, env.tree.pos(),
  2890                     site.tsym, unboundSearchResolveContext, unboundLookupHelper);
  2892             if (unboundSym.kind != WRONG_MTH && unboundSym.kind != WRONG_MTHS) {
  2893                 if (shouldCheckForStaticness) {
  2894                     if (unboundSym.isStatic()) {
  2895                         staticErrorForUnbound = true;
  2896                         if (hasAnotherApplicableMethod(
  2897                                 unboundSearchResolveContext, unboundSym, false)) {
  2898                             unboundSearchResultKind = SearchResultKind.BAD_MATCH_MORE_SPECIFIC;
  2899                         } else {
  2900                             unboundSearchResultKind = SearchResultKind.BAD_MATCH;
  2901                             if (unboundSym.kind < ERRONEOUS) {
  2902                                 unboundSym = methodWithCorrectStaticnessNotFound;
  2905                     } else if (unboundSym.kind < ERRONEOUS) {
  2906                         unboundSearchResultKind = SearchResultKind.GOOD_MATCH;
  2912         //merge results
  2913         Pair<Symbol, ReferenceLookupHelper> res;
  2914         Symbol bestSym = choose(boundSym, unboundSym);
  2915         if (bestSym.kind < ERRONEOUS && (staticErrorForBound || staticErrorForUnbound)) {
  2916             if (staticErrorForBound) {
  2917                 boundSym = methodWithCorrectStaticnessNotFound;
  2919             if (staticErrorForUnbound) {
  2920                 unboundSym = methodWithCorrectStaticnessNotFound;
  2922             bestSym = choose(boundSym, unboundSym);
  2924         if (bestSym == methodWithCorrectStaticnessNotFound && mode == AttrMode.CHECK) {
  2925             Symbol symToPrint = origBoundSym;
  2926             String errorFragmentToPrint = "non-static.cant.be.ref";
  2927             if (staticErrorForBound && staticErrorForUnbound) {
  2928                 if (unboundSearchResultKind == SearchResultKind.BAD_MATCH_MORE_SPECIFIC) {
  2929                     symToPrint = origUnboundSym;
  2930                     errorFragmentToPrint = "static.method.in.unbound.lookup";
  2932             } else {
  2933                 if (!staticErrorForBound) {
  2934                     symToPrint = origUnboundSym;
  2935                     errorFragmentToPrint = "static.method.in.unbound.lookup";
  2938             log.error(referenceTree.expr.pos(), "invalid.mref",
  2939                 Kinds.kindName(referenceTree.getMode()),
  2940                 diags.fragment(errorFragmentToPrint,
  2941                 Kinds.kindName(symToPrint), symToPrint));
  2943         res = new Pair<>(bestSym,
  2944                 bestSym == unboundSym ? unboundLookupHelper : boundLookupHelper);
  2945         env.info.pendingResolutionPhase = bestSym == unboundSym ?
  2946                 unboundEnv.info.pendingResolutionPhase :
  2947                 boundEnv.info.pendingResolutionPhase;
  2949         return res;
  2952     enum SearchResultKind {
  2953         GOOD_MATCH,                 //type I
  2954         BAD_MATCH_MORE_SPECIFIC,    //type II
  2955         BAD_MATCH,                  //type III
  2956         NOT_APPLICABLE_MATCH        //type IV
  2959     boolean hasAnotherApplicableMethod(MethodResolutionContext resolutionContext,
  2960             Symbol bestSoFar, boolean staticMth) {
  2961         for (Candidate c : resolutionContext.candidates) {
  2962             if (resolutionContext.step != c.step ||
  2963                 !c.isApplicable() ||
  2964                 c.sym == bestSoFar) {
  2965                 continue;
  2966             } else {
  2967                 if (c.sym.isStatic() == staticMth) {
  2968                     return true;
  2972         return false;
  2975     //where
  2976         private Symbol choose(Symbol boundSym, Symbol unboundSym) {
  2977             if (lookupSuccess(boundSym) && lookupSuccess(unboundSym)) {
  2978                 return ambiguityError(boundSym, unboundSym);
  2979             } else if (lookupSuccess(boundSym) ||
  2980                     (canIgnore(unboundSym) && !canIgnore(boundSym))) {
  2981                 return boundSym;
  2982             } else if (lookupSuccess(unboundSym) ||
  2983                     (canIgnore(boundSym) && !canIgnore(unboundSym))) {
  2984                 return unboundSym;
  2985             } else {
  2986                 return boundSym;
  2990         private boolean lookupSuccess(Symbol s) {
  2991             return s.kind == MTH || s.kind == AMBIGUOUS;
  2994         private boolean canIgnore(Symbol s) {
  2995             switch (s.kind) {
  2996                 case ABSENT_MTH:
  2997                     return true;
  2998                 case WRONG_MTH:
  2999                     InapplicableSymbolError errSym =
  3000                             (InapplicableSymbolError)s.baseSymbol();
  3001                     return new Template(MethodCheckDiag.ARITY_MISMATCH.regex())
  3002                             .matches(errSym.errCandidate().snd);
  3003                 case WRONG_MTHS:
  3004                     InapplicableSymbolsError errSyms =
  3005                             (InapplicableSymbolsError)s.baseSymbol();
  3006                     return errSyms.filterCandidates(errSyms.mapCandidates()).isEmpty();
  3007                 case WRONG_STATICNESS:
  3008                     return false;
  3009                 default:
  3010                     return false;
  3014     /**
  3015      * Helper for defining custom method-like lookup logic; a lookup helper
  3016      * provides hooks for (i) the actual lookup logic and (ii) accessing the
  3017      * lookup result (this step might result in compiler diagnostics to be generated)
  3018      */
  3019     abstract class LookupHelper {
  3021         /** name of the symbol to lookup */
  3022         Name name;
  3024         /** location in which the lookup takes place */
  3025         Type site;
  3027         /** actual types used during the lookup */
  3028         List<Type> argtypes;
  3030         /** type arguments used during the lookup */
  3031         List<Type> typeargtypes;
  3033         /** Max overload resolution phase handled by this helper */
  3034         MethodResolutionPhase maxPhase;
  3036         LookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  3037             this.name = name;
  3038             this.site = site;
  3039             this.argtypes = argtypes;
  3040             this.typeargtypes = typeargtypes;
  3041             this.maxPhase = maxPhase;
  3044         /**
  3045          * Should lookup stop at given phase with given result
  3046          */
  3047         final boolean shouldStop(Symbol sym, MethodResolutionPhase phase) {
  3048             return phase.ordinal() > maxPhase.ordinal() ||
  3049                     sym.kind < ERRONEOUS || sym.kind == AMBIGUOUS;
  3052         /**
  3053          * Search for a symbol under a given overload resolution phase - this method
  3054          * is usually called several times, once per each overload resolution phase
  3055          */
  3056         abstract Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase);
  3058         /**
  3059          * Dump overload resolution info
  3060          */
  3061         void debug(DiagnosticPosition pos, Symbol sym) {
  3062             //do nothing
  3065         /**
  3066          * Validate the result of the lookup
  3067          */
  3068         abstract Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym);
  3071     abstract class BasicLookupHelper extends LookupHelper {
  3073         BasicLookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes) {
  3074             this(name, site, argtypes, typeargtypes, MethodResolutionPhase.VARARITY);
  3077         BasicLookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  3078             super(name, site, argtypes, typeargtypes, maxPhase);
  3081         @Override
  3082         final Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  3083             Symbol sym = doLookup(env, phase);
  3084             if (sym.kind == AMBIGUOUS) {
  3085                 AmbiguityError a_err = (AmbiguityError)sym.baseSymbol();
  3086                 sym = a_err.mergeAbstracts(site);
  3088             return sym;
  3091         abstract Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase);
  3093         @Override
  3094         Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  3095             if (sym.kind >= AMBIGUOUS) {
  3096                 //if nothing is found return the 'first' error
  3097                 sym = accessMethod(sym, pos, location, site, name, true, argtypes, typeargtypes);
  3099             return sym;
  3102         @Override
  3103         void debug(DiagnosticPosition pos, Symbol sym) {
  3104             reportVerboseResolutionDiagnostic(pos, name, site, argtypes, typeargtypes, sym);
  3108     /**
  3109      * Helper class for member reference lookup. A reference lookup helper
  3110      * defines the basic logic for member reference lookup; a method gives
  3111      * access to an 'unbound' helper used to perform an unbound member
  3112      * reference lookup.
  3113      */
  3114     abstract class ReferenceLookupHelper extends LookupHelper {
  3116         /** The member reference tree */
  3117         JCMemberReference referenceTree;
  3119         ReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
  3120                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  3121             super(name, site, argtypes, typeargtypes, maxPhase);
  3122             this.referenceTree = referenceTree;
  3125         /**
  3126          * Returns an unbound version of this lookup helper. By default, this
  3127          * method returns an dummy lookup helper.
  3128          */
  3129         ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
  3130             //dummy loopkup helper that always return 'methodNotFound'
  3131             return new ReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase) {
  3132                 @Override
  3133                 ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
  3134                     return this;
  3136                 @Override
  3137                 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  3138                     return methodNotFound;
  3140                 @Override
  3141                 ReferenceKind referenceKind(Symbol sym) {
  3142                     Assert.error();
  3143                     return null;
  3145             };
  3148         /**
  3149          * Get the kind of the member reference
  3150          */
  3151         abstract JCMemberReference.ReferenceKind referenceKind(Symbol sym);
  3153         Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  3154             if (sym.kind == AMBIGUOUS) {
  3155                 AmbiguityError a_err = (AmbiguityError)sym.baseSymbol();
  3156                 sym = a_err.mergeAbstracts(site);
  3158             //skip error reporting
  3159             return sym;
  3163     /**
  3164      * Helper class for method reference lookup. The lookup logic is based
  3165      * upon Resolve.findMethod; in certain cases, this helper class has a
  3166      * corresponding unbound helper class (see UnboundMethodReferenceLookupHelper).
  3167      * In such cases, non-static lookup results are thrown away.
  3168      */
  3169     class MethodReferenceLookupHelper extends ReferenceLookupHelper {
  3171         MethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
  3172                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  3173             super(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
  3176         @Override
  3177         final Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  3178             return findMethod(env, site, name, argtypes, typeargtypes,
  3179                     phase.isBoxingRequired(), phase.isVarargsRequired(), syms.operatorNames.contains(name));
  3182         @Override
  3183         ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
  3184             if (TreeInfo.isStaticSelector(referenceTree.expr, names) &&
  3185                     argtypes.nonEmpty() &&
  3186                     (argtypes.head.hasTag(NONE) ||
  3187                     types.isSubtypeUnchecked(inferenceContext.asUndetVar(argtypes.head), site))) {
  3188                 return new UnboundMethodReferenceLookupHelper(referenceTree, name,
  3189                         site, argtypes, typeargtypes, maxPhase);
  3190             } else {
  3191                 return super.unboundLookup(inferenceContext);
  3195         @Override
  3196         ReferenceKind referenceKind(Symbol sym) {
  3197             if (sym.isStatic()) {
  3198                 return ReferenceKind.STATIC;
  3199             } else {
  3200                 Name selName = TreeInfo.name(referenceTree.getQualifierExpression());
  3201                 return selName != null && selName == names._super ?
  3202                         ReferenceKind.SUPER :
  3203                         ReferenceKind.BOUND;
  3208     /**
  3209      * Helper class for unbound method reference lookup. Essentially the same
  3210      * as the basic method reference lookup helper; main difference is that static
  3211      * lookup results are thrown away. If qualifier type is raw, an attempt to
  3212      * infer a parameterized type is made using the first actual argument (that
  3213      * would otherwise be ignored during the lookup).
  3214      */
  3215     class UnboundMethodReferenceLookupHelper extends MethodReferenceLookupHelper {
  3217         UnboundMethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
  3218                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  3219             super(referenceTree, name, site, argtypes.tail, typeargtypes, maxPhase);
  3220             if (site.isRaw() && !argtypes.head.hasTag(NONE)) {
  3221                 Type asSuperSite = types.asSuper(argtypes.head, site.tsym);
  3222                 this.site = types.capture(asSuperSite);
  3226         @Override
  3227         ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
  3228             return this;
  3231         @Override
  3232         ReferenceKind referenceKind(Symbol sym) {
  3233             return ReferenceKind.UNBOUND;
  3237     /**
  3238      * Helper class for array constructor lookup; an array constructor lookup
  3239      * is simulated by looking up a method that returns the array type specified
  3240      * as qualifier, and that accepts a single int parameter (size of the array).
  3241      */
  3242     class ArrayConstructorReferenceLookupHelper extends ReferenceLookupHelper {
  3244         ArrayConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
  3245                 List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  3246             super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase);
  3249         @Override
  3250         protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  3251             Scope sc = new Scope(syms.arrayClass);
  3252             MethodSymbol arrayConstr = new MethodSymbol(PUBLIC, name, null, site.tsym);
  3253             arrayConstr.type = new MethodType(List.<Type>of(syms.intType), site, List.<Type>nil(), syms.methodClass);
  3254             sc.enter(arrayConstr);
  3255             return findMethodInScope(env, site, name, argtypes, typeargtypes, sc, methodNotFound, phase.isBoxingRequired(), phase.isVarargsRequired(), false, false);
  3258         @Override
  3259         ReferenceKind referenceKind(Symbol sym) {
  3260             return ReferenceKind.ARRAY_CTOR;
  3264     /**
  3265      * Helper class for constructor reference lookup. The lookup logic is based
  3266      * upon either Resolve.findMethod or Resolve.findDiamond - depending on
  3267      * whether the constructor reference needs diamond inference (this is the case
  3268      * if the qualifier type is raw). A special erroneous symbol is returned
  3269      * if the lookup returns the constructor of an inner class and there's no
  3270      * enclosing instance in scope.
  3271      */
  3272     class ConstructorReferenceLookupHelper extends ReferenceLookupHelper {
  3274         boolean needsInference;
  3276         ConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
  3277                 List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  3278             super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase);
  3279             if (site.isRaw()) {
  3280                 this.site = new ClassType(site.getEnclosingType(), site.tsym.type.getTypeArguments(), site.tsym);
  3281                 needsInference = true;
  3285         @Override
  3286         protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  3287             Symbol sym = needsInference ?
  3288                 findDiamond(env, site, argtypes, typeargtypes, phase.isBoxingRequired(), phase.isVarargsRequired()) :
  3289                 findMethod(env, site, name, argtypes, typeargtypes,
  3290                         phase.isBoxingRequired(), phase.isVarargsRequired(), syms.operatorNames.contains(name));
  3291             return sym.kind != MTH ||
  3292                           site.getEnclosingType().hasTag(NONE) ||
  3293                           hasEnclosingInstance(env, site) ?
  3294                           sym : new InvalidSymbolError(Kinds.MISSING_ENCL, sym, null) {
  3295                     @Override
  3296                     JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
  3297                        return diags.create(dkind, log.currentSource(), pos,
  3298                             "cant.access.inner.cls.constr", site.tsym.name, argtypes, site.getEnclosingType());
  3300                 };
  3303         @Override
  3304         ReferenceKind referenceKind(Symbol sym) {
  3305             return site.getEnclosingType().hasTag(NONE) ?
  3306                     ReferenceKind.TOPLEVEL : ReferenceKind.IMPLICIT_INNER;
  3310     /**
  3311      * Main overload resolution routine. On each overload resolution step, a
  3312      * lookup helper class is used to perform the method/constructor lookup;
  3313      * at the end of the lookup, the helper is used to validate the results
  3314      * (this last step might trigger overload resolution diagnostics).
  3315      */
  3316     Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, MethodCheck methodCheck, LookupHelper lookupHelper) {
  3317         MethodResolutionContext resolveContext = new MethodResolutionContext();
  3318         resolveContext.methodCheck = methodCheck;
  3319         return lookupMethod(env, pos, location, resolveContext, lookupHelper);
  3322     Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location,
  3323             MethodResolutionContext resolveContext, LookupHelper lookupHelper) {
  3324         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  3325         try {
  3326             Symbol bestSoFar = methodNotFound;
  3327             currentResolutionContext = resolveContext;
  3328             for (MethodResolutionPhase phase : methodResolutionSteps) {
  3329                 if (!phase.isApplicable(boxingEnabled, varargsEnabled) ||
  3330                         lookupHelper.shouldStop(bestSoFar, phase)) break;
  3331                 MethodResolutionPhase prevPhase = currentResolutionContext.step;
  3332                 Symbol prevBest = bestSoFar;
  3333                 currentResolutionContext.step = phase;
  3334                 Symbol sym = lookupHelper.lookup(env, phase);
  3335                 lookupHelper.debug(pos, sym);
  3336                 bestSoFar = phase.mergeResults(bestSoFar, sym);
  3337                 env.info.pendingResolutionPhase = (prevBest == bestSoFar) ? prevPhase : phase;
  3339             return lookupHelper.access(env, pos, location, bestSoFar);
  3340         } finally {
  3341             currentResolutionContext = prevResolutionContext;
  3345     /**
  3346      * Resolve `c.name' where name == this or name == super.
  3347      * @param pos           The position to use for error reporting.
  3348      * @param env           The environment current at the expression.
  3349      * @param c             The qualifier.
  3350      * @param name          The identifier's name.
  3351      */
  3352     Symbol resolveSelf(DiagnosticPosition pos,
  3353                        Env<AttrContext> env,
  3354                        TypeSymbol c,
  3355                        Name name) {
  3356         Env<AttrContext> env1 = env;
  3357         boolean staticOnly = false;
  3358         while (env1.outer != null) {
  3359             if (isStatic(env1)) staticOnly = true;
  3360             if (env1.enclClass.sym == c) {
  3361                 Symbol sym = env1.info.scope.lookup(name).sym;
  3362                 if (sym != null) {
  3363                     if (staticOnly) sym = new StaticError(sym);
  3364                     return accessBase(sym, pos, env.enclClass.sym.type,
  3365                                   name, true);
  3368             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  3369             env1 = env1.outer;
  3371         if (c.isInterface() &&
  3372             name == names._super && !isStatic(env) &&
  3373             types.isDirectSuperInterface(c, env.enclClass.sym)) {
  3374             //this might be a default super call if one of the superinterfaces is 'c'
  3375             for (Type t : pruneInterfaces(env.enclClass.type)) {
  3376                 if (t.tsym == c) {
  3377                     env.info.defaultSuperCallSite = t;
  3378                     return new VarSymbol(0, names._super,
  3379                             types.asSuper(env.enclClass.type, c), env.enclClass.sym);
  3382             //find a direct superinterface that is a subtype of 'c'
  3383             for (Type i : types.interfaces(env.enclClass.type)) {
  3384                 if (i.tsym.isSubClass(c, types) && i.tsym != c) {
  3385                     log.error(pos, "illegal.default.super.call", c,
  3386                             diags.fragment("redundant.supertype", c, i));
  3387                     return syms.errSymbol;
  3390             Assert.error();
  3392         log.error(pos, "not.encl.class", c);
  3393         return syms.errSymbol;
  3395     //where
  3396     private List<Type> pruneInterfaces(Type t) {
  3397         ListBuffer<Type> result = new ListBuffer<>();
  3398         for (Type t1 : types.interfaces(t)) {
  3399             boolean shouldAdd = true;
  3400             for (Type t2 : types.interfaces(t)) {
  3401                 if (t1 != t2 && types.isSubtypeNoCapture(t2, t1)) {
  3402                     shouldAdd = false;
  3405             if (shouldAdd) {
  3406                 result.append(t1);
  3409         return result.toList();
  3413     /**
  3414      * Resolve `c.this' for an enclosing class c that contains the
  3415      * named member.
  3416      * @param pos           The position to use for error reporting.
  3417      * @param env           The environment current at the expression.
  3418      * @param member        The member that must be contained in the result.
  3419      */
  3420     Symbol resolveSelfContaining(DiagnosticPosition pos,
  3421                                  Env<AttrContext> env,
  3422                                  Symbol member,
  3423                                  boolean isSuperCall) {
  3424         Symbol sym = resolveSelfContainingInternal(env, member, isSuperCall);
  3425         if (sym == null) {
  3426             log.error(pos, "encl.class.required", member);
  3427             return syms.errSymbol;
  3428         } else {
  3429             return accessBase(sym, pos, env.enclClass.sym.type, sym.name, true);
  3433     boolean hasEnclosingInstance(Env<AttrContext> env, Type type) {
  3434         Symbol encl = resolveSelfContainingInternal(env, type.tsym, false);
  3435         return encl != null && encl.kind < ERRONEOUS;
  3438     private Symbol resolveSelfContainingInternal(Env<AttrContext> env,
  3439                                  Symbol member,
  3440                                  boolean isSuperCall) {
  3441         Name name = names._this;
  3442         Env<AttrContext> env1 = isSuperCall ? env.outer : env;
  3443         boolean staticOnly = false;
  3444         if (env1 != null) {
  3445             while (env1 != null && env1.outer != null) {
  3446                 if (isStatic(env1)) staticOnly = true;
  3447                 if (env1.enclClass.sym.isSubClass(member.owner, types)) {
  3448                     Symbol sym = env1.info.scope.lookup(name).sym;
  3449                     if (sym != null) {
  3450                         if (staticOnly) sym = new StaticError(sym);
  3451                         return sym;
  3454                 if ((env1.enclClass.sym.flags() & STATIC) != 0)
  3455                     staticOnly = true;
  3456                 env1 = env1.outer;
  3459         return null;
  3462     /**
  3463      * Resolve an appropriate implicit this instance for t's container.
  3464      * JLS 8.8.5.1 and 15.9.2
  3465      */
  3466     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
  3467         return resolveImplicitThis(pos, env, t, false);
  3470     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t, boolean isSuperCall) {
  3471         Type thisType = (((t.tsym.owner.kind & (MTH|VAR)) != 0)
  3472                          ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
  3473                          : resolveSelfContaining(pos, env, t.tsym, isSuperCall)).type;
  3474         if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
  3475             log.error(pos, "cant.ref.before.ctor.called", "this");
  3476         return thisType;
  3479 /* ***************************************************************************
  3480  *  ResolveError classes, indicating error situations when accessing symbols
  3481  ****************************************************************************/
  3483     //used by TransTypes when checking target type of synthetic cast
  3484     public void logAccessErrorInternal(Env<AttrContext> env, JCTree tree, Type type) {
  3485         AccessError error = new AccessError(env, env.enclClass.type, type.tsym);
  3486         logResolveError(error, tree.pos(), env.enclClass.sym, env.enclClass.type, null, null, null);
  3488     //where
  3489     private void logResolveError(ResolveError error,
  3490             DiagnosticPosition pos,
  3491             Symbol location,
  3492             Type site,
  3493             Name name,
  3494             List<Type> argtypes,
  3495             List<Type> typeargtypes) {
  3496         JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
  3497                 pos, location, site, name, argtypes, typeargtypes);
  3498         if (d != null) {
  3499             d.setFlag(DiagnosticFlag.RESOLVE_ERROR);
  3500             log.report(d);
  3504     private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
  3506     public Object methodArguments(List<Type> argtypes) {
  3507         if (argtypes == null || argtypes.isEmpty()) {
  3508             return noArgs;
  3509         } else {
  3510             ListBuffer<Object> diagArgs = new ListBuffer<>();
  3511             for (Type t : argtypes) {
  3512                 if (t.hasTag(DEFERRED)) {
  3513                     diagArgs.append(((DeferredAttr.DeferredType)t).tree);
  3514                 } else {
  3515                     diagArgs.append(t);
  3518             return diagArgs;
  3522     /**
  3523      * Root class for resolution errors. Subclass of ResolveError
  3524      * represent a different kinds of resolution error - as such they must
  3525      * specify how they map into concrete compiler diagnostics.
  3526      */
  3527     abstract class ResolveError extends Symbol {
  3529         /** The name of the kind of error, for debugging only. */
  3530         final String debugName;
  3532         ResolveError(int kind, String debugName) {
  3533             super(kind, 0, null, null, null);
  3534             this.debugName = debugName;
  3537         @Override
  3538         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
  3539             throw new AssertionError();
  3542         @Override
  3543         public String toString() {
  3544             return debugName;
  3547         @Override
  3548         public boolean exists() {
  3549             return false;
  3552         @Override
  3553         public boolean isStatic() {
  3554             return false;
  3557         /**
  3558          * Create an external representation for this erroneous symbol to be
  3559          * used during attribution - by default this returns the symbol of a
  3560          * brand new error type which stores the original type found
  3561          * during resolution.
  3563          * @param name     the name used during resolution
  3564          * @param location the location from which the symbol is accessed
  3565          */
  3566         protected Symbol access(Name name, TypeSymbol location) {
  3567             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  3570         /**
  3571          * Create a diagnostic representing this resolution error.
  3573          * @param dkind     The kind of the diagnostic to be created (e.g error).
  3574          * @param pos       The position to be used for error reporting.
  3575          * @param site      The original type from where the selection took place.
  3576          * @param name      The name of the symbol to be resolved.
  3577          * @param argtypes  The invocation's value arguments,
  3578          *                  if we looked for a method.
  3579          * @param typeargtypes  The invocation's type arguments,
  3580          *                      if we looked for a method.
  3581          */
  3582         abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3583                 DiagnosticPosition pos,
  3584                 Symbol location,
  3585                 Type site,
  3586                 Name name,
  3587                 List<Type> argtypes,
  3588                 List<Type> typeargtypes);
  3591     /**
  3592      * This class is the root class of all resolution errors caused by
  3593      * an invalid symbol being found during resolution.
  3594      */
  3595     abstract class InvalidSymbolError extends ResolveError {
  3597         /** The invalid symbol found during resolution */
  3598         Symbol sym;
  3600         InvalidSymbolError(int kind, Symbol sym, String debugName) {
  3601             super(kind, debugName);
  3602             this.sym = sym;
  3605         @Override
  3606         public boolean exists() {
  3607             return true;
  3610         @Override
  3611         public String toString() {
  3612              return super.toString() + " wrongSym=" + sym;
  3615         @Override
  3616         public Symbol access(Name name, TypeSymbol location) {
  3617             if ((sym.kind & ERRONEOUS) == 0 && (sym.kind & TYP) != 0)
  3618                 return types.createErrorType(name, location, sym.type).tsym;
  3619             else
  3620                 return sym;
  3624     /**
  3625      * InvalidSymbolError error class indicating that a symbol matching a
  3626      * given name does not exists in a given site.
  3627      */
  3628     class SymbolNotFoundError extends ResolveError {
  3630         SymbolNotFoundError(int kind) {
  3631             this(kind, "symbol not found error");
  3634         SymbolNotFoundError(int kind, String debugName) {
  3635             super(kind, debugName);
  3638         @Override
  3639         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3640                 DiagnosticPosition pos,
  3641                 Symbol location,
  3642                 Type site,
  3643                 Name name,
  3644                 List<Type> argtypes,
  3645                 List<Type> typeargtypes) {
  3646             argtypes = argtypes == null ? List.<Type>nil() : argtypes;
  3647             typeargtypes = typeargtypes == null ? List.<Type>nil() : typeargtypes;
  3648             if (name == names.error)
  3649                 return null;
  3651             if (syms.operatorNames.contains(name)) {
  3652                 boolean isUnaryOp = argtypes.size() == 1;
  3653                 String key = argtypes.size() == 1 ?
  3654                     "operator.cant.be.applied" :
  3655                     "operator.cant.be.applied.1";
  3656                 Type first = argtypes.head;
  3657                 Type second = !isUnaryOp ? argtypes.tail.head : null;
  3658                 return diags.create(dkind, log.currentSource(), pos,
  3659                         key, name, first, second);
  3661             boolean hasLocation = false;
  3662             if (location == null) {
  3663                 location = site.tsym;
  3665             if (!location.name.isEmpty()) {
  3666                 if (location.kind == PCK && !site.tsym.exists()) {
  3667                     return diags.create(dkind, log.currentSource(), pos,
  3668                         "doesnt.exist", location);
  3670                 hasLocation = !location.name.equals(names._this) &&
  3671                         !location.name.equals(names._super);
  3673             boolean isConstructor = (kind == ABSENT_MTH || kind == WRONG_STATICNESS) &&
  3674                     name == names.init;
  3675             KindName kindname = isConstructor ? KindName.CONSTRUCTOR : absentKind(kind);
  3676             Name idname = isConstructor ? site.tsym.name : name;
  3677             String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation);
  3678             if (hasLocation) {
  3679                 return diags.create(dkind, log.currentSource(), pos,
  3680                         errKey, kindname, idname, //symbol kindname, name
  3681                         typeargtypes, args(argtypes), //type parameters and arguments (if any)
  3682                         getLocationDiag(location, site)); //location kindname, type
  3684             else {
  3685                 return diags.create(dkind, log.currentSource(), pos,
  3686                         errKey, kindname, idname, //symbol kindname, name
  3687                         typeargtypes, args(argtypes)); //type parameters and arguments (if any)
  3690         //where
  3691         private Object args(List<Type> args) {
  3692             return args.isEmpty() ? args : methodArguments(args);
  3695         private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) {
  3696             String key = "cant.resolve";
  3697             String suffix = hasLocation ? ".location" : "";
  3698             switch (kindname) {
  3699                 case METHOD:
  3700                 case CONSTRUCTOR: {
  3701                     suffix += ".args";
  3702                     suffix += hasTypeArgs ? ".params" : "";
  3705             return key + suffix;
  3707         private JCDiagnostic getLocationDiag(Symbol location, Type site) {
  3708             if (location.kind == VAR) {
  3709                 return diags.fragment("location.1",
  3710                     kindName(location),
  3711                     location,
  3712                     location.type);
  3713             } else {
  3714                 return diags.fragment("location",
  3715                     typeKindName(site),
  3716                     site,
  3717                     null);
  3722     /**
  3723      * InvalidSymbolError error class indicating that a given symbol
  3724      * (either a method, a constructor or an operand) is not applicable
  3725      * given an actual arguments/type argument list.
  3726      */
  3727     class InapplicableSymbolError extends ResolveError {
  3729         protected MethodResolutionContext resolveContext;
  3731         InapplicableSymbolError(MethodResolutionContext context) {
  3732             this(WRONG_MTH, "inapplicable symbol error", context);
  3735         protected InapplicableSymbolError(int kind, String debugName, MethodResolutionContext context) {
  3736             super(kind, debugName);
  3737             this.resolveContext = context;
  3740         @Override
  3741         public String toString() {
  3742             return super.toString();
  3745         @Override
  3746         public boolean exists() {
  3747             return true;
  3750         @Override
  3751         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3752                 DiagnosticPosition pos,
  3753                 Symbol location,
  3754                 Type site,
  3755                 Name name,
  3756                 List<Type> argtypes,
  3757                 List<Type> typeargtypes) {
  3758             if (name == names.error)
  3759                 return null;
  3761             if (syms.operatorNames.contains(name)) {
  3762                 boolean isUnaryOp = argtypes.size() == 1;
  3763                 String key = argtypes.size() == 1 ?
  3764                     "operator.cant.be.applied" :
  3765                     "operator.cant.be.applied.1";
  3766                 Type first = argtypes.head;
  3767                 Type second = !isUnaryOp ? argtypes.tail.head : null;
  3768                 return diags.create(dkind, log.currentSource(), pos,
  3769                         key, name, first, second);
  3771             else {
  3772                 Pair<Symbol, JCDiagnostic> c = errCandidate();
  3773                 if (compactMethodDiags) {
  3774                     for (Map.Entry<Template, DiagnosticRewriter> _entry :
  3775                             MethodResolutionDiagHelper.rewriters.entrySet()) {
  3776                         if (_entry.getKey().matches(c.snd)) {
  3777                             JCDiagnostic simpleDiag =
  3778                                     _entry.getValue().rewriteDiagnostic(diags, pos,
  3779                                         log.currentSource(), dkind, c.snd);
  3780                             simpleDiag.setFlag(DiagnosticFlag.COMPRESSED);
  3781                             return simpleDiag;
  3785                 Symbol ws = c.fst.asMemberOf(site, types);
  3786                 return diags.create(dkind, log.currentSource(), pos,
  3787                           "cant.apply.symbol",
  3788                           kindName(ws),
  3789                           ws.name == names.init ? ws.owner.name : ws.name,
  3790                           methodArguments(ws.type.getParameterTypes()),
  3791                           methodArguments(argtypes),
  3792                           kindName(ws.owner),
  3793                           ws.owner.type,
  3794                           c.snd);
  3798         @Override
  3799         public Symbol access(Name name, TypeSymbol location) {
  3800             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  3803         protected Pair<Symbol, JCDiagnostic> errCandidate() {
  3804             Candidate bestSoFar = null;
  3805             for (Candidate c : resolveContext.candidates) {
  3806                 if (c.isApplicable()) continue;
  3807                 bestSoFar = c;
  3809             Assert.checkNonNull(bestSoFar);
  3810             return new Pair<Symbol, JCDiagnostic>(bestSoFar.sym, bestSoFar.details);
  3814     /**
  3815      * ResolveError error class indicating that a set of symbols
  3816      * (either methods, constructors or operands) is not applicable
  3817      * given an actual arguments/type argument list.
  3818      */
  3819     class InapplicableSymbolsError extends InapplicableSymbolError {
  3821         InapplicableSymbolsError(MethodResolutionContext context) {
  3822             super(WRONG_MTHS, "inapplicable symbols", context);
  3825         @Override
  3826         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3827                 DiagnosticPosition pos,
  3828                 Symbol location,
  3829                 Type site,
  3830                 Name name,
  3831                 List<Type> argtypes,
  3832                 List<Type> typeargtypes) {
  3833             Map<Symbol, JCDiagnostic> candidatesMap = mapCandidates();
  3834             Map<Symbol, JCDiagnostic> filteredCandidates = compactMethodDiags ?
  3835                     filterCandidates(candidatesMap) :
  3836                     mapCandidates();
  3837             if (filteredCandidates.isEmpty()) {
  3838                 filteredCandidates = candidatesMap;
  3840             boolean truncatedDiag = candidatesMap.size() != filteredCandidates.size();
  3841             if (filteredCandidates.size() > 1) {
  3842                 JCDiagnostic err = diags.create(dkind,
  3843                         null,
  3844                         truncatedDiag ?
  3845                             EnumSet.of(DiagnosticFlag.COMPRESSED) :
  3846                             EnumSet.noneOf(DiagnosticFlag.class),
  3847                         log.currentSource(),
  3848                         pos,
  3849                         "cant.apply.symbols",
  3850                         name == names.init ? KindName.CONSTRUCTOR : absentKind(kind),
  3851                         name == names.init ? site.tsym.name : name,
  3852                         methodArguments(argtypes));
  3853                 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(filteredCandidates, site));
  3854             } else if (filteredCandidates.size() == 1) {
  3855                 Map.Entry<Symbol, JCDiagnostic> _e =
  3856                                 filteredCandidates.entrySet().iterator().next();
  3857                 final Pair<Symbol, JCDiagnostic> p = new Pair<Symbol, JCDiagnostic>(_e.getKey(), _e.getValue());
  3858                 JCDiagnostic d = new InapplicableSymbolError(resolveContext) {
  3859                     @Override
  3860                     protected Pair<Symbol, JCDiagnostic> errCandidate() {
  3861                         return p;
  3863                 }.getDiagnostic(dkind, pos,
  3864                     location, site, name, argtypes, typeargtypes);
  3865                 if (truncatedDiag) {
  3866                     d.setFlag(DiagnosticFlag.COMPRESSED);
  3868                 return d;
  3869             } else {
  3870                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
  3871                     location, site, name, argtypes, typeargtypes);
  3874         //where
  3875             private Map<Symbol, JCDiagnostic> mapCandidates() {
  3876                 Map<Symbol, JCDiagnostic> candidates = new LinkedHashMap<Symbol, JCDiagnostic>();
  3877                 for (Candidate c : resolveContext.candidates) {
  3878                     if (c.isApplicable()) continue;
  3879                     candidates.put(c.sym, c.details);
  3881                 return candidates;
  3884             Map<Symbol, JCDiagnostic> filterCandidates(Map<Symbol, JCDiagnostic> candidatesMap) {
  3885                 Map<Symbol, JCDiagnostic> candidates = new LinkedHashMap<Symbol, JCDiagnostic>();
  3886                 for (Map.Entry<Symbol, JCDiagnostic> _entry : candidatesMap.entrySet()) {
  3887                     JCDiagnostic d = _entry.getValue();
  3888                     if (!new Template(MethodCheckDiag.ARITY_MISMATCH.regex()).matches(d)) {
  3889                         candidates.put(_entry.getKey(), d);
  3892                 return candidates;
  3895             private List<JCDiagnostic> candidateDetails(Map<Symbol, JCDiagnostic> candidatesMap, Type site) {
  3896                 List<JCDiagnostic> details = List.nil();
  3897                 for (Map.Entry<Symbol, JCDiagnostic> _entry : candidatesMap.entrySet()) {
  3898                     Symbol sym = _entry.getKey();
  3899                     JCDiagnostic detailDiag = diags.fragment("inapplicable.method",
  3900                             Kinds.kindName(sym),
  3901                             sym.location(site, types),
  3902                             sym.asMemberOf(site, types),
  3903                             _entry.getValue());
  3904                     details = details.prepend(detailDiag);
  3906                 //typically members are visited in reverse order (see Scope)
  3907                 //so we need to reverse the candidate list so that candidates
  3908                 //conform to source order
  3909                 return details;
  3913     /**
  3914      * An InvalidSymbolError error class indicating that a symbol is not
  3915      * accessible from a given site
  3916      */
  3917     class AccessError extends InvalidSymbolError {
  3919         private Env<AttrContext> env;
  3920         private Type site;
  3922         AccessError(Symbol sym) {
  3923             this(null, null, sym);
  3926         AccessError(Env<AttrContext> env, Type site, Symbol sym) {
  3927             super(HIDDEN, sym, "access error");
  3928             this.env = env;
  3929             this.site = site;
  3930             if (debugResolve)
  3931                 log.error("proc.messager", sym + " @ " + site + " is inaccessible.");
  3934         @Override
  3935         public boolean exists() {
  3936             return false;
  3939         @Override
  3940         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3941                 DiagnosticPosition pos,
  3942                 Symbol location,
  3943                 Type site,
  3944                 Name name,
  3945                 List<Type> argtypes,
  3946                 List<Type> typeargtypes) {
  3947             if (sym.owner.type.hasTag(ERROR))
  3948                 return null;
  3950             if (sym.name == names.init && sym.owner != site.tsym) {
  3951                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
  3952                         pos, location, site, name, argtypes, typeargtypes);
  3954             else if ((sym.flags() & PUBLIC) != 0
  3955                 || (env != null && this.site != null
  3956                     && !isAccessible(env, this.site))) {
  3957                 return diags.create(dkind, log.currentSource(),
  3958                         pos, "not.def.access.class.intf.cant.access",
  3959                     sym, sym.location());
  3961             else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) {
  3962                 return diags.create(dkind, log.currentSource(),
  3963                         pos, "report.access", sym,
  3964                         asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
  3965                         sym.location());
  3967             else {
  3968                 return diags.create(dkind, log.currentSource(),
  3969                         pos, "not.def.public.cant.access", sym, sym.location());
  3974     /**
  3975      * InvalidSymbolError error class indicating that an instance member
  3976      * has erroneously been accessed from a static context.
  3977      */
  3978     class StaticError extends InvalidSymbolError {
  3980         StaticError(Symbol sym) {
  3981             super(STATICERR, sym, "static error");
  3984         @Override
  3985         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3986                 DiagnosticPosition pos,
  3987                 Symbol location,
  3988                 Type site,
  3989                 Name name,
  3990                 List<Type> argtypes,
  3991                 List<Type> typeargtypes) {
  3992             Symbol errSym = ((sym.kind == TYP && sym.type.hasTag(CLASS))
  3993                 ? types.erasure(sym.type).tsym
  3994                 : sym);
  3995             return diags.create(dkind, log.currentSource(), pos,
  3996                     "non-static.cant.be.ref", kindName(sym), errSym);
  4000     /**
  4001      * InvalidSymbolError error class indicating that a pair of symbols
  4002      * (either methods, constructors or operands) are ambiguous
  4003      * given an actual arguments/type argument list.
  4004      */
  4005     class AmbiguityError extends ResolveError {
  4007         /** The other maximally specific symbol */
  4008         List<Symbol> ambiguousSyms = List.nil();
  4010         @Override
  4011         public boolean exists() {
  4012             return true;
  4015         AmbiguityError(Symbol sym1, Symbol sym2) {
  4016             super(AMBIGUOUS, "ambiguity error");
  4017             ambiguousSyms = flatten(sym2).appendList(flatten(sym1));
  4020         private List<Symbol> flatten(Symbol sym) {
  4021             if (sym.kind == AMBIGUOUS) {
  4022                 return ((AmbiguityError)sym.baseSymbol()).ambiguousSyms;
  4023             } else {
  4024                 return List.of(sym);
  4028         AmbiguityError addAmbiguousSymbol(Symbol s) {
  4029             ambiguousSyms = ambiguousSyms.prepend(s);
  4030             return this;
  4033         @Override
  4034         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  4035                 DiagnosticPosition pos,
  4036                 Symbol location,
  4037                 Type site,
  4038                 Name name,
  4039                 List<Type> argtypes,
  4040                 List<Type> typeargtypes) {
  4041             List<Symbol> diagSyms = ambiguousSyms.reverse();
  4042             Symbol s1 = diagSyms.head;
  4043             Symbol s2 = diagSyms.tail.head;
  4044             Name sname = s1.name;
  4045             if (sname == names.init) sname = s1.owner.name;
  4046             return diags.create(dkind, log.currentSource(),
  4047                       pos, "ref.ambiguous", sname,
  4048                       kindName(s1),
  4049                       s1,
  4050                       s1.location(site, types),
  4051                       kindName(s2),
  4052                       s2,
  4053                       s2.location(site, types));
  4056         /**
  4057          * If multiple applicable methods are found during overload and none of them
  4058          * is more specific than the others, attempt to merge their signatures.
  4059          */
  4060         Symbol mergeAbstracts(Type site) {
  4061             List<Symbol> ambiguousInOrder = ambiguousSyms.reverse();
  4062             for (Symbol s : ambiguousInOrder) {
  4063                 Type mt = types.memberType(site, s);
  4064                 boolean found = true;
  4065                 List<Type> allThrown = mt.getThrownTypes();
  4066                 for (Symbol s2 : ambiguousInOrder) {
  4067                     Type mt2 = types.memberType(site, s2);
  4068                     if ((s2.flags() & ABSTRACT) == 0 ||
  4069                         !types.overrideEquivalent(mt, mt2) ||
  4070                         !types.isSameTypes(s.erasure(types).getParameterTypes(),
  4071                                        s2.erasure(types).getParameterTypes())) {
  4072                         //ambiguity cannot be resolved
  4073                         return this;
  4075                     Type mst = mostSpecificReturnType(mt, mt2);
  4076                     if (mst == null || mst != mt) {
  4077                         found = false;
  4078                         break;
  4080                     allThrown = chk.intersect(allThrown, mt2.getThrownTypes());
  4082                 if (found) {
  4083                     //all ambiguous methods were abstract and one method had
  4084                     //most specific return type then others
  4085                     return (allThrown == mt.getThrownTypes()) ?
  4086                             s : new MethodSymbol(
  4087                                 s.flags(),
  4088                                 s.name,
  4089                                 types.createMethodTypeWithThrown(s.type, allThrown),
  4090                                 s.owner);
  4093             return this;
  4096         @Override
  4097         protected Symbol access(Name name, TypeSymbol location) {
  4098             Symbol firstAmbiguity = ambiguousSyms.last();
  4099             return firstAmbiguity.kind == TYP ?
  4100                     types.createErrorType(name, location, firstAmbiguity.type).tsym :
  4101                     firstAmbiguity;
  4105     class BadVarargsMethod extends ResolveError {
  4107         ResolveError delegatedError;
  4109         BadVarargsMethod(ResolveError delegatedError) {
  4110             super(delegatedError.kind, "badVarargs");
  4111             this.delegatedError = delegatedError;
  4114         @Override
  4115         public Symbol baseSymbol() {
  4116             return delegatedError.baseSymbol();
  4119         @Override
  4120         protected Symbol access(Name name, TypeSymbol location) {
  4121             return delegatedError.access(name, location);
  4124         @Override
  4125         public boolean exists() {
  4126             return true;
  4129         @Override
  4130         JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
  4131             return delegatedError.getDiagnostic(dkind, pos, location, site, name, argtypes, typeargtypes);
  4135     /**
  4136      * Helper class for method resolution diagnostic simplification.
  4137      * Certain resolution diagnostic are rewritten as simpler diagnostic
  4138      * where the enclosing resolution diagnostic (i.e. 'inapplicable method')
  4139      * is stripped away, as it doesn't carry additional info. The logic
  4140      * for matching a given diagnostic is given in terms of a template
  4141      * hierarchy: a diagnostic template can be specified programmatically,
  4142      * so that only certain diagnostics are matched. Each templete is then
  4143      * associated with a rewriter object that carries out the task of rewtiting
  4144      * the diagnostic to a simpler one.
  4145      */
  4146     static class MethodResolutionDiagHelper {
  4148         /**
  4149          * A diagnostic rewriter transforms a method resolution diagnostic
  4150          * into a simpler one
  4151          */
  4152         interface DiagnosticRewriter {
  4153             JCDiagnostic rewriteDiagnostic(JCDiagnostic.Factory diags,
  4154                     DiagnosticPosition preferedPos, DiagnosticSource preferredSource,
  4155                     DiagnosticType preferredKind, JCDiagnostic d);
  4158         /**
  4159          * A diagnostic template is made up of two ingredients: (i) a regular
  4160          * expression for matching a diagnostic key and (ii) a list of sub-templates
  4161          * for matching diagnostic arguments.
  4162          */
  4163         static class Template {
  4165             /** regex used to match diag key */
  4166             String regex;
  4168             /** templates used to match diagnostic args */
  4169             Template[] subTemplates;
  4171             Template(String key, Template... subTemplates) {
  4172                 this.regex = key;
  4173                 this.subTemplates = subTemplates;
  4176             /**
  4177              * Returns true if the regex matches the diagnostic key and if
  4178              * all diagnostic arguments are matches by corresponding sub-templates.
  4179              */
  4180             boolean matches(Object o) {
  4181                 JCDiagnostic d = (JCDiagnostic)o;
  4182                 Object[] args = d.getArgs();
  4183                 if (!d.getCode().matches(regex) ||
  4184                         subTemplates.length != d.getArgs().length) {
  4185                     return false;
  4187                 for (int i = 0; i < args.length ; i++) {
  4188                     if (!subTemplates[i].matches(args[i])) {
  4189                         return false;
  4192                 return true;
  4196         /** a dummy template that match any diagnostic argument */
  4197         static final Template skip = new Template("") {
  4198             @Override
  4199             boolean matches(Object d) {
  4200                 return true;
  4202         };
  4204         /** rewriter map used for method resolution simplification */
  4205         static final Map<Template, DiagnosticRewriter> rewriters =
  4206                 new LinkedHashMap<Template, DiagnosticRewriter>();
  4208         static {
  4209             String argMismatchRegex = MethodCheckDiag.ARG_MISMATCH.regex();
  4210             rewriters.put(new Template(argMismatchRegex, skip),
  4211                     new DiagnosticRewriter() {
  4212                 @Override
  4213                 public JCDiagnostic rewriteDiagnostic(JCDiagnostic.Factory diags,
  4214                         DiagnosticPosition preferedPos, DiagnosticSource preferredSource,
  4215                         DiagnosticType preferredKind, JCDiagnostic d) {
  4216                     JCDiagnostic cause = (JCDiagnostic)d.getArgs()[0];
  4217                     return diags.create(preferredKind, preferredSource, d.getDiagnosticPosition(),
  4218                             "prob.found.req", cause);
  4220             });
  4224     enum MethodResolutionPhase {
  4225         BASIC(false, false),
  4226         BOX(true, false),
  4227         VARARITY(true, true) {
  4228             @Override
  4229             public Symbol mergeResults(Symbol bestSoFar, Symbol sym) {
  4230                 //Check invariants (see {@code LookupHelper.shouldStop})
  4231                 Assert.check(bestSoFar.kind >= ERRONEOUS && bestSoFar.kind != AMBIGUOUS);
  4232                 if (sym.kind < ERRONEOUS) {
  4233                     //varargs resolution successful
  4234                     return sym;
  4235                 } else {
  4236                     //pick best error
  4237                     switch (bestSoFar.kind) {
  4238                         case WRONG_MTH:
  4239                         case WRONG_MTHS:
  4240                             //Override previous errors if they were caused by argument mismatch.
  4241                             //This generally means preferring current symbols - but we need to pay
  4242                             //attention to the fact that the varargs lookup returns 'less' candidates
  4243                             //than the previous rounds, and adjust that accordingly.
  4244                             switch (sym.kind) {
  4245                                 case WRONG_MTH:
  4246                                     //if the previous round matched more than one method, return that
  4247                                     //result instead
  4248                                     return bestSoFar.kind == WRONG_MTHS ?
  4249                                             bestSoFar : sym;
  4250                                 case ABSENT_MTH:
  4251                                     //do not override erroneous symbol if the arity lookup did not
  4252                                     //match any method
  4253                                     return bestSoFar;
  4254                                 case WRONG_MTHS:
  4255                                 default:
  4256                                     //safe to override
  4257                                     return sym;
  4259                         default:
  4260                             //otherwise, return first error
  4261                             return bestSoFar;
  4265         };
  4267         final boolean isBoxingRequired;
  4268         final boolean isVarargsRequired;
  4270         MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) {
  4271            this.isBoxingRequired = isBoxingRequired;
  4272            this.isVarargsRequired = isVarargsRequired;
  4275         public boolean isBoxingRequired() {
  4276             return isBoxingRequired;
  4279         public boolean isVarargsRequired() {
  4280             return isVarargsRequired;
  4283         public boolean isApplicable(boolean boxingEnabled, boolean varargsEnabled) {
  4284             return (varargsEnabled || !isVarargsRequired) &&
  4285                    (boxingEnabled || !isBoxingRequired);
  4288         public Symbol mergeResults(Symbol prev, Symbol sym) {
  4289             return sym;
  4293     final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
  4295     /**
  4296      * A resolution context is used to keep track of intermediate results of
  4297      * overload resolution, such as list of method that are not applicable
  4298      * (used to generate more precise diagnostics) and so on. Resolution contexts
  4299      * can be nested - this means that when each overload resolution routine should
  4300      * work within the resolution context it created.
  4301      */
  4302     class MethodResolutionContext {
  4304         private List<Candidate> candidates = List.nil();
  4306         MethodResolutionPhase step = null;
  4308         MethodCheck methodCheck = resolveMethodCheck;
  4310         private boolean internalResolution = false;
  4311         private DeferredAttr.AttrMode attrMode = DeferredAttr.AttrMode.SPECULATIVE;
  4313         void addInapplicableCandidate(Symbol sym, JCDiagnostic details) {
  4314             Candidate c = new Candidate(currentResolutionContext.step, sym, details, null);
  4315             candidates = candidates.append(c);
  4318         void addApplicableCandidate(Symbol sym, Type mtype) {
  4319             Candidate c = new Candidate(currentResolutionContext.step, sym, null, mtype);
  4320             candidates = candidates.append(c);
  4323         DeferredAttrContext deferredAttrContext(Symbol sym, InferenceContext inferenceContext, ResultInfo pendingResult, Warner warn) {
  4324             DeferredAttrContext parent = (pendingResult == null)
  4325                 ? deferredAttr.emptyDeferredAttrContext
  4326                 : pendingResult.checkContext.deferredAttrContext();
  4327             return deferredAttr.new DeferredAttrContext(attrMode, sym, step,
  4328                     inferenceContext, parent, warn);
  4331         /**
  4332          * This class represents an overload resolution candidate. There are two
  4333          * kinds of candidates: applicable methods and inapplicable methods;
  4334          * applicable methods have a pointer to the instantiated method type,
  4335          * while inapplicable candidates contain further details about the
  4336          * reason why the method has been considered inapplicable.
  4337          */
  4338         @SuppressWarnings("overrides")
  4339         class Candidate {
  4341             final MethodResolutionPhase step;
  4342             final Symbol sym;
  4343             final JCDiagnostic details;
  4344             final Type mtype;
  4346             private Candidate(MethodResolutionPhase step, Symbol sym, JCDiagnostic details, Type mtype) {
  4347                 this.step = step;
  4348                 this.sym = sym;
  4349                 this.details = details;
  4350                 this.mtype = mtype;
  4353             @Override
  4354             public boolean equals(Object o) {
  4355                 if (o instanceof Candidate) {
  4356                     Symbol s1 = this.sym;
  4357                     Symbol s2 = ((Candidate)o).sym;
  4358                     if  ((s1 != s2 &&
  4359                             (s1.overrides(s2, s1.owner.type.tsym, types, false) ||
  4360                             (s2.overrides(s1, s2.owner.type.tsym, types, false)))) ||
  4361                             ((s1.isConstructor() || s2.isConstructor()) && s1.owner != s2.owner))
  4362                         return true;
  4364                 return false;
  4367             boolean isApplicable() {
  4368                 return mtype != null;
  4372         DeferredAttr.AttrMode attrMode() {
  4373             return attrMode;
  4376         boolean internal() {
  4377             return internalResolution;
  4381     MethodResolutionContext currentResolutionContext = null;

mercurial