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

Thu, 15 Aug 2013 22:36:08 +0200

author
jlahoda
date
Thu, 15 Aug 2013 22:36:08 +0200
changeset 1956
f657d400c736
parent 1945
f7f271bd74a2
child 1970
2068190f8ac2
permissions
-rw-r--r--

8022508: javac crashes if the generics arity of a base class is wrong
Reviewed-by: mcimadamore, vromero

     1 /*
     2  * Copyright (c) 1999, 2013, 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.tools.javac.api.Formattable.LocalizedString;
    29 import com.sun.tools.javac.code.*;
    30 import com.sun.tools.javac.code.Symbol.*;
    31 import com.sun.tools.javac.code.Type.*;
    32 import com.sun.tools.javac.comp.Attr.ResultInfo;
    33 import com.sun.tools.javac.comp.Check.CheckContext;
    34 import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
    35 import com.sun.tools.javac.comp.DeferredAttr.DeferredAttrContext;
    36 import com.sun.tools.javac.comp.DeferredAttr.DeferredType;
    37 import com.sun.tools.javac.comp.Infer.InferenceContext;
    38 import com.sun.tools.javac.comp.Infer.FreeTypeListener;
    39 import com.sun.tools.javac.comp.Resolve.MethodResolutionContext.Candidate;
    40 import com.sun.tools.javac.comp.Resolve.MethodResolutionDiagHelper.DiagnosticRewriter;
    41 import com.sun.tools.javac.comp.Resolve.MethodResolutionDiagHelper.Template;
    42 import com.sun.tools.javac.jvm.*;
    43 import com.sun.tools.javac.main.Option;
    44 import com.sun.tools.javac.tree.*;
    45 import com.sun.tools.javac.tree.JCTree.*;
    46 import com.sun.tools.javac.tree.JCTree.JCMemberReference.ReferenceKind;
    47 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
    48 import com.sun.tools.javac.util.*;
    49 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
    50 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    51 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType;
    53 import java.util.Arrays;
    54 import java.util.Collection;
    55 import java.util.EnumMap;
    56 import java.util.EnumSet;
    57 import java.util.Iterator;
    58 import java.util.LinkedHashMap;
    59 import java.util.LinkedHashSet;
    60 import java.util.Map;
    62 import javax.lang.model.element.ElementVisitor;
    64 import static com.sun.tools.javac.code.Flags.*;
    65 import static com.sun.tools.javac.code.Flags.BLOCK;
    66 import static com.sun.tools.javac.code.Kinds.*;
    67 import static com.sun.tools.javac.code.Kinds.ERRONEOUS;
    68 import static com.sun.tools.javac.code.TypeTag.*;
    69 import static com.sun.tools.javac.comp.Resolve.MethodResolutionPhase.*;
    70 import static com.sun.tools.javac.tree.JCTree.Tag.*;
    72 /** Helper class for name resolution, used mostly by the attribution phase.
    73  *
    74  *  <p><b>This is NOT part of any supported API.
    75  *  If you write code that depends on this, you do so at your own risk.
    76  *  This code and its internal interfaces are subject to change or
    77  *  deletion without notice.</b>
    78  */
    79 public class Resolve {
    80     protected static final Context.Key<Resolve> resolveKey =
    81         new Context.Key<Resolve>();
    83     Names names;
    84     Log log;
    85     Symtab syms;
    86     Attr attr;
    87     DeferredAttr deferredAttr;
    88     Check chk;
    89     Infer infer;
    90     ClassReader reader;
    91     TreeInfo treeinfo;
    92     Types types;
    93     JCDiagnostic.Factory diags;
    94     public final boolean boxingEnabled; // = source.allowBoxing();
    95     public final boolean varargsEnabled; // = source.allowVarargs();
    96     public final boolean allowMethodHandles;
    97     public final boolean allowDefaultMethods;
    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         typeNotFound = new
   114             SymbolNotFoundError(ABSENT_TYP);
   116         names = Names.instance(context);
   117         log = Log.instance(context);
   118         attr = Attr.instance(context);
   119         deferredAttr = DeferredAttr.instance(context);
   120         chk = Check.instance(context);
   121         infer = Infer.instance(context);
   122         reader = ClassReader.instance(context);
   123         treeinfo = TreeInfo.instance(context);
   124         types = Types.instance(context);
   125         diags = JCDiagnostic.Factory.instance(context);
   126         Source source = Source.instance(context);
   127         boxingEnabled = source.allowBoxing();
   128         varargsEnabled = source.allowVarargs();
   129         Options options = Options.instance(context);
   130         debugResolve = options.isSet("debugresolve");
   131         compactMethodDiags = options.isSet(Option.XDIAGS, "compact") ||
   132                 options.isUnset(Option.XDIAGS) && options.isUnset("rawDiagnostics");
   133         verboseResolutionMode = VerboseResolutionMode.getVerboseResolutionMode(options);
   134         Target target = Target.instance(context);
   135         allowMethodHandles = target.hasMethodHandles();
   136         allowDefaultMethods = source.allowDefaultMethods();
   137         allowStructuralMostSpecific = source.allowStructuralMostSpecific();
   138         polymorphicSignatureScope = new Scope(syms.noSymbol);
   140         inapplicableMethodException = new InapplicableMethodException(diags);
   141     }
   143     /** error symbols, which are returned when resolution fails
   144      */
   145     private final SymbolNotFoundError varNotFound;
   146     private final SymbolNotFoundError methodNotFound;
   147     private final SymbolNotFoundError typeNotFound;
   149     public static Resolve instance(Context context) {
   150         Resolve instance = context.get(resolveKey);
   151         if (instance == null)
   152             instance = new Resolve(context);
   153         return instance;
   154     }
   156     // <editor-fold defaultstate="collapsed" desc="Verbose resolution diagnostics support">
   157     enum VerboseResolutionMode {
   158         SUCCESS("success"),
   159         FAILURE("failure"),
   160         APPLICABLE("applicable"),
   161         INAPPLICABLE("inapplicable"),
   162         DEFERRED_INST("deferred-inference"),
   163         PREDEF("predef"),
   164         OBJECT_INIT("object-init"),
   165         INTERNAL("internal");
   167         final String opt;
   169         private VerboseResolutionMode(String opt) {
   170             this.opt = opt;
   171         }
   173         static EnumSet<VerboseResolutionMode> getVerboseResolutionMode(Options opts) {
   174             String s = opts.get("verboseResolution");
   175             EnumSet<VerboseResolutionMode> res = EnumSet.noneOf(VerboseResolutionMode.class);
   176             if (s == null) return res;
   177             if (s.contains("all")) {
   178                 res = EnumSet.allOf(VerboseResolutionMode.class);
   179             }
   180             Collection<String> args = Arrays.asList(s.split(","));
   181             for (VerboseResolutionMode mode : values()) {
   182                 if (args.contains(mode.opt)) {
   183                     res.add(mode);
   184                 } else if (args.contains("-" + mode.opt)) {
   185                     res.remove(mode);
   186                 }
   187             }
   188             return res;
   189         }
   190     }
   192     void reportVerboseResolutionDiagnostic(DiagnosticPosition dpos, Name name, Type site,
   193             List<Type> argtypes, List<Type> typeargtypes, Symbol bestSoFar) {
   194         boolean success = bestSoFar.kind < ERRONEOUS;
   196         if (success && !verboseResolutionMode.contains(VerboseResolutionMode.SUCCESS)) {
   197             return;
   198         } else if (!success && !verboseResolutionMode.contains(VerboseResolutionMode.FAILURE)) {
   199             return;
   200         }
   202         if (bestSoFar.name == names.init &&
   203                 bestSoFar.owner == syms.objectType.tsym &&
   204                 !verboseResolutionMode.contains(VerboseResolutionMode.OBJECT_INIT)) {
   205             return; //skip diags for Object constructor resolution
   206         } else if (site == syms.predefClass.type &&
   207                 !verboseResolutionMode.contains(VerboseResolutionMode.PREDEF)) {
   208             return; //skip spurious diags for predef symbols (i.e. operators)
   209         } else if (currentResolutionContext.internalResolution &&
   210                 !verboseResolutionMode.contains(VerboseResolutionMode.INTERNAL)) {
   211             return;
   212         }
   214         int pos = 0;
   215         int mostSpecificPos = -1;
   216         ListBuffer<JCDiagnostic> subDiags = ListBuffer.lb();
   217         for (Candidate c : currentResolutionContext.candidates) {
   218             if (currentResolutionContext.step != c.step ||
   219                     (c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.APPLICABLE)) ||
   220                     (!c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.INAPPLICABLE))) {
   221                 continue;
   222             } else {
   223                 subDiags.append(c.isApplicable() ?
   224                         getVerboseApplicableCandidateDiag(pos, c.sym, c.mtype) :
   225                         getVerboseInapplicableCandidateDiag(pos, c.sym, c.details));
   226                 if (c.sym == bestSoFar)
   227                     mostSpecificPos = pos;
   228                 pos++;
   229             }
   230         }
   231         String key = success ? "verbose.resolve.multi" : "verbose.resolve.multi.1";
   232         List<Type> argtypes2 = Type.map(argtypes,
   233                     deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, bestSoFar, currentResolutionContext.step));
   234         JCDiagnostic main = diags.note(log.currentSource(), dpos, key, name,
   235                 site.tsym, mostSpecificPos, currentResolutionContext.step,
   236                 methodArguments(argtypes2),
   237                 methodArguments(typeargtypes));
   238         JCDiagnostic d = new JCDiagnostic.MultilineDiagnostic(main, subDiags.toList());
   239         log.report(d);
   240     }
   242     JCDiagnostic getVerboseApplicableCandidateDiag(int pos, Symbol sym, Type inst) {
   243         JCDiagnostic subDiag = null;
   244         if (sym.type.hasTag(FORALL)) {
   245             subDiag = diags.fragment("partial.inst.sig", inst);
   246         }
   248         String key = subDiag == null ?
   249                 "applicable.method.found" :
   250                 "applicable.method.found.1";
   252         return diags.fragment(key, pos, sym, subDiag);
   253     }
   255     JCDiagnostic getVerboseInapplicableCandidateDiag(int pos, Symbol sym, JCDiagnostic subDiag) {
   256         return diags.fragment("not.applicable.method.found", pos, sym, subDiag);
   257     }
   258     // </editor-fold>
   260 /* ************************************************************************
   261  * Identifier resolution
   262  *************************************************************************/
   264     /** An environment is "static" if its static level is greater than
   265      *  the one of its outer environment
   266      */
   267     protected static boolean isStatic(Env<AttrContext> env) {
   268         return env.info.staticLevel > env.outer.info.staticLevel;
   269     }
   271     /** An environment is an "initializer" if it is a constructor or
   272      *  an instance initializer.
   273      */
   274     static boolean isInitializer(Env<AttrContext> env) {
   275         Symbol owner = env.info.scope.owner;
   276         return owner.isConstructor() ||
   277             owner.owner.kind == TYP &&
   278             (owner.kind == VAR ||
   279              owner.kind == MTH && (owner.flags() & BLOCK) != 0) &&
   280             (owner.flags() & STATIC) == 0;
   281     }
   283     /** Is class accessible in given evironment?
   284      *  @param env    The current environment.
   285      *  @param c      The class whose accessibility is checked.
   286      */
   287     public boolean isAccessible(Env<AttrContext> env, TypeSymbol c) {
   288         return isAccessible(env, c, false);
   289     }
   291     public boolean isAccessible(Env<AttrContext> env, TypeSymbol c, boolean checkInner) {
   292         boolean isAccessible = false;
   293         switch ((short)(c.flags() & AccessFlags)) {
   294             case PRIVATE:
   295                 isAccessible =
   296                     env.enclClass.sym.outermostClass() ==
   297                     c.owner.outermostClass();
   298                 break;
   299             case 0:
   300                 isAccessible =
   301                     env.toplevel.packge == c.owner // fast special case
   302                     ||
   303                     env.toplevel.packge == c.packge()
   304                     ||
   305                     // Hack: this case is added since synthesized default constructors
   306                     // of anonymous classes should be allowed to access
   307                     // classes which would be inaccessible otherwise.
   308                     env.enclMethod != null &&
   309                     (env.enclMethod.mods.flags & ANONCONSTR) != 0;
   310                 break;
   311             default: // error recovery
   312             case PUBLIC:
   313                 isAccessible = true;
   314                 break;
   315             case PROTECTED:
   316                 isAccessible =
   317                     env.toplevel.packge == c.owner // fast special case
   318                     ||
   319                     env.toplevel.packge == c.packge()
   320                     ||
   321                     isInnerSubClass(env.enclClass.sym, c.owner);
   322                 break;
   323         }
   324         return (checkInner == false || c.type.getEnclosingType() == Type.noType) ?
   325             isAccessible :
   326             isAccessible && isAccessible(env, c.type.getEnclosingType(), checkInner);
   327     }
   328     //where
   329         /** Is given class a subclass of given base class, or an inner class
   330          *  of a subclass?
   331          *  Return null if no such class exists.
   332          *  @param c     The class which is the subclass or is contained in it.
   333          *  @param base  The base class
   334          */
   335         private boolean isInnerSubClass(ClassSymbol c, Symbol base) {
   336             while (c != null && !c.isSubClass(base, types)) {
   337                 c = c.owner.enclClass();
   338             }
   339             return c != null;
   340         }
   342     boolean isAccessible(Env<AttrContext> env, Type t) {
   343         return isAccessible(env, t, false);
   344     }
   346     boolean isAccessible(Env<AttrContext> env, Type t, boolean checkInner) {
   347         return (t.hasTag(ARRAY))
   348             ? isAccessible(env, types.upperBound(types.elemtype(t)))
   349             : isAccessible(env, t.tsym, checkInner);
   350     }
   352     /** Is symbol accessible as a member of given type in given environment?
   353      *  @param env    The current environment.
   354      *  @param site   The type of which the tested symbol is regarded
   355      *                as a member.
   356      *  @param sym    The symbol.
   357      */
   358     public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym) {
   359         return isAccessible(env, site, sym, false);
   360     }
   361     public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym, boolean checkInner) {
   362         if (sym.name == names.init && sym.owner != site.tsym) return false;
   363         switch ((short)(sym.flags() & AccessFlags)) {
   364         case PRIVATE:
   365             return
   366                 (env.enclClass.sym == sym.owner // fast special case
   367                  ||
   368                  env.enclClass.sym.outermostClass() ==
   369                  sym.owner.outermostClass())
   370                 &&
   371                 sym.isInheritedIn(site.tsym, types);
   372         case 0:
   373             return
   374                 (env.toplevel.packge == sym.owner.owner // fast special case
   375                  ||
   376                  env.toplevel.packge == sym.packge())
   377                 &&
   378                 isAccessible(env, site, checkInner)
   379                 &&
   380                 sym.isInheritedIn(site.tsym, types)
   381                 &&
   382                 notOverriddenIn(site, sym);
   383         case PROTECTED:
   384             return
   385                 (env.toplevel.packge == sym.owner.owner // fast special case
   386                  ||
   387                  env.toplevel.packge == sym.packge()
   388                  ||
   389                  isProtectedAccessible(sym, env.enclClass.sym, site)
   390                  ||
   391                  // OK to select instance method or field from 'super' or type name
   392                  // (but type names should be disallowed elsewhere!)
   393                  env.info.selectSuper && (sym.flags() & STATIC) == 0 && sym.kind != TYP)
   394                 &&
   395                 isAccessible(env, site, checkInner)
   396                 &&
   397                 notOverriddenIn(site, sym);
   398         default: // this case includes erroneous combinations as well
   399             return isAccessible(env, site, checkInner) && notOverriddenIn(site, sym);
   400         }
   401     }
   402     //where
   403     /* `sym' is accessible only if not overridden by
   404      * another symbol which is a member of `site'
   405      * (because, if it is overridden, `sym' is not strictly
   406      * speaking a member of `site'). A polymorphic signature method
   407      * cannot be overridden (e.g. MH.invokeExact(Object[])).
   408      */
   409     private boolean notOverriddenIn(Type site, Symbol sym) {
   410         if (sym.kind != MTH || sym.isConstructor() || sym.isStatic())
   411             return true;
   412         else {
   413             Symbol s2 = ((MethodSymbol)sym).implementation(site.tsym, types, true);
   414             return (s2 == null || s2 == sym || sym.owner == s2.owner ||
   415                     !types.isSubSignature(types.memberType(site, s2), types.memberType(site, sym)));
   416         }
   417     }
   418     //where
   419         /** Is given protected symbol accessible if it is selected from given site
   420          *  and the selection takes place in given class?
   421          *  @param sym     The symbol with protected access
   422          *  @param c       The class where the access takes place
   423          *  @site          The type of the qualifier
   424          */
   425         private
   426         boolean isProtectedAccessible(Symbol sym, ClassSymbol c, Type site) {
   427             while (c != null &&
   428                    !(c.isSubClass(sym.owner, types) &&
   429                      (c.flags() & INTERFACE) == 0 &&
   430                      // In JLS 2e 6.6.2.1, the subclass restriction applies
   431                      // only to instance fields and methods -- types are excluded
   432                      // regardless of whether they are declared 'static' or not.
   433                      ((sym.flags() & STATIC) != 0 || sym.kind == TYP || site.tsym.isSubClass(c, types))))
   434                 c = c.owner.enclClass();
   435             return c != null;
   436         }
   438     /**
   439      * Performs a recursive scan of a type looking for accessibility problems
   440      * from current attribution environment
   441      */
   442     void checkAccessibleType(Env<AttrContext> env, Type t) {
   443         accessibilityChecker.visit(t, env);
   444     }
   446     /**
   447      * Accessibility type-visitor
   448      */
   449     Types.SimpleVisitor<Void, Env<AttrContext>> accessibilityChecker =
   450             new Types.SimpleVisitor<Void, Env<AttrContext>>() {
   452         void visit(List<Type> ts, Env<AttrContext> env) {
   453             for (Type t : ts) {
   454                 visit(t, env);
   455             }
   456         }
   458         public Void visitType(Type t, Env<AttrContext> env) {
   459             return null;
   460         }
   462         @Override
   463         public Void visitArrayType(ArrayType t, Env<AttrContext> env) {
   464             visit(t.elemtype, env);
   465             return null;
   466         }
   468         @Override
   469         public Void visitClassType(ClassType t, Env<AttrContext> env) {
   470             visit(t.getTypeArguments(), env);
   471             if (!isAccessible(env, t, true)) {
   472                 accessBase(new AccessError(t.tsym), env.tree.pos(), env.enclClass.sym, t, t.tsym.name, true);
   473             }
   474             return null;
   475         }
   477         @Override
   478         public Void visitWildcardType(WildcardType t, Env<AttrContext> env) {
   479             visit(t.type, env);
   480             return null;
   481         }
   483         @Override
   484         public Void visitMethodType(MethodType t, Env<AttrContext> env) {
   485             visit(t.getParameterTypes(), env);
   486             visit(t.getReturnType(), env);
   487             visit(t.getThrownTypes(), env);
   488             return null;
   489         }
   490     };
   492     /** Try to instantiate the type of a method so that it fits
   493      *  given type arguments and argument types. If successful, return
   494      *  the method's instantiated type, else return null.
   495      *  The instantiation will take into account an additional leading
   496      *  formal parameter if the method is an instance method seen as a member
   497      *  of an under determined site. In this case, we treat site as an additional
   498      *  parameter and the parameters of the class containing the method as
   499      *  additional type variables that get instantiated.
   500      *
   501      *  @param env         The current environment
   502      *  @param site        The type of which the method is a member.
   503      *  @param m           The method symbol.
   504      *  @param argtypes    The invocation's given value arguments.
   505      *  @param typeargtypes    The invocation's given type arguments.
   506      *  @param allowBoxing Allow boxing conversions of arguments.
   507      *  @param useVarargs Box trailing arguments into an array for varargs.
   508      */
   509     Type rawInstantiate(Env<AttrContext> env,
   510                         Type site,
   511                         Symbol m,
   512                         ResultInfo resultInfo,
   513                         List<Type> argtypes,
   514                         List<Type> typeargtypes,
   515                         boolean allowBoxing,
   516                         boolean useVarargs,
   517                         Warner warn) throws Infer.InferenceException {
   519         Type mt = types.memberType(site, m);
   520         // tvars is the list of formal type variables for which type arguments
   521         // need to inferred.
   522         List<Type> tvars = List.nil();
   523         if (typeargtypes == null) typeargtypes = List.nil();
   524         if (!mt.hasTag(FORALL) && typeargtypes.nonEmpty()) {
   525             // This is not a polymorphic method, but typeargs are supplied
   526             // which is fine, see JLS 15.12.2.1
   527         } else if (mt.hasTag(FORALL) && typeargtypes.nonEmpty()) {
   528             ForAll pmt = (ForAll) mt;
   529             if (typeargtypes.length() != pmt.tvars.length())
   530                 throw inapplicableMethodException.setMessage("arg.length.mismatch"); // not enough args
   531             // Check type arguments are within bounds
   532             List<Type> formals = pmt.tvars;
   533             List<Type> actuals = typeargtypes;
   534             while (formals.nonEmpty() && actuals.nonEmpty()) {
   535                 List<Type> bounds = types.subst(types.getBounds((TypeVar)formals.head),
   536                                                 pmt.tvars, typeargtypes);
   537                 for (; bounds.nonEmpty(); bounds = bounds.tail)
   538                     if (!types.isSubtypeUnchecked(actuals.head, bounds.head, warn))
   539                         throw inapplicableMethodException.setMessage("explicit.param.do.not.conform.to.bounds",actuals.head, bounds);
   540                 formals = formals.tail;
   541                 actuals = actuals.tail;
   542             }
   543             mt = types.subst(pmt.qtype, pmt.tvars, typeargtypes);
   544         } else if (mt.hasTag(FORALL)) {
   545             ForAll pmt = (ForAll) mt;
   546             List<Type> tvars1 = types.newInstances(pmt.tvars);
   547             tvars = tvars.appendList(tvars1);
   548             mt = types.subst(pmt.qtype, pmt.tvars, tvars1);
   549         }
   551         // find out whether we need to go the slow route via infer
   552         boolean instNeeded = tvars.tail != null; /*inlined: tvars.nonEmpty()*/
   553         for (List<Type> l = argtypes;
   554              l.tail != null/*inlined: l.nonEmpty()*/ && !instNeeded;
   555              l = l.tail) {
   556             if (l.head.hasTag(FORALL)) instNeeded = true;
   557         }
   559         if (instNeeded)
   560             return infer.instantiateMethod(env,
   561                                     tvars,
   562                                     (MethodType)mt,
   563                                     resultInfo,
   564                                     m,
   565                                     argtypes,
   566                                     allowBoxing,
   567                                     useVarargs,
   568                                     currentResolutionContext,
   569                                     warn);
   571         currentResolutionContext.methodCheck.argumentsAcceptable(env, currentResolutionContext.deferredAttrContext(m, infer.emptyContext, resultInfo, warn),
   572                                 argtypes, mt.getParameterTypes(), warn);
   573         return mt;
   574     }
   576     Type checkMethod(Env<AttrContext> env,
   577                      Type site,
   578                      Symbol m,
   579                      ResultInfo resultInfo,
   580                      List<Type> argtypes,
   581                      List<Type> typeargtypes,
   582                      Warner warn) {
   583         MethodResolutionContext prevContext = currentResolutionContext;
   584         try {
   585             currentResolutionContext = new MethodResolutionContext();
   586             currentResolutionContext.attrMode = DeferredAttr.AttrMode.CHECK;
   587             if (env.tree.hasTag(JCTree.Tag.REFERENCE)) {
   588                 //method/constructor references need special check class
   589                 //to handle inference variables in 'argtypes' (might happen
   590                 //during an unsticking round)
   591                 currentResolutionContext.methodCheck =
   592                         new MethodReferenceCheck(resultInfo.checkContext.inferenceContext());
   593             }
   594             MethodResolutionPhase step = currentResolutionContext.step = env.info.pendingResolutionPhase;
   595             return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
   596                     step.isBoxingRequired(), step.isVarargsRequired(), warn);
   597         }
   598         finally {
   599             currentResolutionContext = prevContext;
   600         }
   601     }
   603     /** Same but returns null instead throwing a NoInstanceException
   604      */
   605     Type instantiate(Env<AttrContext> env,
   606                      Type site,
   607                      Symbol m,
   608                      ResultInfo resultInfo,
   609                      List<Type> argtypes,
   610                      List<Type> typeargtypes,
   611                      boolean allowBoxing,
   612                      boolean useVarargs,
   613                      Warner warn) {
   614         try {
   615             return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
   616                                   allowBoxing, useVarargs, warn);
   617         } catch (InapplicableMethodException ex) {
   618             return null;
   619         }
   620     }
   622     /**
   623      * This interface defines an entry point that should be used to perform a
   624      * method check. A method check usually consist in determining as to whether
   625      * a set of types (actuals) is compatible with another set of types (formals).
   626      * Since the notion of compatibility can vary depending on the circumstances,
   627      * this interfaces allows to easily add new pluggable method check routines.
   628      */
   629     interface MethodCheck {
   630         /**
   631          * Main method check routine. A method check usually consist in determining
   632          * as to whether a set of types (actuals) is compatible with another set of
   633          * types (formals). If an incompatibility is found, an unchecked exception
   634          * is assumed to be thrown.
   635          */
   636         void argumentsAcceptable(Env<AttrContext> env,
   637                                 DeferredAttrContext deferredAttrContext,
   638                                 List<Type> argtypes,
   639                                 List<Type> formals,
   640                                 Warner warn);
   642         /**
   643          * Retrieve the method check object that will be used during a
   644          * most specific check.
   645          */
   646         MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict);
   647     }
   649     /**
   650      * Helper enum defining all method check diagnostics (used by resolveMethodCheck).
   651      */
   652     enum MethodCheckDiag {
   653         /**
   654          * Actuals and formals differs in length.
   655          */
   656         ARITY_MISMATCH("arg.length.mismatch", "infer.arg.length.mismatch"),
   657         /**
   658          * An actual is incompatible with a formal.
   659          */
   660         ARG_MISMATCH("no.conforming.assignment.exists", "infer.no.conforming.assignment.exists"),
   661         /**
   662          * An actual is incompatible with the varargs element type.
   663          */
   664         VARARG_MISMATCH("varargs.argument.mismatch", "infer.varargs.argument.mismatch"),
   665         /**
   666          * The varargs element type is inaccessible.
   667          */
   668         INACCESSIBLE_VARARGS("inaccessible.varargs.type", "inaccessible.varargs.type");
   670         final String basicKey;
   671         final String inferKey;
   673         MethodCheckDiag(String basicKey, String inferKey) {
   674             this.basicKey = basicKey;
   675             this.inferKey = inferKey;
   676         }
   678         String regex() {
   679             return String.format("([a-z]*\\.)*(%s|%s)", basicKey, inferKey);
   680         }
   681     }
   683     /**
   684      * Dummy method check object. All methods are deemed applicable, regardless
   685      * of their formal parameter types.
   686      */
   687     MethodCheck nilMethodCheck = new MethodCheck() {
   688         public void argumentsAcceptable(Env<AttrContext> env, DeferredAttrContext deferredAttrContext, List<Type> argtypes, List<Type> formals, Warner warn) {
   689             //do nothing - method always applicable regardless of actuals
   690         }
   692         public MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict) {
   693             return this;
   694         }
   695     };
   697     /**
   698      * Base class for 'real' method checks. The class defines the logic for
   699      * iterating through formals and actuals and provides and entry point
   700      * that can be used by subclasses in order to define the actual check logic.
   701      */
   702     abstract class AbstractMethodCheck implements MethodCheck {
   703         @Override
   704         public void argumentsAcceptable(final Env<AttrContext> env,
   705                                     DeferredAttrContext deferredAttrContext,
   706                                     List<Type> argtypes,
   707                                     List<Type> formals,
   708                                     Warner warn) {
   709             //should we expand formals?
   710             boolean useVarargs = deferredAttrContext.phase.isVarargsRequired();
   711             List<JCExpression> trees = TreeInfo.args(env.tree);
   713             //inference context used during this method check
   714             InferenceContext inferenceContext = deferredAttrContext.inferenceContext;
   716             Type varargsFormal = useVarargs ? formals.last() : null;
   718             if (varargsFormal == null &&
   719                     argtypes.size() != formals.size()) {
   720                 reportMC(env.tree, MethodCheckDiag.ARITY_MISMATCH, inferenceContext); // not enough args
   721             }
   723             while (argtypes.nonEmpty() && formals.head != varargsFormal) {
   724                 DiagnosticPosition pos = trees != null ? trees.head : null;
   725                 checkArg(pos, false, argtypes.head, formals.head, deferredAttrContext, warn);
   726                 argtypes = argtypes.tail;
   727                 formals = formals.tail;
   728                 trees = trees != null ? trees.tail : trees;
   729             }
   731             if (formals.head != varargsFormal) {
   732                 reportMC(env.tree, MethodCheckDiag.ARITY_MISMATCH, inferenceContext); // not enough args
   733             }
   735             if (useVarargs) {
   736                 //note: if applicability check is triggered by most specific test,
   737                 //the last argument of a varargs is _not_ an array type (see JLS 15.12.2.5)
   738                 final Type elt = types.elemtype(varargsFormal);
   739                 while (argtypes.nonEmpty()) {
   740                     DiagnosticPosition pos = trees != null ? trees.head : null;
   741                     checkArg(pos, true, argtypes.head, elt, deferredAttrContext, warn);
   742                     argtypes = argtypes.tail;
   743                     trees = trees != null ? trees.tail : trees;
   744                 }
   745             }
   746         }
   748         /**
   749          * Does the actual argument conforms to the corresponding formal?
   750          */
   751         abstract void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn);
   753         protected void reportMC(DiagnosticPosition pos, MethodCheckDiag diag, InferenceContext inferenceContext, Object... args) {
   754             boolean inferDiag = inferenceContext != infer.emptyContext;
   755             InapplicableMethodException ex = inferDiag ?
   756                     infer.inferenceException : inapplicableMethodException;
   757             if (inferDiag && (!diag.inferKey.equals(diag.basicKey))) {
   758                 Object[] args2 = new Object[args.length + 1];
   759                 System.arraycopy(args, 0, args2, 1, args.length);
   760                 args2[0] = inferenceContext.inferenceVars();
   761                 args = args2;
   762             }
   763             String key = inferDiag ? diag.inferKey : diag.basicKey;
   764             throw ex.setMessage(diags.create(DiagnosticType.FRAGMENT, log.currentSource(), pos, key, args));
   765         }
   767         public MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict) {
   768             return nilMethodCheck;
   769         }
   770     }
   772     /**
   773      * Arity-based method check. A method is applicable if the number of actuals
   774      * supplied conforms to the method signature.
   775      */
   776     MethodCheck arityMethodCheck = new AbstractMethodCheck() {
   777         @Override
   778         void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn) {
   779             //do nothing - actual always compatible to formals
   780         }
   781     };
   783     List<Type> dummyArgs(int length) {
   784         ListBuffer<Type> buf = ListBuffer.lb();
   785         for (int i = 0 ; i < length ; i++) {
   786             buf.append(Type.noType);
   787         }
   788         return buf.toList();
   789     }
   791     /**
   792      * Main method applicability routine. Given a list of actual types A,
   793      * a list of formal types F, determines whether the types in A are
   794      * compatible (by method invocation conversion) with the types in F.
   795      *
   796      * Since this routine is shared between overload resolution and method
   797      * type-inference, a (possibly empty) inference context is used to convert
   798      * formal types to the corresponding 'undet' form ahead of a compatibility
   799      * check so that constraints can be propagated and collected.
   800      *
   801      * Moreover, if one or more types in A is a deferred type, this routine uses
   802      * DeferredAttr in order to perform deferred attribution. If one or more actual
   803      * deferred types are stuck, they are placed in a queue and revisited later
   804      * after the remainder of the arguments have been seen. If this is not sufficient
   805      * to 'unstuck' the argument, a cyclic inference error is called out.
   806      *
   807      * A method check handler (see above) is used in order to report errors.
   808      */
   809     MethodCheck resolveMethodCheck = new AbstractMethodCheck() {
   811         @Override
   812         void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn) {
   813             ResultInfo mresult = methodCheckResult(varargs, formal, deferredAttrContext, warn);
   814             mresult.check(pos, actual);
   815         }
   817         @Override
   818         public void argumentsAcceptable(final Env<AttrContext> env,
   819                                     DeferredAttrContext deferredAttrContext,
   820                                     List<Type> argtypes,
   821                                     List<Type> formals,
   822                                     Warner warn) {
   823             super.argumentsAcceptable(env, deferredAttrContext, argtypes, formals, warn);
   824             //should we expand formals?
   825             if (deferredAttrContext.phase.isVarargsRequired()) {
   826                 //check varargs element type accessibility
   827                 varargsAccessible(env, types.elemtype(formals.last()),
   828                         deferredAttrContext.inferenceContext);
   829             }
   830         }
   832         private void varargsAccessible(final Env<AttrContext> env, final Type t, final InferenceContext inferenceContext) {
   833             if (inferenceContext.free(t)) {
   834                 inferenceContext.addFreeTypeListener(List.of(t), new FreeTypeListener() {
   835                     @Override
   836                     public void typesInferred(InferenceContext inferenceContext) {
   837                         varargsAccessible(env, inferenceContext.asInstType(t), inferenceContext);
   838                     }
   839                 });
   840             } else {
   841                 if (!isAccessible(env, t)) {
   842                     Symbol location = env.enclClass.sym;
   843                     reportMC(env.tree, MethodCheckDiag.INACCESSIBLE_VARARGS, inferenceContext, t, Kinds.kindName(location), location);
   844                 }
   845             }
   846         }
   848         private ResultInfo methodCheckResult(final boolean varargsCheck, Type to,
   849                 final DeferredAttr.DeferredAttrContext deferredAttrContext, Warner rsWarner) {
   850             CheckContext checkContext = new MethodCheckContext(!deferredAttrContext.phase.isBoxingRequired(), deferredAttrContext, rsWarner) {
   851                 MethodCheckDiag methodDiag = varargsCheck ?
   852                                  MethodCheckDiag.VARARG_MISMATCH : MethodCheckDiag.ARG_MISMATCH;
   854                 @Override
   855                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
   856                     reportMC(pos, methodDiag, deferredAttrContext.inferenceContext, details);
   857                 }
   858             };
   859             return new MethodResultInfo(to, checkContext);
   860         }
   862         @Override
   863         public MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict) {
   864             return new MostSpecificCheck(strict, actuals);
   865         }
   866     };
   868     class MethodReferenceCheck extends AbstractMethodCheck {
   870         InferenceContext pendingInferenceContext;
   872         MethodReferenceCheck(InferenceContext pendingInferenceContext) {
   873             this.pendingInferenceContext = pendingInferenceContext;
   874         }
   876         @Override
   877         void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn) {
   878             ResultInfo mresult = methodCheckResult(varargs, formal, deferredAttrContext, warn);
   879             mresult.check(pos, actual);
   880         }
   882         private ResultInfo methodCheckResult(final boolean varargsCheck, Type to,
   883                 final DeferredAttr.DeferredAttrContext deferredAttrContext, Warner rsWarner) {
   884             CheckContext checkContext = new MethodCheckContext(!deferredAttrContext.phase.isBoxingRequired(), deferredAttrContext, rsWarner) {
   885                 MethodCheckDiag methodDiag = varargsCheck ?
   886                                  MethodCheckDiag.VARARG_MISMATCH : MethodCheckDiag.ARG_MISMATCH;
   888                 @Override
   889                 public boolean compatible(Type found, Type req, Warner warn) {
   890                     found = pendingInferenceContext.asFree(found);
   891                     req = infer.returnConstraintTarget(found, req);
   892                     return super.compatible(found, req, warn);
   893                 }
   895                 @Override
   896                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
   897                     reportMC(pos, methodDiag, deferredAttrContext.inferenceContext, details);
   898                 }
   899             };
   900             return new MethodResultInfo(to, checkContext);
   901         }
   903         @Override
   904         public MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict) {
   905             return new MostSpecificCheck(strict, actuals);
   906         }
   907     };
   909     /**
   910      * Check context to be used during method applicability checks. A method check
   911      * context might contain inference variables.
   912      */
   913     abstract class MethodCheckContext implements CheckContext {
   915         boolean strict;
   916         DeferredAttrContext deferredAttrContext;
   917         Warner rsWarner;
   919         public MethodCheckContext(boolean strict, DeferredAttrContext deferredAttrContext, Warner rsWarner) {
   920            this.strict = strict;
   921            this.deferredAttrContext = deferredAttrContext;
   922            this.rsWarner = rsWarner;
   923         }
   925         public boolean compatible(Type found, Type req, Warner warn) {
   926             return strict ?
   927                     types.isSubtypeUnchecked(found, deferredAttrContext.inferenceContext.asFree(req), warn) :
   928                     types.isConvertible(found, deferredAttrContext.inferenceContext.asFree(req), warn);
   929         }
   931         public void report(DiagnosticPosition pos, JCDiagnostic details) {
   932             throw inapplicableMethodException.setMessage(details);
   933         }
   935         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
   936             return rsWarner;
   937         }
   939         public InferenceContext inferenceContext() {
   940             return deferredAttrContext.inferenceContext;
   941         }
   943         public DeferredAttrContext deferredAttrContext() {
   944             return deferredAttrContext;
   945         }
   946     }
   948     /**
   949      * ResultInfo class to be used during method applicability checks. Check
   950      * for deferred types goes through special path.
   951      */
   952     class MethodResultInfo extends ResultInfo {
   954         public MethodResultInfo(Type pt, CheckContext checkContext) {
   955             attr.super(VAL, pt, checkContext);
   956         }
   958         @Override
   959         protected Type check(DiagnosticPosition pos, Type found) {
   960             if (found.hasTag(DEFERRED)) {
   961                 DeferredType dt = (DeferredType)found;
   962                 return dt.check(this);
   963             } else {
   964                 return super.check(pos, chk.checkNonVoid(pos, types.capture(U(found.baseType()))));
   965             }
   966         }
   968         /**
   969          * javac has a long-standing 'simplification' (see 6391995):
   970          * given an actual argument type, the method check is performed
   971          * on its upper bound. This leads to inconsistencies when an
   972          * argument type is checked against itself. For example, given
   973          * a type-variable T, it is not true that {@code U(T) <: T},
   974          * so we need to guard against that.
   975          */
   976         private Type U(Type found) {
   977             return found == pt ?
   978                     found : types.upperBound(found);
   979         }
   981         @Override
   982         protected MethodResultInfo dup(Type newPt) {
   983             return new MethodResultInfo(newPt, checkContext);
   984         }
   986         @Override
   987         protected ResultInfo dup(CheckContext newContext) {
   988             return new MethodResultInfo(pt, newContext);
   989         }
   990     }
   992     /**
   993      * Most specific method applicability routine. Given a list of actual types A,
   994      * a list of formal types F1, and a list of formal types F2, the routine determines
   995      * as to whether the types in F1 can be considered more specific than those in F2 w.r.t.
   996      * argument types A.
   997      */
   998     class MostSpecificCheck implements MethodCheck {
  1000         boolean strict;
  1001         List<Type> actuals;
  1003         MostSpecificCheck(boolean strict, List<Type> actuals) {
  1004             this.strict = strict;
  1005             this.actuals = actuals;
  1008         @Override
  1009         public void argumentsAcceptable(final Env<AttrContext> env,
  1010                                     DeferredAttrContext deferredAttrContext,
  1011                                     List<Type> formals1,
  1012                                     List<Type> formals2,
  1013                                     Warner warn) {
  1014             formals2 = adjustArgs(formals2, deferredAttrContext.msym, formals1.length(), deferredAttrContext.phase.isVarargsRequired());
  1015             while (formals2.nonEmpty()) {
  1016                 ResultInfo mresult = methodCheckResult(formals2.head, deferredAttrContext, warn, actuals.head);
  1017                 mresult.check(null, formals1.head);
  1018                 formals1 = formals1.tail;
  1019                 formals2 = formals2.tail;
  1020                 actuals = actuals.isEmpty() ? actuals : actuals.tail;
  1024        /**
  1025         * Create a method check context to be used during the most specific applicability check
  1026         */
  1027         ResultInfo methodCheckResult(Type to, DeferredAttr.DeferredAttrContext deferredAttrContext,
  1028                Warner rsWarner, Type actual) {
  1029            return attr.new ResultInfo(Kinds.VAL, to,
  1030                    new MostSpecificCheckContext(strict, deferredAttrContext, rsWarner, actual));
  1033         /**
  1034          * Subclass of method check context class that implements most specific
  1035          * method conversion. If the actual type under analysis is a deferred type
  1036          * a full blown structural analysis is carried out.
  1037          */
  1038         class MostSpecificCheckContext extends MethodCheckContext {
  1040             Type actual;
  1042             public MostSpecificCheckContext(boolean strict, DeferredAttrContext deferredAttrContext, Warner rsWarner, Type actual) {
  1043                 super(strict, deferredAttrContext, rsWarner);
  1044                 this.actual = actual;
  1047             public boolean compatible(Type found, Type req, Warner warn) {
  1048                 if (!allowStructuralMostSpecific || actual == null) {
  1049                     return super.compatible(found, req, warn);
  1050                 } else {
  1051                     switch (actual.getTag()) {
  1052                         case DEFERRED:
  1053                             DeferredType dt = (DeferredType) actual;
  1054                             DeferredType.SpeculativeCache.Entry e = dt.speculativeCache.get(deferredAttrContext.msym, deferredAttrContext.phase);
  1055                             return (e == null || e.speculativeTree == deferredAttr.stuckTree)
  1056                                     ? false : mostSpecific(found, req, e.speculativeTree, warn);
  1057                         default:
  1058                             return standaloneMostSpecific(found, req, actual, warn);
  1063             private boolean mostSpecific(Type t, Type s, JCTree tree, Warner warn) {
  1064                 MostSpecificChecker msc = new MostSpecificChecker(t, s, warn);
  1065                 msc.scan(tree);
  1066                 return msc.result;
  1069             boolean polyMostSpecific(Type t1, Type t2, Warner warn) {
  1070                 return (!t1.isPrimitive() && t2.isPrimitive())
  1071                         ? true : super.compatible(t1, t2, warn);
  1074             boolean standaloneMostSpecific(Type t1, Type t2, Type exprType, Warner warn) {
  1075                 return (exprType.isPrimitive() == t1.isPrimitive()
  1076                         && exprType.isPrimitive() != t2.isPrimitive())
  1077                         ? true : super.compatible(t1, t2, warn);
  1080             /**
  1081              * Structural checker for most specific.
  1082              */
  1083             class MostSpecificChecker extends DeferredAttr.PolyScanner {
  1085                 final Type t;
  1086                 final Type s;
  1087                 final Warner warn;
  1088                 boolean result;
  1090                 MostSpecificChecker(Type t, Type s, Warner warn) {
  1091                     this.t = t;
  1092                     this.s = s;
  1093                     this.warn = warn;
  1094                     result = true;
  1097                 @Override
  1098                 void skip(JCTree tree) {
  1099                     result &= standaloneMostSpecific(t, s, tree.type, warn);
  1102                 @Override
  1103                 public void visitConditional(JCConditional tree) {
  1104                     if (tree.polyKind == PolyKind.STANDALONE) {
  1105                         result &= standaloneMostSpecific(t, s, tree.type, warn);
  1106                     } else {
  1107                         super.visitConditional(tree);
  1111                 @Override
  1112                 public void visitApply(JCMethodInvocation tree) {
  1113                     result &= (tree.polyKind == PolyKind.STANDALONE)
  1114                             ? standaloneMostSpecific(t, s, tree.type, warn)
  1115                             : polyMostSpecific(t, s, warn);
  1118                 @Override
  1119                 public void visitNewClass(JCNewClass tree) {
  1120                     result &= (tree.polyKind == PolyKind.STANDALONE)
  1121                             ? standaloneMostSpecific(t, s, tree.type, warn)
  1122                             : polyMostSpecific(t, s, warn);
  1125                 @Override
  1126                 public void visitReference(JCMemberReference tree) {
  1127                     if (types.isFunctionalInterface(t.tsym) &&
  1128                             types.isFunctionalInterface(s.tsym) &&
  1129                             types.asSuper(t, s.tsym) == null &&
  1130                             types.asSuper(s, t.tsym) == null) {
  1131                         Type desc_t = types.findDescriptorType(t);
  1132                         Type desc_s = types.findDescriptorType(s);
  1133                         if (types.isSameTypes(desc_t.getParameterTypes(), desc_s.getParameterTypes())) {
  1134                             if (!desc_s.getReturnType().hasTag(VOID)) {
  1135                                 //perform structural comparison
  1136                                 Type ret_t = desc_t.getReturnType();
  1137                                 Type ret_s = desc_s.getReturnType();
  1138                                 result &= ((tree.refPolyKind == PolyKind.STANDALONE)
  1139                                         ? standaloneMostSpecific(ret_t, ret_s, tree.sym.type.getReturnType(), warn)
  1140                                         : polyMostSpecific(ret_t, ret_s, warn));
  1141                             } else {
  1142                                 return;
  1144                         } else {
  1145                             result &= false;
  1147                     } else {
  1148                         result &= MostSpecificCheckContext.super.compatible(t, s, warn);
  1152                 @Override
  1153                 public void visitLambda(JCLambda tree) {
  1154                     if (types.isFunctionalInterface(t.tsym) &&
  1155                             types.isFunctionalInterface(s.tsym) &&
  1156                             types.asSuper(t, s.tsym) == null &&
  1157                             types.asSuper(s, t.tsym) == null) {
  1158                         Type desc_t = types.findDescriptorType(t);
  1159                         Type desc_s = types.findDescriptorType(s);
  1160                         if (tree.paramKind == JCLambda.ParameterKind.EXPLICIT
  1161                                 || types.isSameTypes(desc_t.getParameterTypes(), desc_s.getParameterTypes())) {
  1162                             if (!desc_s.getReturnType().hasTag(VOID)) {
  1163                                 //perform structural comparison
  1164                                 Type ret_t = desc_t.getReturnType();
  1165                                 Type ret_s = desc_s.getReturnType();
  1166                                 scanLambdaBody(tree, ret_t, ret_s);
  1167                             } else {
  1168                                 return;
  1170                         } else {
  1171                             result &= false;
  1173                     } else {
  1174                         result &= MostSpecificCheckContext.super.compatible(t, s, warn);
  1177                 //where
  1179                 void scanLambdaBody(JCLambda lambda, final Type t, final Type s) {
  1180                     if (lambda.getBodyKind() == JCTree.JCLambda.BodyKind.EXPRESSION) {
  1181                         result &= MostSpecificCheckContext.this.mostSpecific(t, s, lambda.body, warn);
  1182                     } else {
  1183                         DeferredAttr.LambdaReturnScanner lambdaScanner =
  1184                                 new DeferredAttr.LambdaReturnScanner() {
  1185                                     @Override
  1186                                     public void visitReturn(JCReturn tree) {
  1187                                         if (tree.expr != null) {
  1188                                             result &= MostSpecificCheckContext.this.mostSpecific(t, s, tree.expr, warn);
  1191                                 };
  1192                         lambdaScanner.scan(lambda.body);
  1198         public MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict) {
  1199             Assert.error("Cannot get here!");
  1200             return null;
  1204     public static class InapplicableMethodException extends RuntimeException {
  1205         private static final long serialVersionUID = 0;
  1207         JCDiagnostic diagnostic;
  1208         JCDiagnostic.Factory diags;
  1210         InapplicableMethodException(JCDiagnostic.Factory diags) {
  1211             this.diagnostic = null;
  1212             this.diags = diags;
  1214         InapplicableMethodException setMessage() {
  1215             return setMessage((JCDiagnostic)null);
  1217         InapplicableMethodException setMessage(String key) {
  1218             return setMessage(key != null ? diags.fragment(key) : null);
  1220         InapplicableMethodException setMessage(String key, Object... args) {
  1221             return setMessage(key != null ? diags.fragment(key, args) : null);
  1223         InapplicableMethodException setMessage(JCDiagnostic diag) {
  1224             this.diagnostic = diag;
  1225             return this;
  1228         public JCDiagnostic getDiagnostic() {
  1229             return diagnostic;
  1232     private final InapplicableMethodException inapplicableMethodException;
  1234 /* ***************************************************************************
  1235  *  Symbol lookup
  1236  *  the following naming conventions for arguments are used
  1238  *       env      is the environment where the symbol was mentioned
  1239  *       site     is the type of which the symbol is a member
  1240  *       name     is the symbol's name
  1241  *                if no arguments are given
  1242  *       argtypes are the value arguments, if we search for a method
  1244  *  If no symbol was found, a ResolveError detailing the problem is returned.
  1245  ****************************************************************************/
  1247     /** Find field. Synthetic fields are always skipped.
  1248      *  @param env     The current environment.
  1249      *  @param site    The original type from where the selection takes place.
  1250      *  @param name    The name of the field.
  1251      *  @param c       The class to search for the field. This is always
  1252      *                 a superclass or implemented interface of site's class.
  1253      */
  1254     Symbol findField(Env<AttrContext> env,
  1255                      Type site,
  1256                      Name name,
  1257                      TypeSymbol c) {
  1258         while (c.type.hasTag(TYPEVAR))
  1259             c = c.type.getUpperBound().tsym;
  1260         Symbol bestSoFar = varNotFound;
  1261         Symbol sym;
  1262         Scope.Entry e = c.members().lookup(name);
  1263         while (e.scope != null) {
  1264             if (e.sym.kind == VAR && (e.sym.flags_field & SYNTHETIC) == 0) {
  1265                 return isAccessible(env, site, e.sym)
  1266                     ? e.sym : new AccessError(env, site, e.sym);
  1268             e = e.next();
  1270         Type st = types.supertype(c.type);
  1271         if (st != null && (st.hasTag(CLASS) || st.hasTag(TYPEVAR))) {
  1272             sym = findField(env, site, name, st.tsym);
  1273             if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1275         for (List<Type> l = types.interfaces(c.type);
  1276              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
  1277              l = l.tail) {
  1278             sym = findField(env, site, name, l.head.tsym);
  1279             if (bestSoFar.exists() && sym.exists() &&
  1280                 sym.owner != bestSoFar.owner)
  1281                 bestSoFar = new AmbiguityError(bestSoFar, sym);
  1282             else if (sym.kind < bestSoFar.kind)
  1283                 bestSoFar = sym;
  1285         return bestSoFar;
  1288     /** Resolve a field identifier, throw a fatal error if not found.
  1289      *  @param pos       The position to use for error reporting.
  1290      *  @param env       The environment current at the method invocation.
  1291      *  @param site      The type of the qualifying expression, in which
  1292      *                   identifier is searched.
  1293      *  @param name      The identifier's name.
  1294      */
  1295     public VarSymbol resolveInternalField(DiagnosticPosition pos, Env<AttrContext> env,
  1296                                           Type site, Name name) {
  1297         Symbol sym = findField(env, site, name, site.tsym);
  1298         if (sym.kind == VAR) return (VarSymbol)sym;
  1299         else throw new FatalError(
  1300                  diags.fragment("fatal.err.cant.locate.field",
  1301                                 name));
  1304     /** Find unqualified variable or field with given name.
  1305      *  Synthetic fields always skipped.
  1306      *  @param env     The current environment.
  1307      *  @param name    The name of the variable or field.
  1308      */
  1309     Symbol findVar(Env<AttrContext> env, Name name) {
  1310         Symbol bestSoFar = varNotFound;
  1311         Symbol sym;
  1312         Env<AttrContext> env1 = env;
  1313         boolean staticOnly = false;
  1314         while (env1.outer != null) {
  1315             if (isStatic(env1)) staticOnly = true;
  1316             Scope.Entry e = env1.info.scope.lookup(name);
  1317             while (e.scope != null &&
  1318                    (e.sym.kind != VAR ||
  1319                     (e.sym.flags_field & SYNTHETIC) != 0))
  1320                 e = e.next();
  1321             sym = (e.scope != null)
  1322                 ? e.sym
  1323                 : findField(
  1324                     env1, env1.enclClass.sym.type, name, env1.enclClass.sym);
  1325             if (sym.exists()) {
  1326                 if (staticOnly &&
  1327                     sym.kind == VAR &&
  1328                     sym.owner.kind == TYP &&
  1329                     (sym.flags() & STATIC) == 0)
  1330                     return new StaticError(sym);
  1331                 else
  1332                     return sym;
  1333             } else if (sym.kind < bestSoFar.kind) {
  1334                 bestSoFar = sym;
  1337             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  1338             env1 = env1.outer;
  1341         sym = findField(env, syms.predefClass.type, name, syms.predefClass);
  1342         if (sym.exists())
  1343             return sym;
  1344         if (bestSoFar.exists())
  1345             return bestSoFar;
  1347         Symbol origin = null;
  1348         for (Scope sc : new Scope[] { env.toplevel.namedImportScope, env.toplevel.starImportScope }) {
  1349             Scope.Entry e = sc.lookup(name);
  1350             for (; e.scope != null; e = e.next()) {
  1351                 sym = e.sym;
  1352                 if (sym.kind != VAR)
  1353                     continue;
  1354                 // invariant: sym.kind == VAR
  1355                 if (bestSoFar.kind < AMBIGUOUS && sym.owner != bestSoFar.owner)
  1356                     return new AmbiguityError(bestSoFar, sym);
  1357                 else if (bestSoFar.kind >= VAR) {
  1358                     origin = e.getOrigin().owner;
  1359                     bestSoFar = isAccessible(env, origin.type, sym)
  1360                         ? sym : new AccessError(env, origin.type, sym);
  1363             if (bestSoFar.exists()) break;
  1365         if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type)
  1366             return bestSoFar.clone(origin);
  1367         else
  1368             return bestSoFar;
  1371     Warner noteWarner = new Warner();
  1373     /** Select the best method for a call site among two choices.
  1374      *  @param env              The current environment.
  1375      *  @param site             The original type from where the
  1376      *                          selection takes place.
  1377      *  @param argtypes         The invocation's value arguments,
  1378      *  @param typeargtypes     The invocation's type arguments,
  1379      *  @param sym              Proposed new best match.
  1380      *  @param bestSoFar        Previously found best match.
  1381      *  @param allowBoxing Allow boxing conversions of arguments.
  1382      *  @param useVarargs Box trailing arguments into an array for varargs.
  1383      */
  1384     @SuppressWarnings("fallthrough")
  1385     Symbol selectBest(Env<AttrContext> env,
  1386                       Type site,
  1387                       List<Type> argtypes,
  1388                       List<Type> typeargtypes,
  1389                       Symbol sym,
  1390                       Symbol bestSoFar,
  1391                       boolean allowBoxing,
  1392                       boolean useVarargs,
  1393                       boolean operator) {
  1394         if (sym.kind == ERR ||
  1395                 !sym.isInheritedIn(site.tsym, types)) {
  1396             return bestSoFar;
  1397         } else if (useVarargs && (sym.flags() & VARARGS) == 0) {
  1398             return bestSoFar.kind >= ERRONEOUS ?
  1399                     new BadVarargsMethod((ResolveError)bestSoFar) :
  1400                     bestSoFar;
  1402         Assert.check(sym.kind < AMBIGUOUS);
  1403         try {
  1404             Type mt = rawInstantiate(env, site, sym, null, argtypes, typeargtypes,
  1405                                allowBoxing, useVarargs, types.noWarnings);
  1406             if (!operator || verboseResolutionMode.contains(VerboseResolutionMode.PREDEF))
  1407                 currentResolutionContext.addApplicableCandidate(sym, mt);
  1408         } catch (InapplicableMethodException ex) {
  1409             if (!operator)
  1410                 currentResolutionContext.addInapplicableCandidate(sym, ex.getDiagnostic());
  1411             switch (bestSoFar.kind) {
  1412                 case ABSENT_MTH:
  1413                     return new InapplicableSymbolError(currentResolutionContext);
  1414                 case WRONG_MTH:
  1415                     if (operator) return bestSoFar;
  1416                     bestSoFar = new InapplicableSymbolsError(currentResolutionContext);
  1417                 default:
  1418                     return bestSoFar;
  1421         if (!isAccessible(env, site, sym)) {
  1422             return (bestSoFar.kind == ABSENT_MTH)
  1423                 ? new AccessError(env, site, sym)
  1424                 : bestSoFar;
  1426         return (bestSoFar.kind > AMBIGUOUS)
  1427             ? sym
  1428             : mostSpecific(argtypes, sym, bestSoFar, env, site,
  1429                            allowBoxing && operator, useVarargs);
  1432     /* Return the most specific of the two methods for a call,
  1433      *  given that both are accessible and applicable.
  1434      *  @param m1               A new candidate for most specific.
  1435      *  @param m2               The previous most specific candidate.
  1436      *  @param env              The current environment.
  1437      *  @param site             The original type from where the selection
  1438      *                          takes place.
  1439      *  @param allowBoxing Allow boxing conversions of arguments.
  1440      *  @param useVarargs Box trailing arguments into an array for varargs.
  1441      */
  1442     Symbol mostSpecific(List<Type> argtypes, Symbol m1,
  1443                         Symbol m2,
  1444                         Env<AttrContext> env,
  1445                         final Type site,
  1446                         boolean allowBoxing,
  1447                         boolean useVarargs) {
  1448         switch (m2.kind) {
  1449         case MTH:
  1450             if (m1 == m2) return m1;
  1451             boolean m1SignatureMoreSpecific =
  1452                     signatureMoreSpecific(argtypes, env, site, m1, m2, allowBoxing, useVarargs);
  1453             boolean m2SignatureMoreSpecific =
  1454                     signatureMoreSpecific(argtypes, env, site, m2, m1, allowBoxing, useVarargs);
  1455             if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) {
  1456                 Type mt1 = types.memberType(site, m1);
  1457                 Type mt2 = types.memberType(site, m2);
  1458                 if (!types.overrideEquivalent(mt1, mt2))
  1459                     return ambiguityError(m1, m2);
  1461                 // same signature; select (a) the non-bridge method, or
  1462                 // (b) the one that overrides the other, or (c) the concrete
  1463                 // one, or (d) merge both abstract signatures
  1464                 if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE))
  1465                     return ((m1.flags() & BRIDGE) != 0) ? m2 : m1;
  1467                 // if one overrides or hides the other, use it
  1468                 TypeSymbol m1Owner = (TypeSymbol)m1.owner;
  1469                 TypeSymbol m2Owner = (TypeSymbol)m2.owner;
  1470                 if (types.asSuper(m1Owner.type, m2Owner) != null &&
  1471                     ((m1.owner.flags_field & INTERFACE) == 0 ||
  1472                      (m2.owner.flags_field & INTERFACE) != 0) &&
  1473                     m1.overrides(m2, m1Owner, types, false))
  1474                     return m1;
  1475                 if (types.asSuper(m2Owner.type, m1Owner) != null &&
  1476                     ((m2.owner.flags_field & INTERFACE) == 0 ||
  1477                      (m1.owner.flags_field & INTERFACE) != 0) &&
  1478                     m2.overrides(m1, m2Owner, types, false))
  1479                     return m2;
  1480                 boolean m1Abstract = (m1.flags() & ABSTRACT) != 0;
  1481                 boolean m2Abstract = (m2.flags() & ABSTRACT) != 0;
  1482                 if (m1Abstract && !m2Abstract) return m2;
  1483                 if (m2Abstract && !m1Abstract) return m1;
  1484                 // both abstract or both concrete
  1485                 return ambiguityError(m1, m2);
  1487             if (m1SignatureMoreSpecific) return m1;
  1488             if (m2SignatureMoreSpecific) return m2;
  1489             return ambiguityError(m1, m2);
  1490         case AMBIGUOUS:
  1491             //check if m1 is more specific than all ambiguous methods in m2
  1492             AmbiguityError e = (AmbiguityError)m2;
  1493             for (Symbol s : e.ambiguousSyms) {
  1494                 if (mostSpecific(argtypes, m1, s, env, site, allowBoxing, useVarargs) != m1) {
  1495                     return e.addAmbiguousSymbol(m1);
  1498             return m1;
  1499         default:
  1500             throw new AssertionError();
  1503     //where
  1504     private boolean signatureMoreSpecific(List<Type> actuals, Env<AttrContext> env, Type site, Symbol m1, Symbol m2, boolean allowBoxing, boolean useVarargs) {
  1505         noteWarner.clear();
  1506         int maxLength = Math.max(
  1507                             Math.max(m1.type.getParameterTypes().length(), actuals.length()),
  1508                             m2.type.getParameterTypes().length());
  1509         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  1510         try {
  1511             currentResolutionContext = new MethodResolutionContext();
  1512             currentResolutionContext.step = prevResolutionContext.step;
  1513             currentResolutionContext.methodCheck =
  1514                     prevResolutionContext.methodCheck.mostSpecificCheck(actuals, !allowBoxing);
  1515             Type mst = instantiate(env, site, m2, null,
  1516                     adjustArgs(types.lowerBounds(types.memberType(site, m1).getParameterTypes()), m1, maxLength, useVarargs), null,
  1517                     allowBoxing, useVarargs, noteWarner);
  1518             return mst != null &&
  1519                     !noteWarner.hasLint(Lint.LintCategory.UNCHECKED);
  1520         } finally {
  1521             currentResolutionContext = prevResolutionContext;
  1524     private List<Type> adjustArgs(List<Type> args, Symbol msym, int length, boolean allowVarargs) {
  1525         if ((msym.flags() & VARARGS) != 0 && allowVarargs) {
  1526             Type varargsElem = types.elemtype(args.last());
  1527             if (varargsElem == null) {
  1528                 Assert.error("Bad varargs = " + args.last() + " " + msym);
  1530             List<Type> newArgs = args.reverse().tail.prepend(varargsElem).reverse();
  1531             while (newArgs.length() < length) {
  1532                 newArgs = newArgs.append(newArgs.last());
  1534             return newArgs;
  1535         } else {
  1536             return args;
  1539     //where
  1540     Type mostSpecificReturnType(Type mt1, Type mt2) {
  1541         Type rt1 = mt1.getReturnType();
  1542         Type rt2 = mt2.getReturnType();
  1544         if (mt1.hasTag(FORALL) && mt2.hasTag(FORALL)) {
  1545             //if both are generic methods, adjust return type ahead of subtyping check
  1546             rt1 = types.subst(rt1, mt1.getTypeArguments(), mt2.getTypeArguments());
  1548         //first use subtyping, then return type substitutability
  1549         if (types.isSubtype(rt1, rt2)) {
  1550             return mt1;
  1551         } else if (types.isSubtype(rt2, rt1)) {
  1552             return mt2;
  1553         } else if (types.returnTypeSubstitutable(mt1, mt2)) {
  1554             return mt1;
  1555         } else if (types.returnTypeSubstitutable(mt2, mt1)) {
  1556             return mt2;
  1557         } else {
  1558             return null;
  1561     //where
  1562     Symbol ambiguityError(Symbol m1, Symbol m2) {
  1563         if (((m1.flags() | m2.flags()) & CLASH) != 0) {
  1564             return (m1.flags() & CLASH) == 0 ? m1 : m2;
  1565         } else {
  1566             return new AmbiguityError(m1, m2);
  1570     Symbol findMethodInScope(Env<AttrContext> env,
  1571             Type site,
  1572             Name name,
  1573             List<Type> argtypes,
  1574             List<Type> typeargtypes,
  1575             Scope sc,
  1576             Symbol bestSoFar,
  1577             boolean allowBoxing,
  1578             boolean useVarargs,
  1579             boolean operator,
  1580             boolean abstractok) {
  1581         for (Symbol s : sc.getElementsByName(name, new LookupFilter(abstractok))) {
  1582             bestSoFar = selectBest(env, site, argtypes, typeargtypes, s,
  1583                     bestSoFar, allowBoxing, useVarargs, operator);
  1585         return bestSoFar;
  1587     //where
  1588         class LookupFilter implements Filter<Symbol> {
  1590             boolean abstractOk;
  1592             LookupFilter(boolean abstractOk) {
  1593                 this.abstractOk = abstractOk;
  1596             public boolean accepts(Symbol s) {
  1597                 long flags = s.flags();
  1598                 return s.kind == MTH &&
  1599                         (flags & SYNTHETIC) == 0 &&
  1600                         (abstractOk ||
  1601                         (flags & DEFAULT) != 0 ||
  1602                         (flags & ABSTRACT) == 0);
  1604         };
  1606     /** Find best qualified method matching given name, type and value
  1607      *  arguments.
  1608      *  @param env       The current environment.
  1609      *  @param site      The original type from where the selection
  1610      *                   takes place.
  1611      *  @param name      The method's name.
  1612      *  @param argtypes  The method's value arguments.
  1613      *  @param typeargtypes The method's type arguments
  1614      *  @param allowBoxing Allow boxing conversions of arguments.
  1615      *  @param useVarargs Box trailing arguments into an array for varargs.
  1616      */
  1617     Symbol findMethod(Env<AttrContext> env,
  1618                       Type site,
  1619                       Name name,
  1620                       List<Type> argtypes,
  1621                       List<Type> typeargtypes,
  1622                       boolean allowBoxing,
  1623                       boolean useVarargs,
  1624                       boolean operator) {
  1625         Symbol bestSoFar = methodNotFound;
  1626         bestSoFar = findMethod(env,
  1627                           site,
  1628                           name,
  1629                           argtypes,
  1630                           typeargtypes,
  1631                           site.tsym.type,
  1632                           bestSoFar,
  1633                           allowBoxing,
  1634                           useVarargs,
  1635                           operator);
  1636         return bestSoFar;
  1638     // where
  1639     private Symbol findMethod(Env<AttrContext> env,
  1640                               Type site,
  1641                               Name name,
  1642                               List<Type> argtypes,
  1643                               List<Type> typeargtypes,
  1644                               Type intype,
  1645                               Symbol bestSoFar,
  1646                               boolean allowBoxing,
  1647                               boolean useVarargs,
  1648                               boolean operator) {
  1649         @SuppressWarnings({"unchecked","rawtypes"})
  1650         List<Type>[] itypes = (List<Type>[])new List[] { List.<Type>nil(), List.<Type>nil() };
  1651         InterfaceLookupPhase iphase = InterfaceLookupPhase.ABSTRACT_OK;
  1652         for (TypeSymbol s : superclasses(intype)) {
  1653             bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
  1654                     s.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
  1655             if (name == names.init) return bestSoFar;
  1656             iphase = (iphase == null) ? null : iphase.update(s, this);
  1657             if (iphase != null) {
  1658                 for (Type itype : types.interfaces(s.type)) {
  1659                     itypes[iphase.ordinal()] = types.union(types.closure(itype), itypes[iphase.ordinal()]);
  1664         Symbol concrete = bestSoFar.kind < ERR &&
  1665                 (bestSoFar.flags() & ABSTRACT) == 0 ?
  1666                 bestSoFar : methodNotFound;
  1668         for (InterfaceLookupPhase iphase2 : InterfaceLookupPhase.values()) {
  1669             if (iphase2 == InterfaceLookupPhase.DEFAULT_OK && !allowDefaultMethods) break;
  1670             //keep searching for abstract methods
  1671             for (Type itype : itypes[iphase2.ordinal()]) {
  1672                 if (!itype.isInterface()) continue; //skip j.l.Object (included by Types.closure())
  1673                 if (iphase2 == InterfaceLookupPhase.DEFAULT_OK &&
  1674                         (itype.tsym.flags() & DEFAULT) == 0) continue;
  1675                 bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
  1676                         itype.tsym.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
  1677                 if (concrete != bestSoFar &&
  1678                         concrete.kind < ERR  && bestSoFar.kind < ERR &&
  1679                         types.isSubSignature(concrete.type, bestSoFar.type)) {
  1680                     //this is an hack - as javac does not do full membership checks
  1681                     //most specific ends up comparing abstract methods that might have
  1682                     //been implemented by some concrete method in a subclass and,
  1683                     //because of raw override, it is possible for an abstract method
  1684                     //to be more specific than the concrete method - so we need
  1685                     //to explicitly call that out (see CR 6178365)
  1686                     bestSoFar = concrete;
  1690         return bestSoFar;
  1693     enum InterfaceLookupPhase {
  1694         ABSTRACT_OK() {
  1695             @Override
  1696             InterfaceLookupPhase update(Symbol s, Resolve rs) {
  1697                 //We should not look for abstract methods if receiver is a concrete class
  1698                 //(as concrete classes are expected to implement all abstracts coming
  1699                 //from superinterfaces)
  1700                 if ((s.flags() & (ABSTRACT | INTERFACE | ENUM)) != 0) {
  1701                     return this;
  1702                 } else if (rs.allowDefaultMethods) {
  1703                     return DEFAULT_OK;
  1704                 } else {
  1705                     return null;
  1708         },
  1709         DEFAULT_OK() {
  1710             @Override
  1711             InterfaceLookupPhase update(Symbol s, Resolve rs) {
  1712                 return this;
  1714         };
  1716         abstract InterfaceLookupPhase update(Symbol s, Resolve rs);
  1719     /**
  1720      * Return an Iterable object to scan the superclasses of a given type.
  1721      * It's crucial that the scan is done lazily, as we don't want to accidentally
  1722      * access more supertypes than strictly needed (as this could trigger completion
  1723      * errors if some of the not-needed supertypes are missing/ill-formed).
  1724      */
  1725     Iterable<TypeSymbol> superclasses(final Type intype) {
  1726         return new Iterable<TypeSymbol>() {
  1727             public Iterator<TypeSymbol> iterator() {
  1728                 return new Iterator<TypeSymbol>() {
  1730                     List<TypeSymbol> seen = List.nil();
  1731                     TypeSymbol currentSym = symbolFor(intype);
  1732                     TypeSymbol prevSym = null;
  1734                     public boolean hasNext() {
  1735                         if (currentSym == syms.noSymbol) {
  1736                             currentSym = symbolFor(types.supertype(prevSym.type));
  1738                         return currentSym != null;
  1741                     public TypeSymbol next() {
  1742                         prevSym = currentSym;
  1743                         currentSym = syms.noSymbol;
  1744                         Assert.check(prevSym != null || prevSym != syms.noSymbol);
  1745                         return prevSym;
  1748                     public void remove() {
  1749                         throw new UnsupportedOperationException();
  1752                     TypeSymbol symbolFor(Type t) {
  1753                         if (!t.hasTag(CLASS) &&
  1754                                 !t.hasTag(TYPEVAR)) {
  1755                             return null;
  1757                         while (t.hasTag(TYPEVAR))
  1758                             t = t.getUpperBound();
  1759                         if (seen.contains(t.tsym)) {
  1760                             //degenerate case in which we have a circular
  1761                             //class hierarchy - because of ill-formed classfiles
  1762                             return null;
  1764                         seen = seen.prepend(t.tsym);
  1765                         return t.tsym;
  1767                 };
  1769         };
  1772     /** Find unqualified method matching given name, type and value arguments.
  1773      *  @param env       The current environment.
  1774      *  @param name      The method's name.
  1775      *  @param argtypes  The method's value arguments.
  1776      *  @param typeargtypes  The method's type arguments.
  1777      *  @param allowBoxing Allow boxing conversions of arguments.
  1778      *  @param useVarargs Box trailing arguments into an array for varargs.
  1779      */
  1780     Symbol findFun(Env<AttrContext> env, Name name,
  1781                    List<Type> argtypes, List<Type> typeargtypes,
  1782                    boolean allowBoxing, boolean useVarargs) {
  1783         Symbol bestSoFar = methodNotFound;
  1784         Symbol sym;
  1785         Env<AttrContext> env1 = env;
  1786         boolean staticOnly = false;
  1787         while (env1.outer != null) {
  1788             if (isStatic(env1)) staticOnly = true;
  1789             sym = findMethod(
  1790                 env1, env1.enclClass.sym.type, name, argtypes, typeargtypes,
  1791                 allowBoxing, useVarargs, false);
  1792             if (sym.exists()) {
  1793                 if (staticOnly &&
  1794                     sym.kind == MTH &&
  1795                     sym.owner.kind == TYP &&
  1796                     (sym.flags() & STATIC) == 0) return new StaticError(sym);
  1797                 else return sym;
  1798             } else if (sym.kind < bestSoFar.kind) {
  1799                 bestSoFar = sym;
  1801             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  1802             env1 = env1.outer;
  1805         sym = findMethod(env, syms.predefClass.type, name, argtypes,
  1806                          typeargtypes, allowBoxing, useVarargs, false);
  1807         if (sym.exists())
  1808             return sym;
  1810         Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
  1811         for (; e.scope != null; e = e.next()) {
  1812             sym = e.sym;
  1813             Type origin = e.getOrigin().owner.type;
  1814             if (sym.kind == MTH) {
  1815                 if (e.sym.owner.type != origin)
  1816                     sym = sym.clone(e.getOrigin().owner);
  1817                 if (!isAccessible(env, origin, sym))
  1818                     sym = new AccessError(env, origin, sym);
  1819                 bestSoFar = selectBest(env, origin,
  1820                                        argtypes, typeargtypes,
  1821                                        sym, bestSoFar,
  1822                                        allowBoxing, useVarargs, false);
  1825         if (bestSoFar.exists())
  1826             return bestSoFar;
  1828         e = env.toplevel.starImportScope.lookup(name);
  1829         for (; e.scope != null; e = e.next()) {
  1830             sym = e.sym;
  1831             Type origin = e.getOrigin().owner.type;
  1832             if (sym.kind == MTH) {
  1833                 if (e.sym.owner.type != origin)
  1834                     sym = sym.clone(e.getOrigin().owner);
  1835                 if (!isAccessible(env, origin, sym))
  1836                     sym = new AccessError(env, origin, sym);
  1837                 bestSoFar = selectBest(env, origin,
  1838                                        argtypes, typeargtypes,
  1839                                        sym, bestSoFar,
  1840                                        allowBoxing, useVarargs, false);
  1843         return bestSoFar;
  1846     /** Load toplevel or member class with given fully qualified name and
  1847      *  verify that it is accessible.
  1848      *  @param env       The current environment.
  1849      *  @param name      The fully qualified name of the class to be loaded.
  1850      */
  1851     Symbol loadClass(Env<AttrContext> env, Name name) {
  1852         try {
  1853             ClassSymbol c = reader.loadClass(name);
  1854             return isAccessible(env, c) ? c : new AccessError(c);
  1855         } catch (ClassReader.BadClassFile err) {
  1856             throw err;
  1857         } catch (CompletionFailure ex) {
  1858             return typeNotFound;
  1862     /** Find qualified member type.
  1863      *  @param env       The current environment.
  1864      *  @param site      The original type from where the selection takes
  1865      *                   place.
  1866      *  @param name      The type's name.
  1867      *  @param c         The class to search for the member type. This is
  1868      *                   always a superclass or implemented interface of
  1869      *                   site's class.
  1870      */
  1871     Symbol findMemberType(Env<AttrContext> env,
  1872                           Type site,
  1873                           Name name,
  1874                           TypeSymbol c) {
  1875         Symbol bestSoFar = typeNotFound;
  1876         Symbol sym;
  1877         Scope.Entry e = c.members().lookup(name);
  1878         while (e.scope != null) {
  1879             if (e.sym.kind == TYP) {
  1880                 return isAccessible(env, site, e.sym)
  1881                     ? e.sym
  1882                     : new AccessError(env, site, e.sym);
  1884             e = e.next();
  1886         Type st = types.supertype(c.type);
  1887         if (st != null && st.hasTag(CLASS)) {
  1888             sym = findMemberType(env, site, name, st.tsym);
  1889             if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1891         for (List<Type> l = types.interfaces(c.type);
  1892              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
  1893              l = l.tail) {
  1894             sym = findMemberType(env, site, name, l.head.tsym);
  1895             if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
  1896                 sym.owner != bestSoFar.owner)
  1897                 bestSoFar = new AmbiguityError(bestSoFar, sym);
  1898             else if (sym.kind < bestSoFar.kind)
  1899                 bestSoFar = sym;
  1901         return bestSoFar;
  1904     /** Find a global type in given scope and load corresponding class.
  1905      *  @param env       The current environment.
  1906      *  @param scope     The scope in which to look for the type.
  1907      *  @param name      The type's name.
  1908      */
  1909     Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name) {
  1910         Symbol bestSoFar = typeNotFound;
  1911         for (Scope.Entry e = scope.lookup(name); e.scope != null; e = e.next()) {
  1912             Symbol sym = loadClass(env, e.sym.flatName());
  1913             if (bestSoFar.kind == TYP && sym.kind == TYP &&
  1914                 bestSoFar != sym)
  1915                 return new AmbiguityError(bestSoFar, sym);
  1916             else if (sym.kind < bestSoFar.kind)
  1917                 bestSoFar = sym;
  1919         return bestSoFar;
  1922     /** Find an unqualified type symbol.
  1923      *  @param env       The current environment.
  1924      *  @param name      The type's name.
  1925      */
  1926     Symbol findType(Env<AttrContext> env, Name name) {
  1927         Symbol bestSoFar = typeNotFound;
  1928         Symbol sym;
  1929         boolean staticOnly = false;
  1930         for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
  1931             if (isStatic(env1)) staticOnly = true;
  1932             for (Scope.Entry e = env1.info.scope.lookup(name);
  1933                  e.scope != null;
  1934                  e = e.next()) {
  1935                 if (e.sym.kind == TYP) {
  1936                     if (staticOnly &&
  1937                         e.sym.type.hasTag(TYPEVAR) &&
  1938                         e.sym.owner.kind == TYP) return new StaticError(e.sym);
  1939                     return e.sym;
  1943             sym = findMemberType(env1, env1.enclClass.sym.type, name,
  1944                                  env1.enclClass.sym);
  1945             if (staticOnly && sym.kind == TYP &&
  1946                 sym.type.hasTag(CLASS) &&
  1947                 sym.type.getEnclosingType().hasTag(CLASS) &&
  1948                 env1.enclClass.sym.type.isParameterized() &&
  1949                 sym.type.getEnclosingType().isParameterized())
  1950                 return new StaticError(sym);
  1951             else if (sym.exists()) return sym;
  1952             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1954             JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass;
  1955             if ((encl.sym.flags() & STATIC) != 0)
  1956                 staticOnly = true;
  1959         if (!env.tree.hasTag(IMPORT)) {
  1960             sym = findGlobalType(env, env.toplevel.namedImportScope, name);
  1961             if (sym.exists()) return sym;
  1962             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1964             sym = findGlobalType(env, env.toplevel.packge.members(), name);
  1965             if (sym.exists()) return sym;
  1966             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1968             sym = findGlobalType(env, env.toplevel.starImportScope, name);
  1969             if (sym.exists()) return sym;
  1970             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1973         return bestSoFar;
  1976     /** Find an unqualified identifier which matches a specified kind set.
  1977      *  @param env       The current environment.
  1978      *  @param name      The identifier's name.
  1979      *  @param kind      Indicates the possible symbol kinds
  1980      *                   (a subset of VAL, TYP, PCK).
  1981      */
  1982     Symbol findIdent(Env<AttrContext> env, Name name, int kind) {
  1983         Symbol bestSoFar = typeNotFound;
  1984         Symbol sym;
  1986         if ((kind & VAR) != 0) {
  1987             sym = findVar(env, name);
  1988             if (sym.exists()) return sym;
  1989             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1992         if ((kind & TYP) != 0) {
  1993             sym = findType(env, name);
  1994             if (sym.kind==TYP) {
  1995                  reportDependence(env.enclClass.sym, sym);
  1997             if (sym.exists()) return sym;
  1998             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  2001         if ((kind & PCK) != 0) return reader.enterPackage(name);
  2002         else return bestSoFar;
  2005     /** Report dependencies.
  2006      * @param from The enclosing class sym
  2007      * @param to   The found identifier that the class depends on.
  2008      */
  2009     public void reportDependence(Symbol from, Symbol to) {
  2010         // Override if you want to collect the reported dependencies.
  2013     /** Find an identifier in a package which matches a specified kind set.
  2014      *  @param env       The current environment.
  2015      *  @param name      The identifier's name.
  2016      *  @param kind      Indicates the possible symbol kinds
  2017      *                   (a nonempty subset of TYP, PCK).
  2018      */
  2019     Symbol findIdentInPackage(Env<AttrContext> env, TypeSymbol pck,
  2020                               Name name, int kind) {
  2021         Name fullname = TypeSymbol.formFullName(name, pck);
  2022         Symbol bestSoFar = typeNotFound;
  2023         PackageSymbol pack = null;
  2024         if ((kind & PCK) != 0) {
  2025             pack = reader.enterPackage(fullname);
  2026             if (pack.exists()) return pack;
  2028         if ((kind & TYP) != 0) {
  2029             Symbol sym = loadClass(env, fullname);
  2030             if (sym.exists()) {
  2031                 // don't allow programs to use flatnames
  2032                 if (name == sym.name) return sym;
  2034             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  2036         return (pack != null) ? pack : bestSoFar;
  2039     /** Find an identifier among the members of a given type `site'.
  2040      *  @param env       The current environment.
  2041      *  @param site      The type containing the symbol to be found.
  2042      *  @param name      The identifier's name.
  2043      *  @param kind      Indicates the possible symbol kinds
  2044      *                   (a subset of VAL, TYP).
  2045      */
  2046     Symbol findIdentInType(Env<AttrContext> env, Type site,
  2047                            Name name, int kind) {
  2048         Symbol bestSoFar = typeNotFound;
  2049         Symbol sym;
  2050         if ((kind & VAR) != 0) {
  2051             sym = findField(env, site, name, site.tsym);
  2052             if (sym.exists()) return sym;
  2053             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  2056         if ((kind & TYP) != 0) {
  2057             sym = findMemberType(env, site, name, site.tsym);
  2058             if (sym.exists()) return sym;
  2059             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  2061         return bestSoFar;
  2064 /* ***************************************************************************
  2065  *  Access checking
  2066  *  The following methods convert ResolveErrors to ErrorSymbols, issuing
  2067  *  an error message in the process
  2068  ****************************************************************************/
  2070     /** If `sym' is a bad symbol: report error and return errSymbol
  2071      *  else pass through unchanged,
  2072      *  additional arguments duplicate what has been used in trying to find the
  2073      *  symbol {@literal (--> flyweight pattern)}. This improves performance since we
  2074      *  expect misses to happen frequently.
  2076      *  @param sym       The symbol that was found, or a ResolveError.
  2077      *  @param pos       The position to use for error reporting.
  2078      *  @param location  The symbol the served as a context for this lookup
  2079      *  @param site      The original type from where the selection took place.
  2080      *  @param name      The symbol's name.
  2081      *  @param qualified Did we get here through a qualified expression resolution?
  2082      *  @param argtypes  The invocation's value arguments,
  2083      *                   if we looked for a method.
  2084      *  @param typeargtypes  The invocation's type arguments,
  2085      *                   if we looked for a method.
  2086      *  @param logResolveHelper helper class used to log resolve errors
  2087      */
  2088     Symbol accessInternal(Symbol sym,
  2089                   DiagnosticPosition pos,
  2090                   Symbol location,
  2091                   Type site,
  2092                   Name name,
  2093                   boolean qualified,
  2094                   List<Type> argtypes,
  2095                   List<Type> typeargtypes,
  2096                   LogResolveHelper logResolveHelper) {
  2097         if (sym.kind >= AMBIGUOUS) {
  2098             ResolveError errSym = (ResolveError)sym;
  2099             sym = errSym.access(name, qualified ? site.tsym : syms.noSymbol);
  2100             argtypes = logResolveHelper.getArgumentTypes(errSym, sym, name, argtypes);
  2101             if (logResolveHelper.resolveDiagnosticNeeded(site, argtypes, typeargtypes)) {
  2102                 logResolveError(errSym, pos, location, site, name, argtypes, typeargtypes);
  2105         return sym;
  2108     /**
  2109      * Variant of the generalized access routine, to be used for generating method
  2110      * resolution diagnostics
  2111      */
  2112     Symbol accessMethod(Symbol sym,
  2113                   DiagnosticPosition pos,
  2114                   Symbol location,
  2115                   Type site,
  2116                   Name name,
  2117                   boolean qualified,
  2118                   List<Type> argtypes,
  2119                   List<Type> typeargtypes) {
  2120         return accessInternal(sym, pos, location, site, name, qualified, argtypes, typeargtypes, methodLogResolveHelper);
  2123     /** Same as original accessMethod(), but without location.
  2124      */
  2125     Symbol accessMethod(Symbol sym,
  2126                   DiagnosticPosition pos,
  2127                   Type site,
  2128                   Name name,
  2129                   boolean qualified,
  2130                   List<Type> argtypes,
  2131                   List<Type> typeargtypes) {
  2132         return accessMethod(sym, pos, site.tsym, site, name, qualified, argtypes, typeargtypes);
  2135     /**
  2136      * Variant of the generalized access routine, to be used for generating variable,
  2137      * type resolution diagnostics
  2138      */
  2139     Symbol accessBase(Symbol sym,
  2140                   DiagnosticPosition pos,
  2141                   Symbol location,
  2142                   Type site,
  2143                   Name name,
  2144                   boolean qualified) {
  2145         return accessInternal(sym, pos, location, site, name, qualified, List.<Type>nil(), null, basicLogResolveHelper);
  2148     /** Same as original accessBase(), but without location.
  2149      */
  2150     Symbol accessBase(Symbol sym,
  2151                   DiagnosticPosition pos,
  2152                   Type site,
  2153                   Name name,
  2154                   boolean qualified) {
  2155         return accessBase(sym, pos, site.tsym, site, name, qualified);
  2158     interface LogResolveHelper {
  2159         boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes);
  2160         List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes);
  2163     LogResolveHelper basicLogResolveHelper = new LogResolveHelper() {
  2164         public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
  2165             return !site.isErroneous();
  2167         public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
  2168             return argtypes;
  2170     };
  2172     LogResolveHelper methodLogResolveHelper = new LogResolveHelper() {
  2173         public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
  2174             return !site.isErroneous() &&
  2175                         !Type.isErroneous(argtypes) &&
  2176                         (typeargtypes == null || !Type.isErroneous(typeargtypes));
  2178         public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
  2179             return (syms.operatorNames.contains(name)) ?
  2180                     argtypes :
  2181                     Type.map(argtypes, new ResolveDeferredRecoveryMap(accessedSym));
  2184         class ResolveDeferredRecoveryMap extends DeferredAttr.RecoveryDeferredTypeMap {
  2186             public ResolveDeferredRecoveryMap(Symbol msym) {
  2187                 deferredAttr.super(AttrMode.SPECULATIVE, msym, currentResolutionContext.step);
  2190             @Override
  2191             protected Type typeOf(DeferredType dt) {
  2192                 Type res = super.typeOf(dt);
  2193                 if (!res.isErroneous()) {
  2194                     switch (TreeInfo.skipParens(dt.tree).getTag()) {
  2195                         case LAMBDA:
  2196                         case REFERENCE:
  2197                             return dt;
  2198                         case CONDEXPR:
  2199                             return res == Type.recoveryType ?
  2200                                     dt : res;
  2203                 return res;
  2206     };
  2208     /** Check that sym is not an abstract method.
  2209      */
  2210     void checkNonAbstract(DiagnosticPosition pos, Symbol sym) {
  2211         if ((sym.flags() & ABSTRACT) != 0 && (sym.flags() & DEFAULT) == 0)
  2212             log.error(pos, "abstract.cant.be.accessed.directly",
  2213                       kindName(sym), sym, sym.location());
  2216 /* ***************************************************************************
  2217  *  Debugging
  2218  ****************************************************************************/
  2220     /** print all scopes starting with scope s and proceeding outwards.
  2221      *  used for debugging.
  2222      */
  2223     public void printscopes(Scope s) {
  2224         while (s != null) {
  2225             if (s.owner != null)
  2226                 System.err.print(s.owner + ": ");
  2227             for (Scope.Entry e = s.elems; e != null; e = e.sibling) {
  2228                 if ((e.sym.flags() & ABSTRACT) != 0)
  2229                     System.err.print("abstract ");
  2230                 System.err.print(e.sym + " ");
  2232             System.err.println();
  2233             s = s.next;
  2237     void printscopes(Env<AttrContext> env) {
  2238         while (env.outer != null) {
  2239             System.err.println("------------------------------");
  2240             printscopes(env.info.scope);
  2241             env = env.outer;
  2245     public void printscopes(Type t) {
  2246         while (t.hasTag(CLASS)) {
  2247             printscopes(t.tsym.members());
  2248             t = types.supertype(t);
  2252 /* ***************************************************************************
  2253  *  Name resolution
  2254  *  Naming conventions are as for symbol lookup
  2255  *  Unlike the find... methods these methods will report access errors
  2256  ****************************************************************************/
  2258     /** Resolve an unqualified (non-method) identifier.
  2259      *  @param pos       The position to use for error reporting.
  2260      *  @param env       The environment current at the identifier use.
  2261      *  @param name      The identifier's name.
  2262      *  @param kind      The set of admissible symbol kinds for the identifier.
  2263      */
  2264     Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env,
  2265                         Name name, int kind) {
  2266         return accessBase(
  2267             findIdent(env, name, kind),
  2268             pos, env.enclClass.sym.type, name, false);
  2271     /** Resolve an unqualified method identifier.
  2272      *  @param pos       The position to use for error reporting.
  2273      *  @param env       The environment current at the method invocation.
  2274      *  @param name      The identifier's name.
  2275      *  @param argtypes  The types of the invocation's value arguments.
  2276      *  @param typeargtypes  The types of the invocation's type arguments.
  2277      */
  2278     Symbol resolveMethod(DiagnosticPosition pos,
  2279                          Env<AttrContext> env,
  2280                          Name name,
  2281                          List<Type> argtypes,
  2282                          List<Type> typeargtypes) {
  2283         return lookupMethod(env, pos, env.enclClass.sym, resolveMethodCheck,
  2284                 new BasicLookupHelper(name, env.enclClass.sym.type, argtypes, typeargtypes) {
  2285                     @Override
  2286                     Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2287                         return findFun(env, name, argtypes, typeargtypes,
  2288                                 phase.isBoxingRequired(),
  2289                                 phase.isVarargsRequired());
  2290                     }});
  2293     /** Resolve a qualified method identifier
  2294      *  @param pos       The position to use for error reporting.
  2295      *  @param env       The environment current at the method invocation.
  2296      *  @param site      The type of the qualifying expression, in which
  2297      *                   identifier is searched.
  2298      *  @param name      The identifier's name.
  2299      *  @param argtypes  The types of the invocation's value arguments.
  2300      *  @param typeargtypes  The types of the invocation's type arguments.
  2301      */
  2302     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
  2303                                   Type site, Name name, List<Type> argtypes,
  2304                                   List<Type> typeargtypes) {
  2305         return resolveQualifiedMethod(pos, env, site.tsym, site, name, argtypes, typeargtypes);
  2307     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
  2308                                   Symbol location, Type site, Name name, List<Type> argtypes,
  2309                                   List<Type> typeargtypes) {
  2310         return resolveQualifiedMethod(new MethodResolutionContext(), pos, env, location, site, name, argtypes, typeargtypes);
  2312     private Symbol resolveQualifiedMethod(MethodResolutionContext resolveContext,
  2313                                   DiagnosticPosition pos, Env<AttrContext> env,
  2314                                   Symbol location, Type site, Name name, List<Type> argtypes,
  2315                                   List<Type> typeargtypes) {
  2316         return lookupMethod(env, pos, location, resolveContext, new BasicLookupHelper(name, site, argtypes, typeargtypes) {
  2317             @Override
  2318             Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2319                 return findMethod(env, site, name, argtypes, typeargtypes,
  2320                         phase.isBoxingRequired(),
  2321                         phase.isVarargsRequired(), false);
  2323             @Override
  2324             Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2325                 if (sym.kind >= AMBIGUOUS) {
  2326                     sym = super.access(env, pos, location, sym);
  2327                 } else if (allowMethodHandles) {
  2328                     MethodSymbol msym = (MethodSymbol)sym;
  2329                     if ((msym.flags() & SIGNATURE_POLYMORPHIC) != 0) {
  2330                         return findPolymorphicSignatureInstance(env, sym, argtypes);
  2333                 return sym;
  2335         });
  2338     /** Find or create an implicit method of exactly the given type (after erasure).
  2339      *  Searches in a side table, not the main scope of the site.
  2340      *  This emulates the lookup process required by JSR 292 in JVM.
  2341      *  @param env       Attribution environment
  2342      *  @param spMethod  signature polymorphic method - i.e. MH.invokeExact
  2343      *  @param argtypes  The required argument types
  2344      */
  2345     Symbol findPolymorphicSignatureInstance(Env<AttrContext> env,
  2346                                             final Symbol spMethod,
  2347                                             List<Type> argtypes) {
  2348         Type mtype = infer.instantiatePolymorphicSignatureInstance(env,
  2349                 (MethodSymbol)spMethod, currentResolutionContext, argtypes);
  2350         for (Symbol sym : polymorphicSignatureScope.getElementsByName(spMethod.name)) {
  2351             if (types.isSameType(mtype, sym.type)) {
  2352                return sym;
  2356         // create the desired method
  2357         long flags = ABSTRACT | HYPOTHETICAL | spMethod.flags() & Flags.AccessFlags;
  2358         Symbol msym = new MethodSymbol(flags, spMethod.name, mtype, spMethod.owner) {
  2359             @Override
  2360             public Symbol baseSymbol() {
  2361                 return spMethod;
  2363         };
  2364         polymorphicSignatureScope.enter(msym);
  2365         return msym;
  2368     /** Resolve a qualified method identifier, throw a fatal error if not
  2369      *  found.
  2370      *  @param pos       The position to use for error reporting.
  2371      *  @param env       The environment current at the method invocation.
  2372      *  @param site      The type of the qualifying expression, in which
  2373      *                   identifier is searched.
  2374      *  @param name      The identifier's name.
  2375      *  @param argtypes  The types of the invocation's value arguments.
  2376      *  @param typeargtypes  The types of the invocation's type arguments.
  2377      */
  2378     public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env,
  2379                                         Type site, Name name,
  2380                                         List<Type> argtypes,
  2381                                         List<Type> typeargtypes) {
  2382         MethodResolutionContext resolveContext = new MethodResolutionContext();
  2383         resolveContext.internalResolution = true;
  2384         Symbol sym = resolveQualifiedMethod(resolveContext, pos, env, site.tsym,
  2385                 site, name, argtypes, typeargtypes);
  2386         if (sym.kind == MTH) return (MethodSymbol)sym;
  2387         else throw new FatalError(
  2388                  diags.fragment("fatal.err.cant.locate.meth",
  2389                                 name));
  2392     /** Resolve constructor.
  2393      *  @param pos       The position to use for error reporting.
  2394      *  @param env       The environment current at the constructor invocation.
  2395      *  @param site      The type of class for which a constructor is searched.
  2396      *  @param argtypes  The types of the constructor invocation's value
  2397      *                   arguments.
  2398      *  @param typeargtypes  The types of the constructor invocation's type
  2399      *                   arguments.
  2400      */
  2401     Symbol resolveConstructor(DiagnosticPosition pos,
  2402                               Env<AttrContext> env,
  2403                               Type site,
  2404                               List<Type> argtypes,
  2405                               List<Type> typeargtypes) {
  2406         return resolveConstructor(new MethodResolutionContext(), pos, env, site, argtypes, typeargtypes);
  2409     private Symbol resolveConstructor(MethodResolutionContext resolveContext,
  2410                               final DiagnosticPosition pos,
  2411                               Env<AttrContext> env,
  2412                               Type site,
  2413                               List<Type> argtypes,
  2414                               List<Type> typeargtypes) {
  2415         return lookupMethod(env, pos, site.tsym, resolveContext, new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
  2416             @Override
  2417             Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2418                 return findConstructor(pos, env, site, argtypes, typeargtypes,
  2419                         phase.isBoxingRequired(),
  2420                         phase.isVarargsRequired());
  2422         });
  2425     /** Resolve a constructor, throw a fatal error if not found.
  2426      *  @param pos       The position to use for error reporting.
  2427      *  @param env       The environment current at the method invocation.
  2428      *  @param site      The type to be constructed.
  2429      *  @param argtypes  The types of the invocation's value arguments.
  2430      *  @param typeargtypes  The types of the invocation's type arguments.
  2431      */
  2432     public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  2433                                         Type site,
  2434                                         List<Type> argtypes,
  2435                                         List<Type> typeargtypes) {
  2436         MethodResolutionContext resolveContext = new MethodResolutionContext();
  2437         resolveContext.internalResolution = true;
  2438         Symbol sym = resolveConstructor(resolveContext, pos, env, site, argtypes, typeargtypes);
  2439         if (sym.kind == MTH) return (MethodSymbol)sym;
  2440         else throw new FatalError(
  2441                  diags.fragment("fatal.err.cant.locate.ctor", site));
  2444     Symbol findConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  2445                               Type site, List<Type> argtypes,
  2446                               List<Type> typeargtypes,
  2447                               boolean allowBoxing,
  2448                               boolean useVarargs) {
  2449         Symbol sym = findMethod(env, site,
  2450                                     names.init, argtypes,
  2451                                     typeargtypes, allowBoxing,
  2452                                     useVarargs, false);
  2453         chk.checkDeprecated(pos, env.info.scope.owner, sym);
  2454         return sym;
  2457     /** Resolve constructor using diamond inference.
  2458      *  @param pos       The position to use for error reporting.
  2459      *  @param env       The environment current at the constructor invocation.
  2460      *  @param site      The type of class for which a constructor is searched.
  2461      *                   The scope of this class has been touched in attribution.
  2462      *  @param argtypes  The types of the constructor invocation's value
  2463      *                   arguments.
  2464      *  @param typeargtypes  The types of the constructor invocation's type
  2465      *                   arguments.
  2466      */
  2467     Symbol resolveDiamond(DiagnosticPosition pos,
  2468                               Env<AttrContext> env,
  2469                               Type site,
  2470                               List<Type> argtypes,
  2471                               List<Type> typeargtypes) {
  2472         return lookupMethod(env, pos, site.tsym, resolveMethodCheck,
  2473                 new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
  2474                     @Override
  2475                     Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2476                         return findDiamond(env, site, argtypes, typeargtypes,
  2477                                 phase.isBoxingRequired(),
  2478                                 phase.isVarargsRequired());
  2480                     @Override
  2481                     Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2482                         if (sym.kind >= AMBIGUOUS) {
  2483                             final JCDiagnostic details = sym.kind == WRONG_MTH ?
  2484                                             ((InapplicableSymbolError)sym).errCandidate().snd :
  2485                                             null;
  2486                             sym = new InapplicableSymbolError(sym.kind, "diamondError", currentResolutionContext) {
  2487                                 @Override
  2488                                 JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos,
  2489                                         Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
  2490                                     String key = details == null ?
  2491                                         "cant.apply.diamond" :
  2492                                         "cant.apply.diamond.1";
  2493                                     return diags.create(dkind, log.currentSource(), pos, key,
  2494                                             diags.fragment("diamond", site.tsym), details);
  2496                             };
  2497                             sym = accessMethod(sym, pos, site, names.init, true, argtypes, typeargtypes);
  2498                             env.info.pendingResolutionPhase = currentResolutionContext.step;
  2500                         return sym;
  2501                     }});
  2504     /** This method scans all the constructor symbol in a given class scope -
  2505      *  assuming that the original scope contains a constructor of the kind:
  2506      *  {@code Foo(X x, Y y)}, where X,Y are class type-variables declared in Foo,
  2507      *  a method check is executed against the modified constructor type:
  2508      *  {@code <X,Y>Foo<X,Y>(X x, Y y)}. This is crucial in order to enable diamond
  2509      *  inference. The inferred return type of the synthetic constructor IS
  2510      *  the inferred type for the diamond operator.
  2511      */
  2512     private Symbol findDiamond(Env<AttrContext> env,
  2513                               Type site,
  2514                               List<Type> argtypes,
  2515                               List<Type> typeargtypes,
  2516                               boolean allowBoxing,
  2517                               boolean useVarargs) {
  2518         Symbol bestSoFar = methodNotFound;
  2519         for (Scope.Entry e = site.tsym.members().lookup(names.init);
  2520              e.scope != null;
  2521              e = e.next()) {
  2522             final Symbol sym = e.sym;
  2523             //- System.out.println(" e " + e.sym);
  2524             if (sym.kind == MTH &&
  2525                 (sym.flags_field & SYNTHETIC) == 0) {
  2526                     List<Type> oldParams = e.sym.type.hasTag(FORALL) ?
  2527                             ((ForAll)sym.type).tvars :
  2528                             List.<Type>nil();
  2529                     Type constrType = new ForAll(site.tsym.type.getTypeArguments().appendList(oldParams),
  2530                             types.createMethodTypeWithReturn(sym.type.asMethodType(), site));
  2531                     MethodSymbol newConstr = new MethodSymbol(sym.flags(), names.init, constrType, site.tsym) {
  2532                         @Override
  2533                         public Symbol baseSymbol() {
  2534                             return sym;
  2536                     };
  2537                     bestSoFar = selectBest(env, site, argtypes, typeargtypes,
  2538                             newConstr,
  2539                             bestSoFar,
  2540                             allowBoxing,
  2541                             useVarargs,
  2542                             false);
  2545         return bestSoFar;
  2550     /** Resolve operator.
  2551      *  @param pos       The position to use for error reporting.
  2552      *  @param optag     The tag of the operation tree.
  2553      *  @param env       The environment current at the operation.
  2554      *  @param argtypes  The types of the operands.
  2555      */
  2556     Symbol resolveOperator(DiagnosticPosition pos, JCTree.Tag optag,
  2557                            Env<AttrContext> env, List<Type> argtypes) {
  2558         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  2559         try {
  2560             currentResolutionContext = new MethodResolutionContext();
  2561             Name name = treeinfo.operatorName(optag);
  2562             return lookupMethod(env, pos, syms.predefClass, currentResolutionContext,
  2563                     new BasicLookupHelper(name, syms.predefClass.type, argtypes, null, BOX) {
  2564                 @Override
  2565                 Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2566                     return findMethod(env, site, name, argtypes, typeargtypes,
  2567                             phase.isBoxingRequired(),
  2568                             phase.isVarargsRequired(), true);
  2570                 @Override
  2571                 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2572                     return accessMethod(sym, pos, env.enclClass.sym.type, name,
  2573                           false, argtypes, null);
  2575             });
  2576         } finally {
  2577             currentResolutionContext = prevResolutionContext;
  2581     /** Resolve operator.
  2582      *  @param pos       The position to use for error reporting.
  2583      *  @param optag     The tag of the operation tree.
  2584      *  @param env       The environment current at the operation.
  2585      *  @param arg       The type of the operand.
  2586      */
  2587     Symbol resolveUnaryOperator(DiagnosticPosition pos, JCTree.Tag optag, Env<AttrContext> env, Type arg) {
  2588         return resolveOperator(pos, optag, env, List.of(arg));
  2591     /** Resolve binary operator.
  2592      *  @param pos       The position to use for error reporting.
  2593      *  @param optag     The tag of the operation tree.
  2594      *  @param env       The environment current at the operation.
  2595      *  @param left      The types of the left operand.
  2596      *  @param right     The types of the right operand.
  2597      */
  2598     Symbol resolveBinaryOperator(DiagnosticPosition pos,
  2599                                  JCTree.Tag optag,
  2600                                  Env<AttrContext> env,
  2601                                  Type left,
  2602                                  Type right) {
  2603         return resolveOperator(pos, optag, env, List.of(left, right));
  2606     /**
  2607      * Resolution of member references is typically done as a single
  2608      * overload resolution step, where the argument types A are inferred from
  2609      * the target functional descriptor.
  2611      * If the member reference is a method reference with a type qualifier,
  2612      * a two-step lookup process is performed. The first step uses the
  2613      * expected argument list A, while the second step discards the first
  2614      * type from A (which is treated as a receiver type).
  2616      * There are two cases in which inference is performed: (i) if the member
  2617      * reference is a constructor reference and the qualifier type is raw - in
  2618      * which case diamond inference is used to infer a parameterization for the
  2619      * type qualifier; (ii) if the member reference is an unbound reference
  2620      * where the type qualifier is raw - in that case, during the unbound lookup
  2621      * the receiver argument type is used to infer an instantiation for the raw
  2622      * qualifier type.
  2624      * When a multi-step resolution process is exploited, it is an error
  2625      * if two candidates are found (ambiguity).
  2627      * This routine returns a pair (T,S), where S is the member reference symbol,
  2628      * and T is the type of the class in which S is defined. This is necessary as
  2629      * the type T might be dynamically inferred (i.e. if constructor reference
  2630      * has a raw qualifier).
  2631      */
  2632     Pair<Symbol, ReferenceLookupHelper> resolveMemberReference(DiagnosticPosition pos,
  2633                                   Env<AttrContext> env,
  2634                                   JCMemberReference referenceTree,
  2635                                   Type site,
  2636                                   Name name, List<Type> argtypes,
  2637                                   List<Type> typeargtypes,
  2638                                   boolean boxingAllowed,
  2639                                   MethodCheck methodCheck,
  2640                                   InferenceContext inferenceContext) {
  2641         MethodResolutionPhase maxPhase = boxingAllowed ? VARARITY : BASIC;
  2643         if (site.hasTag(TYPEVAR)) {
  2644             return resolveMemberReference(pos, env, referenceTree, site.getUpperBound(),
  2645                     name, argtypes, typeargtypes, boxingAllowed, methodCheck, inferenceContext);
  2648         site = types.capture(site);
  2650         ReferenceLookupHelper boundLookupHelper;
  2651         if (!name.equals(names.init)) {
  2652             //method reference
  2653             boundLookupHelper =
  2654                     new MethodReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
  2655         } else if (site.hasTag(ARRAY)) {
  2656             //array constructor reference
  2657             boundLookupHelper =
  2658                     new ArrayConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase);
  2659         } else {
  2660             //class constructor reference
  2661             boundLookupHelper =
  2662                     new ConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase);
  2665         //step 1 - bound lookup
  2666         Env<AttrContext> boundEnv = env.dup(env.tree, env.info.dup());
  2667         Symbol boundSym = lookupMethod(boundEnv, env.tree.pos(), site.tsym, methodCheck, boundLookupHelper);
  2669         //step 2 - unbound lookup
  2670         ReferenceLookupHelper unboundLookupHelper = boundLookupHelper.unboundLookup(inferenceContext);
  2671         Env<AttrContext> unboundEnv = env.dup(env.tree, env.info.dup());
  2672         Symbol unboundSym = lookupMethod(unboundEnv, env.tree.pos(), site.tsym, methodCheck, unboundLookupHelper);
  2674         //merge results
  2675         Pair<Symbol, ReferenceLookupHelper> res;
  2676         Symbol bestSym = choose(boundSym, unboundSym);
  2677         res = new Pair<Symbol, ReferenceLookupHelper>(bestSym,
  2678                 bestSym == unboundSym ? unboundLookupHelper : boundLookupHelper);
  2679         env.info.pendingResolutionPhase = bestSym == unboundSym ?
  2680                 unboundEnv.info.pendingResolutionPhase :
  2681                 boundEnv.info.pendingResolutionPhase;
  2683         return res;
  2685     //where
  2686         private Symbol choose(Symbol s1, Symbol s2) {
  2687             if (lookupSuccess(s1) && lookupSuccess(s2)) {
  2688                 return ambiguityError(s1, s2);
  2689             } else if (lookupSuccess(s1) ||
  2690                     (canIgnore(s2) && !canIgnore(s1))) {
  2691                 return s1;
  2692             } else if (lookupSuccess(s2) ||
  2693                     (canIgnore(s1) && !canIgnore(s2))) {
  2694                 return s2;
  2695             } else {
  2696                 return s1;
  2700         private boolean lookupSuccess(Symbol s) {
  2701             return s.kind == MTH || s.kind == AMBIGUOUS;
  2704         private boolean canIgnore(Symbol s) {
  2705             switch (s.kind) {
  2706                 case ABSENT_MTH:
  2707                     return true;
  2708                 case WRONG_MTH:
  2709                     InapplicableSymbolError errSym =
  2710                             (InapplicableSymbolError)s;
  2711                     return new Template(MethodCheckDiag.ARITY_MISMATCH.regex())
  2712                             .matches(errSym.errCandidate().snd);
  2713                 case WRONG_MTHS:
  2714                     InapplicableSymbolsError errSyms =
  2715                             (InapplicableSymbolsError)s;
  2716                     return errSyms.filterCandidates(errSyms.mapCandidates()).isEmpty();
  2717                 default:
  2718                     return false;
  2722     /**
  2723      * Helper for defining custom method-like lookup logic; a lookup helper
  2724      * provides hooks for (i) the actual lookup logic and (ii) accessing the
  2725      * lookup result (this step might result in compiler diagnostics to be generated)
  2726      */
  2727     abstract class LookupHelper {
  2729         /** name of the symbol to lookup */
  2730         Name name;
  2732         /** location in which the lookup takes place */
  2733         Type site;
  2735         /** actual types used during the lookup */
  2736         List<Type> argtypes;
  2738         /** type arguments used during the lookup */
  2739         List<Type> typeargtypes;
  2741         /** Max overload resolution phase handled by this helper */
  2742         MethodResolutionPhase maxPhase;
  2744         LookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2745             this.name = name;
  2746             this.site = site;
  2747             this.argtypes = argtypes;
  2748             this.typeargtypes = typeargtypes;
  2749             this.maxPhase = maxPhase;
  2752         /**
  2753          * Should lookup stop at given phase with given result
  2754          */
  2755         protected boolean shouldStop(Symbol sym, MethodResolutionPhase phase) {
  2756             return phase.ordinal() > maxPhase.ordinal() ||
  2757                     sym.kind < ERRONEOUS || sym.kind == AMBIGUOUS;
  2760         /**
  2761          * Search for a symbol under a given overload resolution phase - this method
  2762          * is usually called several times, once per each overload resolution phase
  2763          */
  2764         abstract Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase);
  2766         /**
  2767          * Dump overload resolution info
  2768          */
  2769         void debug(DiagnosticPosition pos, Symbol sym) {
  2770             //do nothing
  2773         /**
  2774          * Validate the result of the lookup
  2775          */
  2776         abstract Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym);
  2779     abstract class BasicLookupHelper extends LookupHelper {
  2781         BasicLookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes) {
  2782             this(name, site, argtypes, typeargtypes, MethodResolutionPhase.VARARITY);
  2785         BasicLookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2786             super(name, site, argtypes, typeargtypes, maxPhase);
  2789         @Override
  2790         final Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2791             Symbol sym = doLookup(env, phase);
  2792             if (sym.kind == AMBIGUOUS) {
  2793                 AmbiguityError a_err = (AmbiguityError)sym;
  2794                 sym = a_err.mergeAbstracts(site);
  2796             return sym;
  2799         abstract Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase);
  2801         @Override
  2802         Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2803             if (sym.kind >= AMBIGUOUS) {
  2804                 //if nothing is found return the 'first' error
  2805                 sym = accessMethod(sym, pos, location, site, name, true, argtypes, typeargtypes);
  2807             return sym;
  2810         @Override
  2811         void debug(DiagnosticPosition pos, Symbol sym) {
  2812             reportVerboseResolutionDiagnostic(pos, name, site, argtypes, typeargtypes, sym);
  2816     /**
  2817      * Helper class for member reference lookup. A reference lookup helper
  2818      * defines the basic logic for member reference lookup; a method gives
  2819      * access to an 'unbound' helper used to perform an unbound member
  2820      * reference lookup.
  2821      */
  2822     abstract class ReferenceLookupHelper extends LookupHelper {
  2824         /** The member reference tree */
  2825         JCMemberReference referenceTree;
  2827         ReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
  2828                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2829             super(name, site, argtypes, typeargtypes, maxPhase);
  2830             this.referenceTree = referenceTree;
  2834         /**
  2835          * Returns an unbound version of this lookup helper. By default, this
  2836          * method returns an dummy lookup helper.
  2837          */
  2838         ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
  2839             //dummy loopkup helper that always return 'methodNotFound'
  2840             return new ReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase) {
  2841                 @Override
  2842                 ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
  2843                     return this;
  2845                 @Override
  2846                 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2847                     return methodNotFound;
  2849                 @Override
  2850                 ReferenceKind referenceKind(Symbol sym) {
  2851                     Assert.error();
  2852                     return null;
  2854             };
  2857         /**
  2858          * Get the kind of the member reference
  2859          */
  2860         abstract JCMemberReference.ReferenceKind referenceKind(Symbol sym);
  2862         Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2863             if (sym.kind == AMBIGUOUS) {
  2864                 AmbiguityError a_err = (AmbiguityError)sym;
  2865                 sym = a_err.mergeAbstracts(site);
  2867             //skip error reporting
  2868             return sym;
  2872     /**
  2873      * Helper class for method reference lookup. The lookup logic is based
  2874      * upon Resolve.findMethod; in certain cases, this helper class has a
  2875      * corresponding unbound helper class (see UnboundMethodReferenceLookupHelper).
  2876      * In such cases, non-static lookup results are thrown away.
  2877      */
  2878     class MethodReferenceLookupHelper extends ReferenceLookupHelper {
  2880         MethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
  2881                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2882             super(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
  2885         @Override
  2886         final Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2887             return findMethod(env, site, name, argtypes, typeargtypes,
  2888                     phase.isBoxingRequired(), phase.isVarargsRequired(), syms.operatorNames.contains(name));
  2891         @Override
  2892         ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
  2893             if (TreeInfo.isStaticSelector(referenceTree.expr, names) &&
  2894                     argtypes.nonEmpty() &&
  2895                     (argtypes.head.hasTag(NONE) ||
  2896                     types.isSubtypeUnchecked(inferenceContext.asFree(argtypes.head), site))) {
  2897                 return new UnboundMethodReferenceLookupHelper(referenceTree, name,
  2898                         site, argtypes, typeargtypes, maxPhase);
  2899             } else {
  2900                 return super.unboundLookup(inferenceContext);
  2904         @Override
  2905         ReferenceKind referenceKind(Symbol sym) {
  2906             if (sym.isStatic()) {
  2907                 return ReferenceKind.STATIC;
  2908             } else {
  2909                 Name selName = TreeInfo.name(referenceTree.getQualifierExpression());
  2910                 return selName != null && selName == names._super ?
  2911                         ReferenceKind.SUPER :
  2912                         ReferenceKind.BOUND;
  2917     /**
  2918      * Helper class for unbound method reference lookup. Essentially the same
  2919      * as the basic method reference lookup helper; main difference is that static
  2920      * lookup results are thrown away. If qualifier type is raw, an attempt to
  2921      * infer a parameterized type is made using the first actual argument (that
  2922      * would otherwise be ignored during the lookup).
  2923      */
  2924     class UnboundMethodReferenceLookupHelper extends MethodReferenceLookupHelper {
  2926         UnboundMethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
  2927                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2928             super(referenceTree, name, site, argtypes.tail, typeargtypes, maxPhase);
  2929             if (site.isRaw() && !argtypes.head.hasTag(NONE)) {
  2930                 Type asSuperSite = types.asSuper(argtypes.head, site.tsym);
  2931                 this.site = asSuperSite;
  2935         @Override
  2936         ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
  2937             return this;
  2940         @Override
  2941         ReferenceKind referenceKind(Symbol sym) {
  2942             return ReferenceKind.UNBOUND;
  2946     /**
  2947      * Helper class for array constructor lookup; an array constructor lookup
  2948      * is simulated by looking up a method that returns the array type specified
  2949      * as qualifier, and that accepts a single int parameter (size of the array).
  2950      */
  2951     class ArrayConstructorReferenceLookupHelper extends ReferenceLookupHelper {
  2953         ArrayConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
  2954                 List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2955             super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase);
  2958         @Override
  2959         protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2960             Scope sc = new Scope(syms.arrayClass);
  2961             MethodSymbol arrayConstr = new MethodSymbol(PUBLIC, name, null, site.tsym);
  2962             arrayConstr.type = new MethodType(List.<Type>of(syms.intType), site, List.<Type>nil(), syms.methodClass);
  2963             sc.enter(arrayConstr);
  2964             return findMethodInScope(env, site, name, argtypes, typeargtypes, sc, methodNotFound, phase.isBoxingRequired(), phase.isVarargsRequired(), false, false);
  2967         @Override
  2968         ReferenceKind referenceKind(Symbol sym) {
  2969             return ReferenceKind.ARRAY_CTOR;
  2973     /**
  2974      * Helper class for constructor reference lookup. The lookup logic is based
  2975      * upon either Resolve.findMethod or Resolve.findDiamond - depending on
  2976      * whether the constructor reference needs diamond inference (this is the case
  2977      * if the qualifier type is raw). A special erroneous symbol is returned
  2978      * if the lookup returns the constructor of an inner class and there's no
  2979      * enclosing instance in scope.
  2980      */
  2981     class ConstructorReferenceLookupHelper extends ReferenceLookupHelper {
  2983         boolean needsInference;
  2985         ConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
  2986                 List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2987             super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase);
  2988             if (site.isRaw()) {
  2989                 this.site = new ClassType(site.getEnclosingType(), site.tsym.type.getTypeArguments(), site.tsym);
  2990                 needsInference = true;
  2994         @Override
  2995         protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2996             Symbol sym = needsInference ?
  2997                 findDiamond(env, site, argtypes, typeargtypes, phase.isBoxingRequired(), phase.isVarargsRequired()) :
  2998                 findMethod(env, site, name, argtypes, typeargtypes,
  2999                         phase.isBoxingRequired(), phase.isVarargsRequired(), syms.operatorNames.contains(name));
  3000             return sym.kind != MTH ||
  3001                           site.getEnclosingType().hasTag(NONE) ||
  3002                           hasEnclosingInstance(env, site) ?
  3003                           sym : new InvalidSymbolError(Kinds.MISSING_ENCL, sym, null) {
  3004                     @Override
  3005                     JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
  3006                        return diags.create(dkind, log.currentSource(), pos,
  3007                             "cant.access.inner.cls.constr", site.tsym.name, argtypes, site.getEnclosingType());
  3009                 };
  3012         @Override
  3013         ReferenceKind referenceKind(Symbol sym) {
  3014             return site.getEnclosingType().hasTag(NONE) ?
  3015                     ReferenceKind.TOPLEVEL : ReferenceKind.IMPLICIT_INNER;
  3019     /**
  3020      * Main overload resolution routine. On each overload resolution step, a
  3021      * lookup helper class is used to perform the method/constructor lookup;
  3022      * at the end of the lookup, the helper is used to validate the results
  3023      * (this last step might trigger overload resolution diagnostics).
  3024      */
  3025     Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, MethodCheck methodCheck, LookupHelper lookupHelper) {
  3026         MethodResolutionContext resolveContext = new MethodResolutionContext();
  3027         resolveContext.methodCheck = methodCheck;
  3028         return lookupMethod(env, pos, location, resolveContext, lookupHelper);
  3031     Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location,
  3032             MethodResolutionContext resolveContext, LookupHelper lookupHelper) {
  3033         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  3034         try {
  3035             Symbol bestSoFar = methodNotFound;
  3036             currentResolutionContext = resolveContext;
  3037             for (MethodResolutionPhase phase : methodResolutionSteps) {
  3038                 if (!phase.isApplicable(boxingEnabled, varargsEnabled) ||
  3039                         lookupHelper.shouldStop(bestSoFar, phase)) break;
  3040                 MethodResolutionPhase prevPhase = currentResolutionContext.step;
  3041                 Symbol prevBest = bestSoFar;
  3042                 currentResolutionContext.step = phase;
  3043                 Symbol sym = lookupHelper.lookup(env, phase);
  3044                 lookupHelper.debug(pos, sym);
  3045                 bestSoFar = phase.mergeResults(bestSoFar, sym);
  3046                 env.info.pendingResolutionPhase = (prevBest == bestSoFar) ? prevPhase : phase;
  3048             return lookupHelper.access(env, pos, location, bestSoFar);
  3049         } finally {
  3050             currentResolutionContext = prevResolutionContext;
  3054     /**
  3055      * Resolve `c.name' where name == this or name == super.
  3056      * @param pos           The position to use for error reporting.
  3057      * @param env           The environment current at the expression.
  3058      * @param c             The qualifier.
  3059      * @param name          The identifier's name.
  3060      */
  3061     Symbol resolveSelf(DiagnosticPosition pos,
  3062                        Env<AttrContext> env,
  3063                        TypeSymbol c,
  3064                        Name name) {
  3065         Env<AttrContext> env1 = env;
  3066         boolean staticOnly = false;
  3067         while (env1.outer != null) {
  3068             if (isStatic(env1)) staticOnly = true;
  3069             if (env1.enclClass.sym == c) {
  3070                 Symbol sym = env1.info.scope.lookup(name).sym;
  3071                 if (sym != null) {
  3072                     if (staticOnly) sym = new StaticError(sym);
  3073                     return accessBase(sym, pos, env.enclClass.sym.type,
  3074                                   name, true);
  3077             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  3078             env1 = env1.outer;
  3080         if (allowDefaultMethods && c.isInterface() &&
  3081                 name == names._super && !isStatic(env) &&
  3082                 types.isDirectSuperInterface(c, env.enclClass.sym)) {
  3083             //this might be a default super call if one of the superinterfaces is 'c'
  3084             for (Type t : pruneInterfaces(env.enclClass.type)) {
  3085                 if (t.tsym == c) {
  3086                     env.info.defaultSuperCallSite = t;
  3087                     return new VarSymbol(0, names._super,
  3088                             types.asSuper(env.enclClass.type, c), env.enclClass.sym);
  3091             //find a direct superinterface that is a subtype of 'c'
  3092             for (Type i : types.interfaces(env.enclClass.type)) {
  3093                 if (i.tsym.isSubClass(c, types) && i.tsym != c) {
  3094                     log.error(pos, "illegal.default.super.call", c,
  3095                             diags.fragment("redundant.supertype", c, i));
  3096                     return syms.errSymbol;
  3099             Assert.error();
  3101         log.error(pos, "not.encl.class", c);
  3102         return syms.errSymbol;
  3104     //where
  3105     private List<Type> pruneInterfaces(Type t) {
  3106         ListBuffer<Type> result = ListBuffer.lb();
  3107         for (Type t1 : types.interfaces(t)) {
  3108             boolean shouldAdd = true;
  3109             for (Type t2 : types.interfaces(t)) {
  3110                 if (t1 != t2 && types.isSubtypeNoCapture(t2, t1)) {
  3111                     shouldAdd = false;
  3114             if (shouldAdd) {
  3115                 result.append(t1);
  3118         return result.toList();
  3122     /**
  3123      * Resolve `c.this' for an enclosing class c that contains the
  3124      * named member.
  3125      * @param pos           The position to use for error reporting.
  3126      * @param env           The environment current at the expression.
  3127      * @param member        The member that must be contained in the result.
  3128      */
  3129     Symbol resolveSelfContaining(DiagnosticPosition pos,
  3130                                  Env<AttrContext> env,
  3131                                  Symbol member,
  3132                                  boolean isSuperCall) {
  3133         Symbol sym = resolveSelfContainingInternal(env, member, isSuperCall);
  3134         if (sym == null) {
  3135             log.error(pos, "encl.class.required", member);
  3136             return syms.errSymbol;
  3137         } else {
  3138             return accessBase(sym, pos, env.enclClass.sym.type, sym.name, true);
  3142     boolean hasEnclosingInstance(Env<AttrContext> env, Type type) {
  3143         Symbol encl = resolveSelfContainingInternal(env, type.tsym, false);
  3144         return encl != null && encl.kind < ERRONEOUS;
  3147     private Symbol resolveSelfContainingInternal(Env<AttrContext> env,
  3148                                  Symbol member,
  3149                                  boolean isSuperCall) {
  3150         Name name = names._this;
  3151         Env<AttrContext> env1 = isSuperCall ? env.outer : env;
  3152         boolean staticOnly = false;
  3153         if (env1 != null) {
  3154             while (env1 != null && env1.outer != null) {
  3155                 if (isStatic(env1)) staticOnly = true;
  3156                 if (env1.enclClass.sym.isSubClass(member.owner, types)) {
  3157                     Symbol sym = env1.info.scope.lookup(name).sym;
  3158                     if (sym != null) {
  3159                         if (staticOnly) sym = new StaticError(sym);
  3160                         return sym;
  3163                 if ((env1.enclClass.sym.flags() & STATIC) != 0)
  3164                     staticOnly = true;
  3165                 env1 = env1.outer;
  3168         return null;
  3171     /**
  3172      * Resolve an appropriate implicit this instance for t's container.
  3173      * JLS 8.8.5.1 and 15.9.2
  3174      */
  3175     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
  3176         return resolveImplicitThis(pos, env, t, false);
  3179     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t, boolean isSuperCall) {
  3180         Type thisType = (((t.tsym.owner.kind & (MTH|VAR)) != 0)
  3181                          ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
  3182                          : resolveSelfContaining(pos, env, t.tsym, isSuperCall)).type;
  3183         if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
  3184             log.error(pos, "cant.ref.before.ctor.called", "this");
  3185         return thisType;
  3188 /* ***************************************************************************
  3189  *  ResolveError classes, indicating error situations when accessing symbols
  3190  ****************************************************************************/
  3192     //used by TransTypes when checking target type of synthetic cast
  3193     public void logAccessErrorInternal(Env<AttrContext> env, JCTree tree, Type type) {
  3194         AccessError error = new AccessError(env, env.enclClass.type, type.tsym);
  3195         logResolveError(error, tree.pos(), env.enclClass.sym, env.enclClass.type, null, null, null);
  3197     //where
  3198     private void logResolveError(ResolveError error,
  3199             DiagnosticPosition pos,
  3200             Symbol location,
  3201             Type site,
  3202             Name name,
  3203             List<Type> argtypes,
  3204             List<Type> typeargtypes) {
  3205         JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
  3206                 pos, location, site, name, argtypes, typeargtypes);
  3207         if (d != null) {
  3208             d.setFlag(DiagnosticFlag.RESOLVE_ERROR);
  3209             log.report(d);
  3213     private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
  3215     public Object methodArguments(List<Type> argtypes) {
  3216         if (argtypes == null || argtypes.isEmpty()) {
  3217             return noArgs;
  3218         } else {
  3219             ListBuffer<Object> diagArgs = ListBuffer.lb();
  3220             for (Type t : argtypes) {
  3221                 if (t.hasTag(DEFERRED)) {
  3222                     diagArgs.append(((DeferredAttr.DeferredType)t).tree);
  3223                 } else {
  3224                     diagArgs.append(t);
  3227             return diagArgs;
  3231     /**
  3232      * Root class for resolution errors. Subclass of ResolveError
  3233      * represent a different kinds of resolution error - as such they must
  3234      * specify how they map into concrete compiler diagnostics.
  3235      */
  3236     abstract class ResolveError extends Symbol {
  3238         /** The name of the kind of error, for debugging only. */
  3239         final String debugName;
  3241         ResolveError(int kind, String debugName) {
  3242             super(kind, 0, null, null, null);
  3243             this.debugName = debugName;
  3246         @Override
  3247         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
  3248             throw new AssertionError();
  3251         @Override
  3252         public String toString() {
  3253             return debugName;
  3256         @Override
  3257         public boolean exists() {
  3258             return false;
  3261         /**
  3262          * Create an external representation for this erroneous symbol to be
  3263          * used during attribution - by default this returns the symbol of a
  3264          * brand new error type which stores the original type found
  3265          * during resolution.
  3267          * @param name     the name used during resolution
  3268          * @param location the location from which the symbol is accessed
  3269          */
  3270         protected Symbol access(Name name, TypeSymbol location) {
  3271             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  3274         /**
  3275          * Create a diagnostic representing this resolution error.
  3277          * @param dkind     The kind of the diagnostic to be created (e.g error).
  3278          * @param pos       The position to be used for error reporting.
  3279          * @param site      The original type from where the selection took place.
  3280          * @param name      The name of the symbol to be resolved.
  3281          * @param argtypes  The invocation's value arguments,
  3282          *                  if we looked for a method.
  3283          * @param typeargtypes  The invocation's type arguments,
  3284          *                      if we looked for a method.
  3285          */
  3286         abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3287                 DiagnosticPosition pos,
  3288                 Symbol location,
  3289                 Type site,
  3290                 Name name,
  3291                 List<Type> argtypes,
  3292                 List<Type> typeargtypes);
  3295     /**
  3296      * This class is the root class of all resolution errors caused by
  3297      * an invalid symbol being found during resolution.
  3298      */
  3299     abstract class InvalidSymbolError extends ResolveError {
  3301         /** The invalid symbol found during resolution */
  3302         Symbol sym;
  3304         InvalidSymbolError(int kind, Symbol sym, String debugName) {
  3305             super(kind, debugName);
  3306             this.sym = sym;
  3309         @Override
  3310         public boolean exists() {
  3311             return true;
  3314         @Override
  3315         public String toString() {
  3316              return super.toString() + " wrongSym=" + sym;
  3319         @Override
  3320         public Symbol access(Name name, TypeSymbol location) {
  3321             if ((sym.kind & ERRONEOUS) == 0 && (sym.kind & TYP) != 0)
  3322                 return types.createErrorType(name, location, sym.type).tsym;
  3323             else
  3324                 return sym;
  3328     /**
  3329      * InvalidSymbolError error class indicating that a symbol matching a
  3330      * given name does not exists in a given site.
  3331      */
  3332     class SymbolNotFoundError extends ResolveError {
  3334         SymbolNotFoundError(int kind) {
  3335             super(kind, "symbol not found error");
  3338         @Override
  3339         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3340                 DiagnosticPosition pos,
  3341                 Symbol location,
  3342                 Type site,
  3343                 Name name,
  3344                 List<Type> argtypes,
  3345                 List<Type> typeargtypes) {
  3346             argtypes = argtypes == null ? List.<Type>nil() : argtypes;
  3347             typeargtypes = typeargtypes == null ? List.<Type>nil() : typeargtypes;
  3348             if (name == names.error)
  3349                 return null;
  3351             if (syms.operatorNames.contains(name)) {
  3352                 boolean isUnaryOp = argtypes.size() == 1;
  3353                 String key = argtypes.size() == 1 ?
  3354                     "operator.cant.be.applied" :
  3355                     "operator.cant.be.applied.1";
  3356                 Type first = argtypes.head;
  3357                 Type second = !isUnaryOp ? argtypes.tail.head : null;
  3358                 return diags.create(dkind, log.currentSource(), pos,
  3359                         key, name, first, second);
  3361             boolean hasLocation = false;
  3362             if (location == null) {
  3363                 location = site.tsym;
  3365             if (!location.name.isEmpty()) {
  3366                 if (location.kind == PCK && !site.tsym.exists()) {
  3367                     return diags.create(dkind, log.currentSource(), pos,
  3368                         "doesnt.exist", location);
  3370                 hasLocation = !location.name.equals(names._this) &&
  3371                         !location.name.equals(names._super);
  3373             boolean isConstructor = kind == ABSENT_MTH && name == names.init;
  3374             KindName kindname = isConstructor ? KindName.CONSTRUCTOR : absentKind(kind);
  3375             Name idname = isConstructor ? site.tsym.name : name;
  3376             String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation);
  3377             if (hasLocation) {
  3378                 return diags.create(dkind, log.currentSource(), pos,
  3379                         errKey, kindname, idname, //symbol kindname, name
  3380                         typeargtypes, args(argtypes), //type parameters and arguments (if any)
  3381                         getLocationDiag(location, site)); //location kindname, type
  3383             else {
  3384                 return diags.create(dkind, log.currentSource(), pos,
  3385                         errKey, kindname, idname, //symbol kindname, name
  3386                         typeargtypes, args(argtypes)); //type parameters and arguments (if any)
  3389         //where
  3390         private Object args(List<Type> args) {
  3391             return args.isEmpty() ? args : methodArguments(args);
  3394         private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) {
  3395             String key = "cant.resolve";
  3396             String suffix = hasLocation ? ".location" : "";
  3397             switch (kindname) {
  3398                 case METHOD:
  3399                 case CONSTRUCTOR: {
  3400                     suffix += ".args";
  3401                     suffix += hasTypeArgs ? ".params" : "";
  3404             return key + suffix;
  3406         private JCDiagnostic getLocationDiag(Symbol location, Type site) {
  3407             if (location.kind == VAR) {
  3408                 return diags.fragment("location.1",
  3409                     kindName(location),
  3410                     location,
  3411                     location.type);
  3412             } else {
  3413                 return diags.fragment("location",
  3414                     typeKindName(site),
  3415                     site,
  3416                     null);
  3421     /**
  3422      * InvalidSymbolError error class indicating that a given symbol
  3423      * (either a method, a constructor or an operand) is not applicable
  3424      * given an actual arguments/type argument list.
  3425      */
  3426     class InapplicableSymbolError extends ResolveError {
  3428         protected MethodResolutionContext resolveContext;
  3430         InapplicableSymbolError(MethodResolutionContext context) {
  3431             this(WRONG_MTH, "inapplicable symbol error", context);
  3434         protected InapplicableSymbolError(int kind, String debugName, MethodResolutionContext context) {
  3435             super(kind, debugName);
  3436             this.resolveContext = context;
  3439         @Override
  3440         public String toString() {
  3441             return super.toString();
  3444         @Override
  3445         public boolean exists() {
  3446             return true;
  3449         @Override
  3450         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3451                 DiagnosticPosition pos,
  3452                 Symbol location,
  3453                 Type site,
  3454                 Name name,
  3455                 List<Type> argtypes,
  3456                 List<Type> typeargtypes) {
  3457             if (name == names.error)
  3458                 return null;
  3460             if (syms.operatorNames.contains(name)) {
  3461                 boolean isUnaryOp = argtypes.size() == 1;
  3462                 String key = argtypes.size() == 1 ?
  3463                     "operator.cant.be.applied" :
  3464                     "operator.cant.be.applied.1";
  3465                 Type first = argtypes.head;
  3466                 Type second = !isUnaryOp ? argtypes.tail.head : null;
  3467                 return diags.create(dkind, log.currentSource(), pos,
  3468                         key, name, first, second);
  3470             else {
  3471                 Pair<Symbol, JCDiagnostic> c = errCandidate();
  3472                 if (compactMethodDiags) {
  3473                     for (Map.Entry<Template, DiagnosticRewriter> _entry :
  3474                             MethodResolutionDiagHelper.rewriters.entrySet()) {
  3475                         if (_entry.getKey().matches(c.snd)) {
  3476                             JCDiagnostic simpleDiag =
  3477                                     _entry.getValue().rewriteDiagnostic(diags, pos,
  3478                                         log.currentSource(), dkind, c.snd);
  3479                             simpleDiag.setFlag(DiagnosticFlag.COMPRESSED);
  3480                             return simpleDiag;
  3484                 Symbol ws = c.fst.asMemberOf(site, types);
  3485                 return diags.create(dkind, log.currentSource(), pos,
  3486                           "cant.apply.symbol",
  3487                           kindName(ws),
  3488                           ws.name == names.init ? ws.owner.name : ws.name,
  3489                           methodArguments(ws.type.getParameterTypes()),
  3490                           methodArguments(argtypes),
  3491                           kindName(ws.owner),
  3492                           ws.owner.type,
  3493                           c.snd);
  3497         @Override
  3498         public Symbol access(Name name, TypeSymbol location) {
  3499             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  3502         protected Pair<Symbol, JCDiagnostic> errCandidate() {
  3503             Candidate bestSoFar = null;
  3504             for (Candidate c : resolveContext.candidates) {
  3505                 if (c.isApplicable()) continue;
  3506                 bestSoFar = c;
  3508             Assert.checkNonNull(bestSoFar);
  3509             return new Pair<Symbol, JCDiagnostic>(bestSoFar.sym, bestSoFar.details);
  3513     /**
  3514      * ResolveError error class indicating that a set of symbols
  3515      * (either methods, constructors or operands) is not applicable
  3516      * given an actual arguments/type argument list.
  3517      */
  3518     class InapplicableSymbolsError extends InapplicableSymbolError {
  3520         InapplicableSymbolsError(MethodResolutionContext context) {
  3521             super(WRONG_MTHS, "inapplicable symbols", context);
  3524         @Override
  3525         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3526                 DiagnosticPosition pos,
  3527                 Symbol location,
  3528                 Type site,
  3529                 Name name,
  3530                 List<Type> argtypes,
  3531                 List<Type> typeargtypes) {
  3532             Map<Symbol, JCDiagnostic> candidatesMap = mapCandidates();
  3533             Map<Symbol, JCDiagnostic> filteredCandidates = compactMethodDiags ?
  3534                     filterCandidates(candidatesMap) :
  3535                     mapCandidates();
  3536             if (filteredCandidates.isEmpty()) {
  3537                 filteredCandidates = candidatesMap;
  3539             boolean truncatedDiag = candidatesMap.size() != filteredCandidates.size();
  3540             if (filteredCandidates.size() > 1) {
  3541                 JCDiagnostic err = diags.create(dkind,
  3542                         null,
  3543                         truncatedDiag ?
  3544                             EnumSet.of(DiagnosticFlag.COMPRESSED) :
  3545                             EnumSet.noneOf(DiagnosticFlag.class),
  3546                         log.currentSource(),
  3547                         pos,
  3548                         "cant.apply.symbols",
  3549                         name == names.init ? KindName.CONSTRUCTOR : absentKind(kind),
  3550                         name == names.init ? site.tsym.name : name,
  3551                         methodArguments(argtypes));
  3552                 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(filteredCandidates, site));
  3553             } else if (filteredCandidates.size() == 1) {
  3554                 Map.Entry<Symbol, JCDiagnostic> _e =
  3555                                 filteredCandidates.entrySet().iterator().next();
  3556                 final Pair<Symbol, JCDiagnostic> p = new Pair<Symbol, JCDiagnostic>(_e.getKey(), _e.getValue());
  3557                 JCDiagnostic d = new InapplicableSymbolError(resolveContext) {
  3558                     @Override
  3559                     protected Pair<Symbol, JCDiagnostic> errCandidate() {
  3560                         return p;
  3562                 }.getDiagnostic(dkind, pos,
  3563                     location, site, name, argtypes, typeargtypes);
  3564                 if (truncatedDiag) {
  3565                     d.setFlag(DiagnosticFlag.COMPRESSED);
  3567                 return d;
  3568             } else {
  3569                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
  3570                     location, site, name, argtypes, typeargtypes);
  3573         //where
  3574             private Map<Symbol, JCDiagnostic> mapCandidates() {
  3575                 Map<Symbol, JCDiagnostic> candidates = new LinkedHashMap<Symbol, JCDiagnostic>();
  3576                 for (Candidate c : resolveContext.candidates) {
  3577                     if (c.isApplicable()) continue;
  3578                     candidates.put(c.sym, c.details);
  3580                 return candidates;
  3583             Map<Symbol, JCDiagnostic> filterCandidates(Map<Symbol, JCDiagnostic> candidatesMap) {
  3584                 Map<Symbol, JCDiagnostic> candidates = new LinkedHashMap<Symbol, JCDiagnostic>();
  3585                 for (Map.Entry<Symbol, JCDiagnostic> _entry : candidatesMap.entrySet()) {
  3586                     JCDiagnostic d = _entry.getValue();
  3587                     if (!new Template(MethodCheckDiag.ARITY_MISMATCH.regex()).matches(d)) {
  3588                         candidates.put(_entry.getKey(), d);
  3591                 return candidates;
  3594             private List<JCDiagnostic> candidateDetails(Map<Symbol, JCDiagnostic> candidatesMap, Type site) {
  3595                 List<JCDiagnostic> details = List.nil();
  3596                 for (Map.Entry<Symbol, JCDiagnostic> _entry : candidatesMap.entrySet()) {
  3597                     Symbol sym = _entry.getKey();
  3598                     JCDiagnostic detailDiag = diags.fragment("inapplicable.method",
  3599                             Kinds.kindName(sym),
  3600                             sym.location(site, types),
  3601                             sym.asMemberOf(site, types),
  3602                             _entry.getValue());
  3603                     details = details.prepend(detailDiag);
  3605                 //typically members are visited in reverse order (see Scope)
  3606                 //so we need to reverse the candidate list so that candidates
  3607                 //conform to source order
  3608                 return details;
  3612     /**
  3613      * An InvalidSymbolError error class indicating that a symbol is not
  3614      * accessible from a given site
  3615      */
  3616     class AccessError extends InvalidSymbolError {
  3618         private Env<AttrContext> env;
  3619         private Type site;
  3621         AccessError(Symbol sym) {
  3622             this(null, null, sym);
  3625         AccessError(Env<AttrContext> env, Type site, Symbol sym) {
  3626             super(HIDDEN, sym, "access error");
  3627             this.env = env;
  3628             this.site = site;
  3629             if (debugResolve)
  3630                 log.error("proc.messager", sym + " @ " + site + " is inaccessible.");
  3633         @Override
  3634         public boolean exists() {
  3635             return false;
  3638         @Override
  3639         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3640                 DiagnosticPosition pos,
  3641                 Symbol location,
  3642                 Type site,
  3643                 Name name,
  3644                 List<Type> argtypes,
  3645                 List<Type> typeargtypes) {
  3646             if (sym.owner.type.hasTag(ERROR))
  3647                 return null;
  3649             if (sym.name == names.init && sym.owner != site.tsym) {
  3650                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
  3651                         pos, location, site, name, argtypes, typeargtypes);
  3653             else if ((sym.flags() & PUBLIC) != 0
  3654                 || (env != null && this.site != null
  3655                     && !isAccessible(env, this.site))) {
  3656                 return diags.create(dkind, log.currentSource(),
  3657                         pos, "not.def.access.class.intf.cant.access",
  3658                     sym, sym.location());
  3660             else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) {
  3661                 return diags.create(dkind, log.currentSource(),
  3662                         pos, "report.access", sym,
  3663                         asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
  3664                         sym.location());
  3666             else {
  3667                 return diags.create(dkind, log.currentSource(),
  3668                         pos, "not.def.public.cant.access", sym, sym.location());
  3673     /**
  3674      * InvalidSymbolError error class indicating that an instance member
  3675      * has erroneously been accessed from a static context.
  3676      */
  3677     class StaticError extends InvalidSymbolError {
  3679         StaticError(Symbol sym) {
  3680             super(STATICERR, sym, "static error");
  3683         @Override
  3684         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3685                 DiagnosticPosition pos,
  3686                 Symbol location,
  3687                 Type site,
  3688                 Name name,
  3689                 List<Type> argtypes,
  3690                 List<Type> typeargtypes) {
  3691             Symbol errSym = ((sym.kind == TYP && sym.type.hasTag(CLASS))
  3692                 ? types.erasure(sym.type).tsym
  3693                 : sym);
  3694             return diags.create(dkind, log.currentSource(), pos,
  3695                     "non-static.cant.be.ref", kindName(sym), errSym);
  3699     /**
  3700      * InvalidSymbolError error class indicating that a pair of symbols
  3701      * (either methods, constructors or operands) are ambiguous
  3702      * given an actual arguments/type argument list.
  3703      */
  3704     class AmbiguityError extends ResolveError {
  3706         /** The other maximally specific symbol */
  3707         List<Symbol> ambiguousSyms = List.nil();
  3709         @Override
  3710         public boolean exists() {
  3711             return true;
  3714         AmbiguityError(Symbol sym1, Symbol sym2) {
  3715             super(AMBIGUOUS, "ambiguity error");
  3716             ambiguousSyms = flatten(sym2).appendList(flatten(sym1));
  3719         private List<Symbol> flatten(Symbol sym) {
  3720             if (sym.kind == AMBIGUOUS) {
  3721                 return ((AmbiguityError)sym).ambiguousSyms;
  3722             } else {
  3723                 return List.of(sym);
  3727         AmbiguityError addAmbiguousSymbol(Symbol s) {
  3728             ambiguousSyms = ambiguousSyms.prepend(s);
  3729             return this;
  3732         @Override
  3733         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3734                 DiagnosticPosition pos,
  3735                 Symbol location,
  3736                 Type site,
  3737                 Name name,
  3738                 List<Type> argtypes,
  3739                 List<Type> typeargtypes) {
  3740             List<Symbol> diagSyms = ambiguousSyms.reverse();
  3741             Symbol s1 = diagSyms.head;
  3742             Symbol s2 = diagSyms.tail.head;
  3743             Name sname = s1.name;
  3744             if (sname == names.init) sname = s1.owner.name;
  3745             return diags.create(dkind, log.currentSource(),
  3746                       pos, "ref.ambiguous", sname,
  3747                       kindName(s1),
  3748                       s1,
  3749                       s1.location(site, types),
  3750                       kindName(s2),
  3751                       s2,
  3752                       s2.location(site, types));
  3755         /**
  3756          * If multiple applicable methods are found during overload and none of them
  3757          * is more specific than the others, attempt to merge their signatures.
  3758          */
  3759         Symbol mergeAbstracts(Type site) {
  3760             List<Symbol> ambiguousInOrder = ambiguousSyms.reverse();
  3761             for (Symbol s : ambiguousInOrder) {
  3762                 Type mt = types.memberType(site, s);
  3763                 boolean found = true;
  3764                 List<Type> allThrown = mt.getThrownTypes();
  3765                 for (Symbol s2 : ambiguousInOrder) {
  3766                     Type mt2 = types.memberType(site, s2);
  3767                     if ((s2.flags() & ABSTRACT) == 0 ||
  3768                         !types.overrideEquivalent(mt, mt2) ||
  3769                         !types.isSameTypes(s.erasure(types).getParameterTypes(),
  3770                                        s2.erasure(types).getParameterTypes())) {
  3771                         //ambiguity cannot be resolved
  3772                         return this;
  3774                     Type mst = mostSpecificReturnType(mt, mt2);
  3775                     if (mst == null || mst != mt) {
  3776                         found = false;
  3777                         break;
  3779                     allThrown = chk.intersect(allThrown, mt2.getThrownTypes());
  3781                 if (found) {
  3782                     //all ambiguous methods were abstract and one method had
  3783                     //most specific return type then others
  3784                     return (allThrown == mt.getThrownTypes()) ?
  3785                             s : new MethodSymbol(
  3786                                 s.flags(),
  3787                                 s.name,
  3788                                 types.createMethodTypeWithThrown(mt, allThrown),
  3789                                 s.owner);
  3792             return this;
  3795         @Override
  3796         protected Symbol access(Name name, TypeSymbol location) {
  3797             Symbol firstAmbiguity = ambiguousSyms.last();
  3798             return firstAmbiguity.kind == TYP ?
  3799                     types.createErrorType(name, location, firstAmbiguity.type).tsym :
  3800                     firstAmbiguity;
  3804     class BadVarargsMethod extends ResolveError {
  3806         ResolveError delegatedError;
  3808         BadVarargsMethod(ResolveError delegatedError) {
  3809             super(delegatedError.kind, "badVarargs");
  3810             this.delegatedError = delegatedError;
  3813         @Override
  3814         public Symbol baseSymbol() {
  3815             return delegatedError.baseSymbol();
  3818         @Override
  3819         protected Symbol access(Name name, TypeSymbol location) {
  3820             return delegatedError.access(name, location);
  3823         @Override
  3824         public boolean exists() {
  3825             return true;
  3828         @Override
  3829         JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
  3830             return delegatedError.getDiagnostic(dkind, pos, location, site, name, argtypes, typeargtypes);
  3834     /**
  3835      * Helper class for method resolution diagnostic simplification.
  3836      * Certain resolution diagnostic are rewritten as simpler diagnostic
  3837      * where the enclosing resolution diagnostic (i.e. 'inapplicable method')
  3838      * is stripped away, as it doesn't carry additional info. The logic
  3839      * for matching a given diagnostic is given in terms of a template
  3840      * hierarchy: a diagnostic template can be specified programmatically,
  3841      * so that only certain diagnostics are matched. Each templete is then
  3842      * associated with a rewriter object that carries out the task of rewtiting
  3843      * the diagnostic to a simpler one.
  3844      */
  3845     static class MethodResolutionDiagHelper {
  3847         /**
  3848          * A diagnostic rewriter transforms a method resolution diagnostic
  3849          * into a simpler one
  3850          */
  3851         interface DiagnosticRewriter {
  3852             JCDiagnostic rewriteDiagnostic(JCDiagnostic.Factory diags,
  3853                     DiagnosticPosition preferedPos, DiagnosticSource preferredSource,
  3854                     DiagnosticType preferredKind, JCDiagnostic d);
  3857         /**
  3858          * A diagnostic template is made up of two ingredients: (i) a regular
  3859          * expression for matching a diagnostic key and (ii) a list of sub-templates
  3860          * for matching diagnostic arguments.
  3861          */
  3862         static class Template {
  3864             /** regex used to match diag key */
  3865             String regex;
  3867             /** templates used to match diagnostic args */
  3868             Template[] subTemplates;
  3870             Template(String key, Template... subTemplates) {
  3871                 this.regex = key;
  3872                 this.subTemplates = subTemplates;
  3875             /**
  3876              * Returns true if the regex matches the diagnostic key and if
  3877              * all diagnostic arguments are matches by corresponding sub-templates.
  3878              */
  3879             boolean matches(Object o) {
  3880                 JCDiagnostic d = (JCDiagnostic)o;
  3881                 Object[] args = d.getArgs();
  3882                 if (!d.getCode().matches(regex) ||
  3883                         subTemplates.length != d.getArgs().length) {
  3884                     return false;
  3886                 for (int i = 0; i < args.length ; i++) {
  3887                     if (!subTemplates[i].matches(args[i])) {
  3888                         return false;
  3891                 return true;
  3895         /** a dummy template that match any diagnostic argument */
  3896         static final Template skip = new Template("") {
  3897             @Override
  3898             boolean matches(Object d) {
  3899                 return true;
  3901         };
  3903         /** rewriter map used for method resolution simplification */
  3904         static final Map<Template, DiagnosticRewriter> rewriters =
  3905                 new LinkedHashMap<Template, DiagnosticRewriter>();
  3907         static {
  3908             String argMismatchRegex = MethodCheckDiag.ARG_MISMATCH.regex();
  3909             rewriters.put(new Template(argMismatchRegex, new Template("(.*)(bad.arg.types.in.lambda)", skip, skip)),
  3910                     new DiagnosticRewriter() {
  3911                 @Override
  3912                 public JCDiagnostic rewriteDiagnostic(JCDiagnostic.Factory diags,
  3913                         DiagnosticPosition preferedPos, DiagnosticSource preferredSource,
  3914                         DiagnosticType preferredKind, JCDiagnostic d) {
  3915                     return (JCDiagnostic)((JCDiagnostic)d.getArgs()[0]).getArgs()[1];
  3917             });
  3919             rewriters.put(new Template(argMismatchRegex, skip),
  3920                     new DiagnosticRewriter() {
  3921                 @Override
  3922                 public JCDiagnostic rewriteDiagnostic(JCDiagnostic.Factory diags,
  3923                         DiagnosticPosition preferedPos, DiagnosticSource preferredSource,
  3924                         DiagnosticType preferredKind, JCDiagnostic d) {
  3925                     JCDiagnostic cause = (JCDiagnostic)d.getArgs()[0];
  3926                     return diags.create(preferredKind, preferredSource, d.getDiagnosticPosition(),
  3927                             "prob.found.req", cause);
  3929             });
  3933     enum MethodResolutionPhase {
  3934         BASIC(false, false),
  3935         BOX(true, false),
  3936         VARARITY(true, true) {
  3937             @Override
  3938             public Symbol mergeResults(Symbol bestSoFar, Symbol sym) {
  3939                 switch (sym.kind) {
  3940                     case WRONG_MTH:
  3941                         return (bestSoFar.kind == WRONG_MTH || bestSoFar.kind == WRONG_MTHS) ?
  3942                             bestSoFar :
  3943                             sym;
  3944                     case ABSENT_MTH:
  3945                         return bestSoFar;
  3946                     default:
  3947                         return sym;
  3950         };
  3952         final boolean isBoxingRequired;
  3953         final boolean isVarargsRequired;
  3955         MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) {
  3956            this.isBoxingRequired = isBoxingRequired;
  3957            this.isVarargsRequired = isVarargsRequired;
  3960         public boolean isBoxingRequired() {
  3961             return isBoxingRequired;
  3964         public boolean isVarargsRequired() {
  3965             return isVarargsRequired;
  3968         public boolean isApplicable(boolean boxingEnabled, boolean varargsEnabled) {
  3969             return (varargsEnabled || !isVarargsRequired) &&
  3970                    (boxingEnabled || !isBoxingRequired);
  3973         public Symbol mergeResults(Symbol prev, Symbol sym) {
  3974             return sym;
  3978     final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
  3980     /**
  3981      * A resolution context is used to keep track of intermediate results of
  3982      * overload resolution, such as list of method that are not applicable
  3983      * (used to generate more precise diagnostics) and so on. Resolution contexts
  3984      * can be nested - this means that when each overload resolution routine should
  3985      * work within the resolution context it created.
  3986      */
  3987     class MethodResolutionContext {
  3989         private List<Candidate> candidates = List.nil();
  3991         MethodResolutionPhase step = null;
  3993         MethodCheck methodCheck = resolveMethodCheck;
  3995         private boolean internalResolution = false;
  3996         private DeferredAttr.AttrMode attrMode = DeferredAttr.AttrMode.SPECULATIVE;
  3998         void addInapplicableCandidate(Symbol sym, JCDiagnostic details) {
  3999             Candidate c = new Candidate(currentResolutionContext.step, sym, details, null);
  4000             candidates = candidates.append(c);
  4003         void addApplicableCandidate(Symbol sym, Type mtype) {
  4004             Candidate c = new Candidate(currentResolutionContext.step, sym, null, mtype);
  4005             candidates = candidates.append(c);
  4008         DeferredAttrContext deferredAttrContext(Symbol sym, InferenceContext inferenceContext, ResultInfo pendingResult, Warner warn) {
  4009             return deferredAttr.new DeferredAttrContext(attrMode, sym, step, inferenceContext, pendingResult != null ? pendingResult.checkContext.deferredAttrContext() : deferredAttr.emptyDeferredAttrContext, warn);
  4012         /**
  4013          * This class represents an overload resolution candidate. There are two
  4014          * kinds of candidates: applicable methods and inapplicable methods;
  4015          * applicable methods have a pointer to the instantiated method type,
  4016          * while inapplicable candidates contain further details about the
  4017          * reason why the method has been considered inapplicable.
  4018          */
  4019         @SuppressWarnings("overrides")
  4020         class Candidate {
  4022             final MethodResolutionPhase step;
  4023             final Symbol sym;
  4024             final JCDiagnostic details;
  4025             final Type mtype;
  4027             private Candidate(MethodResolutionPhase step, Symbol sym, JCDiagnostic details, Type mtype) {
  4028                 this.step = step;
  4029                 this.sym = sym;
  4030                 this.details = details;
  4031                 this.mtype = mtype;
  4034             @Override
  4035             public boolean equals(Object o) {
  4036                 if (o instanceof Candidate) {
  4037                     Symbol s1 = this.sym;
  4038                     Symbol s2 = ((Candidate)o).sym;
  4039                     if  ((s1 != s2 &&
  4040                             (s1.overrides(s2, s1.owner.type.tsym, types, false) ||
  4041                             (s2.overrides(s1, s2.owner.type.tsym, types, false)))) ||
  4042                             ((s1.isConstructor() || s2.isConstructor()) && s1.owner != s2.owner))
  4043                         return true;
  4045                 return false;
  4048             boolean isApplicable() {
  4049                 return mtype != null;
  4053         DeferredAttr.AttrMode attrMode() {
  4054             return attrMode;
  4057         boolean internal() {
  4058             return internalResolution;
  4062     MethodResolutionContext currentResolutionContext = null;

mercurial