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

Sat, 14 Sep 2013 15:23:21 +0100

author
vromero
date
Sat, 14 Sep 2013 15:23:21 +0100
changeset 2026
03c26c60499c
parent 2003
9be0afbdf244
child 2047
5f915a0c9615
permissions
-rw-r--r--

8024207: javac crash in Flow.AssignAnalyzer.visitIdent
Reviewed-by: jjg

     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         DeferredAttr.DeferredAttrContext dc = currentResolutionContext.deferredAttrContext(m, infer.emptyContext, resultInfo, warn);
   572         currentResolutionContext.methodCheck.argumentsAcceptable(env, dc,
   573                                 argtypes, mt.getParameterTypes(), warn);
   574         dc.complete();
   575         return mt;
   576     }
   578     Type checkMethod(Env<AttrContext> env,
   579                      Type site,
   580                      Symbol m,
   581                      ResultInfo resultInfo,
   582                      List<Type> argtypes,
   583                      List<Type> typeargtypes,
   584                      Warner warn) {
   585         MethodResolutionContext prevContext = currentResolutionContext;
   586         try {
   587             currentResolutionContext = new MethodResolutionContext();
   588             currentResolutionContext.attrMode = DeferredAttr.AttrMode.CHECK;
   589             if (env.tree.hasTag(JCTree.Tag.REFERENCE)) {
   590                 //method/constructor references need special check class
   591                 //to handle inference variables in 'argtypes' (might happen
   592                 //during an unsticking round)
   593                 currentResolutionContext.methodCheck =
   594                         new MethodReferenceCheck(resultInfo.checkContext.inferenceContext());
   595             }
   596             MethodResolutionPhase step = currentResolutionContext.step = env.info.pendingResolutionPhase;
   597             return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
   598                     step.isBoxingRequired(), step.isVarargsRequired(), warn);
   599         }
   600         finally {
   601             currentResolutionContext = prevContext;
   602         }
   603     }
   605     /** Same but returns null instead throwing a NoInstanceException
   606      */
   607     Type instantiate(Env<AttrContext> env,
   608                      Type site,
   609                      Symbol m,
   610                      ResultInfo resultInfo,
   611                      List<Type> argtypes,
   612                      List<Type> typeargtypes,
   613                      boolean allowBoxing,
   614                      boolean useVarargs,
   615                      Warner warn) {
   616         try {
   617             return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
   618                                   allowBoxing, useVarargs, warn);
   619         } catch (InapplicableMethodException ex) {
   620             return null;
   621         }
   622     }
   624     /**
   625      * This interface defines an entry point that should be used to perform a
   626      * method check. A method check usually consist in determining as to whether
   627      * a set of types (actuals) is compatible with another set of types (formals).
   628      * Since the notion of compatibility can vary depending on the circumstances,
   629      * this interfaces allows to easily add new pluggable method check routines.
   630      */
   631     interface MethodCheck {
   632         /**
   633          * Main method check routine. A method check usually consist in determining
   634          * as to whether a set of types (actuals) is compatible with another set of
   635          * types (formals). If an incompatibility is found, an unchecked exception
   636          * is assumed to be thrown.
   637          */
   638         void argumentsAcceptable(Env<AttrContext> env,
   639                                 DeferredAttrContext deferredAttrContext,
   640                                 List<Type> argtypes,
   641                                 List<Type> formals,
   642                                 Warner warn);
   644         /**
   645          * Retrieve the method check object that will be used during a
   646          * most specific check.
   647          */
   648         MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict);
   649     }
   651     /**
   652      * Helper enum defining all method check diagnostics (used by resolveMethodCheck).
   653      */
   654     enum MethodCheckDiag {
   655         /**
   656          * Actuals and formals differs in length.
   657          */
   658         ARITY_MISMATCH("arg.length.mismatch", "infer.arg.length.mismatch"),
   659         /**
   660          * An actual is incompatible with a formal.
   661          */
   662         ARG_MISMATCH("no.conforming.assignment.exists", "infer.no.conforming.assignment.exists"),
   663         /**
   664          * An actual is incompatible with the varargs element type.
   665          */
   666         VARARG_MISMATCH("varargs.argument.mismatch", "infer.varargs.argument.mismatch"),
   667         /**
   668          * The varargs element type is inaccessible.
   669          */
   670         INACCESSIBLE_VARARGS("inaccessible.varargs.type", "inaccessible.varargs.type");
   672         final String basicKey;
   673         final String inferKey;
   675         MethodCheckDiag(String basicKey, String inferKey) {
   676             this.basicKey = basicKey;
   677             this.inferKey = inferKey;
   678         }
   680         String regex() {
   681             return String.format("([a-z]*\\.)*(%s|%s)", basicKey, inferKey);
   682         }
   683     }
   685     /**
   686      * Dummy method check object. All methods are deemed applicable, regardless
   687      * of their formal parameter types.
   688      */
   689     MethodCheck nilMethodCheck = new MethodCheck() {
   690         public void argumentsAcceptable(Env<AttrContext> env, DeferredAttrContext deferredAttrContext, List<Type> argtypes, List<Type> formals, Warner warn) {
   691             //do nothing - method always applicable regardless of actuals
   692         }
   694         public MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict) {
   695             return this;
   696         }
   697     };
   699     /**
   700      * Base class for 'real' method checks. The class defines the logic for
   701      * iterating through formals and actuals and provides and entry point
   702      * that can be used by subclasses in order to define the actual check logic.
   703      */
   704     abstract class AbstractMethodCheck implements MethodCheck {
   705         @Override
   706         public void argumentsAcceptable(final Env<AttrContext> env,
   707                                     DeferredAttrContext deferredAttrContext,
   708                                     List<Type> argtypes,
   709                                     List<Type> formals,
   710                                     Warner warn) {
   711             //should we expand formals?
   712             boolean useVarargs = deferredAttrContext.phase.isVarargsRequired();
   713             List<JCExpression> trees = TreeInfo.args(env.tree);
   715             //inference context used during this method check
   716             InferenceContext inferenceContext = deferredAttrContext.inferenceContext;
   718             Type varargsFormal = useVarargs ? formals.last() : null;
   720             if (varargsFormal == null &&
   721                     argtypes.size() != formals.size()) {
   722                 reportMC(env.tree, MethodCheckDiag.ARITY_MISMATCH, inferenceContext); // not enough args
   723             }
   725             while (argtypes.nonEmpty() && formals.head != varargsFormal) {
   726                 DiagnosticPosition pos = trees != null ? trees.head : null;
   727                 checkArg(pos, false, argtypes.head, formals.head, deferredAttrContext, warn);
   728                 argtypes = argtypes.tail;
   729                 formals = formals.tail;
   730                 trees = trees != null ? trees.tail : trees;
   731             }
   733             if (formals.head != varargsFormal) {
   734                 reportMC(env.tree, MethodCheckDiag.ARITY_MISMATCH, inferenceContext); // not enough args
   735             }
   737             if (useVarargs) {
   738                 //note: if applicability check is triggered by most specific test,
   739                 //the last argument of a varargs is _not_ an array type (see JLS 15.12.2.5)
   740                 final Type elt = types.elemtype(varargsFormal);
   741                 while (argtypes.nonEmpty()) {
   742                     DiagnosticPosition pos = trees != null ? trees.head : null;
   743                     checkArg(pos, true, argtypes.head, elt, deferredAttrContext, warn);
   744                     argtypes = argtypes.tail;
   745                     trees = trees != null ? trees.tail : trees;
   746                 }
   747             }
   748         }
   750         /**
   751          * Does the actual argument conforms to the corresponding formal?
   752          */
   753         abstract void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn);
   755         protected void reportMC(DiagnosticPosition pos, MethodCheckDiag diag, InferenceContext inferenceContext, Object... args) {
   756             boolean inferDiag = inferenceContext != infer.emptyContext;
   757             InapplicableMethodException ex = inferDiag ?
   758                     infer.inferenceException : inapplicableMethodException;
   759             if (inferDiag && (!diag.inferKey.equals(diag.basicKey))) {
   760                 Object[] args2 = new Object[args.length + 1];
   761                 System.arraycopy(args, 0, args2, 1, args.length);
   762                 args2[0] = inferenceContext.inferenceVars();
   763                 args = args2;
   764             }
   765             String key = inferDiag ? diag.inferKey : diag.basicKey;
   766             throw ex.setMessage(diags.create(DiagnosticType.FRAGMENT, log.currentSource(), pos, key, args));
   767         }
   769         public MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict) {
   770             return nilMethodCheck;
   771         }
   772     }
   774     /**
   775      * Arity-based method check. A method is applicable if the number of actuals
   776      * supplied conforms to the method signature.
   777      */
   778     MethodCheck arityMethodCheck = new AbstractMethodCheck() {
   779         @Override
   780         void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn) {
   781             //do nothing - actual always compatible to formals
   782         }
   783     };
   785     List<Type> dummyArgs(int length) {
   786         ListBuffer<Type> buf = ListBuffer.lb();
   787         for (int i = 0 ; i < length ; i++) {
   788             buf.append(Type.noType);
   789         }
   790         return buf.toList();
   791     }
   793     /**
   794      * Main method applicability routine. Given a list of actual types A,
   795      * a list of formal types F, determines whether the types in A are
   796      * compatible (by method invocation conversion) with the types in F.
   797      *
   798      * Since this routine is shared between overload resolution and method
   799      * type-inference, a (possibly empty) inference context is used to convert
   800      * formal types to the corresponding 'undet' form ahead of a compatibility
   801      * check so that constraints can be propagated and collected.
   802      *
   803      * Moreover, if one or more types in A is a deferred type, this routine uses
   804      * DeferredAttr in order to perform deferred attribution. If one or more actual
   805      * deferred types are stuck, they are placed in a queue and revisited later
   806      * after the remainder of the arguments have been seen. If this is not sufficient
   807      * to 'unstuck' the argument, a cyclic inference error is called out.
   808      *
   809      * A method check handler (see above) is used in order to report errors.
   810      */
   811     MethodCheck resolveMethodCheck = new AbstractMethodCheck() {
   813         @Override
   814         void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn) {
   815             ResultInfo mresult = methodCheckResult(varargs, formal, deferredAttrContext, warn);
   816             mresult.check(pos, actual);
   817         }
   819         @Override
   820         public void argumentsAcceptable(final Env<AttrContext> env,
   821                                     DeferredAttrContext deferredAttrContext,
   822                                     List<Type> argtypes,
   823                                     List<Type> formals,
   824                                     Warner warn) {
   825             super.argumentsAcceptable(env, deferredAttrContext, argtypes, formals, warn);
   826             //should we expand formals?
   827             if (deferredAttrContext.phase.isVarargsRequired()) {
   828                 //check varargs element type accessibility
   829                 varargsAccessible(env, types.elemtype(formals.last()),
   830                         deferredAttrContext.inferenceContext);
   831             }
   832         }
   834         private void varargsAccessible(final Env<AttrContext> env, final Type t, final InferenceContext inferenceContext) {
   835             if (inferenceContext.free(t)) {
   836                 inferenceContext.addFreeTypeListener(List.of(t), new FreeTypeListener() {
   837                     @Override
   838                     public void typesInferred(InferenceContext inferenceContext) {
   839                         varargsAccessible(env, inferenceContext.asInstType(t), inferenceContext);
   840                     }
   841                 });
   842             } else {
   843                 if (!isAccessible(env, t)) {
   844                     Symbol location = env.enclClass.sym;
   845                     reportMC(env.tree, MethodCheckDiag.INACCESSIBLE_VARARGS, inferenceContext, t, Kinds.kindName(location), location);
   846                 }
   847             }
   848         }
   850         private ResultInfo methodCheckResult(final boolean varargsCheck, Type to,
   851                 final DeferredAttr.DeferredAttrContext deferredAttrContext, Warner rsWarner) {
   852             CheckContext checkContext = new MethodCheckContext(!deferredAttrContext.phase.isBoxingRequired(), deferredAttrContext, rsWarner) {
   853                 MethodCheckDiag methodDiag = varargsCheck ?
   854                                  MethodCheckDiag.VARARG_MISMATCH : MethodCheckDiag.ARG_MISMATCH;
   856                 @Override
   857                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
   858                     reportMC(pos, methodDiag, deferredAttrContext.inferenceContext, details);
   859                 }
   860             };
   861             return new MethodResultInfo(to, checkContext);
   862         }
   864         @Override
   865         public MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict) {
   866             return new MostSpecificCheck(strict, actuals);
   867         }
   868     };
   870     class MethodReferenceCheck extends AbstractMethodCheck {
   872         InferenceContext pendingInferenceContext;
   874         MethodReferenceCheck(InferenceContext pendingInferenceContext) {
   875             this.pendingInferenceContext = pendingInferenceContext;
   876         }
   878         @Override
   879         void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn) {
   880             ResultInfo mresult = methodCheckResult(varargs, formal, deferredAttrContext, warn);
   881             mresult.check(pos, actual);
   882         }
   884         private ResultInfo methodCheckResult(final boolean varargsCheck, Type to,
   885                 final DeferredAttr.DeferredAttrContext deferredAttrContext, Warner rsWarner) {
   886             CheckContext checkContext = new MethodCheckContext(!deferredAttrContext.phase.isBoxingRequired(), deferredAttrContext, rsWarner) {
   887                 MethodCheckDiag methodDiag = varargsCheck ?
   888                                  MethodCheckDiag.VARARG_MISMATCH : MethodCheckDiag.ARG_MISMATCH;
   890                 @Override
   891                 public boolean compatible(Type found, Type req, Warner warn) {
   892                     found = pendingInferenceContext.asFree(found);
   893                     req = infer.returnConstraintTarget(found, req);
   894                     return super.compatible(found, req, warn);
   895                 }
   897                 @Override
   898                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
   899                     reportMC(pos, methodDiag, deferredAttrContext.inferenceContext, details);
   900                 }
   901             };
   902             return new MethodResultInfo(to, checkContext);
   903         }
   905         @Override
   906         public MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict) {
   907             return new MostSpecificCheck(strict, actuals);
   908         }
   909     };
   911     /**
   912      * Check context to be used during method applicability checks. A method check
   913      * context might contain inference variables.
   914      */
   915     abstract class MethodCheckContext implements CheckContext {
   917         boolean strict;
   918         DeferredAttrContext deferredAttrContext;
   919         Warner rsWarner;
   921         public MethodCheckContext(boolean strict, DeferredAttrContext deferredAttrContext, Warner rsWarner) {
   922            this.strict = strict;
   923            this.deferredAttrContext = deferredAttrContext;
   924            this.rsWarner = rsWarner;
   925         }
   927         public boolean compatible(Type found, Type req, Warner warn) {
   928             return strict ?
   929                     types.isSubtypeUnchecked(found, deferredAttrContext.inferenceContext.asFree(req), warn) :
   930                     types.isConvertible(found, deferredAttrContext.inferenceContext.asFree(req), warn);
   931         }
   933         public void report(DiagnosticPosition pos, JCDiagnostic details) {
   934             throw inapplicableMethodException.setMessage(details);
   935         }
   937         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
   938             return rsWarner;
   939         }
   941         public InferenceContext inferenceContext() {
   942             return deferredAttrContext.inferenceContext;
   943         }
   945         public DeferredAttrContext deferredAttrContext() {
   946             return deferredAttrContext;
   947         }
   948     }
   950     /**
   951      * ResultInfo class to be used during method applicability checks. Check
   952      * for deferred types goes through special path.
   953      */
   954     class MethodResultInfo extends ResultInfo {
   956         public MethodResultInfo(Type pt, CheckContext checkContext) {
   957             attr.super(VAL, pt, checkContext);
   958         }
   960         @Override
   961         protected Type check(DiagnosticPosition pos, Type found) {
   962             if (found.hasTag(DEFERRED)) {
   963                 DeferredType dt = (DeferredType)found;
   964                 return dt.check(this);
   965             } else {
   966                 return super.check(pos, chk.checkNonVoid(pos, types.capture(U(found.baseType()))));
   967             }
   968         }
   970         /**
   971          * javac has a long-standing 'simplification' (see 6391995):
   972          * given an actual argument type, the method check is performed
   973          * on its upper bound. This leads to inconsistencies when an
   974          * argument type is checked against itself. For example, given
   975          * a type-variable T, it is not true that {@code U(T) <: T},
   976          * so we need to guard against that.
   977          */
   978         private Type U(Type found) {
   979             return found == pt ?
   980                     found : types.upperBound(found);
   981         }
   983         @Override
   984         protected MethodResultInfo dup(Type newPt) {
   985             return new MethodResultInfo(newPt, checkContext);
   986         }
   988         @Override
   989         protected ResultInfo dup(CheckContext newContext) {
   990             return new MethodResultInfo(pt, newContext);
   991         }
   992     }
   994     /**
   995      * Most specific method applicability routine. Given a list of actual types A,
   996      * a list of formal types F1, and a list of formal types F2, the routine determines
   997      * as to whether the types in F1 can be considered more specific than those in F2 w.r.t.
   998      * argument types A.
   999      */
  1000     class MostSpecificCheck implements MethodCheck {
  1002         boolean strict;
  1003         List<Type> actuals;
  1005         MostSpecificCheck(boolean strict, List<Type> actuals) {
  1006             this.strict = strict;
  1007             this.actuals = actuals;
  1010         @Override
  1011         public void argumentsAcceptable(final Env<AttrContext> env,
  1012                                     DeferredAttrContext deferredAttrContext,
  1013                                     List<Type> formals1,
  1014                                     List<Type> formals2,
  1015                                     Warner warn) {
  1016             formals2 = adjustArgs(formals2, deferredAttrContext.msym, formals1.length(), deferredAttrContext.phase.isVarargsRequired());
  1017             while (formals2.nonEmpty()) {
  1018                 ResultInfo mresult = methodCheckResult(formals2.head, deferredAttrContext, warn, actuals.head);
  1019                 mresult.check(null, formals1.head);
  1020                 formals1 = formals1.tail;
  1021                 formals2 = formals2.tail;
  1022                 actuals = actuals.isEmpty() ? actuals : actuals.tail;
  1026        /**
  1027         * Create a method check context to be used during the most specific applicability check
  1028         */
  1029         ResultInfo methodCheckResult(Type to, DeferredAttr.DeferredAttrContext deferredAttrContext,
  1030                Warner rsWarner, Type actual) {
  1031            return attr.new ResultInfo(Kinds.VAL, to,
  1032                    new MostSpecificCheckContext(strict, deferredAttrContext, rsWarner, actual));
  1035         /**
  1036          * Subclass of method check context class that implements most specific
  1037          * method conversion. If the actual type under analysis is a deferred type
  1038          * a full blown structural analysis is carried out.
  1039          */
  1040         class MostSpecificCheckContext extends MethodCheckContext {
  1042             Type actual;
  1044             public MostSpecificCheckContext(boolean strict, DeferredAttrContext deferredAttrContext, Warner rsWarner, Type actual) {
  1045                 super(strict, deferredAttrContext, rsWarner);
  1046                 this.actual = actual;
  1049             public boolean compatible(Type found, Type req, Warner warn) {
  1050                 if (!allowStructuralMostSpecific || actual == null) {
  1051                     return super.compatible(found, req, warn);
  1052                 } else {
  1053                     switch (actual.getTag()) {
  1054                         case DEFERRED:
  1055                             DeferredType dt = (DeferredType) actual;
  1056                             DeferredType.SpeculativeCache.Entry e = dt.speculativeCache.get(deferredAttrContext.msym, deferredAttrContext.phase);
  1057                             return (e == null || e.speculativeTree == deferredAttr.stuckTree)
  1058                                     ? super.compatible(found, req, warn) :
  1059                                       mostSpecific(found, req, e.speculativeTree, warn);
  1060                         default:
  1061                             return standaloneMostSpecific(found, req, actual, warn);
  1066             private boolean mostSpecific(Type t, Type s, JCTree tree, Warner warn) {
  1067                 MostSpecificChecker msc = new MostSpecificChecker(t, s, warn);
  1068                 msc.scan(tree);
  1069                 return msc.result;
  1072             boolean polyMostSpecific(Type t1, Type t2, Warner warn) {
  1073                 return (!t1.isPrimitive() && t2.isPrimitive())
  1074                         ? true : super.compatible(t1, t2, warn);
  1077             boolean standaloneMostSpecific(Type t1, Type t2, Type exprType, Warner warn) {
  1078                 return (exprType.isPrimitive() == t1.isPrimitive()
  1079                         && exprType.isPrimitive() != t2.isPrimitive())
  1080                         ? true : super.compatible(t1, t2, warn);
  1083             /**
  1084              * Structural checker for most specific.
  1085              */
  1086             class MostSpecificChecker extends DeferredAttr.PolyScanner {
  1088                 final Type t;
  1089                 final Type s;
  1090                 final Warner warn;
  1091                 boolean result;
  1093                 MostSpecificChecker(Type t, Type s, Warner warn) {
  1094                     this.t = t;
  1095                     this.s = s;
  1096                     this.warn = warn;
  1097                     result = true;
  1100                 @Override
  1101                 void skip(JCTree tree) {
  1102                     result &= standaloneMostSpecific(t, s, tree.type, warn);
  1105                 @Override
  1106                 public void visitConditional(JCConditional tree) {
  1107                     if (tree.polyKind == PolyKind.STANDALONE) {
  1108                         result &= standaloneMostSpecific(t, s, tree.type, warn);
  1109                     } else {
  1110                         super.visitConditional(tree);
  1114                 @Override
  1115                 public void visitApply(JCMethodInvocation tree) {
  1116                     result &= (tree.polyKind == PolyKind.STANDALONE)
  1117                             ? standaloneMostSpecific(t, s, tree.type, warn)
  1118                             : polyMostSpecific(t, s, warn);
  1121                 @Override
  1122                 public void visitNewClass(JCNewClass tree) {
  1123                     result &= (tree.polyKind == PolyKind.STANDALONE)
  1124                             ? standaloneMostSpecific(t, s, tree.type, warn)
  1125                             : polyMostSpecific(t, s, warn);
  1128                 @Override
  1129                 public void visitReference(JCMemberReference tree) {
  1130                     if (types.isFunctionalInterface(t.tsym) &&
  1131                             types.isFunctionalInterface(s.tsym)) {
  1132                         Type desc_t = types.findDescriptorType(t);
  1133                         Type desc_s = types.findDescriptorType(s);
  1134                         if (types.isSameTypes(desc_t.getParameterTypes(),
  1135                                 inferenceContext().asFree(desc_s.getParameterTypes()))) {
  1136                             if (types.asSuper(t, s.tsym) != null ||
  1137                                 types.asSuper(s, t.tsym) != null) {
  1138                                 result &= MostSpecificCheckContext.super.compatible(t, s, warn);
  1139                             } else if (!desc_s.getReturnType().hasTag(VOID)) {
  1140                                 //perform structural comparison
  1141                                 Type ret_t = desc_t.getReturnType();
  1142                                 Type ret_s = desc_s.getReturnType();
  1143                                 result &= ((tree.refPolyKind == PolyKind.STANDALONE)
  1144                                         ? standaloneMostSpecific(ret_t, ret_s, tree.sym.type.getReturnType(), warn)
  1145                                         : polyMostSpecific(ret_t, ret_s, warn));
  1146                             } else {
  1147                                 return;
  1150                     } else {
  1151                         result &= false;
  1155                 @Override
  1156                 public void visitLambda(JCLambda tree) {
  1157                     if (types.isFunctionalInterface(t.tsym) &&
  1158                             types.isFunctionalInterface(s.tsym)) {
  1159                         Type desc_t = types.findDescriptorType(t);
  1160                         Type desc_s = types.findDescriptorType(s);
  1161                         if (types.isSameTypes(desc_t.getParameterTypes(),
  1162                                 inferenceContext().asFree(desc_s.getParameterTypes()))) {
  1163                             if (types.asSuper(t, s.tsym) != null ||
  1164                                 types.asSuper(s, t.tsym) != null) {
  1165                                 result &= MostSpecificCheckContext.super.compatible(t, s, warn);
  1166                             } else if (!desc_s.getReturnType().hasTag(VOID)) {
  1167                                 //perform structural comparison
  1168                                 Type ret_t = desc_t.getReturnType();
  1169                                 Type ret_s = desc_s.getReturnType();
  1170                                 scanLambdaBody(tree, ret_t, ret_s);
  1171                             } else {
  1172                                 return;
  1175                     } else {
  1176                         result &= false;
  1179                 //where
  1181                 void scanLambdaBody(JCLambda lambda, final Type t, final Type s) {
  1182                     if (lambda.getBodyKind() == JCTree.JCLambda.BodyKind.EXPRESSION) {
  1183                         result &= MostSpecificCheckContext.this.mostSpecific(t, s, lambda.body, warn);
  1184                     } else {
  1185                         DeferredAttr.LambdaReturnScanner lambdaScanner =
  1186                                 new DeferredAttr.LambdaReturnScanner() {
  1187                                     @Override
  1188                                     public void visitReturn(JCReturn tree) {
  1189                                         if (tree.expr != null) {
  1190                                             result &= MostSpecificCheckContext.this.mostSpecific(t, s, tree.expr, warn);
  1193                                 };
  1194                         lambdaScanner.scan(lambda.body);
  1200         public MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict) {
  1201             Assert.error("Cannot get here!");
  1202             return null;
  1206     public static class InapplicableMethodException extends RuntimeException {
  1207         private static final long serialVersionUID = 0;
  1209         JCDiagnostic diagnostic;
  1210         JCDiagnostic.Factory diags;
  1212         InapplicableMethodException(JCDiagnostic.Factory diags) {
  1213             this.diagnostic = null;
  1214             this.diags = diags;
  1216         InapplicableMethodException setMessage() {
  1217             return setMessage((JCDiagnostic)null);
  1219         InapplicableMethodException setMessage(String key) {
  1220             return setMessage(key != null ? diags.fragment(key) : null);
  1222         InapplicableMethodException setMessage(String key, Object... args) {
  1223             return setMessage(key != null ? diags.fragment(key, args) : null);
  1225         InapplicableMethodException setMessage(JCDiagnostic diag) {
  1226             this.diagnostic = diag;
  1227             return this;
  1230         public JCDiagnostic getDiagnostic() {
  1231             return diagnostic;
  1234     private final InapplicableMethodException inapplicableMethodException;
  1236 /* ***************************************************************************
  1237  *  Symbol lookup
  1238  *  the following naming conventions for arguments are used
  1240  *       env      is the environment where the symbol was mentioned
  1241  *       site     is the type of which the symbol is a member
  1242  *       name     is the symbol's name
  1243  *                if no arguments are given
  1244  *       argtypes are the value arguments, if we search for a method
  1246  *  If no symbol was found, a ResolveError detailing the problem is returned.
  1247  ****************************************************************************/
  1249     /** Find field. Synthetic fields are always skipped.
  1250      *  @param env     The current environment.
  1251      *  @param site    The original type from where the selection takes place.
  1252      *  @param name    The name of the field.
  1253      *  @param c       The class to search for the field. This is always
  1254      *                 a superclass or implemented interface of site's class.
  1255      */
  1256     Symbol findField(Env<AttrContext> env,
  1257                      Type site,
  1258                      Name name,
  1259                      TypeSymbol c) {
  1260         while (c.type.hasTag(TYPEVAR))
  1261             c = c.type.getUpperBound().tsym;
  1262         Symbol bestSoFar = varNotFound;
  1263         Symbol sym;
  1264         Scope.Entry e = c.members().lookup(name);
  1265         while (e.scope != null) {
  1266             if (e.sym.kind == VAR && (e.sym.flags_field & SYNTHETIC) == 0) {
  1267                 return isAccessible(env, site, e.sym)
  1268                     ? e.sym : new AccessError(env, site, e.sym);
  1270             e = e.next();
  1272         Type st = types.supertype(c.type);
  1273         if (st != null && (st.hasTag(CLASS) || st.hasTag(TYPEVAR))) {
  1274             sym = findField(env, site, name, st.tsym);
  1275             if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1277         for (List<Type> l = types.interfaces(c.type);
  1278              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
  1279              l = l.tail) {
  1280             sym = findField(env, site, name, l.head.tsym);
  1281             if (bestSoFar.exists() && sym.exists() &&
  1282                 sym.owner != bestSoFar.owner)
  1283                 bestSoFar = new AmbiguityError(bestSoFar, sym);
  1284             else if (sym.kind < bestSoFar.kind)
  1285                 bestSoFar = sym;
  1287         return bestSoFar;
  1290     /** Resolve a field identifier, throw a fatal error if not found.
  1291      *  @param pos       The position to use for error reporting.
  1292      *  @param env       The environment current at the method invocation.
  1293      *  @param site      The type of the qualifying expression, in which
  1294      *                   identifier is searched.
  1295      *  @param name      The identifier's name.
  1296      */
  1297     public VarSymbol resolveInternalField(DiagnosticPosition pos, Env<AttrContext> env,
  1298                                           Type site, Name name) {
  1299         Symbol sym = findField(env, site, name, site.tsym);
  1300         if (sym.kind == VAR) return (VarSymbol)sym;
  1301         else throw new FatalError(
  1302                  diags.fragment("fatal.err.cant.locate.field",
  1303                                 name));
  1306     /** Find unqualified variable or field with given name.
  1307      *  Synthetic fields always skipped.
  1308      *  @param env     The current environment.
  1309      *  @param name    The name of the variable or field.
  1310      */
  1311     Symbol findVar(Env<AttrContext> env, Name name) {
  1312         Symbol bestSoFar = varNotFound;
  1313         Symbol sym;
  1314         Env<AttrContext> env1 = env;
  1315         boolean staticOnly = false;
  1316         while (env1.outer != null) {
  1317             if (isStatic(env1)) staticOnly = true;
  1318             Scope.Entry e = env1.info.scope.lookup(name);
  1319             while (e.scope != null &&
  1320                    (e.sym.kind != VAR ||
  1321                     (e.sym.flags_field & SYNTHETIC) != 0))
  1322                 e = e.next();
  1323             sym = (e.scope != null)
  1324                 ? e.sym
  1325                 : findField(
  1326                     env1, env1.enclClass.sym.type, name, env1.enclClass.sym);
  1327             if (sym.exists()) {
  1328                 if (staticOnly &&
  1329                     sym.kind == VAR &&
  1330                     sym.owner.kind == TYP &&
  1331                     (sym.flags() & STATIC) == 0)
  1332                     return new StaticError(sym);
  1333                 else
  1334                     return sym;
  1335             } else if (sym.kind < bestSoFar.kind) {
  1336                 bestSoFar = sym;
  1339             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  1340             env1 = env1.outer;
  1343         sym = findField(env, syms.predefClass.type, name, syms.predefClass);
  1344         if (sym.exists())
  1345             return sym;
  1346         if (bestSoFar.exists())
  1347             return bestSoFar;
  1349         Symbol origin = null;
  1350         for (Scope sc : new Scope[] { env.toplevel.namedImportScope, env.toplevel.starImportScope }) {
  1351             Scope.Entry e = sc.lookup(name);
  1352             for (; e.scope != null; e = e.next()) {
  1353                 sym = e.sym;
  1354                 if (sym.kind != VAR)
  1355                     continue;
  1356                 // invariant: sym.kind == VAR
  1357                 if (bestSoFar.kind < AMBIGUOUS && sym.owner != bestSoFar.owner)
  1358                     return new AmbiguityError(bestSoFar, sym);
  1359                 else if (bestSoFar.kind >= VAR) {
  1360                     origin = e.getOrigin().owner;
  1361                     bestSoFar = isAccessible(env, origin.type, sym)
  1362                         ? sym : new AccessError(env, origin.type, sym);
  1365             if (bestSoFar.exists()) break;
  1367         if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type)
  1368             return bestSoFar.clone(origin);
  1369         else
  1370             return bestSoFar;
  1373     Warner noteWarner = new Warner();
  1375     /** Select the best method for a call site among two choices.
  1376      *  @param env              The current environment.
  1377      *  @param site             The original type from where the
  1378      *                          selection takes place.
  1379      *  @param argtypes         The invocation's value arguments,
  1380      *  @param typeargtypes     The invocation's type arguments,
  1381      *  @param sym              Proposed new best match.
  1382      *  @param bestSoFar        Previously found best match.
  1383      *  @param allowBoxing Allow boxing conversions of arguments.
  1384      *  @param useVarargs Box trailing arguments into an array for varargs.
  1385      */
  1386     @SuppressWarnings("fallthrough")
  1387     Symbol selectBest(Env<AttrContext> env,
  1388                       Type site,
  1389                       List<Type> argtypes,
  1390                       List<Type> typeargtypes,
  1391                       Symbol sym,
  1392                       Symbol bestSoFar,
  1393                       boolean allowBoxing,
  1394                       boolean useVarargs,
  1395                       boolean operator) {
  1396         if (sym.kind == ERR ||
  1397                 !sym.isInheritedIn(site.tsym, types)) {
  1398             return bestSoFar;
  1399         } else if (useVarargs && (sym.flags() & VARARGS) == 0) {
  1400             return bestSoFar.kind >= ERRONEOUS ?
  1401                     new BadVarargsMethod((ResolveError)bestSoFar) :
  1402                     bestSoFar;
  1404         Assert.check(sym.kind < AMBIGUOUS);
  1405         try {
  1406             Type mt = rawInstantiate(env, site, sym, null, argtypes, typeargtypes,
  1407                                allowBoxing, useVarargs, types.noWarnings);
  1408             if (!operator || verboseResolutionMode.contains(VerboseResolutionMode.PREDEF))
  1409                 currentResolutionContext.addApplicableCandidate(sym, mt);
  1410         } catch (InapplicableMethodException ex) {
  1411             if (!operator)
  1412                 currentResolutionContext.addInapplicableCandidate(sym, ex.getDiagnostic());
  1413             switch (bestSoFar.kind) {
  1414                 case ABSENT_MTH:
  1415                     return new InapplicableSymbolError(currentResolutionContext);
  1416                 case WRONG_MTH:
  1417                     if (operator) return bestSoFar;
  1418                     bestSoFar = new InapplicableSymbolsError(currentResolutionContext);
  1419                 default:
  1420                     return bestSoFar;
  1423         if (!isAccessible(env, site, sym)) {
  1424             return (bestSoFar.kind == ABSENT_MTH)
  1425                 ? new AccessError(env, site, sym)
  1426                 : bestSoFar;
  1428         return (bestSoFar.kind > AMBIGUOUS)
  1429             ? sym
  1430             : mostSpecific(argtypes, sym, bestSoFar, env, site,
  1431                            allowBoxing && operator, useVarargs);
  1434     /* Return the most specific of the two methods for a call,
  1435      *  given that both are accessible and applicable.
  1436      *  @param m1               A new candidate for most specific.
  1437      *  @param m2               The previous most specific candidate.
  1438      *  @param env              The current environment.
  1439      *  @param site             The original type from where the selection
  1440      *                          takes place.
  1441      *  @param allowBoxing Allow boxing conversions of arguments.
  1442      *  @param useVarargs Box trailing arguments into an array for varargs.
  1443      */
  1444     Symbol mostSpecific(List<Type> argtypes, Symbol m1,
  1445                         Symbol m2,
  1446                         Env<AttrContext> env,
  1447                         final Type site,
  1448                         boolean allowBoxing,
  1449                         boolean useVarargs) {
  1450         switch (m2.kind) {
  1451         case MTH:
  1452             if (m1 == m2) return m1;
  1453             boolean m1SignatureMoreSpecific =
  1454                     signatureMoreSpecific(argtypes, env, site, m1, m2, allowBoxing, useVarargs);
  1455             boolean m2SignatureMoreSpecific =
  1456                     signatureMoreSpecific(argtypes, env, site, m2, m1, allowBoxing, useVarargs);
  1457             if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) {
  1458                 Type mt1 = types.memberType(site, m1);
  1459                 Type mt2 = types.memberType(site, m2);
  1460                 if (!types.overrideEquivalent(mt1, mt2))
  1461                     return ambiguityError(m1, m2);
  1463                 // same signature; select (a) the non-bridge method, or
  1464                 // (b) the one that overrides the other, or (c) the concrete
  1465                 // one, or (d) merge both abstract signatures
  1466                 if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE))
  1467                     return ((m1.flags() & BRIDGE) != 0) ? m2 : m1;
  1469                 // if one overrides or hides the other, use it
  1470                 TypeSymbol m1Owner = (TypeSymbol)m1.owner;
  1471                 TypeSymbol m2Owner = (TypeSymbol)m2.owner;
  1472                 if (types.asSuper(m1Owner.type, m2Owner) != null &&
  1473                     ((m1.owner.flags_field & INTERFACE) == 0 ||
  1474                      (m2.owner.flags_field & INTERFACE) != 0) &&
  1475                     m1.overrides(m2, m1Owner, types, false))
  1476                     return m1;
  1477                 if (types.asSuper(m2Owner.type, m1Owner) != null &&
  1478                     ((m2.owner.flags_field & INTERFACE) == 0 ||
  1479                      (m1.owner.flags_field & INTERFACE) != 0) &&
  1480                     m2.overrides(m1, m2Owner, types, false))
  1481                     return m2;
  1482                 boolean m1Abstract = (m1.flags() & ABSTRACT) != 0;
  1483                 boolean m2Abstract = (m2.flags() & ABSTRACT) != 0;
  1484                 if (m1Abstract && !m2Abstract) return m2;
  1485                 if (m2Abstract && !m1Abstract) return m1;
  1486                 // both abstract or both concrete
  1487                 return ambiguityError(m1, m2);
  1489             if (m1SignatureMoreSpecific) return m1;
  1490             if (m2SignatureMoreSpecific) return m2;
  1491             return ambiguityError(m1, m2);
  1492         case AMBIGUOUS:
  1493             //check if m1 is more specific than all ambiguous methods in m2
  1494             AmbiguityError e = (AmbiguityError)m2;
  1495             for (Symbol s : e.ambiguousSyms) {
  1496                 if (mostSpecific(argtypes, m1, s, env, site, allowBoxing, useVarargs) != m1) {
  1497                     return e.addAmbiguousSymbol(m1);
  1500             return m1;
  1501         default:
  1502             throw new AssertionError();
  1505     //where
  1506     private boolean signatureMoreSpecific(List<Type> actuals, Env<AttrContext> env, Type site, Symbol m1, Symbol m2, boolean allowBoxing, boolean useVarargs) {
  1507         noteWarner.clear();
  1508         int maxLength = Math.max(
  1509                             Math.max(m1.type.getParameterTypes().length(), actuals.length()),
  1510                             m2.type.getParameterTypes().length());
  1511         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  1512         try {
  1513             currentResolutionContext = new MethodResolutionContext();
  1514             currentResolutionContext.step = prevResolutionContext.step;
  1515             currentResolutionContext.methodCheck =
  1516                     prevResolutionContext.methodCheck.mostSpecificCheck(actuals, !allowBoxing);
  1517             Type mst = instantiate(env, site, m2, null,
  1518                     adjustArgs(types.lowerBounds(types.memberType(site, m1).getParameterTypes()), m1, maxLength, useVarargs), null,
  1519                     allowBoxing, useVarargs, noteWarner);
  1520             return mst != null &&
  1521                     !noteWarner.hasLint(Lint.LintCategory.UNCHECKED);
  1522         } finally {
  1523             currentResolutionContext = prevResolutionContext;
  1527     List<Type> adjustArgs(List<Type> args, Symbol msym, int length, boolean allowVarargs) {
  1528         if ((msym.flags() & VARARGS) != 0 && allowVarargs) {
  1529             Type varargsElem = types.elemtype(args.last());
  1530             if (varargsElem == null) {
  1531                 Assert.error("Bad varargs = " + args.last() + " " + msym);
  1533             List<Type> newArgs = args.reverse().tail.prepend(varargsElem).reverse();
  1534             while (newArgs.length() < length) {
  1535                 newArgs = newArgs.append(newArgs.last());
  1537             return newArgs;
  1538         } else {
  1539             return args;
  1542     //where
  1543     Type mostSpecificReturnType(Type mt1, Type mt2) {
  1544         Type rt1 = mt1.getReturnType();
  1545         Type rt2 = mt2.getReturnType();
  1547         if (mt1.hasTag(FORALL) && mt2.hasTag(FORALL)) {
  1548             //if both are generic methods, adjust return type ahead of subtyping check
  1549             rt1 = types.subst(rt1, mt1.getTypeArguments(), mt2.getTypeArguments());
  1551         //first use subtyping, then return type substitutability
  1552         if (types.isSubtype(rt1, rt2)) {
  1553             return mt1;
  1554         } else if (types.isSubtype(rt2, rt1)) {
  1555             return mt2;
  1556         } else if (types.returnTypeSubstitutable(mt1, mt2)) {
  1557             return mt1;
  1558         } else if (types.returnTypeSubstitutable(mt2, mt1)) {
  1559             return mt2;
  1560         } else {
  1561             return null;
  1564     //where
  1565     Symbol ambiguityError(Symbol m1, Symbol m2) {
  1566         if (((m1.flags() | m2.flags()) & CLASH) != 0) {
  1567             return (m1.flags() & CLASH) == 0 ? m1 : m2;
  1568         } else {
  1569             return new AmbiguityError(m1, m2);
  1573     Symbol findMethodInScope(Env<AttrContext> env,
  1574             Type site,
  1575             Name name,
  1576             List<Type> argtypes,
  1577             List<Type> typeargtypes,
  1578             Scope sc,
  1579             Symbol bestSoFar,
  1580             boolean allowBoxing,
  1581             boolean useVarargs,
  1582             boolean operator,
  1583             boolean abstractok) {
  1584         for (Symbol s : sc.getElementsByName(name, new LookupFilter(abstractok))) {
  1585             bestSoFar = selectBest(env, site, argtypes, typeargtypes, s,
  1586                     bestSoFar, allowBoxing, useVarargs, operator);
  1588         return bestSoFar;
  1590     //where
  1591         class LookupFilter implements Filter<Symbol> {
  1593             boolean abstractOk;
  1595             LookupFilter(boolean abstractOk) {
  1596                 this.abstractOk = abstractOk;
  1599             public boolean accepts(Symbol s) {
  1600                 long flags = s.flags();
  1601                 return s.kind == MTH &&
  1602                         (flags & SYNTHETIC) == 0 &&
  1603                         (abstractOk ||
  1604                         (flags & DEFAULT) != 0 ||
  1605                         (flags & ABSTRACT) == 0);
  1607         };
  1609     /** Find best qualified method matching given name, type and value
  1610      *  arguments.
  1611      *  @param env       The current environment.
  1612      *  @param site      The original type from where the selection
  1613      *                   takes place.
  1614      *  @param name      The method's name.
  1615      *  @param argtypes  The method's value arguments.
  1616      *  @param typeargtypes The method's type arguments
  1617      *  @param allowBoxing Allow boxing conversions of arguments.
  1618      *  @param useVarargs Box trailing arguments into an array for varargs.
  1619      */
  1620     Symbol findMethod(Env<AttrContext> env,
  1621                       Type site,
  1622                       Name name,
  1623                       List<Type> argtypes,
  1624                       List<Type> typeargtypes,
  1625                       boolean allowBoxing,
  1626                       boolean useVarargs,
  1627                       boolean operator) {
  1628         Symbol bestSoFar = methodNotFound;
  1629         bestSoFar = findMethod(env,
  1630                           site,
  1631                           name,
  1632                           argtypes,
  1633                           typeargtypes,
  1634                           site.tsym.type,
  1635                           bestSoFar,
  1636                           allowBoxing,
  1637                           useVarargs,
  1638                           operator);
  1639         return bestSoFar;
  1641     // where
  1642     private Symbol findMethod(Env<AttrContext> env,
  1643                               Type site,
  1644                               Name name,
  1645                               List<Type> argtypes,
  1646                               List<Type> typeargtypes,
  1647                               Type intype,
  1648                               Symbol bestSoFar,
  1649                               boolean allowBoxing,
  1650                               boolean useVarargs,
  1651                               boolean operator) {
  1652         @SuppressWarnings({"unchecked","rawtypes"})
  1653         List<Type>[] itypes = (List<Type>[])new List[] { List.<Type>nil(), List.<Type>nil() };
  1654         InterfaceLookupPhase iphase = InterfaceLookupPhase.ABSTRACT_OK;
  1655         for (TypeSymbol s : superclasses(intype)) {
  1656             bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
  1657                     s.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
  1658             if (name == names.init) return bestSoFar;
  1659             iphase = (iphase == null) ? null : iphase.update(s, this);
  1660             if (iphase != null) {
  1661                 for (Type itype : types.interfaces(s.type)) {
  1662                     itypes[iphase.ordinal()] = types.union(types.closure(itype), itypes[iphase.ordinal()]);
  1667         Symbol concrete = bestSoFar.kind < ERR &&
  1668                 (bestSoFar.flags() & ABSTRACT) == 0 ?
  1669                 bestSoFar : methodNotFound;
  1671         for (InterfaceLookupPhase iphase2 : InterfaceLookupPhase.values()) {
  1672             if (iphase2 == InterfaceLookupPhase.DEFAULT_OK && !allowDefaultMethods) break;
  1673             //keep searching for abstract methods
  1674             for (Type itype : itypes[iphase2.ordinal()]) {
  1675                 if (!itype.isInterface()) continue; //skip j.l.Object (included by Types.closure())
  1676                 if (iphase2 == InterfaceLookupPhase.DEFAULT_OK &&
  1677                         (itype.tsym.flags() & DEFAULT) == 0) continue;
  1678                 bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
  1679                         itype.tsym.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
  1680                 if (concrete != bestSoFar &&
  1681                         concrete.kind < ERR  && bestSoFar.kind < ERR &&
  1682                         types.isSubSignature(concrete.type, bestSoFar.type)) {
  1683                     //this is an hack - as javac does not do full membership checks
  1684                     //most specific ends up comparing abstract methods that might have
  1685                     //been implemented by some concrete method in a subclass and,
  1686                     //because of raw override, it is possible for an abstract method
  1687                     //to be more specific than the concrete method - so we need
  1688                     //to explicitly call that out (see CR 6178365)
  1689                     bestSoFar = concrete;
  1693         return bestSoFar;
  1696     enum InterfaceLookupPhase {
  1697         ABSTRACT_OK() {
  1698             @Override
  1699             InterfaceLookupPhase update(Symbol s, Resolve rs) {
  1700                 //We should not look for abstract methods if receiver is a concrete class
  1701                 //(as concrete classes are expected to implement all abstracts coming
  1702                 //from superinterfaces)
  1703                 if ((s.flags() & (ABSTRACT | INTERFACE | ENUM)) != 0) {
  1704                     return this;
  1705                 } else if (rs.allowDefaultMethods) {
  1706                     return DEFAULT_OK;
  1707                 } else {
  1708                     return null;
  1711         },
  1712         DEFAULT_OK() {
  1713             @Override
  1714             InterfaceLookupPhase update(Symbol s, Resolve rs) {
  1715                 return this;
  1717         };
  1719         abstract InterfaceLookupPhase update(Symbol s, Resolve rs);
  1722     /**
  1723      * Return an Iterable object to scan the superclasses of a given type.
  1724      * It's crucial that the scan is done lazily, as we don't want to accidentally
  1725      * access more supertypes than strictly needed (as this could trigger completion
  1726      * errors if some of the not-needed supertypes are missing/ill-formed).
  1727      */
  1728     Iterable<TypeSymbol> superclasses(final Type intype) {
  1729         return new Iterable<TypeSymbol>() {
  1730             public Iterator<TypeSymbol> iterator() {
  1731                 return new Iterator<TypeSymbol>() {
  1733                     List<TypeSymbol> seen = List.nil();
  1734                     TypeSymbol currentSym = symbolFor(intype);
  1735                     TypeSymbol prevSym = null;
  1737                     public boolean hasNext() {
  1738                         if (currentSym == syms.noSymbol) {
  1739                             currentSym = symbolFor(types.supertype(prevSym.type));
  1741                         return currentSym != null;
  1744                     public TypeSymbol next() {
  1745                         prevSym = currentSym;
  1746                         currentSym = syms.noSymbol;
  1747                         Assert.check(prevSym != null || prevSym != syms.noSymbol);
  1748                         return prevSym;
  1751                     public void remove() {
  1752                         throw new UnsupportedOperationException();
  1755                     TypeSymbol symbolFor(Type t) {
  1756                         if (!t.hasTag(CLASS) &&
  1757                                 !t.hasTag(TYPEVAR)) {
  1758                             return null;
  1760                         while (t.hasTag(TYPEVAR))
  1761                             t = t.getUpperBound();
  1762                         if (seen.contains(t.tsym)) {
  1763                             //degenerate case in which we have a circular
  1764                             //class hierarchy - because of ill-formed classfiles
  1765                             return null;
  1767                         seen = seen.prepend(t.tsym);
  1768                         return t.tsym;
  1770                 };
  1772         };
  1775     /** Find unqualified method matching given name, type and value arguments.
  1776      *  @param env       The current environment.
  1777      *  @param name      The method's name.
  1778      *  @param argtypes  The method's value arguments.
  1779      *  @param typeargtypes  The method's type arguments.
  1780      *  @param allowBoxing Allow boxing conversions of arguments.
  1781      *  @param useVarargs Box trailing arguments into an array for varargs.
  1782      */
  1783     Symbol findFun(Env<AttrContext> env, Name name,
  1784                    List<Type> argtypes, List<Type> typeargtypes,
  1785                    boolean allowBoxing, boolean useVarargs) {
  1786         Symbol bestSoFar = methodNotFound;
  1787         Symbol sym;
  1788         Env<AttrContext> env1 = env;
  1789         boolean staticOnly = false;
  1790         while (env1.outer != null) {
  1791             if (isStatic(env1)) staticOnly = true;
  1792             sym = findMethod(
  1793                 env1, env1.enclClass.sym.type, name, argtypes, typeargtypes,
  1794                 allowBoxing, useVarargs, false);
  1795             if (sym.exists()) {
  1796                 if (staticOnly &&
  1797                     sym.kind == MTH &&
  1798                     sym.owner.kind == TYP &&
  1799                     (sym.flags() & STATIC) == 0) return new StaticError(sym);
  1800                 else return sym;
  1801             } else if (sym.kind < bestSoFar.kind) {
  1802                 bestSoFar = sym;
  1804             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  1805             env1 = env1.outer;
  1808         sym = findMethod(env, syms.predefClass.type, name, argtypes,
  1809                          typeargtypes, allowBoxing, useVarargs, false);
  1810         if (sym.exists())
  1811             return sym;
  1813         Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
  1814         for (; e.scope != null; e = e.next()) {
  1815             sym = e.sym;
  1816             Type origin = e.getOrigin().owner.type;
  1817             if (sym.kind == MTH) {
  1818                 if (e.sym.owner.type != origin)
  1819                     sym = sym.clone(e.getOrigin().owner);
  1820                 if (!isAccessible(env, origin, sym))
  1821                     sym = new AccessError(env, origin, sym);
  1822                 bestSoFar = selectBest(env, origin,
  1823                                        argtypes, typeargtypes,
  1824                                        sym, bestSoFar,
  1825                                        allowBoxing, useVarargs, false);
  1828         if (bestSoFar.exists())
  1829             return bestSoFar;
  1831         e = env.toplevel.starImportScope.lookup(name);
  1832         for (; e.scope != null; e = e.next()) {
  1833             sym = e.sym;
  1834             Type origin = e.getOrigin().owner.type;
  1835             if (sym.kind == MTH) {
  1836                 if (e.sym.owner.type != origin)
  1837                     sym = sym.clone(e.getOrigin().owner);
  1838                 if (!isAccessible(env, origin, sym))
  1839                     sym = new AccessError(env, origin, sym);
  1840                 bestSoFar = selectBest(env, origin,
  1841                                        argtypes, typeargtypes,
  1842                                        sym, bestSoFar,
  1843                                        allowBoxing, useVarargs, false);
  1846         return bestSoFar;
  1849     /** Load toplevel or member class with given fully qualified name and
  1850      *  verify that it is accessible.
  1851      *  @param env       The current environment.
  1852      *  @param name      The fully qualified name of the class to be loaded.
  1853      */
  1854     Symbol loadClass(Env<AttrContext> env, Name name) {
  1855         try {
  1856             ClassSymbol c = reader.loadClass(name);
  1857             return isAccessible(env, c) ? c : new AccessError(c);
  1858         } catch (ClassReader.BadClassFile err) {
  1859             throw err;
  1860         } catch (CompletionFailure ex) {
  1861             return typeNotFound;
  1866     /**
  1867      * Find a type declared in a scope (not inherited).  Return null
  1868      * if none is found.
  1869      *  @param env       The current environment.
  1870      *  @param site      The original type from where the selection takes
  1871      *                   place.
  1872      *  @param name      The type's name.
  1873      *  @param c         The class to search for the member type. This is
  1874      *                   always a superclass or implemented interface of
  1875      *                   site's class.
  1876      */
  1877     Symbol findImmediateMemberType(Env<AttrContext> env,
  1878                                    Type site,
  1879                                    Name name,
  1880                                    TypeSymbol c) {
  1881         Scope.Entry e = c.members().lookup(name);
  1882         while (e.scope != null) {
  1883             if (e.sym.kind == TYP) {
  1884                 return isAccessible(env, site, e.sym)
  1885                     ? e.sym
  1886                     : new AccessError(env, site, e.sym);
  1888             e = e.next();
  1890         return typeNotFound;
  1893     /** Find a member type inherited from a superclass or interface.
  1894      *  @param env       The current environment.
  1895      *  @param site      The original type from where the selection takes
  1896      *                   place.
  1897      *  @param name      The type's name.
  1898      *  @param c         The class to search for the member type. This is
  1899      *                   always a superclass or implemented interface of
  1900      *                   site's class.
  1901      */
  1902     Symbol findInheritedMemberType(Env<AttrContext> env,
  1903                                    Type site,
  1904                                    Name name,
  1905                                    TypeSymbol c) {
  1906         Symbol bestSoFar = typeNotFound;
  1907         Symbol sym;
  1908         Type st = types.supertype(c.type);
  1909         if (st != null && st.hasTag(CLASS)) {
  1910             sym = findMemberType(env, site, name, st.tsym);
  1911             if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1913         for (List<Type> l = types.interfaces(c.type);
  1914              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
  1915              l = l.tail) {
  1916             sym = findMemberType(env, site, name, l.head.tsym);
  1917             if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
  1918                 sym.owner != bestSoFar.owner)
  1919                 bestSoFar = new AmbiguityError(bestSoFar, sym);
  1920             else if (sym.kind < bestSoFar.kind)
  1921                 bestSoFar = sym;
  1923         return bestSoFar;
  1926     /** Find qualified member type.
  1927      *  @param env       The current environment.
  1928      *  @param site      The original type from where the selection takes
  1929      *                   place.
  1930      *  @param name      The type's name.
  1931      *  @param c         The class to search for the member type. This is
  1932      *                   always a superclass or implemented interface of
  1933      *                   site's class.
  1934      */
  1935     Symbol findMemberType(Env<AttrContext> env,
  1936                           Type site,
  1937                           Name name,
  1938                           TypeSymbol c) {
  1939         Symbol sym = findImmediateMemberType(env, site, name, c);
  1941         if (sym != typeNotFound)
  1942             return sym;
  1944         return findInheritedMemberType(env, site, name, c);
  1948     /** Find a global type in given scope and load corresponding class.
  1949      *  @param env       The current environment.
  1950      *  @param scope     The scope in which to look for the type.
  1951      *  @param name      The type's name.
  1952      */
  1953     Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name) {
  1954         Symbol bestSoFar = typeNotFound;
  1955         for (Scope.Entry e = scope.lookup(name); e.scope != null; e = e.next()) {
  1956             Symbol sym = loadClass(env, e.sym.flatName());
  1957             if (bestSoFar.kind == TYP && sym.kind == TYP &&
  1958                 bestSoFar != sym)
  1959                 return new AmbiguityError(bestSoFar, sym);
  1960             else if (sym.kind < bestSoFar.kind)
  1961                 bestSoFar = sym;
  1963         return bestSoFar;
  1966     Symbol findTypeVar(Env<AttrContext> env, Name name, boolean staticOnly) {
  1967         for (Scope.Entry e = env.info.scope.lookup(name);
  1968              e.scope != null;
  1969              e = e.next()) {
  1970             if (e.sym.kind == TYP) {
  1971                 if (staticOnly &&
  1972                     e.sym.type.hasTag(TYPEVAR) &&
  1973                     e.sym.owner.kind == TYP)
  1974                     return new StaticError(e.sym);
  1975                 return e.sym;
  1978         return typeNotFound;
  1981     /** Find an unqualified type symbol.
  1982      *  @param env       The current environment.
  1983      *  @param name      The type's name.
  1984      */
  1985     Symbol findType(Env<AttrContext> env, Name name) {
  1986         Symbol bestSoFar = typeNotFound;
  1987         Symbol sym;
  1988         boolean staticOnly = false;
  1989         for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
  1990             if (isStatic(env1)) staticOnly = true;
  1991             // First, look for a type variable and the first member type
  1992             final Symbol tyvar = findTypeVar(env1, name, staticOnly);
  1993             sym = findImmediateMemberType(env1, env1.enclClass.sym.type,
  1994                                           name, env1.enclClass.sym);
  1996             // Return the type variable if we have it, and have no
  1997             // immediate member, OR the type variable is for a method.
  1998             if (tyvar != typeNotFound) {
  1999                 if (sym == typeNotFound ||
  2000                     (tyvar.kind == TYP && tyvar.exists() &&
  2001                      tyvar.owner.kind == MTH))
  2002                     return tyvar;
  2005             // If the environment is a class def, finish up,
  2006             // otherwise, do the entire findMemberType
  2007             if (sym == typeNotFound)
  2008                 sym = findInheritedMemberType(env1, env1.enclClass.sym.type,
  2009                                               name, env1.enclClass.sym);
  2011             if (staticOnly && sym.kind == TYP &&
  2012                 sym.type.hasTag(CLASS) &&
  2013                 sym.type.getEnclosingType().hasTag(CLASS) &&
  2014                 env1.enclClass.sym.type.isParameterized() &&
  2015                 sym.type.getEnclosingType().isParameterized())
  2016                 return new StaticError(sym);
  2017             else if (sym.exists()) return sym;
  2018             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  2020             JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass;
  2021             if ((encl.sym.flags() & STATIC) != 0)
  2022                 staticOnly = true;
  2025         if (!env.tree.hasTag(IMPORT)) {
  2026             sym = findGlobalType(env, env.toplevel.namedImportScope, name);
  2027             if (sym.exists()) return sym;
  2028             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  2030             sym = findGlobalType(env, env.toplevel.packge.members(), name);
  2031             if (sym.exists()) return sym;
  2032             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  2034             sym = findGlobalType(env, env.toplevel.starImportScope, name);
  2035             if (sym.exists()) return sym;
  2036             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  2039         return bestSoFar;
  2042     /** Find an unqualified identifier which matches a specified kind set.
  2043      *  @param env       The current environment.
  2044      *  @param name      The identifier's name.
  2045      *  @param kind      Indicates the possible symbol kinds
  2046      *                   (a subset of VAL, TYP, PCK).
  2047      */
  2048     Symbol findIdent(Env<AttrContext> env, Name name, int kind) {
  2049         Symbol bestSoFar = typeNotFound;
  2050         Symbol sym;
  2052         if ((kind & VAR) != 0) {
  2053             sym = findVar(env, name);
  2054             if (sym.exists()) return sym;
  2055             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  2058         if ((kind & TYP) != 0) {
  2059             sym = findType(env, name);
  2060             if (sym.kind==TYP) {
  2061                  reportDependence(env.enclClass.sym, sym);
  2063             if (sym.exists()) return sym;
  2064             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  2067         if ((kind & PCK) != 0) return reader.enterPackage(name);
  2068         else return bestSoFar;
  2071     /** Report dependencies.
  2072      * @param from The enclosing class sym
  2073      * @param to   The found identifier that the class depends on.
  2074      */
  2075     public void reportDependence(Symbol from, Symbol to) {
  2076         // Override if you want to collect the reported dependencies.
  2079     /** Find an identifier in a package which matches a specified kind set.
  2080      *  @param env       The current environment.
  2081      *  @param name      The identifier's name.
  2082      *  @param kind      Indicates the possible symbol kinds
  2083      *                   (a nonempty subset of TYP, PCK).
  2084      */
  2085     Symbol findIdentInPackage(Env<AttrContext> env, TypeSymbol pck,
  2086                               Name name, int kind) {
  2087         Name fullname = TypeSymbol.formFullName(name, pck);
  2088         Symbol bestSoFar = typeNotFound;
  2089         PackageSymbol pack = null;
  2090         if ((kind & PCK) != 0) {
  2091             pack = reader.enterPackage(fullname);
  2092             if (pack.exists()) return pack;
  2094         if ((kind & TYP) != 0) {
  2095             Symbol sym = loadClass(env, fullname);
  2096             if (sym.exists()) {
  2097                 // don't allow programs to use flatnames
  2098                 if (name == sym.name) return sym;
  2100             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  2102         return (pack != null) ? pack : bestSoFar;
  2105     /** Find an identifier among the members of a given type `site'.
  2106      *  @param env       The current environment.
  2107      *  @param site      The type containing the symbol to be found.
  2108      *  @param name      The identifier's name.
  2109      *  @param kind      Indicates the possible symbol kinds
  2110      *                   (a subset of VAL, TYP).
  2111      */
  2112     Symbol findIdentInType(Env<AttrContext> env, Type site,
  2113                            Name name, int kind) {
  2114         Symbol bestSoFar = typeNotFound;
  2115         Symbol sym;
  2116         if ((kind & VAR) != 0) {
  2117             sym = findField(env, site, name, site.tsym);
  2118             if (sym.exists()) return sym;
  2119             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  2122         if ((kind & TYP) != 0) {
  2123             sym = findMemberType(env, site, name, site.tsym);
  2124             if (sym.exists()) return sym;
  2125             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  2127         return bestSoFar;
  2130 /* ***************************************************************************
  2131  *  Access checking
  2132  *  The following methods convert ResolveErrors to ErrorSymbols, issuing
  2133  *  an error message in the process
  2134  ****************************************************************************/
  2136     /** If `sym' is a bad symbol: report error and return errSymbol
  2137      *  else pass through unchanged,
  2138      *  additional arguments duplicate what has been used in trying to find the
  2139      *  symbol {@literal (--> flyweight pattern)}. This improves performance since we
  2140      *  expect misses to happen frequently.
  2142      *  @param sym       The symbol that was found, or a ResolveError.
  2143      *  @param pos       The position to use for error reporting.
  2144      *  @param location  The symbol the served as a context for this lookup
  2145      *  @param site      The original type from where the selection took place.
  2146      *  @param name      The symbol's name.
  2147      *  @param qualified Did we get here through a qualified expression resolution?
  2148      *  @param argtypes  The invocation's value arguments,
  2149      *                   if we looked for a method.
  2150      *  @param typeargtypes  The invocation's type arguments,
  2151      *                   if we looked for a method.
  2152      *  @param logResolveHelper helper class used to log resolve errors
  2153      */
  2154     Symbol accessInternal(Symbol sym,
  2155                   DiagnosticPosition pos,
  2156                   Symbol location,
  2157                   Type site,
  2158                   Name name,
  2159                   boolean qualified,
  2160                   List<Type> argtypes,
  2161                   List<Type> typeargtypes,
  2162                   LogResolveHelper logResolveHelper) {
  2163         if (sym.kind >= AMBIGUOUS) {
  2164             ResolveError errSym = (ResolveError)sym;
  2165             sym = errSym.access(name, qualified ? site.tsym : syms.noSymbol);
  2166             argtypes = logResolveHelper.getArgumentTypes(errSym, sym, name, argtypes);
  2167             if (logResolveHelper.resolveDiagnosticNeeded(site, argtypes, typeargtypes)) {
  2168                 logResolveError(errSym, pos, location, site, name, argtypes, typeargtypes);
  2171         return sym;
  2174     /**
  2175      * Variant of the generalized access routine, to be used for generating method
  2176      * resolution diagnostics
  2177      */
  2178     Symbol accessMethod(Symbol sym,
  2179                   DiagnosticPosition pos,
  2180                   Symbol location,
  2181                   Type site,
  2182                   Name name,
  2183                   boolean qualified,
  2184                   List<Type> argtypes,
  2185                   List<Type> typeargtypes) {
  2186         return accessInternal(sym, pos, location, site, name, qualified, argtypes, typeargtypes, methodLogResolveHelper);
  2189     /** Same as original accessMethod(), but without location.
  2190      */
  2191     Symbol accessMethod(Symbol sym,
  2192                   DiagnosticPosition pos,
  2193                   Type site,
  2194                   Name name,
  2195                   boolean qualified,
  2196                   List<Type> argtypes,
  2197                   List<Type> typeargtypes) {
  2198         return accessMethod(sym, pos, site.tsym, site, name, qualified, argtypes, typeargtypes);
  2201     /**
  2202      * Variant of the generalized access routine, to be used for generating variable,
  2203      * type resolution diagnostics
  2204      */
  2205     Symbol accessBase(Symbol sym,
  2206                   DiagnosticPosition pos,
  2207                   Symbol location,
  2208                   Type site,
  2209                   Name name,
  2210                   boolean qualified) {
  2211         return accessInternal(sym, pos, location, site, name, qualified, List.<Type>nil(), null, basicLogResolveHelper);
  2214     /** Same as original accessBase(), but without location.
  2215      */
  2216     Symbol accessBase(Symbol sym,
  2217                   DiagnosticPosition pos,
  2218                   Type site,
  2219                   Name name,
  2220                   boolean qualified) {
  2221         return accessBase(sym, pos, site.tsym, site, name, qualified);
  2224     interface LogResolveHelper {
  2225         boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes);
  2226         List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes);
  2229     LogResolveHelper basicLogResolveHelper = new LogResolveHelper() {
  2230         public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
  2231             return !site.isErroneous();
  2233         public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
  2234             return argtypes;
  2236     };
  2238     LogResolveHelper methodLogResolveHelper = new LogResolveHelper() {
  2239         public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
  2240             return !site.isErroneous() &&
  2241                         !Type.isErroneous(argtypes) &&
  2242                         (typeargtypes == null || !Type.isErroneous(typeargtypes));
  2244         public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
  2245             return (syms.operatorNames.contains(name)) ?
  2246                     argtypes :
  2247                     Type.map(argtypes, new ResolveDeferredRecoveryMap(AttrMode.SPECULATIVE, accessedSym, currentResolutionContext.step));
  2249     };
  2251     class ResolveDeferredRecoveryMap extends DeferredAttr.RecoveryDeferredTypeMap {
  2253         public ResolveDeferredRecoveryMap(AttrMode mode, Symbol msym, MethodResolutionPhase step) {
  2254             deferredAttr.super(mode, msym, step);
  2257         @Override
  2258         protected Type typeOf(DeferredType dt) {
  2259             Type res = super.typeOf(dt);
  2260             if (!res.isErroneous()) {
  2261                 switch (TreeInfo.skipParens(dt.tree).getTag()) {
  2262                     case LAMBDA:
  2263                     case REFERENCE:
  2264                         return dt;
  2265                     case CONDEXPR:
  2266                         return res == Type.recoveryType ?
  2267                                 dt : res;
  2270             return res;
  2274     /** Check that sym is not an abstract method.
  2275      */
  2276     void checkNonAbstract(DiagnosticPosition pos, Symbol sym) {
  2277         if ((sym.flags() & ABSTRACT) != 0 && (sym.flags() & DEFAULT) == 0)
  2278             log.error(pos, "abstract.cant.be.accessed.directly",
  2279                       kindName(sym), sym, sym.location());
  2282 /* ***************************************************************************
  2283  *  Debugging
  2284  ****************************************************************************/
  2286     /** print all scopes starting with scope s and proceeding outwards.
  2287      *  used for debugging.
  2288      */
  2289     public void printscopes(Scope s) {
  2290         while (s != null) {
  2291             if (s.owner != null)
  2292                 System.err.print(s.owner + ": ");
  2293             for (Scope.Entry e = s.elems; e != null; e = e.sibling) {
  2294                 if ((e.sym.flags() & ABSTRACT) != 0)
  2295                     System.err.print("abstract ");
  2296                 System.err.print(e.sym + " ");
  2298             System.err.println();
  2299             s = s.next;
  2303     void printscopes(Env<AttrContext> env) {
  2304         while (env.outer != null) {
  2305             System.err.println("------------------------------");
  2306             printscopes(env.info.scope);
  2307             env = env.outer;
  2311     public void printscopes(Type t) {
  2312         while (t.hasTag(CLASS)) {
  2313             printscopes(t.tsym.members());
  2314             t = types.supertype(t);
  2318 /* ***************************************************************************
  2319  *  Name resolution
  2320  *  Naming conventions are as for symbol lookup
  2321  *  Unlike the find... methods these methods will report access errors
  2322  ****************************************************************************/
  2324     /** Resolve an unqualified (non-method) identifier.
  2325      *  @param pos       The position to use for error reporting.
  2326      *  @param env       The environment current at the identifier use.
  2327      *  @param name      The identifier's name.
  2328      *  @param kind      The set of admissible symbol kinds for the identifier.
  2329      */
  2330     Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env,
  2331                         Name name, int kind) {
  2332         return accessBase(
  2333             findIdent(env, name, kind),
  2334             pos, env.enclClass.sym.type, name, false);
  2337     /** Resolve an unqualified method identifier.
  2338      *  @param pos       The position to use for error reporting.
  2339      *  @param env       The environment current at the method invocation.
  2340      *  @param name      The identifier's name.
  2341      *  @param argtypes  The types of the invocation's value arguments.
  2342      *  @param typeargtypes  The types of the invocation's type arguments.
  2343      */
  2344     Symbol resolveMethod(DiagnosticPosition pos,
  2345                          Env<AttrContext> env,
  2346                          Name name,
  2347                          List<Type> argtypes,
  2348                          List<Type> typeargtypes) {
  2349         return lookupMethod(env, pos, env.enclClass.sym, resolveMethodCheck,
  2350                 new BasicLookupHelper(name, env.enclClass.sym.type, argtypes, typeargtypes) {
  2351                     @Override
  2352                     Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2353                         return findFun(env, name, argtypes, typeargtypes,
  2354                                 phase.isBoxingRequired(),
  2355                                 phase.isVarargsRequired());
  2356                     }});
  2359     /** Resolve a qualified method identifier
  2360      *  @param pos       The position to use for error reporting.
  2361      *  @param env       The environment current at the method invocation.
  2362      *  @param site      The type of the qualifying expression, in which
  2363      *                   identifier is searched.
  2364      *  @param name      The identifier's name.
  2365      *  @param argtypes  The types of the invocation's value arguments.
  2366      *  @param typeargtypes  The types of the invocation's type arguments.
  2367      */
  2368     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
  2369                                   Type site, Name name, List<Type> argtypes,
  2370                                   List<Type> typeargtypes) {
  2371         return resolveQualifiedMethod(pos, env, site.tsym, site, name, argtypes, typeargtypes);
  2373     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
  2374                                   Symbol location, Type site, Name name, List<Type> argtypes,
  2375                                   List<Type> typeargtypes) {
  2376         return resolveQualifiedMethod(new MethodResolutionContext(), pos, env, location, site, name, argtypes, typeargtypes);
  2378     private Symbol resolveQualifiedMethod(MethodResolutionContext resolveContext,
  2379                                   DiagnosticPosition pos, Env<AttrContext> env,
  2380                                   Symbol location, Type site, Name name, List<Type> argtypes,
  2381                                   List<Type> typeargtypes) {
  2382         return lookupMethod(env, pos, location, resolveContext, new BasicLookupHelper(name, site, argtypes, typeargtypes) {
  2383             @Override
  2384             Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2385                 return findMethod(env, site, name, argtypes, typeargtypes,
  2386                         phase.isBoxingRequired(),
  2387                         phase.isVarargsRequired(), false);
  2389             @Override
  2390             Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2391                 if (sym.kind >= AMBIGUOUS) {
  2392                     sym = super.access(env, pos, location, sym);
  2393                 } else if (allowMethodHandles) {
  2394                     MethodSymbol msym = (MethodSymbol)sym;
  2395                     if ((msym.flags() & SIGNATURE_POLYMORPHIC) != 0) {
  2396                         return findPolymorphicSignatureInstance(env, sym, argtypes);
  2399                 return sym;
  2401         });
  2404     /** Find or create an implicit method of exactly the given type (after erasure).
  2405      *  Searches in a side table, not the main scope of the site.
  2406      *  This emulates the lookup process required by JSR 292 in JVM.
  2407      *  @param env       Attribution environment
  2408      *  @param spMethod  signature polymorphic method - i.e. MH.invokeExact
  2409      *  @param argtypes  The required argument types
  2410      */
  2411     Symbol findPolymorphicSignatureInstance(Env<AttrContext> env,
  2412                                             final Symbol spMethod,
  2413                                             List<Type> argtypes) {
  2414         Type mtype = infer.instantiatePolymorphicSignatureInstance(env,
  2415                 (MethodSymbol)spMethod, currentResolutionContext, argtypes);
  2416         for (Symbol sym : polymorphicSignatureScope.getElementsByName(spMethod.name)) {
  2417             if (types.isSameType(mtype, sym.type)) {
  2418                return sym;
  2422         // create the desired method
  2423         long flags = ABSTRACT | HYPOTHETICAL | spMethod.flags() & Flags.AccessFlags;
  2424         Symbol msym = new MethodSymbol(flags, spMethod.name, mtype, spMethod.owner) {
  2425             @Override
  2426             public Symbol baseSymbol() {
  2427                 return spMethod;
  2429         };
  2430         polymorphicSignatureScope.enter(msym);
  2431         return msym;
  2434     /** Resolve a qualified method identifier, throw a fatal error if not
  2435      *  found.
  2436      *  @param pos       The position to use for error reporting.
  2437      *  @param env       The environment current at the method invocation.
  2438      *  @param site      The type of the qualifying expression, in which
  2439      *                   identifier is searched.
  2440      *  @param name      The identifier's name.
  2441      *  @param argtypes  The types of the invocation's value arguments.
  2442      *  @param typeargtypes  The types of the invocation's type arguments.
  2443      */
  2444     public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env,
  2445                                         Type site, Name name,
  2446                                         List<Type> argtypes,
  2447                                         List<Type> typeargtypes) {
  2448         MethodResolutionContext resolveContext = new MethodResolutionContext();
  2449         resolveContext.internalResolution = true;
  2450         Symbol sym = resolveQualifiedMethod(resolveContext, pos, env, site.tsym,
  2451                 site, name, argtypes, typeargtypes);
  2452         if (sym.kind == MTH) return (MethodSymbol)sym;
  2453         else throw new FatalError(
  2454                  diags.fragment("fatal.err.cant.locate.meth",
  2455                                 name));
  2458     /** Resolve constructor.
  2459      *  @param pos       The position to use for error reporting.
  2460      *  @param env       The environment current at the constructor invocation.
  2461      *  @param site      The type of class for which a constructor is searched.
  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 resolveConstructor(DiagnosticPosition pos,
  2468                               Env<AttrContext> env,
  2469                               Type site,
  2470                               List<Type> argtypes,
  2471                               List<Type> typeargtypes) {
  2472         return resolveConstructor(new MethodResolutionContext(), pos, env, site, argtypes, typeargtypes);
  2475     private Symbol resolveConstructor(MethodResolutionContext resolveContext,
  2476                               final DiagnosticPosition pos,
  2477                               Env<AttrContext> env,
  2478                               Type site,
  2479                               List<Type> argtypes,
  2480                               List<Type> typeargtypes) {
  2481         return lookupMethod(env, pos, site.tsym, resolveContext, new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
  2482             @Override
  2483             Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2484                 return findConstructor(pos, env, site, argtypes, typeargtypes,
  2485                         phase.isBoxingRequired(),
  2486                         phase.isVarargsRequired());
  2488         });
  2491     /** Resolve a constructor, throw a fatal error if not found.
  2492      *  @param pos       The position to use for error reporting.
  2493      *  @param env       The environment current at the method invocation.
  2494      *  @param site      The type to be constructed.
  2495      *  @param argtypes  The types of the invocation's value arguments.
  2496      *  @param typeargtypes  The types of the invocation's type arguments.
  2497      */
  2498     public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  2499                                         Type site,
  2500                                         List<Type> argtypes,
  2501                                         List<Type> typeargtypes) {
  2502         MethodResolutionContext resolveContext = new MethodResolutionContext();
  2503         resolveContext.internalResolution = true;
  2504         Symbol sym = resolveConstructor(resolveContext, pos, env, site, argtypes, typeargtypes);
  2505         if (sym.kind == MTH) return (MethodSymbol)sym;
  2506         else throw new FatalError(
  2507                  diags.fragment("fatal.err.cant.locate.ctor", site));
  2510     Symbol findConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  2511                               Type site, List<Type> argtypes,
  2512                               List<Type> typeargtypes,
  2513                               boolean allowBoxing,
  2514                               boolean useVarargs) {
  2515         Symbol sym = findMethod(env, site,
  2516                                     names.init, argtypes,
  2517                                     typeargtypes, allowBoxing,
  2518                                     useVarargs, false);
  2519         chk.checkDeprecated(pos, env.info.scope.owner, sym);
  2520         return sym;
  2523     /** Resolve constructor using diamond inference.
  2524      *  @param pos       The position to use for error reporting.
  2525      *  @param env       The environment current at the constructor invocation.
  2526      *  @param site      The type of class for which a constructor is searched.
  2527      *                   The scope of this class has been touched in attribution.
  2528      *  @param argtypes  The types of the constructor invocation's value
  2529      *                   arguments.
  2530      *  @param typeargtypes  The types of the constructor invocation's type
  2531      *                   arguments.
  2532      */
  2533     Symbol resolveDiamond(DiagnosticPosition pos,
  2534                               Env<AttrContext> env,
  2535                               Type site,
  2536                               List<Type> argtypes,
  2537                               List<Type> typeargtypes) {
  2538         return lookupMethod(env, pos, site.tsym, resolveMethodCheck,
  2539                 new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
  2540                     @Override
  2541                     Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2542                         return findDiamond(env, site, argtypes, typeargtypes,
  2543                                 phase.isBoxingRequired(),
  2544                                 phase.isVarargsRequired());
  2546                     @Override
  2547                     Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2548                         if (sym.kind >= AMBIGUOUS) {
  2549                             if (sym.kind != WRONG_MTH && sym.kind != WRONG_MTHS) {
  2550                                 sym = super.access(env, pos, location, sym);
  2551                             } else {
  2552                                 final JCDiagnostic details = sym.kind == WRONG_MTH ?
  2553                                                 ((InapplicableSymbolError)sym).errCandidate().snd :
  2554                                                 null;
  2555                                 sym = new InapplicableSymbolError(sym.kind, "diamondError", currentResolutionContext) {
  2556                                     @Override
  2557                                     JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos,
  2558                                             Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
  2559                                         String key = details == null ?
  2560                                             "cant.apply.diamond" :
  2561                                             "cant.apply.diamond.1";
  2562                                         return diags.create(dkind, log.currentSource(), pos, key,
  2563                                                 diags.fragment("diamond", site.tsym), details);
  2565                                 };
  2566                                 sym = accessMethod(sym, pos, site, names.init, true, argtypes, typeargtypes);
  2567                                 env.info.pendingResolutionPhase = currentResolutionContext.step;
  2570                         return sym;
  2571                     }});
  2574     /** This method scans all the constructor symbol in a given class scope -
  2575      *  assuming that the original scope contains a constructor of the kind:
  2576      *  {@code Foo(X x, Y y)}, where X,Y are class type-variables declared in Foo,
  2577      *  a method check is executed against the modified constructor type:
  2578      *  {@code <X,Y>Foo<X,Y>(X x, Y y)}. This is crucial in order to enable diamond
  2579      *  inference. The inferred return type of the synthetic constructor IS
  2580      *  the inferred type for the diamond operator.
  2581      */
  2582     private Symbol findDiamond(Env<AttrContext> env,
  2583                               Type site,
  2584                               List<Type> argtypes,
  2585                               List<Type> typeargtypes,
  2586                               boolean allowBoxing,
  2587                               boolean useVarargs) {
  2588         Symbol bestSoFar = methodNotFound;
  2589         for (Scope.Entry e = site.tsym.members().lookup(names.init);
  2590              e.scope != null;
  2591              e = e.next()) {
  2592             final Symbol sym = e.sym;
  2593             //- System.out.println(" e " + e.sym);
  2594             if (sym.kind == MTH &&
  2595                 (sym.flags_field & SYNTHETIC) == 0) {
  2596                     List<Type> oldParams = e.sym.type.hasTag(FORALL) ?
  2597                             ((ForAll)sym.type).tvars :
  2598                             List.<Type>nil();
  2599                     Type constrType = new ForAll(site.tsym.type.getTypeArguments().appendList(oldParams),
  2600                             types.createMethodTypeWithReturn(sym.type.asMethodType(), site));
  2601                     MethodSymbol newConstr = new MethodSymbol(sym.flags(), names.init, constrType, site.tsym) {
  2602                         @Override
  2603                         public Symbol baseSymbol() {
  2604                             return sym;
  2606                     };
  2607                     bestSoFar = selectBest(env, site, argtypes, typeargtypes,
  2608                             newConstr,
  2609                             bestSoFar,
  2610                             allowBoxing,
  2611                             useVarargs,
  2612                             false);
  2615         return bestSoFar;
  2620     /** Resolve operator.
  2621      *  @param pos       The position to use for error reporting.
  2622      *  @param optag     The tag of the operation tree.
  2623      *  @param env       The environment current at the operation.
  2624      *  @param argtypes  The types of the operands.
  2625      */
  2626     Symbol resolveOperator(DiagnosticPosition pos, JCTree.Tag optag,
  2627                            Env<AttrContext> env, List<Type> argtypes) {
  2628         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  2629         try {
  2630             currentResolutionContext = new MethodResolutionContext();
  2631             Name name = treeinfo.operatorName(optag);
  2632             return lookupMethod(env, pos, syms.predefClass, currentResolutionContext,
  2633                     new BasicLookupHelper(name, syms.predefClass.type, argtypes, null, BOX) {
  2634                 @Override
  2635                 Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2636                     return findMethod(env, site, name, argtypes, typeargtypes,
  2637                             phase.isBoxingRequired(),
  2638                             phase.isVarargsRequired(), true);
  2640                 @Override
  2641                 Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2642                     return accessMethod(sym, pos, env.enclClass.sym.type, name,
  2643                           false, argtypes, null);
  2645             });
  2646         } finally {
  2647             currentResolutionContext = prevResolutionContext;
  2651     /** Resolve operator.
  2652      *  @param pos       The position to use for error reporting.
  2653      *  @param optag     The tag of the operation tree.
  2654      *  @param env       The environment current at the operation.
  2655      *  @param arg       The type of the operand.
  2656      */
  2657     Symbol resolveUnaryOperator(DiagnosticPosition pos, JCTree.Tag optag, Env<AttrContext> env, Type arg) {
  2658         return resolveOperator(pos, optag, env, List.of(arg));
  2661     /** Resolve binary operator.
  2662      *  @param pos       The position to use for error reporting.
  2663      *  @param optag     The tag of the operation tree.
  2664      *  @param env       The environment current at the operation.
  2665      *  @param left      The types of the left operand.
  2666      *  @param right     The types of the right operand.
  2667      */
  2668     Symbol resolveBinaryOperator(DiagnosticPosition pos,
  2669                                  JCTree.Tag optag,
  2670                                  Env<AttrContext> env,
  2671                                  Type left,
  2672                                  Type right) {
  2673         return resolveOperator(pos, optag, env, List.of(left, right));
  2676     /**
  2677      * Resolution of member references is typically done as a single
  2678      * overload resolution step, where the argument types A are inferred from
  2679      * the target functional descriptor.
  2681      * If the member reference is a method reference with a type qualifier,
  2682      * a two-step lookup process is performed. The first step uses the
  2683      * expected argument list A, while the second step discards the first
  2684      * type from A (which is treated as a receiver type).
  2686      * There are two cases in which inference is performed: (i) if the member
  2687      * reference is a constructor reference and the qualifier type is raw - in
  2688      * which case diamond inference is used to infer a parameterization for the
  2689      * type qualifier; (ii) if the member reference is an unbound reference
  2690      * where the type qualifier is raw - in that case, during the unbound lookup
  2691      * the receiver argument type is used to infer an instantiation for the raw
  2692      * qualifier type.
  2694      * When a multi-step resolution process is exploited, it is an error
  2695      * if two candidates are found (ambiguity).
  2697      * This routine returns a pair (T,S), where S is the member reference symbol,
  2698      * and T is the type of the class in which S is defined. This is necessary as
  2699      * the type T might be dynamically inferred (i.e. if constructor reference
  2700      * has a raw qualifier).
  2701      */
  2702     Pair<Symbol, ReferenceLookupHelper> resolveMemberReference(DiagnosticPosition pos,
  2703                                   Env<AttrContext> env,
  2704                                   JCMemberReference referenceTree,
  2705                                   Type site,
  2706                                   Name name, List<Type> argtypes,
  2707                                   List<Type> typeargtypes,
  2708                                   boolean boxingAllowed,
  2709                                   MethodCheck methodCheck,
  2710                                   InferenceContext inferenceContext) {
  2711         MethodResolutionPhase maxPhase = boxingAllowed ? VARARITY : BASIC;
  2713         if (site.hasTag(TYPEVAR)) {
  2714             return resolveMemberReference(pos, env, referenceTree, site.getUpperBound(),
  2715                     name, argtypes, typeargtypes, boxingAllowed, methodCheck, inferenceContext);
  2718         site = types.capture(site);
  2720         ReferenceLookupHelper boundLookupHelper;
  2721         if (!name.equals(names.init)) {
  2722             //method reference
  2723             boundLookupHelper =
  2724                     new MethodReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
  2725         } else if (site.hasTag(ARRAY)) {
  2726             //array constructor reference
  2727             boundLookupHelper =
  2728                     new ArrayConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase);
  2729         } else {
  2730             //class constructor reference
  2731             boundLookupHelper =
  2732                     new ConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase);
  2735         //step 1 - bound lookup
  2736         Env<AttrContext> boundEnv = env.dup(env.tree, env.info.dup());
  2737         Symbol boundSym = lookupMethod(boundEnv, env.tree.pos(), site.tsym, methodCheck, boundLookupHelper);
  2739         //step 2 - unbound lookup
  2740         ReferenceLookupHelper unboundLookupHelper = boundLookupHelper.unboundLookup(inferenceContext);
  2741         Env<AttrContext> unboundEnv = env.dup(env.tree, env.info.dup());
  2742         Symbol unboundSym = lookupMethod(unboundEnv, env.tree.pos(), site.tsym, methodCheck, unboundLookupHelper);
  2744         //merge results
  2745         Pair<Symbol, ReferenceLookupHelper> res;
  2746         Symbol bestSym = choose(boundSym, unboundSym);
  2747         res = new Pair<Symbol, ReferenceLookupHelper>(bestSym,
  2748                 bestSym == unboundSym ? unboundLookupHelper : boundLookupHelper);
  2749         env.info.pendingResolutionPhase = bestSym == unboundSym ?
  2750                 unboundEnv.info.pendingResolutionPhase :
  2751                 boundEnv.info.pendingResolutionPhase;
  2753         return res;
  2755     //where
  2756         private Symbol choose(Symbol s1, Symbol s2) {
  2757             if (lookupSuccess(s1) && lookupSuccess(s2)) {
  2758                 return ambiguityError(s1, s2);
  2759             } else if (lookupSuccess(s1) ||
  2760                     (canIgnore(s2) && !canIgnore(s1))) {
  2761                 return s1;
  2762             } else if (lookupSuccess(s2) ||
  2763                     (canIgnore(s1) && !canIgnore(s2))) {
  2764                 return s2;
  2765             } else {
  2766                 return s1;
  2770         private boolean lookupSuccess(Symbol s) {
  2771             return s.kind == MTH || s.kind == AMBIGUOUS;
  2774         private boolean canIgnore(Symbol s) {
  2775             switch (s.kind) {
  2776                 case ABSENT_MTH:
  2777                     return true;
  2778                 case WRONG_MTH:
  2779                     InapplicableSymbolError errSym =
  2780                             (InapplicableSymbolError)s;
  2781                     return new Template(MethodCheckDiag.ARITY_MISMATCH.regex())
  2782                             .matches(errSym.errCandidate().snd);
  2783                 case WRONG_MTHS:
  2784                     InapplicableSymbolsError errSyms =
  2785                             (InapplicableSymbolsError)s;
  2786                     return errSyms.filterCandidates(errSyms.mapCandidates()).isEmpty();
  2787                 default:
  2788                     return false;
  2792     /**
  2793      * Helper for defining custom method-like lookup logic; a lookup helper
  2794      * provides hooks for (i) the actual lookup logic and (ii) accessing the
  2795      * lookup result (this step might result in compiler diagnostics to be generated)
  2796      */
  2797     abstract class LookupHelper {
  2799         /** name of the symbol to lookup */
  2800         Name name;
  2802         /** location in which the lookup takes place */
  2803         Type site;
  2805         /** actual types used during the lookup */
  2806         List<Type> argtypes;
  2808         /** type arguments used during the lookup */
  2809         List<Type> typeargtypes;
  2811         /** Max overload resolution phase handled by this helper */
  2812         MethodResolutionPhase maxPhase;
  2814         LookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2815             this.name = name;
  2816             this.site = site;
  2817             this.argtypes = argtypes;
  2818             this.typeargtypes = typeargtypes;
  2819             this.maxPhase = maxPhase;
  2822         /**
  2823          * Should lookup stop at given phase with given result
  2824          */
  2825         protected boolean shouldStop(Symbol sym, MethodResolutionPhase phase) {
  2826             return phase.ordinal() > maxPhase.ordinal() ||
  2827                     sym.kind < ERRONEOUS || sym.kind == AMBIGUOUS;
  2830         /**
  2831          * Search for a symbol under a given overload resolution phase - this method
  2832          * is usually called several times, once per each overload resolution phase
  2833          */
  2834         abstract Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase);
  2836         /**
  2837          * Dump overload resolution info
  2838          */
  2839         void debug(DiagnosticPosition pos, Symbol sym) {
  2840             //do nothing
  2843         /**
  2844          * Validate the result of the lookup
  2845          */
  2846         abstract Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym);
  2849     abstract class BasicLookupHelper extends LookupHelper {
  2851         BasicLookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes) {
  2852             this(name, site, argtypes, typeargtypes, MethodResolutionPhase.VARARITY);
  2855         BasicLookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2856             super(name, site, argtypes, typeargtypes, maxPhase);
  2859         @Override
  2860         final Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2861             Symbol sym = doLookup(env, phase);
  2862             if (sym.kind == AMBIGUOUS) {
  2863                 AmbiguityError a_err = (AmbiguityError)sym;
  2864                 sym = a_err.mergeAbstracts(site);
  2866             return sym;
  2869         abstract Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase);
  2871         @Override
  2872         Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2873             if (sym.kind >= AMBIGUOUS) {
  2874                 //if nothing is found return the 'first' error
  2875                 sym = accessMethod(sym, pos, location, site, name, true, argtypes, typeargtypes);
  2877             return sym;
  2880         @Override
  2881         void debug(DiagnosticPosition pos, Symbol sym) {
  2882             reportVerboseResolutionDiagnostic(pos, name, site, argtypes, typeargtypes, sym);
  2886     /**
  2887      * Helper class for member reference lookup. A reference lookup helper
  2888      * defines the basic logic for member reference lookup; a method gives
  2889      * access to an 'unbound' helper used to perform an unbound member
  2890      * reference lookup.
  2891      */
  2892     abstract class ReferenceLookupHelper extends LookupHelper {
  2894         /** The member reference tree */
  2895         JCMemberReference referenceTree;
  2897         ReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
  2898                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2899             super(name, site, argtypes, typeargtypes, maxPhase);
  2900             this.referenceTree = referenceTree;
  2904         /**
  2905          * Returns an unbound version of this lookup helper. By default, this
  2906          * method returns an dummy lookup helper.
  2907          */
  2908         ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
  2909             //dummy loopkup helper that always return 'methodNotFound'
  2910             return new ReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase) {
  2911                 @Override
  2912                 ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
  2913                     return this;
  2915                 @Override
  2916                 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2917                     return methodNotFound;
  2919                 @Override
  2920                 ReferenceKind referenceKind(Symbol sym) {
  2921                     Assert.error();
  2922                     return null;
  2924             };
  2927         /**
  2928          * Get the kind of the member reference
  2929          */
  2930         abstract JCMemberReference.ReferenceKind referenceKind(Symbol sym);
  2932         Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2933             if (sym.kind == AMBIGUOUS) {
  2934                 AmbiguityError a_err = (AmbiguityError)sym;
  2935                 sym = a_err.mergeAbstracts(site);
  2937             //skip error reporting
  2938             return sym;
  2942     /**
  2943      * Helper class for method reference lookup. The lookup logic is based
  2944      * upon Resolve.findMethod; in certain cases, this helper class has a
  2945      * corresponding unbound helper class (see UnboundMethodReferenceLookupHelper).
  2946      * In such cases, non-static lookup results are thrown away.
  2947      */
  2948     class MethodReferenceLookupHelper extends ReferenceLookupHelper {
  2950         MethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
  2951                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2952             super(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
  2955         @Override
  2956         final Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2957             return findMethod(env, site, name, argtypes, typeargtypes,
  2958                     phase.isBoxingRequired(), phase.isVarargsRequired(), syms.operatorNames.contains(name));
  2961         @Override
  2962         ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
  2963             if (TreeInfo.isStaticSelector(referenceTree.expr, names) &&
  2964                     argtypes.nonEmpty() &&
  2965                     (argtypes.head.hasTag(NONE) ||
  2966                     types.isSubtypeUnchecked(inferenceContext.asFree(argtypes.head), site))) {
  2967                 return new UnboundMethodReferenceLookupHelper(referenceTree, name,
  2968                         site, argtypes, typeargtypes, maxPhase);
  2969             } else {
  2970                 return super.unboundLookup(inferenceContext);
  2974         @Override
  2975         ReferenceKind referenceKind(Symbol sym) {
  2976             if (sym.isStatic()) {
  2977                 return ReferenceKind.STATIC;
  2978             } else {
  2979                 Name selName = TreeInfo.name(referenceTree.getQualifierExpression());
  2980                 return selName != null && selName == names._super ?
  2981                         ReferenceKind.SUPER :
  2982                         ReferenceKind.BOUND;
  2987     /**
  2988      * Helper class for unbound method reference lookup. Essentially the same
  2989      * as the basic method reference lookup helper; main difference is that static
  2990      * lookup results are thrown away. If qualifier type is raw, an attempt to
  2991      * infer a parameterized type is made using the first actual argument (that
  2992      * would otherwise be ignored during the lookup).
  2993      */
  2994     class UnboundMethodReferenceLookupHelper extends MethodReferenceLookupHelper {
  2996         UnboundMethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
  2997                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2998             super(referenceTree, name, site, argtypes.tail, typeargtypes, maxPhase);
  2999             if (site.isRaw() && !argtypes.head.hasTag(NONE)) {
  3000                 Type asSuperSite = types.asSuper(argtypes.head, site.tsym);
  3001                 this.site = asSuperSite;
  3005         @Override
  3006         ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
  3007             return this;
  3010         @Override
  3011         ReferenceKind referenceKind(Symbol sym) {
  3012             return ReferenceKind.UNBOUND;
  3016     /**
  3017      * Helper class for array constructor lookup; an array constructor lookup
  3018      * is simulated by looking up a method that returns the array type specified
  3019      * as qualifier, and that accepts a single int parameter (size of the array).
  3020      */
  3021     class ArrayConstructorReferenceLookupHelper extends ReferenceLookupHelper {
  3023         ArrayConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
  3024                 List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  3025             super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase);
  3028         @Override
  3029         protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  3030             Scope sc = new Scope(syms.arrayClass);
  3031             MethodSymbol arrayConstr = new MethodSymbol(PUBLIC, name, null, site.tsym);
  3032             arrayConstr.type = new MethodType(List.<Type>of(syms.intType), site, List.<Type>nil(), syms.methodClass);
  3033             sc.enter(arrayConstr);
  3034             return findMethodInScope(env, site, name, argtypes, typeargtypes, sc, methodNotFound, phase.isBoxingRequired(), phase.isVarargsRequired(), false, false);
  3037         @Override
  3038         ReferenceKind referenceKind(Symbol sym) {
  3039             return ReferenceKind.ARRAY_CTOR;
  3043     /**
  3044      * Helper class for constructor reference lookup. The lookup logic is based
  3045      * upon either Resolve.findMethod or Resolve.findDiamond - depending on
  3046      * whether the constructor reference needs diamond inference (this is the case
  3047      * if the qualifier type is raw). A special erroneous symbol is returned
  3048      * if the lookup returns the constructor of an inner class and there's no
  3049      * enclosing instance in scope.
  3050      */
  3051     class ConstructorReferenceLookupHelper extends ReferenceLookupHelper {
  3053         boolean needsInference;
  3055         ConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
  3056                 List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  3057             super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase);
  3058             if (site.isRaw()) {
  3059                 this.site = new ClassType(site.getEnclosingType(), site.tsym.type.getTypeArguments(), site.tsym);
  3060                 needsInference = true;
  3064         @Override
  3065         protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  3066             Symbol sym = needsInference ?
  3067                 findDiamond(env, site, argtypes, typeargtypes, phase.isBoxingRequired(), phase.isVarargsRequired()) :
  3068                 findMethod(env, site, name, argtypes, typeargtypes,
  3069                         phase.isBoxingRequired(), phase.isVarargsRequired(), syms.operatorNames.contains(name));
  3070             return sym.kind != MTH ||
  3071                           site.getEnclosingType().hasTag(NONE) ||
  3072                           hasEnclosingInstance(env, site) ?
  3073                           sym : new InvalidSymbolError(Kinds.MISSING_ENCL, sym, null) {
  3074                     @Override
  3075                     JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
  3076                        return diags.create(dkind, log.currentSource(), pos,
  3077                             "cant.access.inner.cls.constr", site.tsym.name, argtypes, site.getEnclosingType());
  3079                 };
  3082         @Override
  3083         ReferenceKind referenceKind(Symbol sym) {
  3084             return site.getEnclosingType().hasTag(NONE) ?
  3085                     ReferenceKind.TOPLEVEL : ReferenceKind.IMPLICIT_INNER;
  3089     /**
  3090      * Main overload resolution routine. On each overload resolution step, a
  3091      * lookup helper class is used to perform the method/constructor lookup;
  3092      * at the end of the lookup, the helper is used to validate the results
  3093      * (this last step might trigger overload resolution diagnostics).
  3094      */
  3095     Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, MethodCheck methodCheck, LookupHelper lookupHelper) {
  3096         MethodResolutionContext resolveContext = new MethodResolutionContext();
  3097         resolveContext.methodCheck = methodCheck;
  3098         return lookupMethod(env, pos, location, resolveContext, lookupHelper);
  3101     Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location,
  3102             MethodResolutionContext resolveContext, LookupHelper lookupHelper) {
  3103         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  3104         try {
  3105             Symbol bestSoFar = methodNotFound;
  3106             currentResolutionContext = resolveContext;
  3107             for (MethodResolutionPhase phase : methodResolutionSteps) {
  3108                 if (!phase.isApplicable(boxingEnabled, varargsEnabled) ||
  3109                         lookupHelper.shouldStop(bestSoFar, phase)) break;
  3110                 MethodResolutionPhase prevPhase = currentResolutionContext.step;
  3111                 Symbol prevBest = bestSoFar;
  3112                 currentResolutionContext.step = phase;
  3113                 Symbol sym = lookupHelper.lookup(env, phase);
  3114                 lookupHelper.debug(pos, sym);
  3115                 bestSoFar = phase.mergeResults(bestSoFar, sym);
  3116                 env.info.pendingResolutionPhase = (prevBest == bestSoFar) ? prevPhase : phase;
  3118             return lookupHelper.access(env, pos, location, bestSoFar);
  3119         } finally {
  3120             currentResolutionContext = prevResolutionContext;
  3124     /**
  3125      * Resolve `c.name' where name == this or name == super.
  3126      * @param pos           The position to use for error reporting.
  3127      * @param env           The environment current at the expression.
  3128      * @param c             The qualifier.
  3129      * @param name          The identifier's name.
  3130      */
  3131     Symbol resolveSelf(DiagnosticPosition pos,
  3132                        Env<AttrContext> env,
  3133                        TypeSymbol c,
  3134                        Name name) {
  3135         Env<AttrContext> env1 = env;
  3136         boolean staticOnly = false;
  3137         while (env1.outer != null) {
  3138             if (isStatic(env1)) staticOnly = true;
  3139             if (env1.enclClass.sym == c) {
  3140                 Symbol sym = env1.info.scope.lookup(name).sym;
  3141                 if (sym != null) {
  3142                     if (staticOnly) sym = new StaticError(sym);
  3143                     return accessBase(sym, pos, env.enclClass.sym.type,
  3144                                   name, true);
  3147             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  3148             env1 = env1.outer;
  3150         if (allowDefaultMethods && c.isInterface() &&
  3151                 name == names._super && !isStatic(env) &&
  3152                 types.isDirectSuperInterface(c, env.enclClass.sym)) {
  3153             //this might be a default super call if one of the superinterfaces is 'c'
  3154             for (Type t : pruneInterfaces(env.enclClass.type)) {
  3155                 if (t.tsym == c) {
  3156                     env.info.defaultSuperCallSite = t;
  3157                     return new VarSymbol(0, names._super,
  3158                             types.asSuper(env.enclClass.type, c), env.enclClass.sym);
  3161             //find a direct superinterface that is a subtype of 'c'
  3162             for (Type i : types.interfaces(env.enclClass.type)) {
  3163                 if (i.tsym.isSubClass(c, types) && i.tsym != c) {
  3164                     log.error(pos, "illegal.default.super.call", c,
  3165                             diags.fragment("redundant.supertype", c, i));
  3166                     return syms.errSymbol;
  3169             Assert.error();
  3171         log.error(pos, "not.encl.class", c);
  3172         return syms.errSymbol;
  3174     //where
  3175     private List<Type> pruneInterfaces(Type t) {
  3176         ListBuffer<Type> result = ListBuffer.lb();
  3177         for (Type t1 : types.interfaces(t)) {
  3178             boolean shouldAdd = true;
  3179             for (Type t2 : types.interfaces(t)) {
  3180                 if (t1 != t2 && types.isSubtypeNoCapture(t2, t1)) {
  3181                     shouldAdd = false;
  3184             if (shouldAdd) {
  3185                 result.append(t1);
  3188         return result.toList();
  3192     /**
  3193      * Resolve `c.this' for an enclosing class c that contains the
  3194      * named member.
  3195      * @param pos           The position to use for error reporting.
  3196      * @param env           The environment current at the expression.
  3197      * @param member        The member that must be contained in the result.
  3198      */
  3199     Symbol resolveSelfContaining(DiagnosticPosition pos,
  3200                                  Env<AttrContext> env,
  3201                                  Symbol member,
  3202                                  boolean isSuperCall) {
  3203         Symbol sym = resolveSelfContainingInternal(env, member, isSuperCall);
  3204         if (sym == null) {
  3205             log.error(pos, "encl.class.required", member);
  3206             return syms.errSymbol;
  3207         } else {
  3208             return accessBase(sym, pos, env.enclClass.sym.type, sym.name, true);
  3212     boolean hasEnclosingInstance(Env<AttrContext> env, Type type) {
  3213         Symbol encl = resolveSelfContainingInternal(env, type.tsym, false);
  3214         return encl != null && encl.kind < ERRONEOUS;
  3217     private Symbol resolveSelfContainingInternal(Env<AttrContext> env,
  3218                                  Symbol member,
  3219                                  boolean isSuperCall) {
  3220         Name name = names._this;
  3221         Env<AttrContext> env1 = isSuperCall ? env.outer : env;
  3222         boolean staticOnly = false;
  3223         if (env1 != null) {
  3224             while (env1 != null && env1.outer != null) {
  3225                 if (isStatic(env1)) staticOnly = true;
  3226                 if (env1.enclClass.sym.isSubClass(member.owner, types)) {
  3227                     Symbol sym = env1.info.scope.lookup(name).sym;
  3228                     if (sym != null) {
  3229                         if (staticOnly) sym = new StaticError(sym);
  3230                         return sym;
  3233                 if ((env1.enclClass.sym.flags() & STATIC) != 0)
  3234                     staticOnly = true;
  3235                 env1 = env1.outer;
  3238         return null;
  3241     /**
  3242      * Resolve an appropriate implicit this instance for t's container.
  3243      * JLS 8.8.5.1 and 15.9.2
  3244      */
  3245     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
  3246         return resolveImplicitThis(pos, env, t, false);
  3249     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t, boolean isSuperCall) {
  3250         Type thisType = (((t.tsym.owner.kind & (MTH|VAR)) != 0)
  3251                          ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
  3252                          : resolveSelfContaining(pos, env, t.tsym, isSuperCall)).type;
  3253         if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
  3254             log.error(pos, "cant.ref.before.ctor.called", "this");
  3255         return thisType;
  3258 /* ***************************************************************************
  3259  *  ResolveError classes, indicating error situations when accessing symbols
  3260  ****************************************************************************/
  3262     //used by TransTypes when checking target type of synthetic cast
  3263     public void logAccessErrorInternal(Env<AttrContext> env, JCTree tree, Type type) {
  3264         AccessError error = new AccessError(env, env.enclClass.type, type.tsym);
  3265         logResolveError(error, tree.pos(), env.enclClass.sym, env.enclClass.type, null, null, null);
  3267     //where
  3268     private void logResolveError(ResolveError error,
  3269             DiagnosticPosition pos,
  3270             Symbol location,
  3271             Type site,
  3272             Name name,
  3273             List<Type> argtypes,
  3274             List<Type> typeargtypes) {
  3275         JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
  3276                 pos, location, site, name, argtypes, typeargtypes);
  3277         if (d != null) {
  3278             d.setFlag(DiagnosticFlag.RESOLVE_ERROR);
  3279             log.report(d);
  3283     private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
  3285     public Object methodArguments(List<Type> argtypes) {
  3286         if (argtypes == null || argtypes.isEmpty()) {
  3287             return noArgs;
  3288         } else {
  3289             ListBuffer<Object> diagArgs = ListBuffer.lb();
  3290             for (Type t : argtypes) {
  3291                 if (t.hasTag(DEFERRED)) {
  3292                     diagArgs.append(((DeferredAttr.DeferredType)t).tree);
  3293                 } else {
  3294                     diagArgs.append(t);
  3297             return diagArgs;
  3301     /**
  3302      * Root class for resolution errors. Subclass of ResolveError
  3303      * represent a different kinds of resolution error - as such they must
  3304      * specify how they map into concrete compiler diagnostics.
  3305      */
  3306     abstract class ResolveError extends Symbol {
  3308         /** The name of the kind of error, for debugging only. */
  3309         final String debugName;
  3311         ResolveError(int kind, String debugName) {
  3312             super(kind, 0, null, null, null);
  3313             this.debugName = debugName;
  3316         @Override
  3317         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
  3318             throw new AssertionError();
  3321         @Override
  3322         public String toString() {
  3323             return debugName;
  3326         @Override
  3327         public boolean exists() {
  3328             return false;
  3331         /**
  3332          * Create an external representation for this erroneous symbol to be
  3333          * used during attribution - by default this returns the symbol of a
  3334          * brand new error type which stores the original type found
  3335          * during resolution.
  3337          * @param name     the name used during resolution
  3338          * @param location the location from which the symbol is accessed
  3339          */
  3340         protected Symbol access(Name name, TypeSymbol location) {
  3341             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  3344         /**
  3345          * Create a diagnostic representing this resolution error.
  3347          * @param dkind     The kind of the diagnostic to be created (e.g error).
  3348          * @param pos       The position to be used for error reporting.
  3349          * @param site      The original type from where the selection took place.
  3350          * @param name      The name of the symbol to be resolved.
  3351          * @param argtypes  The invocation's value arguments,
  3352          *                  if we looked for a method.
  3353          * @param typeargtypes  The invocation's type arguments,
  3354          *                      if we looked for a method.
  3355          */
  3356         abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3357                 DiagnosticPosition pos,
  3358                 Symbol location,
  3359                 Type site,
  3360                 Name name,
  3361                 List<Type> argtypes,
  3362                 List<Type> typeargtypes);
  3365     /**
  3366      * This class is the root class of all resolution errors caused by
  3367      * an invalid symbol being found during resolution.
  3368      */
  3369     abstract class InvalidSymbolError extends ResolveError {
  3371         /** The invalid symbol found during resolution */
  3372         Symbol sym;
  3374         InvalidSymbolError(int kind, Symbol sym, String debugName) {
  3375             super(kind, debugName);
  3376             this.sym = sym;
  3379         @Override
  3380         public boolean exists() {
  3381             return true;
  3384         @Override
  3385         public String toString() {
  3386              return super.toString() + " wrongSym=" + sym;
  3389         @Override
  3390         public Symbol access(Name name, TypeSymbol location) {
  3391             if ((sym.kind & ERRONEOUS) == 0 && (sym.kind & TYP) != 0)
  3392                 return types.createErrorType(name, location, sym.type).tsym;
  3393             else
  3394                 return sym;
  3398     /**
  3399      * InvalidSymbolError error class indicating that a symbol matching a
  3400      * given name does not exists in a given site.
  3401      */
  3402     class SymbolNotFoundError extends ResolveError {
  3404         SymbolNotFoundError(int kind) {
  3405             super(kind, "symbol not found error");
  3408         @Override
  3409         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3410                 DiagnosticPosition pos,
  3411                 Symbol location,
  3412                 Type site,
  3413                 Name name,
  3414                 List<Type> argtypes,
  3415                 List<Type> typeargtypes) {
  3416             argtypes = argtypes == null ? List.<Type>nil() : argtypes;
  3417             typeargtypes = typeargtypes == null ? List.<Type>nil() : typeargtypes;
  3418             if (name == names.error)
  3419                 return null;
  3421             if (syms.operatorNames.contains(name)) {
  3422                 boolean isUnaryOp = argtypes.size() == 1;
  3423                 String key = argtypes.size() == 1 ?
  3424                     "operator.cant.be.applied" :
  3425                     "operator.cant.be.applied.1";
  3426                 Type first = argtypes.head;
  3427                 Type second = !isUnaryOp ? argtypes.tail.head : null;
  3428                 return diags.create(dkind, log.currentSource(), pos,
  3429                         key, name, first, second);
  3431             boolean hasLocation = false;
  3432             if (location == null) {
  3433                 location = site.tsym;
  3435             if (!location.name.isEmpty()) {
  3436                 if (location.kind == PCK && !site.tsym.exists()) {
  3437                     return diags.create(dkind, log.currentSource(), pos,
  3438                         "doesnt.exist", location);
  3440                 hasLocation = !location.name.equals(names._this) &&
  3441                         !location.name.equals(names._super);
  3443             boolean isConstructor = kind == ABSENT_MTH && name == names.init;
  3444             KindName kindname = isConstructor ? KindName.CONSTRUCTOR : absentKind(kind);
  3445             Name idname = isConstructor ? site.tsym.name : name;
  3446             String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation);
  3447             if (hasLocation) {
  3448                 return diags.create(dkind, log.currentSource(), pos,
  3449                         errKey, kindname, idname, //symbol kindname, name
  3450                         typeargtypes, args(argtypes), //type parameters and arguments (if any)
  3451                         getLocationDiag(location, site)); //location kindname, type
  3453             else {
  3454                 return diags.create(dkind, log.currentSource(), pos,
  3455                         errKey, kindname, idname, //symbol kindname, name
  3456                         typeargtypes, args(argtypes)); //type parameters and arguments (if any)
  3459         //where
  3460         private Object args(List<Type> args) {
  3461             return args.isEmpty() ? args : methodArguments(args);
  3464         private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) {
  3465             String key = "cant.resolve";
  3466             String suffix = hasLocation ? ".location" : "";
  3467             switch (kindname) {
  3468                 case METHOD:
  3469                 case CONSTRUCTOR: {
  3470                     suffix += ".args";
  3471                     suffix += hasTypeArgs ? ".params" : "";
  3474             return key + suffix;
  3476         private JCDiagnostic getLocationDiag(Symbol location, Type site) {
  3477             if (location.kind == VAR) {
  3478                 return diags.fragment("location.1",
  3479                     kindName(location),
  3480                     location,
  3481                     location.type);
  3482             } else {
  3483                 return diags.fragment("location",
  3484                     typeKindName(site),
  3485                     site,
  3486                     null);
  3491     /**
  3492      * InvalidSymbolError error class indicating that a given symbol
  3493      * (either a method, a constructor or an operand) is not applicable
  3494      * given an actual arguments/type argument list.
  3495      */
  3496     class InapplicableSymbolError extends ResolveError {
  3498         protected MethodResolutionContext resolveContext;
  3500         InapplicableSymbolError(MethodResolutionContext context) {
  3501             this(WRONG_MTH, "inapplicable symbol error", context);
  3504         protected InapplicableSymbolError(int kind, String debugName, MethodResolutionContext context) {
  3505             super(kind, debugName);
  3506             this.resolveContext = context;
  3509         @Override
  3510         public String toString() {
  3511             return super.toString();
  3514         @Override
  3515         public boolean exists() {
  3516             return true;
  3519         @Override
  3520         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3521                 DiagnosticPosition pos,
  3522                 Symbol location,
  3523                 Type site,
  3524                 Name name,
  3525                 List<Type> argtypes,
  3526                 List<Type> typeargtypes) {
  3527             if (name == names.error)
  3528                 return null;
  3530             if (syms.operatorNames.contains(name)) {
  3531                 boolean isUnaryOp = argtypes.size() == 1;
  3532                 String key = argtypes.size() == 1 ?
  3533                     "operator.cant.be.applied" :
  3534                     "operator.cant.be.applied.1";
  3535                 Type first = argtypes.head;
  3536                 Type second = !isUnaryOp ? argtypes.tail.head : null;
  3537                 return diags.create(dkind, log.currentSource(), pos,
  3538                         key, name, first, second);
  3540             else {
  3541                 Pair<Symbol, JCDiagnostic> c = errCandidate();
  3542                 if (compactMethodDiags) {
  3543                     for (Map.Entry<Template, DiagnosticRewriter> _entry :
  3544                             MethodResolutionDiagHelper.rewriters.entrySet()) {
  3545                         if (_entry.getKey().matches(c.snd)) {
  3546                             JCDiagnostic simpleDiag =
  3547                                     _entry.getValue().rewriteDiagnostic(diags, pos,
  3548                                         log.currentSource(), dkind, c.snd);
  3549                             simpleDiag.setFlag(DiagnosticFlag.COMPRESSED);
  3550                             return simpleDiag;
  3554                 Symbol ws = c.fst.asMemberOf(site, types);
  3555                 return diags.create(dkind, log.currentSource(), pos,
  3556                           "cant.apply.symbol",
  3557                           kindName(ws),
  3558                           ws.name == names.init ? ws.owner.name : ws.name,
  3559                           methodArguments(ws.type.getParameterTypes()),
  3560                           methodArguments(argtypes),
  3561                           kindName(ws.owner),
  3562                           ws.owner.type,
  3563                           c.snd);
  3567         @Override
  3568         public Symbol access(Name name, TypeSymbol location) {
  3569             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  3572         protected Pair<Symbol, JCDiagnostic> errCandidate() {
  3573             Candidate bestSoFar = null;
  3574             for (Candidate c : resolveContext.candidates) {
  3575                 if (c.isApplicable()) continue;
  3576                 bestSoFar = c;
  3578             Assert.checkNonNull(bestSoFar);
  3579             return new Pair<Symbol, JCDiagnostic>(bestSoFar.sym, bestSoFar.details);
  3583     /**
  3584      * ResolveError error class indicating that a set of symbols
  3585      * (either methods, constructors or operands) is not applicable
  3586      * given an actual arguments/type argument list.
  3587      */
  3588     class InapplicableSymbolsError extends InapplicableSymbolError {
  3590         InapplicableSymbolsError(MethodResolutionContext context) {
  3591             super(WRONG_MTHS, "inapplicable symbols", context);
  3594         @Override
  3595         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3596                 DiagnosticPosition pos,
  3597                 Symbol location,
  3598                 Type site,
  3599                 Name name,
  3600                 List<Type> argtypes,
  3601                 List<Type> typeargtypes) {
  3602             Map<Symbol, JCDiagnostic> candidatesMap = mapCandidates();
  3603             Map<Symbol, JCDiagnostic> filteredCandidates = compactMethodDiags ?
  3604                     filterCandidates(candidatesMap) :
  3605                     mapCandidates();
  3606             if (filteredCandidates.isEmpty()) {
  3607                 filteredCandidates = candidatesMap;
  3609             boolean truncatedDiag = candidatesMap.size() != filteredCandidates.size();
  3610             if (filteredCandidates.size() > 1) {
  3611                 JCDiagnostic err = diags.create(dkind,
  3612                         null,
  3613                         truncatedDiag ?
  3614                             EnumSet.of(DiagnosticFlag.COMPRESSED) :
  3615                             EnumSet.noneOf(DiagnosticFlag.class),
  3616                         log.currentSource(),
  3617                         pos,
  3618                         "cant.apply.symbols",
  3619                         name == names.init ? KindName.CONSTRUCTOR : absentKind(kind),
  3620                         name == names.init ? site.tsym.name : name,
  3621                         methodArguments(argtypes));
  3622                 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(filteredCandidates, site));
  3623             } else if (filteredCandidates.size() == 1) {
  3624                 Map.Entry<Symbol, JCDiagnostic> _e =
  3625                                 filteredCandidates.entrySet().iterator().next();
  3626                 final Pair<Symbol, JCDiagnostic> p = new Pair<Symbol, JCDiagnostic>(_e.getKey(), _e.getValue());
  3627                 JCDiagnostic d = new InapplicableSymbolError(resolveContext) {
  3628                     @Override
  3629                     protected Pair<Symbol, JCDiagnostic> errCandidate() {
  3630                         return p;
  3632                 }.getDiagnostic(dkind, pos,
  3633                     location, site, name, argtypes, typeargtypes);
  3634                 if (truncatedDiag) {
  3635                     d.setFlag(DiagnosticFlag.COMPRESSED);
  3637                 return d;
  3638             } else {
  3639                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
  3640                     location, site, name, argtypes, typeargtypes);
  3643         //where
  3644             private Map<Symbol, JCDiagnostic> mapCandidates() {
  3645                 Map<Symbol, JCDiagnostic> candidates = new LinkedHashMap<Symbol, JCDiagnostic>();
  3646                 for (Candidate c : resolveContext.candidates) {
  3647                     if (c.isApplicable()) continue;
  3648                     candidates.put(c.sym, c.details);
  3650                 return candidates;
  3653             Map<Symbol, JCDiagnostic> filterCandidates(Map<Symbol, JCDiagnostic> candidatesMap) {
  3654                 Map<Symbol, JCDiagnostic> candidates = new LinkedHashMap<Symbol, JCDiagnostic>();
  3655                 for (Map.Entry<Symbol, JCDiagnostic> _entry : candidatesMap.entrySet()) {
  3656                     JCDiagnostic d = _entry.getValue();
  3657                     if (!new Template(MethodCheckDiag.ARITY_MISMATCH.regex()).matches(d)) {
  3658                         candidates.put(_entry.getKey(), d);
  3661                 return candidates;
  3664             private List<JCDiagnostic> candidateDetails(Map<Symbol, JCDiagnostic> candidatesMap, Type site) {
  3665                 List<JCDiagnostic> details = List.nil();
  3666                 for (Map.Entry<Symbol, JCDiagnostic> _entry : candidatesMap.entrySet()) {
  3667                     Symbol sym = _entry.getKey();
  3668                     JCDiagnostic detailDiag = diags.fragment("inapplicable.method",
  3669                             Kinds.kindName(sym),
  3670                             sym.location(site, types),
  3671                             sym.asMemberOf(site, types),
  3672                             _entry.getValue());
  3673                     details = details.prepend(detailDiag);
  3675                 //typically members are visited in reverse order (see Scope)
  3676                 //so we need to reverse the candidate list so that candidates
  3677                 //conform to source order
  3678                 return details;
  3682     /**
  3683      * An InvalidSymbolError error class indicating that a symbol is not
  3684      * accessible from a given site
  3685      */
  3686     class AccessError extends InvalidSymbolError {
  3688         private Env<AttrContext> env;
  3689         private Type site;
  3691         AccessError(Symbol sym) {
  3692             this(null, null, sym);
  3695         AccessError(Env<AttrContext> env, Type site, Symbol sym) {
  3696             super(HIDDEN, sym, "access error");
  3697             this.env = env;
  3698             this.site = site;
  3699             if (debugResolve)
  3700                 log.error("proc.messager", sym + " @ " + site + " is inaccessible.");
  3703         @Override
  3704         public boolean exists() {
  3705             return false;
  3708         @Override
  3709         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3710                 DiagnosticPosition pos,
  3711                 Symbol location,
  3712                 Type site,
  3713                 Name name,
  3714                 List<Type> argtypes,
  3715                 List<Type> typeargtypes) {
  3716             if (sym.owner.type.hasTag(ERROR))
  3717                 return null;
  3719             if (sym.name == names.init && sym.owner != site.tsym) {
  3720                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
  3721                         pos, location, site, name, argtypes, typeargtypes);
  3723             else if ((sym.flags() & PUBLIC) != 0
  3724                 || (env != null && this.site != null
  3725                     && !isAccessible(env, this.site))) {
  3726                 return diags.create(dkind, log.currentSource(),
  3727                         pos, "not.def.access.class.intf.cant.access",
  3728                     sym, sym.location());
  3730             else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) {
  3731                 return diags.create(dkind, log.currentSource(),
  3732                         pos, "report.access", sym,
  3733                         asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
  3734                         sym.location());
  3736             else {
  3737                 return diags.create(dkind, log.currentSource(),
  3738                         pos, "not.def.public.cant.access", sym, sym.location());
  3743     /**
  3744      * InvalidSymbolError error class indicating that an instance member
  3745      * has erroneously been accessed from a static context.
  3746      */
  3747     class StaticError extends InvalidSymbolError {
  3749         StaticError(Symbol sym) {
  3750             super(STATICERR, sym, "static error");
  3753         @Override
  3754         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3755                 DiagnosticPosition pos,
  3756                 Symbol location,
  3757                 Type site,
  3758                 Name name,
  3759                 List<Type> argtypes,
  3760                 List<Type> typeargtypes) {
  3761             Symbol errSym = ((sym.kind == TYP && sym.type.hasTag(CLASS))
  3762                 ? types.erasure(sym.type).tsym
  3763                 : sym);
  3764             return diags.create(dkind, log.currentSource(), pos,
  3765                     "non-static.cant.be.ref", kindName(sym), errSym);
  3769     /**
  3770      * InvalidSymbolError error class indicating that a pair of symbols
  3771      * (either methods, constructors or operands) are ambiguous
  3772      * given an actual arguments/type argument list.
  3773      */
  3774     class AmbiguityError extends ResolveError {
  3776         /** The other maximally specific symbol */
  3777         List<Symbol> ambiguousSyms = List.nil();
  3779         @Override
  3780         public boolean exists() {
  3781             return true;
  3784         AmbiguityError(Symbol sym1, Symbol sym2) {
  3785             super(AMBIGUOUS, "ambiguity error");
  3786             ambiguousSyms = flatten(sym2).appendList(flatten(sym1));
  3789         private List<Symbol> flatten(Symbol sym) {
  3790             if (sym.kind == AMBIGUOUS) {
  3791                 return ((AmbiguityError)sym).ambiguousSyms;
  3792             } else {
  3793                 return List.of(sym);
  3797         AmbiguityError addAmbiguousSymbol(Symbol s) {
  3798             ambiguousSyms = ambiguousSyms.prepend(s);
  3799             return this;
  3802         @Override
  3803         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3804                 DiagnosticPosition pos,
  3805                 Symbol location,
  3806                 Type site,
  3807                 Name name,
  3808                 List<Type> argtypes,
  3809                 List<Type> typeargtypes) {
  3810             List<Symbol> diagSyms = ambiguousSyms.reverse();
  3811             Symbol s1 = diagSyms.head;
  3812             Symbol s2 = diagSyms.tail.head;
  3813             Name sname = s1.name;
  3814             if (sname == names.init) sname = s1.owner.name;
  3815             return diags.create(dkind, log.currentSource(),
  3816                       pos, "ref.ambiguous", sname,
  3817                       kindName(s1),
  3818                       s1,
  3819                       s1.location(site, types),
  3820                       kindName(s2),
  3821                       s2,
  3822                       s2.location(site, types));
  3825         /**
  3826          * If multiple applicable methods are found during overload and none of them
  3827          * is more specific than the others, attempt to merge their signatures.
  3828          */
  3829         Symbol mergeAbstracts(Type site) {
  3830             List<Symbol> ambiguousInOrder = ambiguousSyms.reverse();
  3831             for (Symbol s : ambiguousInOrder) {
  3832                 Type mt = types.memberType(site, s);
  3833                 boolean found = true;
  3834                 List<Type> allThrown = mt.getThrownTypes();
  3835                 for (Symbol s2 : ambiguousInOrder) {
  3836                     Type mt2 = types.memberType(site, s2);
  3837                     if ((s2.flags() & ABSTRACT) == 0 ||
  3838                         !types.overrideEquivalent(mt, mt2) ||
  3839                         !types.isSameTypes(s.erasure(types).getParameterTypes(),
  3840                                        s2.erasure(types).getParameterTypes())) {
  3841                         //ambiguity cannot be resolved
  3842                         return this;
  3844                     Type mst = mostSpecificReturnType(mt, mt2);
  3845                     if (mst == null || mst != mt) {
  3846                         found = false;
  3847                         break;
  3849                     allThrown = chk.intersect(allThrown, mt2.getThrownTypes());
  3851                 if (found) {
  3852                     //all ambiguous methods were abstract and one method had
  3853                     //most specific return type then others
  3854                     return (allThrown == mt.getThrownTypes()) ?
  3855                             s : new MethodSymbol(
  3856                                 s.flags(),
  3857                                 s.name,
  3858                                 types.createMethodTypeWithThrown(mt, allThrown),
  3859                                 s.owner);
  3862             return this;
  3865         @Override
  3866         protected Symbol access(Name name, TypeSymbol location) {
  3867             Symbol firstAmbiguity = ambiguousSyms.last();
  3868             return firstAmbiguity.kind == TYP ?
  3869                     types.createErrorType(name, location, firstAmbiguity.type).tsym :
  3870                     firstAmbiguity;
  3874     class BadVarargsMethod extends ResolveError {
  3876         ResolveError delegatedError;
  3878         BadVarargsMethod(ResolveError delegatedError) {
  3879             super(delegatedError.kind, "badVarargs");
  3880             this.delegatedError = delegatedError;
  3883         @Override
  3884         public Symbol baseSymbol() {
  3885             return delegatedError.baseSymbol();
  3888         @Override
  3889         protected Symbol access(Name name, TypeSymbol location) {
  3890             return delegatedError.access(name, location);
  3893         @Override
  3894         public boolean exists() {
  3895             return true;
  3898         @Override
  3899         JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
  3900             return delegatedError.getDiagnostic(dkind, pos, location, site, name, argtypes, typeargtypes);
  3904     /**
  3905      * Helper class for method resolution diagnostic simplification.
  3906      * Certain resolution diagnostic are rewritten as simpler diagnostic
  3907      * where the enclosing resolution diagnostic (i.e. 'inapplicable method')
  3908      * is stripped away, as it doesn't carry additional info. The logic
  3909      * for matching a given diagnostic is given in terms of a template
  3910      * hierarchy: a diagnostic template can be specified programmatically,
  3911      * so that only certain diagnostics are matched. Each templete is then
  3912      * associated with a rewriter object that carries out the task of rewtiting
  3913      * the diagnostic to a simpler one.
  3914      */
  3915     static class MethodResolutionDiagHelper {
  3917         /**
  3918          * A diagnostic rewriter transforms a method resolution diagnostic
  3919          * into a simpler one
  3920          */
  3921         interface DiagnosticRewriter {
  3922             JCDiagnostic rewriteDiagnostic(JCDiagnostic.Factory diags,
  3923                     DiagnosticPosition preferedPos, DiagnosticSource preferredSource,
  3924                     DiagnosticType preferredKind, JCDiagnostic d);
  3927         /**
  3928          * A diagnostic template is made up of two ingredients: (i) a regular
  3929          * expression for matching a diagnostic key and (ii) a list of sub-templates
  3930          * for matching diagnostic arguments.
  3931          */
  3932         static class Template {
  3934             /** regex used to match diag key */
  3935             String regex;
  3937             /** templates used to match diagnostic args */
  3938             Template[] subTemplates;
  3940             Template(String key, Template... subTemplates) {
  3941                 this.regex = key;
  3942                 this.subTemplates = subTemplates;
  3945             /**
  3946              * Returns true if the regex matches the diagnostic key and if
  3947              * all diagnostic arguments are matches by corresponding sub-templates.
  3948              */
  3949             boolean matches(Object o) {
  3950                 JCDiagnostic d = (JCDiagnostic)o;
  3951                 Object[] args = d.getArgs();
  3952                 if (!d.getCode().matches(regex) ||
  3953                         subTemplates.length != d.getArgs().length) {
  3954                     return false;
  3956                 for (int i = 0; i < args.length ; i++) {
  3957                     if (!subTemplates[i].matches(args[i])) {
  3958                         return false;
  3961                 return true;
  3965         /** a dummy template that match any diagnostic argument */
  3966         static final Template skip = new Template("") {
  3967             @Override
  3968             boolean matches(Object d) {
  3969                 return true;
  3971         };
  3973         /** rewriter map used for method resolution simplification */
  3974         static final Map<Template, DiagnosticRewriter> rewriters =
  3975                 new LinkedHashMap<Template, DiagnosticRewriter>();
  3977         static {
  3978             String argMismatchRegex = MethodCheckDiag.ARG_MISMATCH.regex();
  3979             rewriters.put(new Template(argMismatchRegex, skip),
  3980                     new DiagnosticRewriter() {
  3981                 @Override
  3982                 public JCDiagnostic rewriteDiagnostic(JCDiagnostic.Factory diags,
  3983                         DiagnosticPosition preferedPos, DiagnosticSource preferredSource,
  3984                         DiagnosticType preferredKind, JCDiagnostic d) {
  3985                     JCDiagnostic cause = (JCDiagnostic)d.getArgs()[0];
  3986                     return diags.create(preferredKind, preferredSource, d.getDiagnosticPosition(),
  3987                             "prob.found.req", cause);
  3989             });
  3993     enum MethodResolutionPhase {
  3994         BASIC(false, false),
  3995         BOX(true, false),
  3996         VARARITY(true, true) {
  3997             @Override
  3998             public Symbol mergeResults(Symbol bestSoFar, Symbol sym) {
  3999                 switch (sym.kind) {
  4000                     case WRONG_MTH:
  4001                         return (bestSoFar.kind == WRONG_MTH || bestSoFar.kind == WRONG_MTHS) ?
  4002                             bestSoFar :
  4003                             sym;
  4004                     case ABSENT_MTH:
  4005                         return bestSoFar;
  4006                     default:
  4007                         return sym;
  4010         };
  4012         final boolean isBoxingRequired;
  4013         final boolean isVarargsRequired;
  4015         MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) {
  4016            this.isBoxingRequired = isBoxingRequired;
  4017            this.isVarargsRequired = isVarargsRequired;
  4020         public boolean isBoxingRequired() {
  4021             return isBoxingRequired;
  4024         public boolean isVarargsRequired() {
  4025             return isVarargsRequired;
  4028         public boolean isApplicable(boolean boxingEnabled, boolean varargsEnabled) {
  4029             return (varargsEnabled || !isVarargsRequired) &&
  4030                    (boxingEnabled || !isBoxingRequired);
  4033         public Symbol mergeResults(Symbol prev, Symbol sym) {
  4034             return sym;
  4038     final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
  4040     /**
  4041      * A resolution context is used to keep track of intermediate results of
  4042      * overload resolution, such as list of method that are not applicable
  4043      * (used to generate more precise diagnostics) and so on. Resolution contexts
  4044      * can be nested - this means that when each overload resolution routine should
  4045      * work within the resolution context it created.
  4046      */
  4047     class MethodResolutionContext {
  4049         private List<Candidate> candidates = List.nil();
  4051         MethodResolutionPhase step = null;
  4053         MethodCheck methodCheck = resolveMethodCheck;
  4055         private boolean internalResolution = false;
  4056         private DeferredAttr.AttrMode attrMode = DeferredAttr.AttrMode.SPECULATIVE;
  4058         void addInapplicableCandidate(Symbol sym, JCDiagnostic details) {
  4059             Candidate c = new Candidate(currentResolutionContext.step, sym, details, null);
  4060             candidates = candidates.append(c);
  4063         void addApplicableCandidate(Symbol sym, Type mtype) {
  4064             Candidate c = new Candidate(currentResolutionContext.step, sym, null, mtype);
  4065             candidates = candidates.append(c);
  4068         DeferredAttrContext deferredAttrContext(Symbol sym, InferenceContext inferenceContext, ResultInfo pendingResult, Warner warn) {
  4069             return deferredAttr.new DeferredAttrContext(attrMode, sym, step, inferenceContext, pendingResult != null ? pendingResult.checkContext.deferredAttrContext() : deferredAttr.emptyDeferredAttrContext, warn);
  4072         /**
  4073          * This class represents an overload resolution candidate. There are two
  4074          * kinds of candidates: applicable methods and inapplicable methods;
  4075          * applicable methods have a pointer to the instantiated method type,
  4076          * while inapplicable candidates contain further details about the
  4077          * reason why the method has been considered inapplicable.
  4078          */
  4079         @SuppressWarnings("overrides")
  4080         class Candidate {
  4082             final MethodResolutionPhase step;
  4083             final Symbol sym;
  4084             final JCDiagnostic details;
  4085             final Type mtype;
  4087             private Candidate(MethodResolutionPhase step, Symbol sym, JCDiagnostic details, Type mtype) {
  4088                 this.step = step;
  4089                 this.sym = sym;
  4090                 this.details = details;
  4091                 this.mtype = mtype;
  4094             @Override
  4095             public boolean equals(Object o) {
  4096                 if (o instanceof Candidate) {
  4097                     Symbol s1 = this.sym;
  4098                     Symbol s2 = ((Candidate)o).sym;
  4099                     if  ((s1 != s2 &&
  4100                             (s1.overrides(s2, s1.owner.type.tsym, types, false) ||
  4101                             (s2.overrides(s1, s2.owner.type.tsym, types, false)))) ||
  4102                             ((s1.isConstructor() || s2.isConstructor()) && s1.owner != s2.owner))
  4103                         return true;
  4105                 return false;
  4108             boolean isApplicable() {
  4109                 return mtype != null;
  4113         DeferredAttr.AttrMode attrMode() {
  4114             return attrMode;
  4117         boolean internal() {
  4118             return internalResolution;
  4122     MethodResolutionContext currentResolutionContext = null;

mercurial