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

Fri, 02 May 2014 01:25:26 +0100

author
vromero
date
Fri, 02 May 2014 01:25:26 +0100
changeset 2382
14979dd5e034
parent 2368
0524f786d7e8
child 2384
327122b01a9e
permissions
-rw-r--r--

8030741: Inference: implement eager resolution of return types, consistent with JDK-8028800
Reviewed-by: dlsmith, jjg

     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 allowStructuralMostSpecific;
    99     private final boolean debugResolve;
   100     private final boolean compactMethodDiags;
   101     final EnumSet<VerboseResolutionMode> verboseResolutionMode;
   103     Scope polymorphicSignatureScope;
   105     protected Resolve(Context context) {
   106         context.put(resolveKey, this);
   107         syms = Symtab.instance(context);
   109         varNotFound = new
   110             SymbolNotFoundError(ABSENT_VAR);
   111         methodNotFound = new
   112             SymbolNotFoundError(ABSENT_MTH);
   113         methodWithCorrectStaticnessNotFound = new
   114             SymbolNotFoundError(WRONG_STATICNESS,
   115                 "method found has incorrect staticness");
   116         typeNotFound = new
   117             SymbolNotFoundError(ABSENT_TYP);
   119         names = Names.instance(context);
   120         log = Log.instance(context);
   121         attr = Attr.instance(context);
   122         deferredAttr = DeferredAttr.instance(context);
   123         chk = Check.instance(context);
   124         infer = Infer.instance(context);
   125         reader = ClassReader.instance(context);
   126         treeinfo = TreeInfo.instance(context);
   127         types = Types.instance(context);
   128         diags = JCDiagnostic.Factory.instance(context);
   129         Source source = Source.instance(context);
   130         boxingEnabled = source.allowBoxing();
   131         varargsEnabled = source.allowVarargs();
   132         Options options = Options.instance(context);
   133         debugResolve = options.isSet("debugresolve");
   134         compactMethodDiags = options.isSet(Option.XDIAGS, "compact") ||
   135                 options.isUnset(Option.XDIAGS) && options.isUnset("rawDiagnostics");
   136         verboseResolutionMode = VerboseResolutionMode.getVerboseResolutionMode(options);
   137         Target target = Target.instance(context);
   138         allowMethodHandles = target.hasMethodHandles();
   139         allowStructuralMostSpecific = source.allowStructuralMostSpecific();
   140         polymorphicSignatureScope = new Scope(syms.noSymbol);
   142         inapplicableMethodException = new InapplicableMethodException(diags);
   143     }
   145     /** error symbols, which are returned when resolution fails
   146      */
   147     private final SymbolNotFoundError varNotFound;
   148     private final SymbolNotFoundError methodNotFound;
   149     private final SymbolNotFoundError methodWithCorrectStaticnessNotFound;
   150     private final SymbolNotFoundError typeNotFound;
   152     public static Resolve instance(Context context) {
   153         Resolve instance = context.get(resolveKey);
   154         if (instance == null)
   155             instance = new Resolve(context);
   156         return instance;
   157     }
   159     // <editor-fold defaultstate="collapsed" desc="Verbose resolution diagnostics support">
   160     enum VerboseResolutionMode {
   161         SUCCESS("success"),
   162         FAILURE("failure"),
   163         APPLICABLE("applicable"),
   164         INAPPLICABLE("inapplicable"),
   165         DEFERRED_INST("deferred-inference"),
   166         PREDEF("predef"),
   167         OBJECT_INIT("object-init"),
   168         INTERNAL("internal");
   170         final String opt;
   172         private VerboseResolutionMode(String opt) {
   173             this.opt = opt;
   174         }
   176         static EnumSet<VerboseResolutionMode> getVerboseResolutionMode(Options opts) {
   177             String s = opts.get("verboseResolution");
   178             EnumSet<VerboseResolutionMode> res = EnumSet.noneOf(VerboseResolutionMode.class);
   179             if (s == null) return res;
   180             if (s.contains("all")) {
   181                 res = EnumSet.allOf(VerboseResolutionMode.class);
   182             }
   183             Collection<String> args = Arrays.asList(s.split(","));
   184             for (VerboseResolutionMode mode : values()) {
   185                 if (args.contains(mode.opt)) {
   186                     res.add(mode);
   187                 } else if (args.contains("-" + mode.opt)) {
   188                     res.remove(mode);
   189                 }
   190             }
   191             return res;
   192         }
   193     }
   195     void reportVerboseResolutionDiagnostic(DiagnosticPosition dpos, Name name, Type site,
   196             List<Type> argtypes, List<Type> typeargtypes, Symbol bestSoFar) {
   197         boolean success = bestSoFar.kind < ERRONEOUS;
   199         if (success && !verboseResolutionMode.contains(VerboseResolutionMode.SUCCESS)) {
   200             return;
   201         } else if (!success && !verboseResolutionMode.contains(VerboseResolutionMode.FAILURE)) {
   202             return;
   203         }
   205         if (bestSoFar.name == names.init &&
   206                 bestSoFar.owner == syms.objectType.tsym &&
   207                 !verboseResolutionMode.contains(VerboseResolutionMode.OBJECT_INIT)) {
   208             return; //skip diags for Object constructor resolution
   209         } else if (site == syms.predefClass.type &&
   210                 !verboseResolutionMode.contains(VerboseResolutionMode.PREDEF)) {
   211             return; //skip spurious diags for predef symbols (i.e. operators)
   212         } else if (currentResolutionContext.internalResolution &&
   213                 !verboseResolutionMode.contains(VerboseResolutionMode.INTERNAL)) {
   214             return;
   215         }
   217         int pos = 0;
   218         int mostSpecificPos = -1;
   219         ListBuffer<JCDiagnostic> subDiags = new ListBuffer<>();
   220         for (Candidate c : currentResolutionContext.candidates) {
   221             if (currentResolutionContext.step != c.step ||
   222                     (c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.APPLICABLE)) ||
   223                     (!c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.INAPPLICABLE))) {
   224                 continue;
   225             } else {
   226                 subDiags.append(c.isApplicable() ?
   227                         getVerboseApplicableCandidateDiag(pos, c.sym, c.mtype) :
   228                         getVerboseInapplicableCandidateDiag(pos, c.sym, c.details));
   229                 if (c.sym == bestSoFar)
   230                     mostSpecificPos = pos;
   231                 pos++;
   232             }
   233         }
   234         String key = success ? "verbose.resolve.multi" : "verbose.resolve.multi.1";
   235         List<Type> argtypes2 = Type.map(argtypes,
   236                     deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, bestSoFar, currentResolutionContext.step));
   237         JCDiagnostic main = diags.note(log.currentSource(), dpos, key, name,
   238                 site.tsym, mostSpecificPos, currentResolutionContext.step,
   239                 methodArguments(argtypes2),
   240                 methodArguments(typeargtypes));
   241         JCDiagnostic d = new JCDiagnostic.MultilineDiagnostic(main, subDiags.toList());
   242         log.report(d);
   243     }
   245     JCDiagnostic getVerboseApplicableCandidateDiag(int pos, Symbol sym, Type inst) {
   246         JCDiagnostic subDiag = null;
   247         if (sym.type.hasTag(FORALL)) {
   248             subDiag = diags.fragment("partial.inst.sig", inst);
   249         }
   251         String key = subDiag == null ?
   252                 "applicable.method.found" :
   253                 "applicable.method.found.1";
   255         return diags.fragment(key, pos, sym, subDiag);
   256     }
   258     JCDiagnostic getVerboseInapplicableCandidateDiag(int pos, Symbol sym, JCDiagnostic subDiag) {
   259         return diags.fragment("not.applicable.method.found", pos, sym, subDiag);
   260     }
   261     // </editor-fold>
   263 /* ************************************************************************
   264  * Identifier resolution
   265  *************************************************************************/
   267     /** An environment is "static" if its static level is greater than
   268      *  the one of its outer environment
   269      */
   270     protected static boolean isStatic(Env<AttrContext> env) {
   271         return env.info.staticLevel > env.outer.info.staticLevel;
   272     }
   274     /** An environment is an "initializer" if it is a constructor or
   275      *  an instance initializer.
   276      */
   277     static boolean isInitializer(Env<AttrContext> env) {
   278         Symbol owner = env.info.scope.owner;
   279         return owner.isConstructor() ||
   280             owner.owner.kind == TYP &&
   281             (owner.kind == VAR ||
   282              owner.kind == MTH && (owner.flags() & BLOCK) != 0) &&
   283             (owner.flags() & STATIC) == 0;
   284     }
   286     /** Is class accessible in given evironment?
   287      *  @param env    The current environment.
   288      *  @param c      The class whose accessibility is checked.
   289      */
   290     public boolean isAccessible(Env<AttrContext> env, TypeSymbol c) {
   291         return isAccessible(env, c, false);
   292     }
   294     public boolean isAccessible(Env<AttrContext> env, TypeSymbol c, boolean checkInner) {
   295         boolean isAccessible = false;
   296         switch ((short)(c.flags() & AccessFlags)) {
   297             case PRIVATE:
   298                 isAccessible =
   299                     env.enclClass.sym.outermostClass() ==
   300                     c.owner.outermostClass();
   301                 break;
   302             case 0:
   303                 isAccessible =
   304                     env.toplevel.packge == c.owner // fast special case
   305                     ||
   306                     env.toplevel.packge == c.packge()
   307                     ||
   308                     // Hack: this case is added since synthesized default constructors
   309                     // of anonymous classes should be allowed to access
   310                     // classes which would be inaccessible otherwise.
   311                     env.enclMethod != null &&
   312                     (env.enclMethod.mods.flags & ANONCONSTR) != 0;
   313                 break;
   314             default: // error recovery
   315             case PUBLIC:
   316                 isAccessible = true;
   317                 break;
   318             case PROTECTED:
   319                 isAccessible =
   320                     env.toplevel.packge == c.owner // fast special case
   321                     ||
   322                     env.toplevel.packge == c.packge()
   323                     ||
   324                     isInnerSubClass(env.enclClass.sym, c.owner);
   325                 break;
   326         }
   327         return (checkInner == false || c.type.getEnclosingType() == Type.noType) ?
   328             isAccessible :
   329             isAccessible && isAccessible(env, c.type.getEnclosingType(), checkInner);
   330     }
   331     //where
   332         /** Is given class a subclass of given base class, or an inner class
   333          *  of a subclass?
   334          *  Return null if no such class exists.
   335          *  @param c     The class which is the subclass or is contained in it.
   336          *  @param base  The base class
   337          */
   338         private boolean isInnerSubClass(ClassSymbol c, Symbol base) {
   339             while (c != null && !c.isSubClass(base, types)) {
   340                 c = c.owner.enclClass();
   341             }
   342             return c != null;
   343         }
   345     boolean isAccessible(Env<AttrContext> env, Type t) {
   346         return isAccessible(env, t, false);
   347     }
   349     boolean isAccessible(Env<AttrContext> env, Type t, boolean checkInner) {
   350         return (t.hasTag(ARRAY))
   351             ? isAccessible(env, types.upperBound(types.elemtype(t)))
   352             : isAccessible(env, t.tsym, checkInner);
   353     }
   355     /** Is symbol accessible as a member of given type in given environment?
   356      *  @param env    The current environment.
   357      *  @param site   The type of which the tested symbol is regarded
   358      *                as a member.
   359      *  @param sym    The symbol.
   360      */
   361     public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym) {
   362         return isAccessible(env, site, sym, false);
   363     }
   364     public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym, boolean checkInner) {
   365         if (sym.name == names.init && sym.owner != site.tsym) return false;
   366         switch ((short)(sym.flags() & AccessFlags)) {
   367         case PRIVATE:
   368             return
   369                 (env.enclClass.sym == sym.owner // fast special case
   370                  ||
   371                  env.enclClass.sym.outermostClass() ==
   372                  sym.owner.outermostClass())
   373                 &&
   374                 sym.isInheritedIn(site.tsym, types);
   375         case 0:
   376             return
   377                 (env.toplevel.packge == sym.owner.owner // fast special case
   378                  ||
   379                  env.toplevel.packge == sym.packge())
   380                 &&
   381                 isAccessible(env, site, checkInner)
   382                 &&
   383                 sym.isInheritedIn(site.tsym, types)
   384                 &&
   385                 notOverriddenIn(site, sym);
   386         case PROTECTED:
   387             return
   388                 (env.toplevel.packge == sym.owner.owner // fast special case
   389                  ||
   390                  env.toplevel.packge == sym.packge()
   391                  ||
   392                  isProtectedAccessible(sym, env.enclClass.sym, site)
   393                  ||
   394                  // OK to select instance method or field from 'super' or type name
   395                  // (but type names should be disallowed elsewhere!)
   396                  env.info.selectSuper && (sym.flags() & STATIC) == 0 && sym.kind != TYP)
   397                 &&
   398                 isAccessible(env, site, checkInner)
   399                 &&
   400                 notOverriddenIn(site, sym);
   401         default: // this case includes erroneous combinations as well
   402             return isAccessible(env, site, checkInner) && notOverriddenIn(site, sym);
   403         }
   404     }
   405     //where
   406     /* `sym' is accessible only if not overridden by
   407      * another symbol which is a member of `site'
   408      * (because, if it is overridden, `sym' is not strictly
   409      * speaking a member of `site'). A polymorphic signature method
   410      * cannot be overridden (e.g. MH.invokeExact(Object[])).
   411      */
   412     private boolean notOverriddenIn(Type site, Symbol sym) {
   413         if (sym.kind != MTH || sym.isConstructor() || sym.isStatic())
   414             return true;
   415         else {
   416             Symbol s2 = ((MethodSymbol)sym).implementation(site.tsym, types, true);
   417             return (s2 == null || s2 == sym || sym.owner == s2.owner ||
   418                     !types.isSubSignature(types.memberType(site, s2), types.memberType(site, sym)));
   419         }
   420     }
   421     //where
   422         /** Is given protected symbol accessible if it is selected from given site
   423          *  and the selection takes place in given class?
   424          *  @param sym     The symbol with protected access
   425          *  @param c       The class where the access takes place
   426          *  @site          The type of the qualifier
   427          */
   428         private
   429         boolean isProtectedAccessible(Symbol sym, ClassSymbol c, Type site) {
   430             Type newSite = site.hasTag(TYPEVAR) ? site.getUpperBound() : site;
   431             while (c != null &&
   432                    !(c.isSubClass(sym.owner, types) &&
   433                      (c.flags() & INTERFACE) == 0 &&
   434                      // In JLS 2e 6.6.2.1, the subclass restriction applies
   435                      // only to instance fields and methods -- types are excluded
   436                      // regardless of whether they are declared 'static' or not.
   437                      ((sym.flags() & STATIC) != 0 || sym.kind == TYP || newSite.tsym.isSubClass(c, types))))
   438                 c = c.owner.enclClass();
   439             return c != null;
   440         }
   442     /**
   443      * Performs a recursive scan of a type looking for accessibility problems
   444      * from current attribution environment
   445      */
   446     void checkAccessibleType(Env<AttrContext> env, Type t) {
   447         accessibilityChecker.visit(t, env);
   448     }
   450     /**
   451      * Accessibility type-visitor
   452      */
   453     Types.SimpleVisitor<Void, Env<AttrContext>> accessibilityChecker =
   454             new Types.SimpleVisitor<Void, Env<AttrContext>>() {
   456         void visit(List<Type> ts, Env<AttrContext> env) {
   457             for (Type t : ts) {
   458                 visit(t, env);
   459             }
   460         }
   462         public Void visitType(Type t, Env<AttrContext> env) {
   463             return null;
   464         }
   466         @Override
   467         public Void visitArrayType(ArrayType t, Env<AttrContext> env) {
   468             visit(t.elemtype, env);
   469             return null;
   470         }
   472         @Override
   473         public Void visitClassType(ClassType t, Env<AttrContext> env) {
   474             visit(t.getTypeArguments(), env);
   475             if (!isAccessible(env, t, true)) {
   476                 accessBase(new AccessError(t.tsym), env.tree.pos(), env.enclClass.sym, t, t.tsym.name, true);
   477             }
   478             return null;
   479         }
   481         @Override
   482         public Void visitWildcardType(WildcardType t, Env<AttrContext> env) {
   483             visit(t.type, env);
   484             return null;
   485         }
   487         @Override
   488         public Void visitMethodType(MethodType t, Env<AttrContext> env) {
   489             visit(t.getParameterTypes(), env);
   490             visit(t.getReturnType(), env);
   491             visit(t.getThrownTypes(), env);
   492             return null;
   493         }
   494     };
   496     /** Try to instantiate the type of a method so that it fits
   497      *  given type arguments and argument types. If successful, return
   498      *  the method's instantiated type, else return null.
   499      *  The instantiation will take into account an additional leading
   500      *  formal parameter if the method is an instance method seen as a member
   501      *  of an under determined site. In this case, we treat site as an additional
   502      *  parameter and the parameters of the class containing the method as
   503      *  additional type variables that get instantiated.
   504      *
   505      *  @param env         The current environment
   506      *  @param site        The type of which the method is a member.
   507      *  @param m           The method symbol.
   508      *  @param argtypes    The invocation's given value arguments.
   509      *  @param typeargtypes    The invocation's given type arguments.
   510      *  @param allowBoxing Allow boxing conversions of arguments.
   511      *  @param useVarargs Box trailing arguments into an array for varargs.
   512      */
   513     Type rawInstantiate(Env<AttrContext> env,
   514                         Type site,
   515                         Symbol m,
   516                         ResultInfo resultInfo,
   517                         List<Type> argtypes,
   518                         List<Type> typeargtypes,
   519                         boolean allowBoxing,
   520                         boolean useVarargs,
   521                         Warner warn) throws Infer.InferenceException {
   523         Type mt = types.memberType(site, m);
   524         // tvars is the list of formal type variables for which type arguments
   525         // need to inferred.
   526         List<Type> tvars = List.nil();
   527         if (typeargtypes == null) typeargtypes = List.nil();
   528         if (!mt.hasTag(FORALL) && typeargtypes.nonEmpty()) {
   529             // This is not a polymorphic method, but typeargs are supplied
   530             // which is fine, see JLS 15.12.2.1
   531         } else if (mt.hasTag(FORALL) && typeargtypes.nonEmpty()) {
   532             ForAll pmt = (ForAll) mt;
   533             if (typeargtypes.length() != pmt.tvars.length())
   534                 throw inapplicableMethodException.setMessage("arg.length.mismatch"); // not enough args
   535             // Check type arguments are within bounds
   536             List<Type> formals = pmt.tvars;
   537             List<Type> actuals = typeargtypes;
   538             while (formals.nonEmpty() && actuals.nonEmpty()) {
   539                 List<Type> bounds = types.subst(types.getBounds((TypeVar)formals.head),
   540                                                 pmt.tvars, typeargtypes);
   541                 for (; bounds.nonEmpty(); bounds = bounds.tail)
   542                     if (!types.isSubtypeUnchecked(actuals.head, bounds.head, warn))
   543                         throw inapplicableMethodException.setMessage("explicit.param.do.not.conform.to.bounds",actuals.head, bounds);
   544                 formals = formals.tail;
   545                 actuals = actuals.tail;
   546             }
   547             mt = types.subst(pmt.qtype, pmt.tvars, typeargtypes);
   548         } else if (mt.hasTag(FORALL)) {
   549             ForAll pmt = (ForAll) mt;
   550             List<Type> tvars1 = types.newInstances(pmt.tvars);
   551             tvars = tvars.appendList(tvars1);
   552             mt = types.subst(pmt.qtype, pmt.tvars, tvars1);
   553         }
   555         // find out whether we need to go the slow route via infer
   556         boolean instNeeded = tvars.tail != null; /*inlined: tvars.nonEmpty()*/
   557         for (List<Type> l = argtypes;
   558              l.tail != null/*inlined: l.nonEmpty()*/ && !instNeeded;
   559              l = l.tail) {
   560             if (l.head.hasTag(FORALL)) instNeeded = true;
   561         }
   563         if (instNeeded)
   564             return infer.instantiateMethod(env,
   565                                     tvars,
   566                                     (MethodType)mt,
   567                                     resultInfo,
   568                                     (MethodSymbol)m,
   569                                     argtypes,
   570                                     allowBoxing,
   571                                     useVarargs,
   572                                     currentResolutionContext,
   573                                     warn);
   575         DeferredAttr.DeferredAttrContext dc = currentResolutionContext.deferredAttrContext(m, infer.emptyContext, resultInfo, warn);
   576         currentResolutionContext.methodCheck.argumentsAcceptable(env, dc,
   577                                 argtypes, mt.getParameterTypes(), warn);
   578         dc.complete();
   579         return mt;
   580     }
   582     Type checkMethod(Env<AttrContext> env,
   583                      Type site,
   584                      Symbol m,
   585                      ResultInfo resultInfo,
   586                      List<Type> argtypes,
   587                      List<Type> typeargtypes,
   588                      Warner warn) {
   589         MethodResolutionContext prevContext = currentResolutionContext;
   590         try {
   591             currentResolutionContext = new MethodResolutionContext();
   592             currentResolutionContext.attrMode = DeferredAttr.AttrMode.CHECK;
   593             if (env.tree.hasTag(JCTree.Tag.REFERENCE)) {
   594                 //method/constructor references need special check class
   595                 //to handle inference variables in 'argtypes' (might happen
   596                 //during an unsticking round)
   597                 currentResolutionContext.methodCheck =
   598                         new MethodReferenceCheck(resultInfo.checkContext.inferenceContext());
   599             }
   600             MethodResolutionPhase step = currentResolutionContext.step = env.info.pendingResolutionPhase;
   601             return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
   602                     step.isBoxingRequired(), step.isVarargsRequired(), warn);
   603         }
   604         finally {
   605             currentResolutionContext = prevContext;
   606         }
   607     }
   609     /** Same but returns null instead throwing a NoInstanceException
   610      */
   611     Type instantiate(Env<AttrContext> env,
   612                      Type site,
   613                      Symbol m,
   614                      ResultInfo resultInfo,
   615                      List<Type> argtypes,
   616                      List<Type> typeargtypes,
   617                      boolean allowBoxing,
   618                      boolean useVarargs,
   619                      Warner warn) {
   620         try {
   621             return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
   622                                   allowBoxing, useVarargs, warn);
   623         } catch (InapplicableMethodException ex) {
   624             return null;
   625         }
   626     }
   628     /**
   629      * This interface defines an entry point that should be used to perform a
   630      * method check. A method check usually consist in determining as to whether
   631      * a set of types (actuals) is compatible with another set of types (formals).
   632      * Since the notion of compatibility can vary depending on the circumstances,
   633      * this interfaces allows to easily add new pluggable method check routines.
   634      */
   635     interface MethodCheck {
   636         /**
   637          * Main method check routine. A method check usually consist in determining
   638          * as to whether a set of types (actuals) is compatible with another set of
   639          * types (formals). If an incompatibility is found, an unchecked exception
   640          * is assumed to be thrown.
   641          */
   642         void argumentsAcceptable(Env<AttrContext> env,
   643                                 DeferredAttrContext deferredAttrContext,
   644                                 List<Type> argtypes,
   645                                 List<Type> formals,
   646                                 Warner warn);
   648         /**
   649          * Retrieve the method check object that will be used during a
   650          * most specific check.
   651          */
   652         MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict);
   653     }
   655     /**
   656      * Helper enum defining all method check diagnostics (used by resolveMethodCheck).
   657      */
   658     enum MethodCheckDiag {
   659         /**
   660          * Actuals and formals differs in length.
   661          */
   662         ARITY_MISMATCH("arg.length.mismatch", "infer.arg.length.mismatch"),
   663         /**
   664          * An actual is incompatible with a formal.
   665          */
   666         ARG_MISMATCH("no.conforming.assignment.exists", "infer.no.conforming.assignment.exists"),
   667         /**
   668          * An actual is incompatible with the varargs element type.
   669          */
   670         VARARG_MISMATCH("varargs.argument.mismatch", "infer.varargs.argument.mismatch"),
   671         /**
   672          * The varargs element type is inaccessible.
   673          */
   674         INACCESSIBLE_VARARGS("inaccessible.varargs.type", "inaccessible.varargs.type");
   676         final String basicKey;
   677         final String inferKey;
   679         MethodCheckDiag(String basicKey, String inferKey) {
   680             this.basicKey = basicKey;
   681             this.inferKey = inferKey;
   682         }
   684         String regex() {
   685             return String.format("([a-z]*\\.)*(%s|%s)", basicKey, inferKey);
   686         }
   687     }
   689     /**
   690      * Dummy method check object. All methods are deemed applicable, regardless
   691      * of their formal parameter types.
   692      */
   693     MethodCheck nilMethodCheck = new MethodCheck() {
   694         public void argumentsAcceptable(Env<AttrContext> env, DeferredAttrContext deferredAttrContext, List<Type> argtypes, List<Type> formals, Warner warn) {
   695             //do nothing - method always applicable regardless of actuals
   696         }
   698         public MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict) {
   699             return this;
   700         }
   701     };
   703     /**
   704      * Base class for 'real' method checks. The class defines the logic for
   705      * iterating through formals and actuals and provides and entry point
   706      * that can be used by subclasses in order to define the actual check logic.
   707      */
   708     abstract class AbstractMethodCheck implements MethodCheck {
   709         @Override
   710         public void argumentsAcceptable(final Env<AttrContext> env,
   711                                     DeferredAttrContext deferredAttrContext,
   712                                     List<Type> argtypes,
   713                                     List<Type> formals,
   714                                     Warner warn) {
   715             //should we expand formals?
   716             boolean useVarargs = deferredAttrContext.phase.isVarargsRequired();
   717             List<JCExpression> trees = TreeInfo.args(env.tree);
   719             //inference context used during this method check
   720             InferenceContext inferenceContext = deferredAttrContext.inferenceContext;
   722             Type varargsFormal = useVarargs ? formals.last() : null;
   724             if (varargsFormal == null &&
   725                     argtypes.size() != formals.size()) {
   726                 reportMC(env.tree, MethodCheckDiag.ARITY_MISMATCH, inferenceContext); // not enough args
   727             }
   729             while (argtypes.nonEmpty() && formals.head != varargsFormal) {
   730                 DiagnosticPosition pos = trees != null ? trees.head : null;
   731                 checkArg(pos, false, argtypes.head, formals.head, deferredAttrContext, warn);
   732                 argtypes = argtypes.tail;
   733                 formals = formals.tail;
   734                 trees = trees != null ? trees.tail : trees;
   735             }
   737             if (formals.head != varargsFormal) {
   738                 reportMC(env.tree, MethodCheckDiag.ARITY_MISMATCH, inferenceContext); // not enough args
   739             }
   741             if (useVarargs) {
   742                 //note: if applicability check is triggered by most specific test,
   743                 //the last argument of a varargs is _not_ an array type (see JLS 15.12.2.5)
   744                 final Type elt = types.elemtype(varargsFormal);
   745                 while (argtypes.nonEmpty()) {
   746                     DiagnosticPosition pos = trees != null ? trees.head : null;
   747                     checkArg(pos, true, argtypes.head, elt, deferredAttrContext, warn);
   748                     argtypes = argtypes.tail;
   749                     trees = trees != null ? trees.tail : trees;
   750                 }
   751             }
   752         }
   754         /**
   755          * Does the actual argument conforms to the corresponding formal?
   756          */
   757         abstract void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn);
   759         protected void reportMC(DiagnosticPosition pos, MethodCheckDiag diag, InferenceContext inferenceContext, Object... args) {
   760             boolean inferDiag = inferenceContext != infer.emptyContext;
   761             InapplicableMethodException ex = inferDiag ?
   762                     infer.inferenceException : inapplicableMethodException;
   763             if (inferDiag && (!diag.inferKey.equals(diag.basicKey))) {
   764                 Object[] args2 = new Object[args.length + 1];
   765                 System.arraycopy(args, 0, args2, 1, args.length);
   766                 args2[0] = inferenceContext.inferenceVars();
   767                 args = args2;
   768             }
   769             String key = inferDiag ? diag.inferKey : diag.basicKey;
   770             throw ex.setMessage(diags.create(DiagnosticType.FRAGMENT, log.currentSource(), pos, key, args));
   771         }
   773         public MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict) {
   774             return nilMethodCheck;
   775         }
   777     }
   779     /**
   780      * Arity-based method check. A method is applicable if the number of actuals
   781      * supplied conforms to the method signature.
   782      */
   783     MethodCheck arityMethodCheck = new AbstractMethodCheck() {
   784         @Override
   785         void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn) {
   786             //do nothing - actual always compatible to formals
   787         }
   789         @Override
   790         public String toString() {
   791             return "arityMethodCheck";
   792         }
   793     };
   795     List<Type> dummyArgs(int length) {
   796         ListBuffer<Type> buf = new ListBuffer<>();
   797         for (int i = 0 ; i < length ; i++) {
   798             buf.append(Type.noType);
   799         }
   800         return buf.toList();
   801     }
   803     /**
   804      * Main method applicability routine. Given a list of actual types A,
   805      * a list of formal types F, determines whether the types in A are
   806      * compatible (by method invocation conversion) with the types in F.
   807      *
   808      * Since this routine is shared between overload resolution and method
   809      * type-inference, a (possibly empty) inference context is used to convert
   810      * formal types to the corresponding 'undet' form ahead of a compatibility
   811      * check so that constraints can be propagated and collected.
   812      *
   813      * Moreover, if one or more types in A is a deferred type, this routine uses
   814      * DeferredAttr in order to perform deferred attribution. If one or more actual
   815      * deferred types are stuck, they are placed in a queue and revisited later
   816      * after the remainder of the arguments have been seen. If this is not sufficient
   817      * to 'unstuck' the argument, a cyclic inference error is called out.
   818      *
   819      * A method check handler (see above) is used in order to report errors.
   820      */
   821     MethodCheck resolveMethodCheck = new AbstractMethodCheck() {
   823         @Override
   824         void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn) {
   825             ResultInfo mresult = methodCheckResult(varargs, formal, deferredAttrContext, warn);
   826             mresult.check(pos, actual);
   827         }
   829         @Override
   830         public void argumentsAcceptable(final Env<AttrContext> env,
   831                                     DeferredAttrContext deferredAttrContext,
   832                                     List<Type> argtypes,
   833                                     List<Type> formals,
   834                                     Warner warn) {
   835             super.argumentsAcceptable(env, deferredAttrContext, argtypes, formals, warn);
   836             //should we expand formals?
   837             if (deferredAttrContext.phase.isVarargsRequired()) {
   838                 //check varargs element type accessibility
   839                 varargsAccessible(env, types.elemtype(formals.last()),
   840                         deferredAttrContext.inferenceContext);
   841             }
   842         }
   844         private void varargsAccessible(final Env<AttrContext> env, final Type t, final InferenceContext inferenceContext) {
   845             if (inferenceContext.free(t)) {
   846                 inferenceContext.addFreeTypeListener(List.of(t), new FreeTypeListener() {
   847                     @Override
   848                     public void typesInferred(InferenceContext inferenceContext) {
   849                         varargsAccessible(env, inferenceContext.asInstType(t), inferenceContext);
   850                     }
   851                 });
   852             } else {
   853                 if (!isAccessible(env, t)) {
   854                     Symbol location = env.enclClass.sym;
   855                     reportMC(env.tree, MethodCheckDiag.INACCESSIBLE_VARARGS, inferenceContext, t, Kinds.kindName(location), location);
   856                 }
   857             }
   858         }
   860         private ResultInfo methodCheckResult(final boolean varargsCheck, Type to,
   861                 final DeferredAttr.DeferredAttrContext deferredAttrContext, Warner rsWarner) {
   862             CheckContext checkContext = new MethodCheckContext(!deferredAttrContext.phase.isBoxingRequired(), deferredAttrContext, rsWarner) {
   863                 MethodCheckDiag methodDiag = varargsCheck ?
   864                                  MethodCheckDiag.VARARG_MISMATCH : MethodCheckDiag.ARG_MISMATCH;
   866                 @Override
   867                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
   868                     reportMC(pos, methodDiag, deferredAttrContext.inferenceContext, details);
   869                 }
   870             };
   871             return new MethodResultInfo(to, checkContext);
   872         }
   874         @Override
   875         public MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict) {
   876             return new MostSpecificCheck(strict, actuals);
   877         }
   879         @Override
   880         public String toString() {
   881             return "resolveMethodCheck";
   882         }
   883     };
   885     /**
   886      * This class handles method reference applicability checks; since during
   887      * these checks it's sometime possible to have inference variables on
   888      * the actual argument types list, the method applicability check must be
   889      * extended so that inference variables are 'opened' as needed.
   890      */
   891     class MethodReferenceCheck extends AbstractMethodCheck {
   893         InferenceContext pendingInferenceContext;
   895         MethodReferenceCheck(InferenceContext pendingInferenceContext) {
   896             this.pendingInferenceContext = pendingInferenceContext;
   897         }
   899         @Override
   900         void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn) {
   901             ResultInfo mresult = methodCheckResult(varargs, formal, deferredAttrContext, warn);
   902             mresult.check(pos, actual);
   903         }
   905         private ResultInfo methodCheckResult(final boolean varargsCheck, Type to,
   906                 final DeferredAttr.DeferredAttrContext deferredAttrContext, Warner rsWarner) {
   907             CheckContext checkContext = new MethodCheckContext(!deferredAttrContext.phase.isBoxingRequired(), deferredAttrContext, rsWarner) {
   908                 MethodCheckDiag methodDiag = varargsCheck ?
   909                                  MethodCheckDiag.VARARG_MISMATCH : MethodCheckDiag.ARG_MISMATCH;
   911                 @Override
   912                 public boolean compatible(Type found, Type req, Warner warn) {
   913                     found = pendingInferenceContext.asUndetVar(found);
   914                     if (found.hasTag(UNDETVAR) && req.isPrimitive()) {
   915                         req = types.boxedClass(req).type;
   916                     }
   917                     return super.compatible(found, req, warn);
   918                 }
   920                 @Override
   921                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
   922                     reportMC(pos, methodDiag, deferredAttrContext.inferenceContext, details);
   923                 }
   924             };
   925             return new MethodResultInfo(to, checkContext);
   926         }
   928         @Override
   929         public MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict) {
   930             return new MostSpecificCheck(strict, actuals);
   931         }
   932     };
   934     /**
   935      * Check context to be used during method applicability checks. A method check
   936      * context might contain inference variables.
   937      */
   938     abstract class MethodCheckContext implements CheckContext {
   940         boolean strict;
   941         DeferredAttrContext deferredAttrContext;
   942         Warner rsWarner;
   944         public MethodCheckContext(boolean strict, DeferredAttrContext deferredAttrContext, Warner rsWarner) {
   945            this.strict = strict;
   946            this.deferredAttrContext = deferredAttrContext;
   947            this.rsWarner = rsWarner;
   948         }
   950         public boolean compatible(Type found, Type req, Warner warn) {
   951             return strict ?
   952                     types.isSubtypeUnchecked(found, deferredAttrContext.inferenceContext.asUndetVar(req), warn) :
   953                     types.isConvertible(found, deferredAttrContext.inferenceContext.asUndetVar(req), warn);
   954         }
   956         public void report(DiagnosticPosition pos, JCDiagnostic details) {
   957             throw inapplicableMethodException.setMessage(details);
   958         }
   960         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
   961             return rsWarner;
   962         }
   964         public InferenceContext inferenceContext() {
   965             return deferredAttrContext.inferenceContext;
   966         }
   968         public DeferredAttrContext deferredAttrContext() {
   969             return deferredAttrContext;
   970         }
   972         @Override
   973         public String toString() {
   974             return "MethodReferenceCheck";
   975         }
   977     }
   979     /**
   980      * ResultInfo class to be used during method applicability checks. Check
   981      * for deferred types goes through special path.
   982      */
   983     class MethodResultInfo extends ResultInfo {
   985         public MethodResultInfo(Type pt, CheckContext checkContext) {
   986             attr.super(VAL, pt, checkContext);
   987         }
   989         @Override
   990         protected Type check(DiagnosticPosition pos, Type found) {
   991             if (found.hasTag(DEFERRED)) {
   992                 DeferredType dt = (DeferredType)found;
   993                 return dt.check(this);
   994             } else {
   995                 Type uResult = U(found.baseType());
   996                 Type capturedType = pos == null || pos.getTree() == null ?
   997                         types.capture(uResult) :
   998                         checkContext.inferenceContext()
   999                             .cachedCapture(pos.getTree(), uResult, true);
  1000                 return super.check(pos, chk.checkNonVoid(pos, capturedType));
  1004         /**
  1005          * javac has a long-standing 'simplification' (see 6391995):
  1006          * given an actual argument type, the method check is performed
  1007          * on its upper bound. This leads to inconsistencies when an
  1008          * argument type is checked against itself. For example, given
  1009          * a type-variable T, it is not true that {@code U(T) <: T},
  1010          * so we need to guard against that.
  1011          */
  1012         private Type U(Type found) {
  1013             return found == pt ?
  1014                     found : types.upperBound(found);
  1017         @Override
  1018         protected MethodResultInfo dup(Type newPt) {
  1019             return new MethodResultInfo(newPt, checkContext);
  1022         @Override
  1023         protected ResultInfo dup(CheckContext newContext) {
  1024             return new MethodResultInfo(pt, newContext);
  1028     /**
  1029      * Most specific method applicability routine. Given a list of actual types A,
  1030      * a list of formal types F1, and a list of formal types F2, the routine determines
  1031      * as to whether the types in F1 can be considered more specific than those in F2 w.r.t.
  1032      * argument types A.
  1033      */
  1034     class MostSpecificCheck implements MethodCheck {
  1036         boolean strict;
  1037         List<Type> actuals;
  1039         MostSpecificCheck(boolean strict, List<Type> actuals) {
  1040             this.strict = strict;
  1041             this.actuals = actuals;
  1044         @Override
  1045         public void argumentsAcceptable(final Env<AttrContext> env,
  1046                                     DeferredAttrContext deferredAttrContext,
  1047                                     List<Type> formals1,
  1048                                     List<Type> formals2,
  1049                                     Warner warn) {
  1050             formals2 = adjustArgs(formals2, deferredAttrContext.msym, formals1.length(), deferredAttrContext.phase.isVarargsRequired());
  1051             while (formals2.nonEmpty()) {
  1052                 ResultInfo mresult = methodCheckResult(formals2.head, deferredAttrContext, warn, actuals.head);
  1053                 mresult.check(null, formals1.head);
  1054                 formals1 = formals1.tail;
  1055                 formals2 = formals2.tail;
  1056                 actuals = actuals.isEmpty() ? actuals : actuals.tail;
  1060        /**
  1061         * Create a method check context to be used during the most specific applicability check
  1062         */
  1063         ResultInfo methodCheckResult(Type to, DeferredAttr.DeferredAttrContext deferredAttrContext,
  1064                Warner rsWarner, Type actual) {
  1065            return attr.new ResultInfo(Kinds.VAL, to,
  1066                    new MostSpecificCheckContext(strict, deferredAttrContext, rsWarner, actual));
  1069         /**
  1070          * Subclass of method check context class that implements most specific
  1071          * method conversion. If the actual type under analysis is a deferred type
  1072          * a full blown structural analysis is carried out.
  1073          */
  1074         class MostSpecificCheckContext extends MethodCheckContext {
  1076             Type actual;
  1078             public MostSpecificCheckContext(boolean strict, DeferredAttrContext deferredAttrContext, Warner rsWarner, Type actual) {
  1079                 super(strict, deferredAttrContext, rsWarner);
  1080                 this.actual = actual;
  1083             public boolean compatible(Type found, Type req, Warner warn) {
  1084                 if (!allowStructuralMostSpecific || actual == null) {
  1085                     return super.compatible(found, req, warn);
  1086                 } else {
  1087                     switch (actual.getTag()) {
  1088                         case DEFERRED:
  1089                             DeferredType dt = (DeferredType) actual;
  1090                             DeferredType.SpeculativeCache.Entry e = dt.speculativeCache.get(deferredAttrContext.msym, deferredAttrContext.phase);
  1091                             return (e == null || e.speculativeTree == deferredAttr.stuckTree)
  1092                                     ? super.compatible(found, req, warn) :
  1093                                       mostSpecific(found, req, e.speculativeTree, warn);
  1094                         default:
  1095                             return standaloneMostSpecific(found, req, actual, warn);
  1100             private boolean mostSpecific(Type t, Type s, JCTree tree, Warner warn) {
  1101                 MostSpecificChecker msc = new MostSpecificChecker(t, s, warn);
  1102                 msc.scan(tree);
  1103                 return msc.result;
  1106             boolean polyMostSpecific(Type t1, Type t2, Warner warn) {
  1107                 return (!t1.isPrimitive() && t2.isPrimitive())
  1108                         ? true : super.compatible(t1, t2, warn);
  1111             boolean standaloneMostSpecific(Type t1, Type t2, Type exprType, Warner warn) {
  1112                 return (exprType.isPrimitive() == t1.isPrimitive()
  1113                         && exprType.isPrimitive() != t2.isPrimitive())
  1114                         ? true : super.compatible(t1, t2, warn);
  1117             /**
  1118              * Structural checker for most specific.
  1119              */
  1120             class MostSpecificChecker extends DeferredAttr.PolyScanner {
  1122                 final Type t;
  1123                 final Type s;
  1124                 final Warner warn;
  1125                 boolean result;
  1127                 MostSpecificChecker(Type t, Type s, Warner warn) {
  1128                     this.t = t;
  1129                     this.s = s;
  1130                     this.warn = warn;
  1131                     result = true;
  1134                 @Override
  1135                 void skip(JCTree tree) {
  1136                     result &= standaloneMostSpecific(t, s, tree.type, warn);
  1139                 @Override
  1140                 public void visitConditional(JCConditional tree) {
  1141                     if (tree.polyKind == PolyKind.STANDALONE) {
  1142                         result &= standaloneMostSpecific(t, s, tree.type, warn);
  1143                     } else {
  1144                         super.visitConditional(tree);
  1148                 @Override
  1149                 public void visitApply(JCMethodInvocation tree) {
  1150                     result &= (tree.polyKind == PolyKind.STANDALONE)
  1151                             ? standaloneMostSpecific(t, s, tree.type, warn)
  1152                             : polyMostSpecific(t, s, warn);
  1155                 @Override
  1156                 public void visitNewClass(JCNewClass tree) {
  1157                     result &= (tree.polyKind == PolyKind.STANDALONE)
  1158                             ? standaloneMostSpecific(t, s, tree.type, warn)
  1159                             : polyMostSpecific(t, s, warn);
  1162                 @Override
  1163                 public void visitReference(JCMemberReference tree) {
  1164                     if (types.isFunctionalInterface(t.tsym) &&
  1165                             types.isFunctionalInterface(s.tsym)) {
  1166                         Type desc_t = types.findDescriptorType(t);
  1167                         Type desc_s = types.findDescriptorType(s);
  1168                         if (types.isSameTypes(desc_t.getParameterTypes(),
  1169                                 inferenceContext().asUndetVars(desc_s.getParameterTypes()))) {
  1170                             if (types.asSuper(t, s.tsym) != null ||
  1171                                 types.asSuper(s, t.tsym) != null) {
  1172                                 result &= MostSpecificCheckContext.super.compatible(t, s, warn);
  1173                             } else if (!desc_s.getReturnType().hasTag(VOID)) {
  1174                                 //perform structural comparison
  1175                                 Type ret_t = desc_t.getReturnType();
  1176                                 Type ret_s = desc_s.getReturnType();
  1177                                 result &= ((tree.refPolyKind == PolyKind.STANDALONE)
  1178                                         ? standaloneMostSpecific(ret_t, ret_s, tree.sym.type.getReturnType(), warn)
  1179                                         : polyMostSpecific(ret_t, ret_s, warn));
  1180                             } else {
  1181                                 return;
  1184                     } else {
  1185                         result &= false;
  1189                 @Override
  1190                 public void visitLambda(JCLambda tree) {
  1191                     if (types.isFunctionalInterface(t.tsym) &&
  1192                             types.isFunctionalInterface(s.tsym)) {
  1193                         Type desc_t = types.findDescriptorType(t);
  1194                         Type desc_s = types.findDescriptorType(s);
  1195                         if (types.isSameTypes(desc_t.getParameterTypes(),
  1196                                 inferenceContext().asUndetVars(desc_s.getParameterTypes()))) {
  1197                             if (types.asSuper(t, s.tsym) != null ||
  1198                                 types.asSuper(s, t.tsym) != null) {
  1199                                 result &= MostSpecificCheckContext.super.compatible(t, s, warn);
  1200                             } else if (!desc_s.getReturnType().hasTag(VOID)) {
  1201                                 //perform structural comparison
  1202                                 Type ret_t = desc_t.getReturnType();
  1203                                 Type ret_s = desc_s.getReturnType();
  1204                                 scanLambdaBody(tree, ret_t, ret_s);
  1205                             } else {
  1206                                 return;
  1209                     } else {
  1210                         result &= false;
  1213                 //where
  1215                 void scanLambdaBody(JCLambda lambda, final Type t, final Type s) {
  1216                     if (lambda.getBodyKind() == JCTree.JCLambda.BodyKind.EXPRESSION) {
  1217                         result &= MostSpecificCheckContext.this.mostSpecific(t, s, lambda.body, warn);
  1218                     } else {
  1219                         DeferredAttr.LambdaReturnScanner lambdaScanner =
  1220                                 new DeferredAttr.LambdaReturnScanner() {
  1221                                     @Override
  1222                                     public void visitReturn(JCReturn tree) {
  1223                                         if (tree.expr != null) {
  1224                                             result &= MostSpecificCheckContext.this.mostSpecific(t, s, tree.expr, warn);
  1227                                 };
  1228                         lambdaScanner.scan(lambda.body);
  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) :
  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             //check if m1 is more specific than all ambiguous methods in m2
  1528             AmbiguityError e = (AmbiguityError)m2.baseSymbol();
  1529             for (Symbol s : e.ambiguousSyms) {
  1530                 if (mostSpecific(argtypes, m1, s, env, site, allowBoxing, useVarargs) != m1) {
  1531                     return e.addAmbiguousSymbol(m1);
  1534             return m1;
  1535         default:
  1536             throw new AssertionError();
  1539     //where
  1540     private boolean signatureMoreSpecific(List<Type> actuals, Env<AttrContext> env, Type site, Symbol m1, Symbol m2, boolean allowBoxing, boolean useVarargs) {
  1541         noteWarner.clear();
  1542         int maxLength = Math.max(
  1543                             Math.max(m1.type.getParameterTypes().length(), actuals.length()),
  1544                             m2.type.getParameterTypes().length());
  1545         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  1546         try {
  1547             currentResolutionContext = new MethodResolutionContext();
  1548             currentResolutionContext.step = prevResolutionContext.step;
  1549             currentResolutionContext.methodCheck =
  1550                     prevResolutionContext.methodCheck.mostSpecificCheck(actuals, !allowBoxing);
  1551             Type mst = instantiate(env, site, m2, null,
  1552                     adjustArgs(types.lowerBounds(types.memberType(site, m1).getParameterTypes()), m1, maxLength, useVarargs), null,
  1553                     allowBoxing, useVarargs, noteWarner);
  1554             return mst != null &&
  1555                     !noteWarner.hasLint(Lint.LintCategory.UNCHECKED);
  1556         } finally {
  1557             currentResolutionContext = prevResolutionContext;
  1561     List<Type> adjustArgs(List<Type> args, Symbol msym, int length, boolean allowVarargs) {
  1562         if ((msym.flags() & VARARGS) != 0 && allowVarargs) {
  1563             Type varargsElem = types.elemtype(args.last());
  1564             if (varargsElem == null) {
  1565                 Assert.error("Bad varargs = " + args.last() + " " + msym);
  1567             List<Type> newArgs = args.reverse().tail.prepend(varargsElem).reverse();
  1568             while (newArgs.length() < length) {
  1569                 newArgs = newArgs.append(newArgs.last());
  1571             return newArgs;
  1572         } else {
  1573             return args;
  1576     //where
  1577     Type mostSpecificReturnType(Type mt1, Type mt2) {
  1578         Type rt1 = mt1.getReturnType();
  1579         Type rt2 = mt2.getReturnType();
  1581         if (mt1.hasTag(FORALL) && mt2.hasTag(FORALL)) {
  1582             //if both are generic methods, adjust return type ahead of subtyping check
  1583             rt1 = types.subst(rt1, mt1.getTypeArguments(), mt2.getTypeArguments());
  1585         //first use subtyping, then return type substitutability
  1586         if (types.isSubtype(rt1, rt2)) {
  1587             return mt1;
  1588         } else if (types.isSubtype(rt2, rt1)) {
  1589             return mt2;
  1590         } else if (types.returnTypeSubstitutable(mt1, mt2)) {
  1591             return mt1;
  1592         } else if (types.returnTypeSubstitutable(mt2, mt1)) {
  1593             return mt2;
  1594         } else {
  1595             return null;
  1598     //where
  1599     Symbol ambiguityError(Symbol m1, Symbol m2) {
  1600         if (((m1.flags() | m2.flags()) & CLASH) != 0) {
  1601             return (m1.flags() & CLASH) == 0 ? m1 : m2;
  1602         } else {
  1603             return new AmbiguityError(m1, m2);
  1607     Symbol findMethodInScope(Env<AttrContext> env,
  1608             Type site,
  1609             Name name,
  1610             List<Type> argtypes,
  1611             List<Type> typeargtypes,
  1612             Scope sc,
  1613             Symbol bestSoFar,
  1614             boolean allowBoxing,
  1615             boolean useVarargs,
  1616             boolean operator,
  1617             boolean abstractok) {
  1618         for (Symbol s : sc.getElementsByName(name, new LookupFilter(abstractok))) {
  1619             bestSoFar = selectBest(env, site, argtypes, typeargtypes, s,
  1620                     bestSoFar, allowBoxing, useVarargs, operator);
  1622         return bestSoFar;
  1624     //where
  1625         class LookupFilter implements Filter<Symbol> {
  1627             boolean abstractOk;
  1629             LookupFilter(boolean abstractOk) {
  1630                 this.abstractOk = abstractOk;
  1633             public boolean accepts(Symbol s) {
  1634                 long flags = s.flags();
  1635                 return s.kind == MTH &&
  1636                         (flags & SYNTHETIC) == 0 &&
  1637                         (abstractOk ||
  1638                         (flags & DEFAULT) != 0 ||
  1639                         (flags & ABSTRACT) == 0);
  1641         };
  1643     /** Find best qualified method matching given name, type and value
  1644      *  arguments.
  1645      *  @param env       The current environment.
  1646      *  @param site      The original type from where the selection
  1647      *                   takes place.
  1648      *  @param name      The method's name.
  1649      *  @param argtypes  The method's value arguments.
  1650      *  @param typeargtypes The method's type arguments
  1651      *  @param allowBoxing Allow boxing conversions of arguments.
  1652      *  @param useVarargs Box trailing arguments into an array for varargs.
  1653      */
  1654     Symbol findMethod(Env<AttrContext> env,
  1655                       Type site,
  1656                       Name name,
  1657                       List<Type> argtypes,
  1658                       List<Type> typeargtypes,
  1659                       boolean allowBoxing,
  1660                       boolean useVarargs,
  1661                       boolean operator) {
  1662         Symbol bestSoFar = methodNotFound;
  1663         bestSoFar = findMethod(env,
  1664                           site,
  1665                           name,
  1666                           argtypes,
  1667                           typeargtypes,
  1668                           site.tsym.type,
  1669                           bestSoFar,
  1670                           allowBoxing,
  1671                           useVarargs,
  1672                           operator);
  1673         return bestSoFar;
  1675     // where
  1676     private Symbol findMethod(Env<AttrContext> env,
  1677                               Type site,
  1678                               Name name,
  1679                               List<Type> argtypes,
  1680                               List<Type> typeargtypes,
  1681                               Type intype,
  1682                               Symbol bestSoFar,
  1683                               boolean allowBoxing,
  1684                               boolean useVarargs,
  1685                               boolean operator) {
  1686         @SuppressWarnings({"unchecked","rawtypes"})
  1687         List<Type>[] itypes = (List<Type>[])new List[] { List.<Type>nil(), List.<Type>nil() };
  1688         InterfaceLookupPhase iphase = InterfaceLookupPhase.ABSTRACT_OK;
  1689         for (TypeSymbol s : superclasses(intype)) {
  1690             bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
  1691                     s.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
  1692             if (name == names.init) return bestSoFar;
  1693             iphase = (iphase == null) ? null : iphase.update(s, this);
  1694             if (iphase != null) {
  1695                 for (Type itype : types.interfaces(s.type)) {
  1696                     itypes[iphase.ordinal()] = types.union(types.closure(itype), itypes[iphase.ordinal()]);
  1701         Symbol concrete = bestSoFar.kind < ERR &&
  1702                 (bestSoFar.flags() & ABSTRACT) == 0 ?
  1703                 bestSoFar : methodNotFound;
  1705         for (InterfaceLookupPhase iphase2 : InterfaceLookupPhase.values()) {
  1706             //keep searching for abstract methods
  1707             for (Type itype : itypes[iphase2.ordinal()]) {
  1708                 if (!itype.isInterface()) continue; //skip j.l.Object (included by Types.closure())
  1709                 if (iphase2 == InterfaceLookupPhase.DEFAULT_OK &&
  1710                         (itype.tsym.flags() & DEFAULT) == 0) continue;
  1711                 bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
  1712                         itype.tsym.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
  1713                 if (concrete != bestSoFar &&
  1714                         concrete.kind < ERR  && bestSoFar.kind < ERR &&
  1715                         types.isSubSignature(concrete.type, bestSoFar.type)) {
  1716                     //this is an hack - as javac does not do full membership checks
  1717                     //most specific ends up comparing abstract methods that might have
  1718                     //been implemented by some concrete method in a subclass and,
  1719                     //because of raw override, it is possible for an abstract method
  1720                     //to be more specific than the concrete method - so we need
  1721                     //to explicitly call that out (see CR 6178365)
  1722                     bestSoFar = concrete;
  1726         return bestSoFar;
  1729     enum InterfaceLookupPhase {
  1730         ABSTRACT_OK() {
  1731             @Override
  1732             InterfaceLookupPhase update(Symbol s, Resolve rs) {
  1733                 //We should not look for abstract methods if receiver is a concrete class
  1734                 //(as concrete classes are expected to implement all abstracts coming
  1735                 //from superinterfaces)
  1736                 if ((s.flags() & (ABSTRACT | INTERFACE | ENUM)) != 0) {
  1737                     return this;
  1738                 } else {
  1739                     return DEFAULT_OK;
  1742         },
  1743         DEFAULT_OK() {
  1744             @Override
  1745             InterfaceLookupPhase update(Symbol s, Resolve rs) {
  1746                 return this;
  1748         };
  1750         abstract InterfaceLookupPhase update(Symbol s, Resolve rs);
  1753     /**
  1754      * Return an Iterable object to scan the superclasses of a given type.
  1755      * It's crucial that the scan is done lazily, as we don't want to accidentally
  1756      * access more supertypes than strictly needed (as this could trigger completion
  1757      * errors if some of the not-needed supertypes are missing/ill-formed).
  1758      */
  1759     Iterable<TypeSymbol> superclasses(final Type intype) {
  1760         return new Iterable<TypeSymbol>() {
  1761             public Iterator<TypeSymbol> iterator() {
  1762                 return new Iterator<TypeSymbol>() {
  1764                     List<TypeSymbol> seen = List.nil();
  1765                     TypeSymbol currentSym = symbolFor(intype);
  1766                     TypeSymbol prevSym = null;
  1768                     public boolean hasNext() {
  1769                         if (currentSym == syms.noSymbol) {
  1770                             currentSym = symbolFor(types.supertype(prevSym.type));
  1772                         return currentSym != null;
  1775                     public TypeSymbol next() {
  1776                         prevSym = currentSym;
  1777                         currentSym = syms.noSymbol;
  1778                         Assert.check(prevSym != null || prevSym != syms.noSymbol);
  1779                         return prevSym;
  1782                     public void remove() {
  1783                         throw new UnsupportedOperationException();
  1786                     TypeSymbol symbolFor(Type t) {
  1787                         if (!t.hasTag(CLASS) &&
  1788                                 !t.hasTag(TYPEVAR)) {
  1789                             return null;
  1791                         while (t.hasTag(TYPEVAR))
  1792                             t = t.getUpperBound();
  1793                         if (seen.contains(t.tsym)) {
  1794                             //degenerate case in which we have a circular
  1795                             //class hierarchy - because of ill-formed classfiles
  1796                             return null;
  1798                         seen = seen.prepend(t.tsym);
  1799                         return t.tsym;
  1801                 };
  1803         };
  1806     /** Find unqualified method matching given name, type and value arguments.
  1807      *  @param env       The current environment.
  1808      *  @param name      The method's name.
  1809      *  @param argtypes  The method's value arguments.
  1810      *  @param typeargtypes  The method's type arguments.
  1811      *  @param allowBoxing Allow boxing conversions of arguments.
  1812      *  @param useVarargs Box trailing arguments into an array for varargs.
  1813      */
  1814     Symbol findFun(Env<AttrContext> env, Name name,
  1815                    List<Type> argtypes, List<Type> typeargtypes,
  1816                    boolean allowBoxing, boolean useVarargs) {
  1817         Symbol bestSoFar = methodNotFound;
  1818         Symbol sym;
  1819         Env<AttrContext> env1 = env;
  1820         boolean staticOnly = false;
  1821         while (env1.outer != null) {
  1822             if (isStatic(env1)) staticOnly = true;
  1823             sym = findMethod(
  1824                 env1, env1.enclClass.sym.type, name, argtypes, typeargtypes,
  1825                 allowBoxing, useVarargs, false);
  1826             if (sym.exists()) {
  1827                 if (staticOnly &&
  1828                     sym.kind == MTH &&
  1829                     sym.owner.kind == TYP &&
  1830                     (sym.flags() & STATIC) == 0) return new StaticError(sym);
  1831                 else return sym;
  1832             } else if (sym.kind < bestSoFar.kind) {
  1833                 bestSoFar = sym;
  1835             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  1836             env1 = env1.outer;
  1839         sym = findMethod(env, syms.predefClass.type, name, argtypes,
  1840                          typeargtypes, allowBoxing, useVarargs, false);
  1841         if (sym.exists())
  1842             return sym;
  1844         Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
  1845         for (; e.scope != null; e = e.next()) {
  1846             sym = e.sym;
  1847             Type origin = e.getOrigin().owner.type;
  1848             if (sym.kind == MTH) {
  1849                 if (e.sym.owner.type != origin)
  1850                     sym = sym.clone(e.getOrigin().owner);
  1851                 if (!isAccessible(env, origin, sym))
  1852                     sym = new AccessError(env, origin, sym);
  1853                 bestSoFar = selectBest(env, origin,
  1854                                        argtypes, typeargtypes,
  1855                                        sym, bestSoFar,
  1856                                        allowBoxing, useVarargs, false);
  1859         if (bestSoFar.exists())
  1860             return bestSoFar;
  1862         e = env.toplevel.starImportScope.lookup(name);
  1863         for (; e.scope != null; e = e.next()) {
  1864             sym = e.sym;
  1865             Type origin = e.getOrigin().owner.type;
  1866             if (sym.kind == MTH) {
  1867                 if (e.sym.owner.type != origin)
  1868                     sym = sym.clone(e.getOrigin().owner);
  1869                 if (!isAccessible(env, origin, sym))
  1870                     sym = new AccessError(env, origin, sym);
  1871                 bestSoFar = selectBest(env, origin,
  1872                                        argtypes, typeargtypes,
  1873                                        sym, bestSoFar,
  1874                                        allowBoxing, useVarargs, false);
  1877         return bestSoFar;
  1880     /** Load toplevel or member class with given fully qualified name and
  1881      *  verify that it is accessible.
  1882      *  @param env       The current environment.
  1883      *  @param name      The fully qualified name of the class to be loaded.
  1884      */
  1885     Symbol loadClass(Env<AttrContext> env, Name name) {
  1886         try {
  1887             ClassSymbol c = reader.loadClass(name);
  1888             return isAccessible(env, c) ? c : new AccessError(c);
  1889         } catch (ClassReader.BadClassFile err) {
  1890             throw err;
  1891         } catch (CompletionFailure ex) {
  1892             return typeNotFound;
  1897     /**
  1898      * Find a type declared in a scope (not inherited).  Return null
  1899      * if none is found.
  1900      *  @param env       The current environment.
  1901      *  @param site      The original type from where the selection takes
  1902      *                   place.
  1903      *  @param name      The type's name.
  1904      *  @param c         The class to search for the member type. This is
  1905      *                   always a superclass or implemented interface of
  1906      *                   site's class.
  1907      */
  1908     Symbol findImmediateMemberType(Env<AttrContext> env,
  1909                                    Type site,
  1910                                    Name name,
  1911                                    TypeSymbol c) {
  1912         Scope.Entry e = c.members().lookup(name);
  1913         while (e.scope != null) {
  1914             if (e.sym.kind == TYP) {
  1915                 return isAccessible(env, site, e.sym)
  1916                     ? e.sym
  1917                     : new AccessError(env, site, e.sym);
  1919             e = e.next();
  1921         return typeNotFound;
  1924     /** Find a member type inherited from a superclass or interface.
  1925      *  @param env       The current environment.
  1926      *  @param site      The original type from where the selection takes
  1927      *                   place.
  1928      *  @param name      The type's name.
  1929      *  @param c         The class to search for the member type. This is
  1930      *                   always a superclass or implemented interface of
  1931      *                   site's class.
  1932      */
  1933     Symbol findInheritedMemberType(Env<AttrContext> env,
  1934                                    Type site,
  1935                                    Name name,
  1936                                    TypeSymbol c) {
  1937         Symbol bestSoFar = typeNotFound;
  1938         Symbol sym;
  1939         Type st = types.supertype(c.type);
  1940         if (st != null && st.hasTag(CLASS)) {
  1941             sym = findMemberType(env, site, name, st.tsym);
  1942             if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1944         for (List<Type> l = types.interfaces(c.type);
  1945              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
  1946              l = l.tail) {
  1947             sym = findMemberType(env, site, name, l.head.tsym);
  1948             if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
  1949                 sym.owner != bestSoFar.owner)
  1950                 bestSoFar = new AmbiguityError(bestSoFar, sym);
  1951             else if (sym.kind < bestSoFar.kind)
  1952                 bestSoFar = sym;
  1954         return bestSoFar;
  1957     /** Find qualified member type.
  1958      *  @param env       The current environment.
  1959      *  @param site      The original type from where the selection takes
  1960      *                   place.
  1961      *  @param name      The type's name.
  1962      *  @param c         The class to search for the member type. This is
  1963      *                   always a superclass or implemented interface of
  1964      *                   site's class.
  1965      */
  1966     Symbol findMemberType(Env<AttrContext> env,
  1967                           Type site,
  1968                           Name name,
  1969                           TypeSymbol c) {
  1970         Symbol sym = findImmediateMemberType(env, site, name, c);
  1972         if (sym != typeNotFound)
  1973             return sym;
  1975         return findInheritedMemberType(env, site, name, c);
  1979     /** Find a global type in given scope and load corresponding class.
  1980      *  @param env       The current environment.
  1981      *  @param scope     The scope in which to look for the type.
  1982      *  @param name      The type's name.
  1983      */
  1984     Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name) {
  1985         Symbol bestSoFar = typeNotFound;
  1986         for (Scope.Entry e = scope.lookup(name); e.scope != null; e = e.next()) {
  1987             Symbol sym = loadClass(env, e.sym.flatName());
  1988             if (bestSoFar.kind == TYP && sym.kind == TYP &&
  1989                 bestSoFar != sym)
  1990                 return new AmbiguityError(bestSoFar, sym);
  1991             else if (sym.kind < bestSoFar.kind)
  1992                 bestSoFar = sym;
  1994         return bestSoFar;
  1997     Symbol findTypeVar(Env<AttrContext> env, Name name, boolean staticOnly) {
  1998         for (Scope.Entry e = env.info.scope.lookup(name);
  1999              e.scope != null;
  2000              e = e.next()) {
  2001             if (e.sym.kind == TYP) {
  2002                 if (staticOnly &&
  2003                     e.sym.type.hasTag(TYPEVAR) &&
  2004                     e.sym.owner.kind == TYP)
  2005                     return new StaticError(e.sym);
  2006                 return e.sym;
  2009         return typeNotFound;
  2012     /** Find an unqualified type symbol.
  2013      *  @param env       The current environment.
  2014      *  @param name      The type's name.
  2015      */
  2016     Symbol findType(Env<AttrContext> env, Name name) {
  2017         Symbol bestSoFar = typeNotFound;
  2018         Symbol sym;
  2019         boolean staticOnly = false;
  2020         for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
  2021             if (isStatic(env1)) staticOnly = true;
  2022             // First, look for a type variable and the first member type
  2023             final Symbol tyvar = findTypeVar(env1, name, staticOnly);
  2024             sym = findImmediateMemberType(env1, env1.enclClass.sym.type,
  2025                                           name, env1.enclClass.sym);
  2027             // Return the type variable if we have it, and have no
  2028             // immediate member, OR the type variable is for a method.
  2029             if (tyvar != typeNotFound) {
  2030                 if (sym == typeNotFound ||
  2031                     (tyvar.kind == TYP && tyvar.exists() &&
  2032                      tyvar.owner.kind == MTH))
  2033                     return tyvar;
  2036             // If the environment is a class def, finish up,
  2037             // otherwise, do the entire findMemberType
  2038             if (sym == typeNotFound)
  2039                 sym = findInheritedMemberType(env1, env1.enclClass.sym.type,
  2040                                               name, env1.enclClass.sym);
  2042             if (staticOnly && sym.kind == TYP &&
  2043                 sym.type.hasTag(CLASS) &&
  2044                 sym.type.getEnclosingType().hasTag(CLASS) &&
  2045                 env1.enclClass.sym.type.isParameterized() &&
  2046                 sym.type.getEnclosingType().isParameterized())
  2047                 return new StaticError(sym);
  2048             else if (sym.exists()) return sym;
  2049             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  2051             JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass;
  2052             if ((encl.sym.flags() & STATIC) != 0)
  2053                 staticOnly = true;
  2056         if (!env.tree.hasTag(IMPORT)) {
  2057             sym = findGlobalType(env, env.toplevel.namedImportScope, name);
  2058             if (sym.exists()) return sym;
  2059             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  2061             sym = findGlobalType(env, env.toplevel.packge.members(), name);
  2062             if (sym.exists()) return sym;
  2063             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  2065             sym = findGlobalType(env, env.toplevel.starImportScope, name);
  2066             if (sym.exists()) return sym;
  2067             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  2070         return bestSoFar;
  2073     /** Find an unqualified identifier which matches a specified kind set.
  2074      *  @param env       The current environment.
  2075      *  @param name      The identifier's name.
  2076      *  @param kind      Indicates the possible symbol kinds
  2077      *                   (a subset of VAL, TYP, PCK).
  2078      */
  2079     Symbol findIdent(Env<AttrContext> env, Name name, int kind) {
  2080         Symbol bestSoFar = typeNotFound;
  2081         Symbol sym;
  2083         if ((kind & VAR) != 0) {
  2084             sym = findVar(env, name);
  2085             if (sym.exists()) return sym;
  2086             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  2089         if ((kind & TYP) != 0) {
  2090             sym = findType(env, name);
  2091             if (sym.kind==TYP) {
  2092                  reportDependence(env.enclClass.sym, sym);
  2094             if (sym.exists()) return sym;
  2095             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  2098         if ((kind & PCK) != 0) return reader.enterPackage(name);
  2099         else return bestSoFar;
  2102     /** Report dependencies.
  2103      * @param from The enclosing class sym
  2104      * @param to   The found identifier that the class depends on.
  2105      */
  2106     public void reportDependence(Symbol from, Symbol to) {
  2107         // Override if you want to collect the reported dependencies.
  2110     /** Find an identifier in a package which matches a specified kind set.
  2111      *  @param env       The current environment.
  2112      *  @param name      The identifier's name.
  2113      *  @param kind      Indicates the possible symbol kinds
  2114      *                   (a nonempty subset of TYP, PCK).
  2115      */
  2116     Symbol findIdentInPackage(Env<AttrContext> env, TypeSymbol pck,
  2117                               Name name, int kind) {
  2118         Name fullname = TypeSymbol.formFullName(name, pck);
  2119         Symbol bestSoFar = typeNotFound;
  2120         PackageSymbol pack = null;
  2121         if ((kind & PCK) != 0) {
  2122             pack = reader.enterPackage(fullname);
  2123             if (pack.exists()) return pack;
  2125         if ((kind & TYP) != 0) {
  2126             Symbol sym = loadClass(env, fullname);
  2127             if (sym.exists()) {
  2128                 // don't allow programs to use flatnames
  2129                 if (name == sym.name) return sym;
  2131             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  2133         return (pack != null) ? pack : bestSoFar;
  2136     /** Find an identifier among the members of a given type `site'.
  2137      *  @param env       The current environment.
  2138      *  @param site      The type containing the symbol to be found.
  2139      *  @param name      The identifier's name.
  2140      *  @param kind      Indicates the possible symbol kinds
  2141      *                   (a subset of VAL, TYP).
  2142      */
  2143     Symbol findIdentInType(Env<AttrContext> env, Type site,
  2144                            Name name, int kind) {
  2145         Symbol bestSoFar = typeNotFound;
  2146         Symbol sym;
  2147         if ((kind & VAR) != 0) {
  2148             sym = findField(env, site, name, site.tsym);
  2149             if (sym.exists()) return sym;
  2150             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  2153         if ((kind & TYP) != 0) {
  2154             sym = findMemberType(env, site, name, site.tsym);
  2155             if (sym.exists()) return sym;
  2156             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  2158         return bestSoFar;
  2161 /* ***************************************************************************
  2162  *  Access checking
  2163  *  The following methods convert ResolveErrors to ErrorSymbols, issuing
  2164  *  an error message in the process
  2165  ****************************************************************************/
  2167     /** If `sym' is a bad symbol: report error and return errSymbol
  2168      *  else pass through unchanged,
  2169      *  additional arguments duplicate what has been used in trying to find the
  2170      *  symbol {@literal (--> flyweight pattern)}. This improves performance since we
  2171      *  expect misses to happen frequently.
  2173      *  @param sym       The symbol that was found, or a ResolveError.
  2174      *  @param pos       The position to use for error reporting.
  2175      *  @param location  The symbol the served as a context for this lookup
  2176      *  @param site      The original type from where the selection took place.
  2177      *  @param name      The symbol's name.
  2178      *  @param qualified Did we get here through a qualified expression resolution?
  2179      *  @param argtypes  The invocation's value arguments,
  2180      *                   if we looked for a method.
  2181      *  @param typeargtypes  The invocation's type arguments,
  2182      *                   if we looked for a method.
  2183      *  @param logResolveHelper helper class used to log resolve errors
  2184      */
  2185     Symbol accessInternal(Symbol sym,
  2186                   DiagnosticPosition pos,
  2187                   Symbol location,
  2188                   Type site,
  2189                   Name name,
  2190                   boolean qualified,
  2191                   List<Type> argtypes,
  2192                   List<Type> typeargtypes,
  2193                   LogResolveHelper logResolveHelper) {
  2194         if (sym.kind >= AMBIGUOUS) {
  2195             ResolveError errSym = (ResolveError)sym;
  2196             sym = errSym.access(name, qualified ? site.tsym : syms.noSymbol);
  2197             argtypes = logResolveHelper.getArgumentTypes(errSym, sym, name, argtypes);
  2198             if (logResolveHelper.resolveDiagnosticNeeded(site, argtypes, typeargtypes)) {
  2199                 logResolveError(errSym, pos, location, site, name, argtypes, typeargtypes);
  2202         return sym;
  2205     /**
  2206      * Variant of the generalized access routine, to be used for generating method
  2207      * resolution diagnostics
  2208      */
  2209     Symbol accessMethod(Symbol sym,
  2210                   DiagnosticPosition pos,
  2211                   Symbol location,
  2212                   Type site,
  2213                   Name name,
  2214                   boolean qualified,
  2215                   List<Type> argtypes,
  2216                   List<Type> typeargtypes) {
  2217         return accessInternal(sym, pos, location, site, name, qualified, argtypes, typeargtypes, methodLogResolveHelper);
  2220     /** Same as original accessMethod(), but without location.
  2221      */
  2222     Symbol accessMethod(Symbol sym,
  2223                   DiagnosticPosition pos,
  2224                   Type site,
  2225                   Name name,
  2226                   boolean qualified,
  2227                   List<Type> argtypes,
  2228                   List<Type> typeargtypes) {
  2229         return accessMethod(sym, pos, site.tsym, site, name, qualified, argtypes, typeargtypes);
  2232     /**
  2233      * Variant of the generalized access routine, to be used for generating variable,
  2234      * type resolution diagnostics
  2235      */
  2236     Symbol accessBase(Symbol sym,
  2237                   DiagnosticPosition pos,
  2238                   Symbol location,
  2239                   Type site,
  2240                   Name name,
  2241                   boolean qualified) {
  2242         return accessInternal(sym, pos, location, site, name, qualified, List.<Type>nil(), null, basicLogResolveHelper);
  2245     /** Same as original accessBase(), but without location.
  2246      */
  2247     Symbol accessBase(Symbol sym,
  2248                   DiagnosticPosition pos,
  2249                   Type site,
  2250                   Name name,
  2251                   boolean qualified) {
  2252         return accessBase(sym, pos, site.tsym, site, name, qualified);
  2255     interface LogResolveHelper {
  2256         boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes);
  2257         List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes);
  2260     LogResolveHelper basicLogResolveHelper = new LogResolveHelper() {
  2261         public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
  2262             return !site.isErroneous();
  2264         public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
  2265             return argtypes;
  2267     };
  2269     LogResolveHelper methodLogResolveHelper = new LogResolveHelper() {
  2270         public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
  2271             return !site.isErroneous() &&
  2272                         !Type.isErroneous(argtypes) &&
  2273                         (typeargtypes == null || !Type.isErroneous(typeargtypes));
  2275         public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
  2276             return (syms.operatorNames.contains(name)) ?
  2277                     argtypes :
  2278                     Type.map(argtypes, new ResolveDeferredRecoveryMap(AttrMode.SPECULATIVE, accessedSym, currentResolutionContext.step));
  2280     };
  2282     class ResolveDeferredRecoveryMap extends DeferredAttr.RecoveryDeferredTypeMap {
  2284         public ResolveDeferredRecoveryMap(AttrMode mode, Symbol msym, MethodResolutionPhase step) {
  2285             deferredAttr.super(mode, msym, step);
  2288         @Override
  2289         protected Type typeOf(DeferredType dt) {
  2290             Type res = super.typeOf(dt);
  2291             if (!res.isErroneous()) {
  2292                 switch (TreeInfo.skipParens(dt.tree).getTag()) {
  2293                     case LAMBDA:
  2294                     case REFERENCE:
  2295                         return dt;
  2296                     case CONDEXPR:
  2297                         return res == Type.recoveryType ?
  2298                                 dt : res;
  2301             return res;
  2305     /** Check that sym is not an abstract method.
  2306      */
  2307     void checkNonAbstract(DiagnosticPosition pos, Symbol sym) {
  2308         if ((sym.flags() & ABSTRACT) != 0 && (sym.flags() & DEFAULT) == 0)
  2309             log.error(pos, "abstract.cant.be.accessed.directly",
  2310                       kindName(sym), sym, sym.location());
  2313 /* ***************************************************************************
  2314  *  Debugging
  2315  ****************************************************************************/
  2317     /** print all scopes starting with scope s and proceeding outwards.
  2318      *  used for debugging.
  2319      */
  2320     public void printscopes(Scope s) {
  2321         while (s != null) {
  2322             if (s.owner != null)
  2323                 System.err.print(s.owner + ": ");
  2324             for (Scope.Entry e = s.elems; e != null; e = e.sibling) {
  2325                 if ((e.sym.flags() & ABSTRACT) != 0)
  2326                     System.err.print("abstract ");
  2327                 System.err.print(e.sym + " ");
  2329             System.err.println();
  2330             s = s.next;
  2334     void printscopes(Env<AttrContext> env) {
  2335         while (env.outer != null) {
  2336             System.err.println("------------------------------");
  2337             printscopes(env.info.scope);
  2338             env = env.outer;
  2342     public void printscopes(Type t) {
  2343         while (t.hasTag(CLASS)) {
  2344             printscopes(t.tsym.members());
  2345             t = types.supertype(t);
  2349 /* ***************************************************************************
  2350  *  Name resolution
  2351  *  Naming conventions are as for symbol lookup
  2352  *  Unlike the find... methods these methods will report access errors
  2353  ****************************************************************************/
  2355     /** Resolve an unqualified (non-method) identifier.
  2356      *  @param pos       The position to use for error reporting.
  2357      *  @param env       The environment current at the identifier use.
  2358      *  @param name      The identifier's name.
  2359      *  @param kind      The set of admissible symbol kinds for the identifier.
  2360      */
  2361     Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env,
  2362                         Name name, int kind) {
  2363         return accessBase(
  2364             findIdent(env, name, kind),
  2365             pos, env.enclClass.sym.type, name, false);
  2368     /** Resolve an unqualified method identifier.
  2369      *  @param pos       The position to use for error reporting.
  2370      *  @param env       The environment current at the method invocation.
  2371      *  @param name      The identifier's name.
  2372      *  @param argtypes  The types of the invocation's value arguments.
  2373      *  @param typeargtypes  The types of the invocation's type arguments.
  2374      */
  2375     Symbol resolveMethod(DiagnosticPosition pos,
  2376                          Env<AttrContext> env,
  2377                          Name name,
  2378                          List<Type> argtypes,
  2379                          List<Type> typeargtypes) {
  2380         return lookupMethod(env, pos, env.enclClass.sym, resolveMethodCheck,
  2381                 new BasicLookupHelper(name, env.enclClass.sym.type, argtypes, typeargtypes) {
  2382                     @Override
  2383                     Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2384                         return findFun(env, name, argtypes, typeargtypes,
  2385                                 phase.isBoxingRequired(),
  2386                                 phase.isVarargsRequired());
  2387                     }});
  2390     /** Resolve a qualified method identifier
  2391      *  @param pos       The position to use for error reporting.
  2392      *  @param env       The environment current at the method invocation.
  2393      *  @param site      The type of the qualifying expression, in which
  2394      *                   identifier is searched.
  2395      *  @param name      The identifier's name.
  2396      *  @param argtypes  The types of the invocation's value arguments.
  2397      *  @param typeargtypes  The types of the invocation's type arguments.
  2398      */
  2399     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
  2400                                   Type site, Name name, List<Type> argtypes,
  2401                                   List<Type> typeargtypes) {
  2402         return resolveQualifiedMethod(pos, env, site.tsym, site, name, argtypes, typeargtypes);
  2404     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
  2405                                   Symbol location, Type site, Name name, List<Type> argtypes,
  2406                                   List<Type> typeargtypes) {
  2407         return resolveQualifiedMethod(new MethodResolutionContext(), pos, env, location, site, name, argtypes, typeargtypes);
  2409     private Symbol resolveQualifiedMethod(MethodResolutionContext resolveContext,
  2410                                   DiagnosticPosition pos, Env<AttrContext> env,
  2411                                   Symbol location, Type site, Name name, List<Type> argtypes,
  2412                                   List<Type> typeargtypes) {
  2413         return lookupMethod(env, pos, location, resolveContext, new BasicLookupHelper(name, site, argtypes, typeargtypes) {
  2414             @Override
  2415             Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2416                 return findMethod(env, site, name, argtypes, typeargtypes,
  2417                         phase.isBoxingRequired(),
  2418                         phase.isVarargsRequired(), false);
  2420             @Override
  2421             Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2422                 if (sym.kind >= AMBIGUOUS) {
  2423                     sym = super.access(env, pos, location, sym);
  2424                 } else if (allowMethodHandles) {
  2425                     MethodSymbol msym = (MethodSymbol)sym;
  2426                     if ((msym.flags() & SIGNATURE_POLYMORPHIC) != 0) {
  2427                         return findPolymorphicSignatureInstance(env, sym, argtypes);
  2430                 return sym;
  2432         });
  2435     /** Find or create an implicit method of exactly the given type (after erasure).
  2436      *  Searches in a side table, not the main scope of the site.
  2437      *  This emulates the lookup process required by JSR 292 in JVM.
  2438      *  @param env       Attribution environment
  2439      *  @param spMethod  signature polymorphic method - i.e. MH.invokeExact
  2440      *  @param argtypes  The required argument types
  2441      */
  2442     Symbol findPolymorphicSignatureInstance(Env<AttrContext> env,
  2443                                             final Symbol spMethod,
  2444                                             List<Type> argtypes) {
  2445         Type mtype = infer.instantiatePolymorphicSignatureInstance(env,
  2446                 (MethodSymbol)spMethod, currentResolutionContext, argtypes);
  2447         for (Symbol sym : polymorphicSignatureScope.getElementsByName(spMethod.name)) {
  2448             if (types.isSameType(mtype, sym.type)) {
  2449                return sym;
  2453         // create the desired method
  2454         long flags = ABSTRACT | HYPOTHETICAL | spMethod.flags() & Flags.AccessFlags;
  2455         Symbol msym = new MethodSymbol(flags, spMethod.name, mtype, spMethod.owner) {
  2456             @Override
  2457             public Symbol baseSymbol() {
  2458                 return spMethod;
  2460         };
  2461         polymorphicSignatureScope.enter(msym);
  2462         return msym;
  2465     /** Resolve a qualified method identifier, throw a fatal error if not
  2466      *  found.
  2467      *  @param pos       The position to use for error reporting.
  2468      *  @param env       The environment current at the method invocation.
  2469      *  @param site      The type of the qualifying expression, in which
  2470      *                   identifier is searched.
  2471      *  @param name      The identifier's name.
  2472      *  @param argtypes  The types of the invocation's value arguments.
  2473      *  @param typeargtypes  The types of the invocation's type arguments.
  2474      */
  2475     public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env,
  2476                                         Type site, Name name,
  2477                                         List<Type> argtypes,
  2478                                         List<Type> typeargtypes) {
  2479         MethodResolutionContext resolveContext = new MethodResolutionContext();
  2480         resolveContext.internalResolution = true;
  2481         Symbol sym = resolveQualifiedMethod(resolveContext, pos, env, site.tsym,
  2482                 site, name, argtypes, typeargtypes);
  2483         if (sym.kind == MTH) return (MethodSymbol)sym;
  2484         else throw new FatalError(
  2485                  diags.fragment("fatal.err.cant.locate.meth",
  2486                                 name));
  2489     /** Resolve constructor.
  2490      *  @param pos       The position to use for error reporting.
  2491      *  @param env       The environment current at the constructor invocation.
  2492      *  @param site      The type of class for which a constructor is searched.
  2493      *  @param argtypes  The types of the constructor invocation's value
  2494      *                   arguments.
  2495      *  @param typeargtypes  The types of the constructor invocation's type
  2496      *                   arguments.
  2497      */
  2498     Symbol resolveConstructor(DiagnosticPosition pos,
  2499                               Env<AttrContext> env,
  2500                               Type site,
  2501                               List<Type> argtypes,
  2502                               List<Type> typeargtypes) {
  2503         return resolveConstructor(new MethodResolutionContext(), pos, env, site, argtypes, typeargtypes);
  2506     private Symbol resolveConstructor(MethodResolutionContext resolveContext,
  2507                               final DiagnosticPosition pos,
  2508                               Env<AttrContext> env,
  2509                               Type site,
  2510                               List<Type> argtypes,
  2511                               List<Type> typeargtypes) {
  2512         return lookupMethod(env, pos, site.tsym, resolveContext, new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
  2513             @Override
  2514             Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2515                 return findConstructor(pos, env, site, argtypes, typeargtypes,
  2516                         phase.isBoxingRequired(),
  2517                         phase.isVarargsRequired());
  2519         });
  2522     /** Resolve a constructor, throw a fatal error if not found.
  2523      *  @param pos       The position to use for error reporting.
  2524      *  @param env       The environment current at the method invocation.
  2525      *  @param site      The type to be constructed.
  2526      *  @param argtypes  The types of the invocation's value arguments.
  2527      *  @param typeargtypes  The types of the invocation's type arguments.
  2528      */
  2529     public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  2530                                         Type site,
  2531                                         List<Type> argtypes,
  2532                                         List<Type> typeargtypes) {
  2533         MethodResolutionContext resolveContext = new MethodResolutionContext();
  2534         resolveContext.internalResolution = true;
  2535         Symbol sym = resolveConstructor(resolveContext, pos, env, site, argtypes, typeargtypes);
  2536         if (sym.kind == MTH) return (MethodSymbol)sym;
  2537         else throw new FatalError(
  2538                  diags.fragment("fatal.err.cant.locate.ctor", site));
  2541     Symbol findConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  2542                               Type site, List<Type> argtypes,
  2543                               List<Type> typeargtypes,
  2544                               boolean allowBoxing,
  2545                               boolean useVarargs) {
  2546         Symbol sym = findMethod(env, site,
  2547                                     names.init, argtypes,
  2548                                     typeargtypes, allowBoxing,
  2549                                     useVarargs, false);
  2550         chk.checkDeprecated(pos, env.info.scope.owner, sym);
  2551         return sym;
  2554     /** Resolve constructor using diamond inference.
  2555      *  @param pos       The position to use for error reporting.
  2556      *  @param env       The environment current at the constructor invocation.
  2557      *  @param site      The type of class for which a constructor is searched.
  2558      *                   The scope of this class has been touched in attribution.
  2559      *  @param argtypes  The types of the constructor invocation's value
  2560      *                   arguments.
  2561      *  @param typeargtypes  The types of the constructor invocation's type
  2562      *                   arguments.
  2563      */
  2564     Symbol resolveDiamond(DiagnosticPosition pos,
  2565                               Env<AttrContext> env,
  2566                               Type site,
  2567                               List<Type> argtypes,
  2568                               List<Type> typeargtypes) {
  2569         return lookupMethod(env, pos, site.tsym, resolveMethodCheck,
  2570                 new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
  2571                     @Override
  2572                     Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2573                         return findDiamond(env, site, argtypes, typeargtypes,
  2574                                 phase.isBoxingRequired(),
  2575                                 phase.isVarargsRequired());
  2577                     @Override
  2578                     Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2579                         if (sym.kind >= AMBIGUOUS) {
  2580                             if (sym.kind != WRONG_MTH && sym.kind != WRONG_MTHS) {
  2581                                 sym = super.access(env, pos, location, sym);
  2582                             } else {
  2583                                 final JCDiagnostic details = sym.kind == WRONG_MTH ?
  2584                                                 ((InapplicableSymbolError)sym).errCandidate().snd :
  2585                                                 null;
  2586                                 sym = new InapplicableSymbolError(sym.kind, "diamondError", currentResolutionContext) {
  2587                                     @Override
  2588                                     JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos,
  2589                                             Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
  2590                                         String key = details == null ?
  2591                                             "cant.apply.diamond" :
  2592                                             "cant.apply.diamond.1";
  2593                                         return diags.create(dkind, log.currentSource(), pos, key,
  2594                                                 diags.fragment("diamond", site.tsym), details);
  2596                                 };
  2597                                 sym = accessMethod(sym, pos, site, names.init, true, argtypes, typeargtypes);
  2598                                 env.info.pendingResolutionPhase = currentResolutionContext.step;
  2601                         return sym;
  2602                     }});
  2605     /** This method scans all the constructor symbol in a given class scope -
  2606      *  assuming that the original scope contains a constructor of the kind:
  2607      *  {@code Foo(X x, Y y)}, where X,Y are class type-variables declared in Foo,
  2608      *  a method check is executed against the modified constructor type:
  2609      *  {@code <X,Y>Foo<X,Y>(X x, Y y)}. This is crucial in order to enable diamond
  2610      *  inference. The inferred return type of the synthetic constructor IS
  2611      *  the inferred type for the diamond operator.
  2612      */
  2613     private Symbol findDiamond(Env<AttrContext> env,
  2614                               Type site,
  2615                               List<Type> argtypes,
  2616                               List<Type> typeargtypes,
  2617                               boolean allowBoxing,
  2618                               boolean useVarargs) {
  2619         Symbol bestSoFar = methodNotFound;
  2620         for (Scope.Entry e = site.tsym.members().lookup(names.init);
  2621              e.scope != null;
  2622              e = e.next()) {
  2623             final Symbol sym = e.sym;
  2624             //- System.out.println(" e " + e.sym);
  2625             if (sym.kind == MTH &&
  2626                 (sym.flags_field & SYNTHETIC) == 0) {
  2627                     List<Type> oldParams = e.sym.type.hasTag(FORALL) ?
  2628                             ((ForAll)sym.type).tvars :
  2629                             List.<Type>nil();
  2630                     Type constrType = new ForAll(site.tsym.type.getTypeArguments().appendList(oldParams),
  2631                             types.createMethodTypeWithReturn(sym.type.asMethodType(), site));
  2632                     MethodSymbol newConstr = new MethodSymbol(sym.flags(), names.init, constrType, site.tsym) {
  2633                         @Override
  2634                         public Symbol baseSymbol() {
  2635                             return sym;
  2637                     };
  2638                     bestSoFar = selectBest(env, site, argtypes, typeargtypes,
  2639                             newConstr,
  2640                             bestSoFar,
  2641                             allowBoxing,
  2642                             useVarargs,
  2643                             false);
  2646         return bestSoFar;
  2651     /** Resolve operator.
  2652      *  @param pos       The position to use for error reporting.
  2653      *  @param optag     The tag of the operation tree.
  2654      *  @param env       The environment current at the operation.
  2655      *  @param argtypes  The types of the operands.
  2656      */
  2657     Symbol resolveOperator(DiagnosticPosition pos, JCTree.Tag optag,
  2658                            Env<AttrContext> env, List<Type> argtypes) {
  2659         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  2660         try {
  2661             currentResolutionContext = new MethodResolutionContext();
  2662             Name name = treeinfo.operatorName(optag);
  2663             return lookupMethod(env, pos, syms.predefClass, currentResolutionContext,
  2664                     new BasicLookupHelper(name, syms.predefClass.type, argtypes, null, BOX) {
  2665                 @Override
  2666                 Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2667                     return findMethod(env, site, name, argtypes, typeargtypes,
  2668                             phase.isBoxingRequired(),
  2669                             phase.isVarargsRequired(), true);
  2671                 @Override
  2672                 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2673                     return accessMethod(sym, pos, env.enclClass.sym.type, name,
  2674                           false, argtypes, null);
  2676             });
  2677         } finally {
  2678             currentResolutionContext = prevResolutionContext;
  2682     /** Resolve operator.
  2683      *  @param pos       The position to use for error reporting.
  2684      *  @param optag     The tag of the operation tree.
  2685      *  @param env       The environment current at the operation.
  2686      *  @param arg       The type of the operand.
  2687      */
  2688     Symbol resolveUnaryOperator(DiagnosticPosition pos, JCTree.Tag optag, Env<AttrContext> env, Type arg) {
  2689         return resolveOperator(pos, optag, env, List.of(arg));
  2692     /** Resolve binary operator.
  2693      *  @param pos       The position to use for error reporting.
  2694      *  @param optag     The tag of the operation tree.
  2695      *  @param env       The environment current at the operation.
  2696      *  @param left      The types of the left operand.
  2697      *  @param right     The types of the right operand.
  2698      */
  2699     Symbol resolveBinaryOperator(DiagnosticPosition pos,
  2700                                  JCTree.Tag optag,
  2701                                  Env<AttrContext> env,
  2702                                  Type left,
  2703                                  Type right) {
  2704         return resolveOperator(pos, optag, env, List.of(left, right));
  2707     Symbol getMemberReference(DiagnosticPosition pos,
  2708             Env<AttrContext> env,
  2709             JCMemberReference referenceTree,
  2710             Type site,
  2711             Name name) {
  2713         site = types.capture(site);
  2715         ReferenceLookupHelper lookupHelper = makeReferenceLookupHelper(
  2716                 referenceTree, site, name, List.<Type>nil(), null, VARARITY);
  2718         Env<AttrContext> newEnv = env.dup(env.tree, env.info.dup());
  2719         Symbol sym = lookupMethod(newEnv, env.tree.pos(), site.tsym,
  2720                 nilMethodCheck, lookupHelper);
  2722         env.info.pendingResolutionPhase = newEnv.info.pendingResolutionPhase;
  2724         return sym;
  2727     ReferenceLookupHelper makeReferenceLookupHelper(JCMemberReference referenceTree,
  2728                                   Type site,
  2729                                   Name name,
  2730                                   List<Type> argtypes,
  2731                                   List<Type> typeargtypes,
  2732                                   MethodResolutionPhase maxPhase) {
  2733         ReferenceLookupHelper result;
  2734         if (!name.equals(names.init)) {
  2735             //method reference
  2736             result =
  2737                     new MethodReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
  2738         } else {
  2739             if (site.hasTag(ARRAY)) {
  2740                 //array constructor reference
  2741                 result =
  2742                         new ArrayConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase);
  2743             } else {
  2744                 //class constructor reference
  2745                 result =
  2746                         new ConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase);
  2749         return result;
  2752     Symbol resolveMemberReferenceByArity(Env<AttrContext> env,
  2753                                   JCMemberReference referenceTree,
  2754                                   Type site,
  2755                                   Name name,
  2756                                   List<Type> argtypes,
  2757                                   InferenceContext inferenceContext) {
  2759         boolean isStaticSelector = TreeInfo.isStaticSelector(referenceTree.expr, names);
  2760         site = types.capture(site);
  2762         ReferenceLookupHelper boundLookupHelper = makeReferenceLookupHelper(
  2763                 referenceTree, site, name, argtypes, null, VARARITY);
  2764         //step 1 - bound lookup
  2765         Env<AttrContext> boundEnv = env.dup(env.tree, env.info.dup());
  2766         Symbol boundSym = lookupMethod(boundEnv, env.tree.pos(), site.tsym,
  2767                 arityMethodCheck, boundLookupHelper);
  2768         if (isStaticSelector &&
  2769             !name.equals(names.init) &&
  2770             !boundSym.isStatic() &&
  2771             boundSym.kind < ERRONEOUS) {
  2772             boundSym = methodNotFound;
  2775         //step 2 - unbound lookup
  2776         Symbol unboundSym = methodNotFound;
  2777         ReferenceLookupHelper unboundLookupHelper = null;
  2778         Env<AttrContext> unboundEnv = env.dup(env.tree, env.info.dup());
  2779         if (isStaticSelector) {
  2780             unboundLookupHelper = boundLookupHelper.unboundLookup(inferenceContext);
  2781             unboundSym = lookupMethod(unboundEnv, env.tree.pos(), site.tsym,
  2782                     arityMethodCheck, unboundLookupHelper);
  2783             if (unboundSym.isStatic() &&
  2784                 unboundSym.kind < ERRONEOUS) {
  2785                 unboundSym = methodNotFound;
  2789         //merge results
  2790         Symbol bestSym = choose(boundSym, unboundSym);
  2791         env.info.pendingResolutionPhase = bestSym == unboundSym ?
  2792                 unboundEnv.info.pendingResolutionPhase :
  2793                 boundEnv.info.pendingResolutionPhase;
  2795         return bestSym;
  2798     /**
  2799      * Resolution of member references is typically done as a single
  2800      * overload resolution step, where the argument types A are inferred from
  2801      * the target functional descriptor.
  2803      * If the member reference is a method reference with a type qualifier,
  2804      * a two-step lookup process is performed. The first step uses the
  2805      * expected argument list A, while the second step discards the first
  2806      * type from A (which is treated as a receiver type).
  2808      * There are two cases in which inference is performed: (i) if the member
  2809      * reference is a constructor reference and the qualifier type is raw - in
  2810      * which case diamond inference is used to infer a parameterization for the
  2811      * type qualifier; (ii) if the member reference is an unbound reference
  2812      * where the type qualifier is raw - in that case, during the unbound lookup
  2813      * the receiver argument type is used to infer an instantiation for the raw
  2814      * qualifier type.
  2816      * When a multi-step resolution process is exploited, it is an error
  2817      * if two candidates are found (ambiguity).
  2819      * This routine returns a pair (T,S), where S is the member reference symbol,
  2820      * and T is the type of the class in which S is defined. This is necessary as
  2821      * the type T might be dynamically inferred (i.e. if constructor reference
  2822      * has a raw qualifier).
  2823      */
  2824     Pair<Symbol, ReferenceLookupHelper> resolveMemberReference(Env<AttrContext> env,
  2825                                   JCMemberReference referenceTree,
  2826                                   Type site,
  2827                                   Name name,
  2828                                   List<Type> argtypes,
  2829                                   List<Type> typeargtypes,
  2830                                   MethodCheck methodCheck,
  2831                                   InferenceContext inferenceContext,
  2832                                   AttrMode mode) {
  2834         site = types.capture(site);
  2835         ReferenceLookupHelper boundLookupHelper = makeReferenceLookupHelper(
  2836                 referenceTree, site, name, argtypes, typeargtypes, VARARITY);
  2838         //step 1 - bound lookup
  2839         Env<AttrContext> boundEnv = env.dup(env.tree, env.info.dup());
  2840         Symbol origBoundSym;
  2841         boolean staticErrorForBound = false;
  2842         MethodResolutionContext boundSearchResolveContext = new MethodResolutionContext();
  2843         boundSearchResolveContext.methodCheck = methodCheck;
  2844         Symbol boundSym = origBoundSym = lookupMethod(boundEnv, env.tree.pos(),
  2845                 site.tsym, boundSearchResolveContext, boundLookupHelper);
  2846         SearchResultKind boundSearchResultKind = SearchResultKind.NOT_APPLICABLE_MATCH;
  2847         boolean isStaticSelector = TreeInfo.isStaticSelector(referenceTree.expr, names);
  2848         boolean shouldCheckForStaticness = isStaticSelector &&
  2849                 referenceTree.getMode() == ReferenceMode.INVOKE;
  2850         if (boundSym.kind != WRONG_MTHS && boundSym.kind != WRONG_MTH) {
  2851             if (shouldCheckForStaticness) {
  2852                 if (!boundSym.isStatic()) {
  2853                     staticErrorForBound = true;
  2854                     if (hasAnotherApplicableMethod(
  2855                             boundSearchResolveContext, boundSym, true)) {
  2856                         boundSearchResultKind = SearchResultKind.BAD_MATCH_MORE_SPECIFIC;
  2857                     } else {
  2858                         boundSearchResultKind = SearchResultKind.BAD_MATCH;
  2859                         if (boundSym.kind < ERRONEOUS) {
  2860                             boundSym = methodWithCorrectStaticnessNotFound;
  2863                 } else if (boundSym.kind < ERRONEOUS) {
  2864                     boundSearchResultKind = SearchResultKind.GOOD_MATCH;
  2869         //step 2 - unbound lookup
  2870         Symbol origUnboundSym = null;
  2871         Symbol unboundSym = methodNotFound;
  2872         ReferenceLookupHelper unboundLookupHelper = null;
  2873         Env<AttrContext> unboundEnv = env.dup(env.tree, env.info.dup());
  2874         SearchResultKind unboundSearchResultKind = SearchResultKind.NOT_APPLICABLE_MATCH;
  2875         boolean staticErrorForUnbound = false;
  2876         if (isStaticSelector) {
  2877             unboundLookupHelper = boundLookupHelper.unboundLookup(inferenceContext);
  2878             MethodResolutionContext unboundSearchResolveContext =
  2879                     new MethodResolutionContext();
  2880             unboundSearchResolveContext.methodCheck = methodCheck;
  2881             unboundSym = origUnboundSym = lookupMethod(unboundEnv, env.tree.pos(),
  2882                     site.tsym, unboundSearchResolveContext, unboundLookupHelper);
  2884             if (unboundSym.kind != WRONG_MTH && unboundSym.kind != WRONG_MTHS) {
  2885                 if (shouldCheckForStaticness) {
  2886                     if (unboundSym.isStatic()) {
  2887                         staticErrorForUnbound = true;
  2888                         if (hasAnotherApplicableMethod(
  2889                                 unboundSearchResolveContext, unboundSym, false)) {
  2890                             unboundSearchResultKind = SearchResultKind.BAD_MATCH_MORE_SPECIFIC;
  2891                         } else {
  2892                             unboundSearchResultKind = SearchResultKind.BAD_MATCH;
  2893                             if (unboundSym.kind < ERRONEOUS) {
  2894                                 unboundSym = methodWithCorrectStaticnessNotFound;
  2897                     } else if (unboundSym.kind < ERRONEOUS) {
  2898                         unboundSearchResultKind = SearchResultKind.GOOD_MATCH;
  2904         //merge results
  2905         Pair<Symbol, ReferenceLookupHelper> res;
  2906         Symbol bestSym = choose(boundSym, unboundSym);
  2907         if (bestSym.kind < ERRONEOUS && (staticErrorForBound || staticErrorForUnbound)) {
  2908             if (staticErrorForBound) {
  2909                 boundSym = methodWithCorrectStaticnessNotFound;
  2911             if (staticErrorForUnbound) {
  2912                 unboundSym = methodWithCorrectStaticnessNotFound;
  2914             bestSym = choose(boundSym, unboundSym);
  2916         if (bestSym == methodWithCorrectStaticnessNotFound && mode == AttrMode.CHECK) {
  2917             Symbol symToPrint = origBoundSym;
  2918             String errorFragmentToPrint = "non-static.cant.be.ref";
  2919             if (staticErrorForBound && staticErrorForUnbound) {
  2920                 if (unboundSearchResultKind == SearchResultKind.BAD_MATCH_MORE_SPECIFIC) {
  2921                     symToPrint = origUnboundSym;
  2922                     errorFragmentToPrint = "static.method.in.unbound.lookup";
  2924             } else {
  2925                 if (!staticErrorForBound) {
  2926                     symToPrint = origUnboundSym;
  2927                     errorFragmentToPrint = "static.method.in.unbound.lookup";
  2930             log.error(referenceTree.expr.pos(), "invalid.mref",
  2931                 Kinds.kindName(referenceTree.getMode()),
  2932                 diags.fragment(errorFragmentToPrint,
  2933                 Kinds.kindName(symToPrint), symToPrint));
  2935         res = new Pair<>(bestSym,
  2936                 bestSym == unboundSym ? unboundLookupHelper : boundLookupHelper);
  2937         env.info.pendingResolutionPhase = bestSym == unboundSym ?
  2938                 unboundEnv.info.pendingResolutionPhase :
  2939                 boundEnv.info.pendingResolutionPhase;
  2941         return res;
  2944     enum SearchResultKind {
  2945         GOOD_MATCH,                 //type I
  2946         BAD_MATCH_MORE_SPECIFIC,    //type II
  2947         BAD_MATCH,                  //type III
  2948         NOT_APPLICABLE_MATCH        //type IV
  2951     boolean hasAnotherApplicableMethod(MethodResolutionContext resolutionContext,
  2952             Symbol bestSoFar, boolean staticMth) {
  2953         for (Candidate c : resolutionContext.candidates) {
  2954             if (resolutionContext.step != c.step ||
  2955                 !c.isApplicable() ||
  2956                 c.sym == bestSoFar) {
  2957                 continue;
  2958             } else {
  2959                 if (c.sym.isStatic() == staticMth) {
  2960                     return true;
  2964         return false;
  2967     //where
  2968         private Symbol choose(Symbol boundSym, Symbol unboundSym) {
  2969             if (lookupSuccess(boundSym) && lookupSuccess(unboundSym)) {
  2970                 return ambiguityError(boundSym, unboundSym);
  2971             } else if (lookupSuccess(boundSym) ||
  2972                     (canIgnore(unboundSym) && !canIgnore(boundSym))) {
  2973                 return boundSym;
  2974             } else if (lookupSuccess(unboundSym) ||
  2975                     (canIgnore(boundSym) && !canIgnore(unboundSym))) {
  2976                 return unboundSym;
  2977             } else {
  2978                 return boundSym;
  2982         private boolean lookupSuccess(Symbol s) {
  2983             return s.kind == MTH || s.kind == AMBIGUOUS;
  2986         private boolean canIgnore(Symbol s) {
  2987             switch (s.kind) {
  2988                 case ABSENT_MTH:
  2989                     return true;
  2990                 case WRONG_MTH:
  2991                     InapplicableSymbolError errSym =
  2992                             (InapplicableSymbolError)s;
  2993                     return new Template(MethodCheckDiag.ARITY_MISMATCH.regex())
  2994                             .matches(errSym.errCandidate().snd);
  2995                 case WRONG_MTHS:
  2996                     InapplicableSymbolsError errSyms =
  2997                             (InapplicableSymbolsError)s;
  2998                     return errSyms.filterCandidates(errSyms.mapCandidates()).isEmpty();
  2999                 case WRONG_STATICNESS:
  3000                     return false;
  3001                 default:
  3002                     return false;
  3006     /**
  3007      * Helper for defining custom method-like lookup logic; a lookup helper
  3008      * provides hooks for (i) the actual lookup logic and (ii) accessing the
  3009      * lookup result (this step might result in compiler diagnostics to be generated)
  3010      */
  3011     abstract class LookupHelper {
  3013         /** name of the symbol to lookup */
  3014         Name name;
  3016         /** location in which the lookup takes place */
  3017         Type site;
  3019         /** actual types used during the lookup */
  3020         List<Type> argtypes;
  3022         /** type arguments used during the lookup */
  3023         List<Type> typeargtypes;
  3025         /** Max overload resolution phase handled by this helper */
  3026         MethodResolutionPhase maxPhase;
  3028         LookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  3029             this.name = name;
  3030             this.site = site;
  3031             this.argtypes = argtypes;
  3032             this.typeargtypes = typeargtypes;
  3033             this.maxPhase = maxPhase;
  3036         /**
  3037          * Should lookup stop at given phase with given result
  3038          */
  3039         protected boolean shouldStop(Symbol sym, MethodResolutionPhase phase) {
  3040             return phase.ordinal() > maxPhase.ordinal() ||
  3041                     sym.kind < ERRONEOUS || sym.kind == AMBIGUOUS;
  3044         /**
  3045          * Search for a symbol under a given overload resolution phase - this method
  3046          * is usually called several times, once per each overload resolution phase
  3047          */
  3048         abstract Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase);
  3050         /**
  3051          * Dump overload resolution info
  3052          */
  3053         void debug(DiagnosticPosition pos, Symbol sym) {
  3054             //do nothing
  3057         /**
  3058          * Validate the result of the lookup
  3059          */
  3060         abstract Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym);
  3063     abstract class BasicLookupHelper extends LookupHelper {
  3065         BasicLookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes) {
  3066             this(name, site, argtypes, typeargtypes, MethodResolutionPhase.VARARITY);
  3069         BasicLookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  3070             super(name, site, argtypes, typeargtypes, maxPhase);
  3073         @Override
  3074         final Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  3075             Symbol sym = doLookup(env, phase);
  3076             if (sym.kind == AMBIGUOUS) {
  3077                 AmbiguityError a_err = (AmbiguityError)sym.baseSymbol();
  3078                 sym = a_err.mergeAbstracts(site);
  3080             return sym;
  3083         abstract Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase);
  3085         @Override
  3086         Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  3087             if (sym.kind >= AMBIGUOUS) {
  3088                 //if nothing is found return the 'first' error
  3089                 sym = accessMethod(sym, pos, location, site, name, true, argtypes, typeargtypes);
  3091             return sym;
  3094         @Override
  3095         void debug(DiagnosticPosition pos, Symbol sym) {
  3096             reportVerboseResolutionDiagnostic(pos, name, site, argtypes, typeargtypes, sym);
  3100     /**
  3101      * Helper class for member reference lookup. A reference lookup helper
  3102      * defines the basic logic for member reference lookup; a method gives
  3103      * access to an 'unbound' helper used to perform an unbound member
  3104      * reference lookup.
  3105      */
  3106     abstract class ReferenceLookupHelper extends LookupHelper {
  3108         /** The member reference tree */
  3109         JCMemberReference referenceTree;
  3111         ReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
  3112                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  3113             super(name, site, argtypes, typeargtypes, maxPhase);
  3114             this.referenceTree = referenceTree;
  3117         /**
  3118          * Returns an unbound version of this lookup helper. By default, this
  3119          * method returns an dummy lookup helper.
  3120          */
  3121         ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
  3122             //dummy loopkup helper that always return 'methodNotFound'
  3123             return new ReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase) {
  3124                 @Override
  3125                 ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
  3126                     return this;
  3128                 @Override
  3129                 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  3130                     return methodNotFound;
  3132                 @Override
  3133                 ReferenceKind referenceKind(Symbol sym) {
  3134                     Assert.error();
  3135                     return null;
  3137             };
  3140         /**
  3141          * Get the kind of the member reference
  3142          */
  3143         abstract JCMemberReference.ReferenceKind referenceKind(Symbol sym);
  3145         Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  3146             if (sym.kind == AMBIGUOUS) {
  3147                 AmbiguityError a_err = (AmbiguityError)sym.baseSymbol();
  3148                 sym = a_err.mergeAbstracts(site);
  3150             //skip error reporting
  3151             return sym;
  3155     /**
  3156      * Helper class for method reference lookup. The lookup logic is based
  3157      * upon Resolve.findMethod; in certain cases, this helper class has a
  3158      * corresponding unbound helper class (see UnboundMethodReferenceLookupHelper).
  3159      * In such cases, non-static lookup results are thrown away.
  3160      */
  3161     class MethodReferenceLookupHelper extends ReferenceLookupHelper {
  3163         MethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
  3164                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  3165             super(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
  3168         @Override
  3169         final Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  3170             return findMethod(env, site, name, argtypes, typeargtypes,
  3171                     phase.isBoxingRequired(), phase.isVarargsRequired(), syms.operatorNames.contains(name));
  3174         @Override
  3175         ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
  3176             if (TreeInfo.isStaticSelector(referenceTree.expr, names) &&
  3177                     argtypes.nonEmpty() &&
  3178                     (argtypes.head.hasTag(NONE) ||
  3179                     types.isSubtypeUnchecked(inferenceContext.asUndetVar(argtypes.head), site))) {
  3180                 return new UnboundMethodReferenceLookupHelper(referenceTree, name,
  3181                         site, argtypes, typeargtypes, maxPhase);
  3182             } else {
  3183                 return super.unboundLookup(inferenceContext);
  3187         @Override
  3188         ReferenceKind referenceKind(Symbol sym) {
  3189             if (sym.isStatic()) {
  3190                 return ReferenceKind.STATIC;
  3191             } else {
  3192                 Name selName = TreeInfo.name(referenceTree.getQualifierExpression());
  3193                 return selName != null && selName == names._super ?
  3194                         ReferenceKind.SUPER :
  3195                         ReferenceKind.BOUND;
  3200     /**
  3201      * Helper class for unbound method reference lookup. Essentially the same
  3202      * as the basic method reference lookup helper; main difference is that static
  3203      * lookup results are thrown away. If qualifier type is raw, an attempt to
  3204      * infer a parameterized type is made using the first actual argument (that
  3205      * would otherwise be ignored during the lookup).
  3206      */
  3207     class UnboundMethodReferenceLookupHelper extends MethodReferenceLookupHelper {
  3209         UnboundMethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
  3210                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  3211             super(referenceTree, name, site, argtypes.tail, typeargtypes, maxPhase);
  3212             if (site.isRaw() && !argtypes.head.hasTag(NONE)) {
  3213                 Type asSuperSite = types.asSuper(argtypes.head, site.tsym);
  3214                 this.site = asSuperSite;
  3218         @Override
  3219         ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
  3220             return this;
  3223         @Override
  3224         ReferenceKind referenceKind(Symbol sym) {
  3225             return ReferenceKind.UNBOUND;
  3229     /**
  3230      * Helper class for array constructor lookup; an array constructor lookup
  3231      * is simulated by looking up a method that returns the array type specified
  3232      * as qualifier, and that accepts a single int parameter (size of the array).
  3233      */
  3234     class ArrayConstructorReferenceLookupHelper extends ReferenceLookupHelper {
  3236         ArrayConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
  3237                 List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  3238             super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase);
  3241         @Override
  3242         protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  3243             Scope sc = new Scope(syms.arrayClass);
  3244             MethodSymbol arrayConstr = new MethodSymbol(PUBLIC, name, null, site.tsym);
  3245             arrayConstr.type = new MethodType(List.<Type>of(syms.intType), site, List.<Type>nil(), syms.methodClass);
  3246             sc.enter(arrayConstr);
  3247             return findMethodInScope(env, site, name, argtypes, typeargtypes, sc, methodNotFound, phase.isBoxingRequired(), phase.isVarargsRequired(), false, false);
  3250         @Override
  3251         ReferenceKind referenceKind(Symbol sym) {
  3252             return ReferenceKind.ARRAY_CTOR;
  3256     /**
  3257      * Helper class for constructor reference lookup. The lookup logic is based
  3258      * upon either Resolve.findMethod or Resolve.findDiamond - depending on
  3259      * whether the constructor reference needs diamond inference (this is the case
  3260      * if the qualifier type is raw). A special erroneous symbol is returned
  3261      * if the lookup returns the constructor of an inner class and there's no
  3262      * enclosing instance in scope.
  3263      */
  3264     class ConstructorReferenceLookupHelper extends ReferenceLookupHelper {
  3266         boolean needsInference;
  3268         ConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
  3269                 List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  3270             super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase);
  3271             if (site.isRaw()) {
  3272                 this.site = new ClassType(site.getEnclosingType(), site.tsym.type.getTypeArguments(), site.tsym);
  3273                 needsInference = true;
  3277         @Override
  3278         protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  3279             Symbol sym = needsInference ?
  3280                 findDiamond(env, site, argtypes, typeargtypes, phase.isBoxingRequired(), phase.isVarargsRequired()) :
  3281                 findMethod(env, site, name, argtypes, typeargtypes,
  3282                         phase.isBoxingRequired(), phase.isVarargsRequired(), syms.operatorNames.contains(name));
  3283             return sym.kind != MTH ||
  3284                           site.getEnclosingType().hasTag(NONE) ||
  3285                           hasEnclosingInstance(env, site) ?
  3286                           sym : new InvalidSymbolError(Kinds.MISSING_ENCL, sym, null) {
  3287                     @Override
  3288                     JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
  3289                        return diags.create(dkind, log.currentSource(), pos,
  3290                             "cant.access.inner.cls.constr", site.tsym.name, argtypes, site.getEnclosingType());
  3292                 };
  3295         @Override
  3296         ReferenceKind referenceKind(Symbol sym) {
  3297             return site.getEnclosingType().hasTag(NONE) ?
  3298                     ReferenceKind.TOPLEVEL : ReferenceKind.IMPLICIT_INNER;
  3302     /**
  3303      * Main overload resolution routine. On each overload resolution step, a
  3304      * lookup helper class is used to perform the method/constructor lookup;
  3305      * at the end of the lookup, the helper is used to validate the results
  3306      * (this last step might trigger overload resolution diagnostics).
  3307      */
  3308     Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, MethodCheck methodCheck, LookupHelper lookupHelper) {
  3309         MethodResolutionContext resolveContext = new MethodResolutionContext();
  3310         resolveContext.methodCheck = methodCheck;
  3311         return lookupMethod(env, pos, location, resolveContext, lookupHelper);
  3314     Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location,
  3315             MethodResolutionContext resolveContext, LookupHelper lookupHelper) {
  3316         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  3317         try {
  3318             Symbol bestSoFar = methodNotFound;
  3319             currentResolutionContext = resolveContext;
  3320             for (MethodResolutionPhase phase : methodResolutionSteps) {
  3321                 if (!phase.isApplicable(boxingEnabled, varargsEnabled) ||
  3322                         lookupHelper.shouldStop(bestSoFar, phase)) break;
  3323                 MethodResolutionPhase prevPhase = currentResolutionContext.step;
  3324                 Symbol prevBest = bestSoFar;
  3325                 currentResolutionContext.step = phase;
  3326                 Symbol sym = lookupHelper.lookup(env, phase);
  3327                 lookupHelper.debug(pos, sym);
  3328                 bestSoFar = phase.mergeResults(bestSoFar, sym);
  3329                 env.info.pendingResolutionPhase = (prevBest == bestSoFar) ? prevPhase : phase;
  3331             return lookupHelper.access(env, pos, location, bestSoFar);
  3332         } finally {
  3333             currentResolutionContext = prevResolutionContext;
  3337     /**
  3338      * Resolve `c.name' where name == this or name == super.
  3339      * @param pos           The position to use for error reporting.
  3340      * @param env           The environment current at the expression.
  3341      * @param c             The qualifier.
  3342      * @param name          The identifier's name.
  3343      */
  3344     Symbol resolveSelf(DiagnosticPosition pos,
  3345                        Env<AttrContext> env,
  3346                        TypeSymbol c,
  3347                        Name name) {
  3348         Env<AttrContext> env1 = env;
  3349         boolean staticOnly = false;
  3350         while (env1.outer != null) {
  3351             if (isStatic(env1)) staticOnly = true;
  3352             if (env1.enclClass.sym == c) {
  3353                 Symbol sym = env1.info.scope.lookup(name).sym;
  3354                 if (sym != null) {
  3355                     if (staticOnly) sym = new StaticError(sym);
  3356                     return accessBase(sym, pos, env.enclClass.sym.type,
  3357                                   name, true);
  3360             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  3361             env1 = env1.outer;
  3363         if (c.isInterface() &&
  3364             name == names._super && !isStatic(env) &&
  3365             types.isDirectSuperInterface(c, env.enclClass.sym)) {
  3366             //this might be a default super call if one of the superinterfaces is 'c'
  3367             for (Type t : pruneInterfaces(env.enclClass.type)) {
  3368                 if (t.tsym == c) {
  3369                     env.info.defaultSuperCallSite = t;
  3370                     return new VarSymbol(0, names._super,
  3371                             types.asSuper(env.enclClass.type, c), env.enclClass.sym);
  3374             //find a direct superinterface that is a subtype of 'c'
  3375             for (Type i : types.interfaces(env.enclClass.type)) {
  3376                 if (i.tsym.isSubClass(c, types) && i.tsym != c) {
  3377                     log.error(pos, "illegal.default.super.call", c,
  3378                             diags.fragment("redundant.supertype", c, i));
  3379                     return syms.errSymbol;
  3382             Assert.error();
  3384         log.error(pos, "not.encl.class", c);
  3385         return syms.errSymbol;
  3387     //where
  3388     private List<Type> pruneInterfaces(Type t) {
  3389         ListBuffer<Type> result = new ListBuffer<>();
  3390         for (Type t1 : types.interfaces(t)) {
  3391             boolean shouldAdd = true;
  3392             for (Type t2 : types.interfaces(t)) {
  3393                 if (t1 != t2 && types.isSubtypeNoCapture(t2, t1)) {
  3394                     shouldAdd = false;
  3397             if (shouldAdd) {
  3398                 result.append(t1);
  3401         return result.toList();
  3405     /**
  3406      * Resolve `c.this' for an enclosing class c that contains the
  3407      * named member.
  3408      * @param pos           The position to use for error reporting.
  3409      * @param env           The environment current at the expression.
  3410      * @param member        The member that must be contained in the result.
  3411      */
  3412     Symbol resolveSelfContaining(DiagnosticPosition pos,
  3413                                  Env<AttrContext> env,
  3414                                  Symbol member,
  3415                                  boolean isSuperCall) {
  3416         Symbol sym = resolveSelfContainingInternal(env, member, isSuperCall);
  3417         if (sym == null) {
  3418             log.error(pos, "encl.class.required", member);
  3419             return syms.errSymbol;
  3420         } else {
  3421             return accessBase(sym, pos, env.enclClass.sym.type, sym.name, true);
  3425     boolean hasEnclosingInstance(Env<AttrContext> env, Type type) {
  3426         Symbol encl = resolveSelfContainingInternal(env, type.tsym, false);
  3427         return encl != null && encl.kind < ERRONEOUS;
  3430     private Symbol resolveSelfContainingInternal(Env<AttrContext> env,
  3431                                  Symbol member,
  3432                                  boolean isSuperCall) {
  3433         Name name = names._this;
  3434         Env<AttrContext> env1 = isSuperCall ? env.outer : env;
  3435         boolean staticOnly = false;
  3436         if (env1 != null) {
  3437             while (env1 != null && env1.outer != null) {
  3438                 if (isStatic(env1)) staticOnly = true;
  3439                 if (env1.enclClass.sym.isSubClass(member.owner, types)) {
  3440                     Symbol sym = env1.info.scope.lookup(name).sym;
  3441                     if (sym != null) {
  3442                         if (staticOnly) sym = new StaticError(sym);
  3443                         return sym;
  3446                 if ((env1.enclClass.sym.flags() & STATIC) != 0)
  3447                     staticOnly = true;
  3448                 env1 = env1.outer;
  3451         return null;
  3454     /**
  3455      * Resolve an appropriate implicit this instance for t's container.
  3456      * JLS 8.8.5.1 and 15.9.2
  3457      */
  3458     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
  3459         return resolveImplicitThis(pos, env, t, false);
  3462     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t, boolean isSuperCall) {
  3463         Type thisType = (((t.tsym.owner.kind & (MTH|VAR)) != 0)
  3464                          ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
  3465                          : resolveSelfContaining(pos, env, t.tsym, isSuperCall)).type;
  3466         if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
  3467             log.error(pos, "cant.ref.before.ctor.called", "this");
  3468         return thisType;
  3471 /* ***************************************************************************
  3472  *  ResolveError classes, indicating error situations when accessing symbols
  3473  ****************************************************************************/
  3475     //used by TransTypes when checking target type of synthetic cast
  3476     public void logAccessErrorInternal(Env<AttrContext> env, JCTree tree, Type type) {
  3477         AccessError error = new AccessError(env, env.enclClass.type, type.tsym);
  3478         logResolveError(error, tree.pos(), env.enclClass.sym, env.enclClass.type, null, null, null);
  3480     //where
  3481     private void logResolveError(ResolveError error,
  3482             DiagnosticPosition pos,
  3483             Symbol location,
  3484             Type site,
  3485             Name name,
  3486             List<Type> argtypes,
  3487             List<Type> typeargtypes) {
  3488         JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
  3489                 pos, location, site, name, argtypes, typeargtypes);
  3490         if (d != null) {
  3491             d.setFlag(DiagnosticFlag.RESOLVE_ERROR);
  3492             log.report(d);
  3496     private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
  3498     public Object methodArguments(List<Type> argtypes) {
  3499         if (argtypes == null || argtypes.isEmpty()) {
  3500             return noArgs;
  3501         } else {
  3502             ListBuffer<Object> diagArgs = new ListBuffer<>();
  3503             for (Type t : argtypes) {
  3504                 if (t.hasTag(DEFERRED)) {
  3505                     diagArgs.append(((DeferredAttr.DeferredType)t).tree);
  3506                 } else {
  3507                     diagArgs.append(t);
  3510             return diagArgs;
  3514     /**
  3515      * Root class for resolution errors. Subclass of ResolveError
  3516      * represent a different kinds of resolution error - as such they must
  3517      * specify how they map into concrete compiler diagnostics.
  3518      */
  3519     abstract class ResolveError extends Symbol {
  3521         /** The name of the kind of error, for debugging only. */
  3522         final String debugName;
  3524         ResolveError(int kind, String debugName) {
  3525             super(kind, 0, null, null, null);
  3526             this.debugName = debugName;
  3529         @Override
  3530         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
  3531             throw new AssertionError();
  3534         @Override
  3535         public String toString() {
  3536             return debugName;
  3539         @Override
  3540         public boolean exists() {
  3541             return false;
  3544         @Override
  3545         public boolean isStatic() {
  3546             return false;
  3549         /**
  3550          * Create an external representation for this erroneous symbol to be
  3551          * used during attribution - by default this returns the symbol of a
  3552          * brand new error type which stores the original type found
  3553          * during resolution.
  3555          * @param name     the name used during resolution
  3556          * @param location the location from which the symbol is accessed
  3557          */
  3558         protected Symbol access(Name name, TypeSymbol location) {
  3559             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  3562         /**
  3563          * Create a diagnostic representing this resolution error.
  3565          * @param dkind     The kind of the diagnostic to be created (e.g error).
  3566          * @param pos       The position to be used for error reporting.
  3567          * @param site      The original type from where the selection took place.
  3568          * @param name      The name of the symbol to be resolved.
  3569          * @param argtypes  The invocation's value arguments,
  3570          *                  if we looked for a method.
  3571          * @param typeargtypes  The invocation's type arguments,
  3572          *                      if we looked for a method.
  3573          */
  3574         abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3575                 DiagnosticPosition pos,
  3576                 Symbol location,
  3577                 Type site,
  3578                 Name name,
  3579                 List<Type> argtypes,
  3580                 List<Type> typeargtypes);
  3583     /**
  3584      * This class is the root class of all resolution errors caused by
  3585      * an invalid symbol being found during resolution.
  3586      */
  3587     abstract class InvalidSymbolError extends ResolveError {
  3589         /** The invalid symbol found during resolution */
  3590         Symbol sym;
  3592         InvalidSymbolError(int kind, Symbol sym, String debugName) {
  3593             super(kind, debugName);
  3594             this.sym = sym;
  3597         @Override
  3598         public boolean exists() {
  3599             return true;
  3602         @Override
  3603         public String toString() {
  3604              return super.toString() + " wrongSym=" + sym;
  3607         @Override
  3608         public Symbol access(Name name, TypeSymbol location) {
  3609             if ((sym.kind & ERRONEOUS) == 0 && (sym.kind & TYP) != 0)
  3610                 return types.createErrorType(name, location, sym.type).tsym;
  3611             else
  3612                 return sym;
  3616     /**
  3617      * InvalidSymbolError error class indicating that a symbol matching a
  3618      * given name does not exists in a given site.
  3619      */
  3620     class SymbolNotFoundError extends ResolveError {
  3622         SymbolNotFoundError(int kind) {
  3623             this(kind, "symbol not found error");
  3626         SymbolNotFoundError(int kind, String debugName) {
  3627             super(kind, debugName);
  3630         @Override
  3631         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3632                 DiagnosticPosition pos,
  3633                 Symbol location,
  3634                 Type site,
  3635                 Name name,
  3636                 List<Type> argtypes,
  3637                 List<Type> typeargtypes) {
  3638             argtypes = argtypes == null ? List.<Type>nil() : argtypes;
  3639             typeargtypes = typeargtypes == null ? List.<Type>nil() : typeargtypes;
  3640             if (name == names.error)
  3641                 return null;
  3643             if (syms.operatorNames.contains(name)) {
  3644                 boolean isUnaryOp = argtypes.size() == 1;
  3645                 String key = argtypes.size() == 1 ?
  3646                     "operator.cant.be.applied" :
  3647                     "operator.cant.be.applied.1";
  3648                 Type first = argtypes.head;
  3649                 Type second = !isUnaryOp ? argtypes.tail.head : null;
  3650                 return diags.create(dkind, log.currentSource(), pos,
  3651                         key, name, first, second);
  3653             boolean hasLocation = false;
  3654             if (location == null) {
  3655                 location = site.tsym;
  3657             if (!location.name.isEmpty()) {
  3658                 if (location.kind == PCK && !site.tsym.exists()) {
  3659                     return diags.create(dkind, log.currentSource(), pos,
  3660                         "doesnt.exist", location);
  3662                 hasLocation = !location.name.equals(names._this) &&
  3663                         !location.name.equals(names._super);
  3665             boolean isConstructor = (kind == ABSENT_MTH || kind == WRONG_STATICNESS) &&
  3666                     name == names.init;
  3667             KindName kindname = isConstructor ? KindName.CONSTRUCTOR : absentKind(kind);
  3668             Name idname = isConstructor ? site.tsym.name : name;
  3669             String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation);
  3670             if (hasLocation) {
  3671                 return diags.create(dkind, log.currentSource(), pos,
  3672                         errKey, kindname, idname, //symbol kindname, name
  3673                         typeargtypes, args(argtypes), //type parameters and arguments (if any)
  3674                         getLocationDiag(location, site)); //location kindname, type
  3676             else {
  3677                 return diags.create(dkind, log.currentSource(), pos,
  3678                         errKey, kindname, idname, //symbol kindname, name
  3679                         typeargtypes, args(argtypes)); //type parameters and arguments (if any)
  3682         //where
  3683         private Object args(List<Type> args) {
  3684             return args.isEmpty() ? args : methodArguments(args);
  3687         private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) {
  3688             String key = "cant.resolve";
  3689             String suffix = hasLocation ? ".location" : "";
  3690             switch (kindname) {
  3691                 case METHOD:
  3692                 case CONSTRUCTOR: {
  3693                     suffix += ".args";
  3694                     suffix += hasTypeArgs ? ".params" : "";
  3697             return key + suffix;
  3699         private JCDiagnostic getLocationDiag(Symbol location, Type site) {
  3700             if (location.kind == VAR) {
  3701                 return diags.fragment("location.1",
  3702                     kindName(location),
  3703                     location,
  3704                     location.type);
  3705             } else {
  3706                 return diags.fragment("location",
  3707                     typeKindName(site),
  3708                     site,
  3709                     null);
  3714     /**
  3715      * InvalidSymbolError error class indicating that a given symbol
  3716      * (either a method, a constructor or an operand) is not applicable
  3717      * given an actual arguments/type argument list.
  3718      */
  3719     class InapplicableSymbolError extends ResolveError {
  3721         protected MethodResolutionContext resolveContext;
  3723         InapplicableSymbolError(MethodResolutionContext context) {
  3724             this(WRONG_MTH, "inapplicable symbol error", context);
  3727         protected InapplicableSymbolError(int kind, String debugName, MethodResolutionContext context) {
  3728             super(kind, debugName);
  3729             this.resolveContext = context;
  3732         @Override
  3733         public String toString() {
  3734             return super.toString();
  3737         @Override
  3738         public boolean exists() {
  3739             return true;
  3742         @Override
  3743         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3744                 DiagnosticPosition pos,
  3745                 Symbol location,
  3746                 Type site,
  3747                 Name name,
  3748                 List<Type> argtypes,
  3749                 List<Type> typeargtypes) {
  3750             if (name == names.error)
  3751                 return null;
  3753             if (syms.operatorNames.contains(name)) {
  3754                 boolean isUnaryOp = argtypes.size() == 1;
  3755                 String key = argtypes.size() == 1 ?
  3756                     "operator.cant.be.applied" :
  3757                     "operator.cant.be.applied.1";
  3758                 Type first = argtypes.head;
  3759                 Type second = !isUnaryOp ? argtypes.tail.head : null;
  3760                 return diags.create(dkind, log.currentSource(), pos,
  3761                         key, name, first, second);
  3763             else {
  3764                 Pair<Symbol, JCDiagnostic> c = errCandidate();
  3765                 if (compactMethodDiags) {
  3766                     for (Map.Entry<Template, DiagnosticRewriter> _entry :
  3767                             MethodResolutionDiagHelper.rewriters.entrySet()) {
  3768                         if (_entry.getKey().matches(c.snd)) {
  3769                             JCDiagnostic simpleDiag =
  3770                                     _entry.getValue().rewriteDiagnostic(diags, pos,
  3771                                         log.currentSource(), dkind, c.snd);
  3772                             simpleDiag.setFlag(DiagnosticFlag.COMPRESSED);
  3773                             return simpleDiag;
  3777                 Symbol ws = c.fst.asMemberOf(site, types);
  3778                 return diags.create(dkind, log.currentSource(), pos,
  3779                           "cant.apply.symbol",
  3780                           kindName(ws),
  3781                           ws.name == names.init ? ws.owner.name : ws.name,
  3782                           methodArguments(ws.type.getParameterTypes()),
  3783                           methodArguments(argtypes),
  3784                           kindName(ws.owner),
  3785                           ws.owner.type,
  3786                           c.snd);
  3790         @Override
  3791         public Symbol access(Name name, TypeSymbol location) {
  3792             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  3795         protected Pair<Symbol, JCDiagnostic> errCandidate() {
  3796             Candidate bestSoFar = null;
  3797             for (Candidate c : resolveContext.candidates) {
  3798                 if (c.isApplicable()) continue;
  3799                 bestSoFar = c;
  3801             Assert.checkNonNull(bestSoFar);
  3802             return new Pair<Symbol, JCDiagnostic>(bestSoFar.sym, bestSoFar.details);
  3806     /**
  3807      * ResolveError error class indicating that a set of symbols
  3808      * (either methods, constructors or operands) is not applicable
  3809      * given an actual arguments/type argument list.
  3810      */
  3811     class InapplicableSymbolsError extends InapplicableSymbolError {
  3813         InapplicableSymbolsError(MethodResolutionContext context) {
  3814             super(WRONG_MTHS, "inapplicable symbols", context);
  3817         @Override
  3818         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3819                 DiagnosticPosition pos,
  3820                 Symbol location,
  3821                 Type site,
  3822                 Name name,
  3823                 List<Type> argtypes,
  3824                 List<Type> typeargtypes) {
  3825             Map<Symbol, JCDiagnostic> candidatesMap = mapCandidates();
  3826             Map<Symbol, JCDiagnostic> filteredCandidates = compactMethodDiags ?
  3827                     filterCandidates(candidatesMap) :
  3828                     mapCandidates();
  3829             if (filteredCandidates.isEmpty()) {
  3830                 filteredCandidates = candidatesMap;
  3832             boolean truncatedDiag = candidatesMap.size() != filteredCandidates.size();
  3833             if (filteredCandidates.size() > 1) {
  3834                 JCDiagnostic err = diags.create(dkind,
  3835                         null,
  3836                         truncatedDiag ?
  3837                             EnumSet.of(DiagnosticFlag.COMPRESSED) :
  3838                             EnumSet.noneOf(DiagnosticFlag.class),
  3839                         log.currentSource(),
  3840                         pos,
  3841                         "cant.apply.symbols",
  3842                         name == names.init ? KindName.CONSTRUCTOR : absentKind(kind),
  3843                         name == names.init ? site.tsym.name : name,
  3844                         methodArguments(argtypes));
  3845                 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(filteredCandidates, site));
  3846             } else if (filteredCandidates.size() == 1) {
  3847                 Map.Entry<Symbol, JCDiagnostic> _e =
  3848                                 filteredCandidates.entrySet().iterator().next();
  3849                 final Pair<Symbol, JCDiagnostic> p = new Pair<Symbol, JCDiagnostic>(_e.getKey(), _e.getValue());
  3850                 JCDiagnostic d = new InapplicableSymbolError(resolveContext) {
  3851                     @Override
  3852                     protected Pair<Symbol, JCDiagnostic> errCandidate() {
  3853                         return p;
  3855                 }.getDiagnostic(dkind, pos,
  3856                     location, site, name, argtypes, typeargtypes);
  3857                 if (truncatedDiag) {
  3858                     d.setFlag(DiagnosticFlag.COMPRESSED);
  3860                 return d;
  3861             } else {
  3862                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
  3863                     location, site, name, argtypes, typeargtypes);
  3866         //where
  3867             private Map<Symbol, JCDiagnostic> mapCandidates() {
  3868                 Map<Symbol, JCDiagnostic> candidates = new LinkedHashMap<Symbol, JCDiagnostic>();
  3869                 for (Candidate c : resolveContext.candidates) {
  3870                     if (c.isApplicable()) continue;
  3871                     candidates.put(c.sym, c.details);
  3873                 return candidates;
  3876             Map<Symbol, JCDiagnostic> filterCandidates(Map<Symbol, JCDiagnostic> candidatesMap) {
  3877                 Map<Symbol, JCDiagnostic> candidates = new LinkedHashMap<Symbol, JCDiagnostic>();
  3878                 for (Map.Entry<Symbol, JCDiagnostic> _entry : candidatesMap.entrySet()) {
  3879                     JCDiagnostic d = _entry.getValue();
  3880                     if (!new Template(MethodCheckDiag.ARITY_MISMATCH.regex()).matches(d)) {
  3881                         candidates.put(_entry.getKey(), d);
  3884                 return candidates;
  3887             private List<JCDiagnostic> candidateDetails(Map<Symbol, JCDiagnostic> candidatesMap, Type site) {
  3888                 List<JCDiagnostic> details = List.nil();
  3889                 for (Map.Entry<Symbol, JCDiagnostic> _entry : candidatesMap.entrySet()) {
  3890                     Symbol sym = _entry.getKey();
  3891                     JCDiagnostic detailDiag = diags.fragment("inapplicable.method",
  3892                             Kinds.kindName(sym),
  3893                             sym.location(site, types),
  3894                             sym.asMemberOf(site, types),
  3895                             _entry.getValue());
  3896                     details = details.prepend(detailDiag);
  3898                 //typically members are visited in reverse order (see Scope)
  3899                 //so we need to reverse the candidate list so that candidates
  3900                 //conform to source order
  3901                 return details;
  3905     /**
  3906      * An InvalidSymbolError error class indicating that a symbol is not
  3907      * accessible from a given site
  3908      */
  3909     class AccessError extends InvalidSymbolError {
  3911         private Env<AttrContext> env;
  3912         private Type site;
  3914         AccessError(Symbol sym) {
  3915             this(null, null, sym);
  3918         AccessError(Env<AttrContext> env, Type site, Symbol sym) {
  3919             super(HIDDEN, sym, "access error");
  3920             this.env = env;
  3921             this.site = site;
  3922             if (debugResolve)
  3923                 log.error("proc.messager", sym + " @ " + site + " is inaccessible.");
  3926         @Override
  3927         public boolean exists() {
  3928             return false;
  3931         @Override
  3932         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3933                 DiagnosticPosition pos,
  3934                 Symbol location,
  3935                 Type site,
  3936                 Name name,
  3937                 List<Type> argtypes,
  3938                 List<Type> typeargtypes) {
  3939             if (sym.owner.type.hasTag(ERROR))
  3940                 return null;
  3942             if (sym.name == names.init && sym.owner != site.tsym) {
  3943                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
  3944                         pos, location, site, name, argtypes, typeargtypes);
  3946             else if ((sym.flags() & PUBLIC) != 0
  3947                 || (env != null && this.site != null
  3948                     && !isAccessible(env, this.site))) {
  3949                 return diags.create(dkind, log.currentSource(),
  3950                         pos, "not.def.access.class.intf.cant.access",
  3951                     sym, sym.location());
  3953             else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) {
  3954                 return diags.create(dkind, log.currentSource(),
  3955                         pos, "report.access", sym,
  3956                         asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
  3957                         sym.location());
  3959             else {
  3960                 return diags.create(dkind, log.currentSource(),
  3961                         pos, "not.def.public.cant.access", sym, sym.location());
  3966     /**
  3967      * InvalidSymbolError error class indicating that an instance member
  3968      * has erroneously been accessed from a static context.
  3969      */
  3970     class StaticError extends InvalidSymbolError {
  3972         StaticError(Symbol sym) {
  3973             super(STATICERR, sym, "static error");
  3976         @Override
  3977         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3978                 DiagnosticPosition pos,
  3979                 Symbol location,
  3980                 Type site,
  3981                 Name name,
  3982                 List<Type> argtypes,
  3983                 List<Type> typeargtypes) {
  3984             Symbol errSym = ((sym.kind == TYP && sym.type.hasTag(CLASS))
  3985                 ? types.erasure(sym.type).tsym
  3986                 : sym);
  3987             return diags.create(dkind, log.currentSource(), pos,
  3988                     "non-static.cant.be.ref", kindName(sym), errSym);
  3992     /**
  3993      * InvalidSymbolError error class indicating that a pair of symbols
  3994      * (either methods, constructors or operands) are ambiguous
  3995      * given an actual arguments/type argument list.
  3996      */
  3997     class AmbiguityError extends ResolveError {
  3999         /** The other maximally specific symbol */
  4000         List<Symbol> ambiguousSyms = List.nil();
  4002         @Override
  4003         public boolean exists() {
  4004             return true;
  4007         AmbiguityError(Symbol sym1, Symbol sym2) {
  4008             super(AMBIGUOUS, "ambiguity error");
  4009             ambiguousSyms = flatten(sym2).appendList(flatten(sym1));
  4012         private List<Symbol> flatten(Symbol sym) {
  4013             if (sym.kind == AMBIGUOUS) {
  4014                 return ((AmbiguityError)sym.baseSymbol()).ambiguousSyms;
  4015             } else {
  4016                 return List.of(sym);
  4020         AmbiguityError addAmbiguousSymbol(Symbol s) {
  4021             ambiguousSyms = ambiguousSyms.prepend(s);
  4022             return this;
  4025         @Override
  4026         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  4027                 DiagnosticPosition pos,
  4028                 Symbol location,
  4029                 Type site,
  4030                 Name name,
  4031                 List<Type> argtypes,
  4032                 List<Type> typeargtypes) {
  4033             List<Symbol> diagSyms = ambiguousSyms.reverse();
  4034             Symbol s1 = diagSyms.head;
  4035             Symbol s2 = diagSyms.tail.head;
  4036             Name sname = s1.name;
  4037             if (sname == names.init) sname = s1.owner.name;
  4038             return diags.create(dkind, log.currentSource(),
  4039                       pos, "ref.ambiguous", sname,
  4040                       kindName(s1),
  4041                       s1,
  4042                       s1.location(site, types),
  4043                       kindName(s2),
  4044                       s2,
  4045                       s2.location(site, types));
  4048         /**
  4049          * If multiple applicable methods are found during overload and none of them
  4050          * is more specific than the others, attempt to merge their signatures.
  4051          */
  4052         Symbol mergeAbstracts(Type site) {
  4053             List<Symbol> ambiguousInOrder = ambiguousSyms.reverse();
  4054             for (Symbol s : ambiguousInOrder) {
  4055                 Type mt = types.memberType(site, s);
  4056                 boolean found = true;
  4057                 List<Type> allThrown = mt.getThrownTypes();
  4058                 for (Symbol s2 : ambiguousInOrder) {
  4059                     Type mt2 = types.memberType(site, s2);
  4060                     if ((s2.flags() & ABSTRACT) == 0 ||
  4061                         !types.overrideEquivalent(mt, mt2) ||
  4062                         !types.isSameTypes(s.erasure(types).getParameterTypes(),
  4063                                        s2.erasure(types).getParameterTypes())) {
  4064                         //ambiguity cannot be resolved
  4065                         return this;
  4067                     Type mst = mostSpecificReturnType(mt, mt2);
  4068                     if (mst == null || mst != mt) {
  4069                         found = false;
  4070                         break;
  4072                     allThrown = chk.intersect(allThrown, mt2.getThrownTypes());
  4074                 if (found) {
  4075                     //all ambiguous methods were abstract and one method had
  4076                     //most specific return type then others
  4077                     return (allThrown == mt.getThrownTypes()) ?
  4078                             s : new MethodSymbol(
  4079                                 s.flags(),
  4080                                 s.name,
  4081                                 types.createMethodTypeWithThrown(mt, allThrown),
  4082                                 s.owner);
  4085             return this;
  4088         @Override
  4089         protected Symbol access(Name name, TypeSymbol location) {
  4090             Symbol firstAmbiguity = ambiguousSyms.last();
  4091             return firstAmbiguity.kind == TYP ?
  4092                     types.createErrorType(name, location, firstAmbiguity.type).tsym :
  4093                     firstAmbiguity;
  4097     class BadVarargsMethod extends ResolveError {
  4099         ResolveError delegatedError;
  4101         BadVarargsMethod(ResolveError delegatedError) {
  4102             super(delegatedError.kind, "badVarargs");
  4103             this.delegatedError = delegatedError;
  4106         @Override
  4107         public Symbol baseSymbol() {
  4108             return delegatedError.baseSymbol();
  4111         @Override
  4112         protected Symbol access(Name name, TypeSymbol location) {
  4113             return delegatedError.access(name, location);
  4116         @Override
  4117         public boolean exists() {
  4118             return true;
  4121         @Override
  4122         JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
  4123             return delegatedError.getDiagnostic(dkind, pos, location, site, name, argtypes, typeargtypes);
  4127     /**
  4128      * Helper class for method resolution diagnostic simplification.
  4129      * Certain resolution diagnostic are rewritten as simpler diagnostic
  4130      * where the enclosing resolution diagnostic (i.e. 'inapplicable method')
  4131      * is stripped away, as it doesn't carry additional info. The logic
  4132      * for matching a given diagnostic is given in terms of a template
  4133      * hierarchy: a diagnostic template can be specified programmatically,
  4134      * so that only certain diagnostics are matched. Each templete is then
  4135      * associated with a rewriter object that carries out the task of rewtiting
  4136      * the diagnostic to a simpler one.
  4137      */
  4138     static class MethodResolutionDiagHelper {
  4140         /**
  4141          * A diagnostic rewriter transforms a method resolution diagnostic
  4142          * into a simpler one
  4143          */
  4144         interface DiagnosticRewriter {
  4145             JCDiagnostic rewriteDiagnostic(JCDiagnostic.Factory diags,
  4146                     DiagnosticPosition preferedPos, DiagnosticSource preferredSource,
  4147                     DiagnosticType preferredKind, JCDiagnostic d);
  4150         /**
  4151          * A diagnostic template is made up of two ingredients: (i) a regular
  4152          * expression for matching a diagnostic key and (ii) a list of sub-templates
  4153          * for matching diagnostic arguments.
  4154          */
  4155         static class Template {
  4157             /** regex used to match diag key */
  4158             String regex;
  4160             /** templates used to match diagnostic args */
  4161             Template[] subTemplates;
  4163             Template(String key, Template... subTemplates) {
  4164                 this.regex = key;
  4165                 this.subTemplates = subTemplates;
  4168             /**
  4169              * Returns true if the regex matches the diagnostic key and if
  4170              * all diagnostic arguments are matches by corresponding sub-templates.
  4171              */
  4172             boolean matches(Object o) {
  4173                 JCDiagnostic d = (JCDiagnostic)o;
  4174                 Object[] args = d.getArgs();
  4175                 if (!d.getCode().matches(regex) ||
  4176                         subTemplates.length != d.getArgs().length) {
  4177                     return false;
  4179                 for (int i = 0; i < args.length ; i++) {
  4180                     if (!subTemplates[i].matches(args[i])) {
  4181                         return false;
  4184                 return true;
  4188         /** a dummy template that match any diagnostic argument */
  4189         static final Template skip = new Template("") {
  4190             @Override
  4191             boolean matches(Object d) {
  4192                 return true;
  4194         };
  4196         /** rewriter map used for method resolution simplification */
  4197         static final Map<Template, DiagnosticRewriter> rewriters =
  4198                 new LinkedHashMap<Template, DiagnosticRewriter>();
  4200         static {
  4201             String argMismatchRegex = MethodCheckDiag.ARG_MISMATCH.regex();
  4202             rewriters.put(new Template(argMismatchRegex, skip),
  4203                     new DiagnosticRewriter() {
  4204                 @Override
  4205                 public JCDiagnostic rewriteDiagnostic(JCDiagnostic.Factory diags,
  4206                         DiagnosticPosition preferedPos, DiagnosticSource preferredSource,
  4207                         DiagnosticType preferredKind, JCDiagnostic d) {
  4208                     JCDiagnostic cause = (JCDiagnostic)d.getArgs()[0];
  4209                     return diags.create(preferredKind, preferredSource, d.getDiagnosticPosition(),
  4210                             "prob.found.req", cause);
  4212             });
  4216     enum MethodResolutionPhase {
  4217         BASIC(false, false),
  4218         BOX(true, false),
  4219         VARARITY(true, true) {
  4220             @Override
  4221             public Symbol mergeResults(Symbol bestSoFar, Symbol sym) {
  4222                 switch (sym.kind) {
  4223                     case WRONG_MTH:
  4224                         return (bestSoFar.kind == WRONG_MTH || bestSoFar.kind == WRONG_MTHS) ?
  4225                             bestSoFar :
  4226                             sym;
  4227                     case ABSENT_MTH:
  4228                         return bestSoFar;
  4229                     default:
  4230                         return sym;
  4233         };
  4235         final boolean isBoxingRequired;
  4236         final boolean isVarargsRequired;
  4238         MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) {
  4239            this.isBoxingRequired = isBoxingRequired;
  4240            this.isVarargsRequired = isVarargsRequired;
  4243         public boolean isBoxingRequired() {
  4244             return isBoxingRequired;
  4247         public boolean isVarargsRequired() {
  4248             return isVarargsRequired;
  4251         public boolean isApplicable(boolean boxingEnabled, boolean varargsEnabled) {
  4252             return (varargsEnabled || !isVarargsRequired) &&
  4253                    (boxingEnabled || !isBoxingRequired);
  4256         public Symbol mergeResults(Symbol prev, Symbol sym) {
  4257             return sym;
  4261     final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
  4263     /**
  4264      * A resolution context is used to keep track of intermediate results of
  4265      * overload resolution, such as list of method that are not applicable
  4266      * (used to generate more precise diagnostics) and so on. Resolution contexts
  4267      * can be nested - this means that when each overload resolution routine should
  4268      * work within the resolution context it created.
  4269      */
  4270     class MethodResolutionContext {
  4272         private List<Candidate> candidates = List.nil();
  4274         MethodResolutionPhase step = null;
  4276         MethodCheck methodCheck = resolveMethodCheck;
  4278         private boolean internalResolution = false;
  4279         private DeferredAttr.AttrMode attrMode = DeferredAttr.AttrMode.SPECULATIVE;
  4281         void addInapplicableCandidate(Symbol sym, JCDiagnostic details) {
  4282             Candidate c = new Candidate(currentResolutionContext.step, sym, details, null);
  4283             candidates = candidates.append(c);
  4286         void addApplicableCandidate(Symbol sym, Type mtype) {
  4287             Candidate c = new Candidate(currentResolutionContext.step, sym, null, mtype);
  4288             candidates = candidates.append(c);
  4291         DeferredAttrContext deferredAttrContext(Symbol sym, InferenceContext inferenceContext, ResultInfo pendingResult, Warner warn) {
  4292             DeferredAttrContext parent = (pendingResult == null)
  4293                 ? deferredAttr.emptyDeferredAttrContext
  4294                 : pendingResult.checkContext.deferredAttrContext();
  4295             return deferredAttr.new DeferredAttrContext(attrMode, sym, step,
  4296                     inferenceContext, parent, warn);
  4299         /**
  4300          * This class represents an overload resolution candidate. There are two
  4301          * kinds of candidates: applicable methods and inapplicable methods;
  4302          * applicable methods have a pointer to the instantiated method type,
  4303          * while inapplicable candidates contain further details about the
  4304          * reason why the method has been considered inapplicable.
  4305          */
  4306         @SuppressWarnings("overrides")
  4307         class Candidate {
  4309             final MethodResolutionPhase step;
  4310             final Symbol sym;
  4311             final JCDiagnostic details;
  4312             final Type mtype;
  4314             private Candidate(MethodResolutionPhase step, Symbol sym, JCDiagnostic details, Type mtype) {
  4315                 this.step = step;
  4316                 this.sym = sym;
  4317                 this.details = details;
  4318                 this.mtype = mtype;
  4321             @Override
  4322             public boolean equals(Object o) {
  4323                 if (o instanceof Candidate) {
  4324                     Symbol s1 = this.sym;
  4325                     Symbol s2 = ((Candidate)o).sym;
  4326                     if  ((s1 != s2 &&
  4327                             (s1.overrides(s2, s1.owner.type.tsym, types, false) ||
  4328                             (s2.overrides(s1, s2.owner.type.tsym, types, false)))) ||
  4329                             ((s1.isConstructor() || s2.isConstructor()) && s1.owner != s2.owner))
  4330                         return true;
  4332                 return false;
  4335             boolean isApplicable() {
  4336                 return mtype != null;
  4340         DeferredAttr.AttrMode attrMode() {
  4341             return attrMode;
  4344         boolean internal() {
  4345             return internalResolution;
  4349     MethodResolutionContext currentResolutionContext = null;

mercurial