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

Fri, 15 Feb 2013 16:29:58 +0000

author
mcimadamore
date
Fri, 15 Feb 2013 16:29:58 +0000
changeset 1581
4ff468de829d
parent 1551
8cdd96f2fdb9
child 1588
2620c953e9fe
permissions
-rw-r--r--

8007462: Fix provisional applicability for method references
Summary: Add speculative arity-based check to rule out potential candidates when stuck reference is passed to method
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.jvm.*;
    41 import com.sun.tools.javac.tree.*;
    42 import com.sun.tools.javac.tree.JCTree.*;
    43 import com.sun.tools.javac.tree.JCTree.JCMemberReference.ReferenceKind;
    44 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
    45 import com.sun.tools.javac.util.*;
    46 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
    47 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    48 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType;
    50 import java.util.Arrays;
    51 import java.util.Collection;
    52 import java.util.EnumMap;
    53 import java.util.EnumSet;
    54 import java.util.Iterator;
    55 import java.util.LinkedHashMap;
    56 import java.util.LinkedHashSet;
    57 import java.util.Map;
    59 import javax.lang.model.element.ElementVisitor;
    61 import static com.sun.tools.javac.code.Flags.*;
    62 import static com.sun.tools.javac.code.Flags.BLOCK;
    63 import static com.sun.tools.javac.code.Kinds.*;
    64 import static com.sun.tools.javac.code.Kinds.ERRONEOUS;
    65 import static com.sun.tools.javac.code.TypeTag.*;
    66 import static com.sun.tools.javac.comp.Resolve.MethodResolutionPhase.*;
    67 import static com.sun.tools.javac.tree.JCTree.Tag.*;
    69 /** Helper class for name resolution, used mostly by the attribution phase.
    70  *
    71  *  <p><b>This is NOT part of any supported API.
    72  *  If you write code that depends on this, you do so at your own risk.
    73  *  This code and its internal interfaces are subject to change or
    74  *  deletion without notice.</b>
    75  */
    76 public class Resolve {
    77     protected static final Context.Key<Resolve> resolveKey =
    78         new Context.Key<Resolve>();
    80     Names names;
    81     Log log;
    82     Symtab syms;
    83     Attr attr;
    84     DeferredAttr deferredAttr;
    85     Check chk;
    86     Infer infer;
    87     ClassReader reader;
    88     TreeInfo treeinfo;
    89     Types types;
    90     JCDiagnostic.Factory diags;
    91     public final boolean boxingEnabled; // = source.allowBoxing();
    92     public final boolean varargsEnabled; // = source.allowVarargs();
    93     public final boolean allowMethodHandles;
    94     public final boolean allowDefaultMethods;
    95     public final boolean allowStructuralMostSpecific;
    96     private final boolean debugResolve;
    97     final EnumSet<VerboseResolutionMode> verboseResolutionMode;
    99     Scope polymorphicSignatureScope;
   101     protected Resolve(Context context) {
   102         context.put(resolveKey, this);
   103         syms = Symtab.instance(context);
   105         varNotFound = new
   106             SymbolNotFoundError(ABSENT_VAR);
   107         methodNotFound = new
   108             SymbolNotFoundError(ABSENT_MTH);
   109         typeNotFound = new
   110             SymbolNotFoundError(ABSENT_TYP);
   112         names = Names.instance(context);
   113         log = Log.instance(context);
   114         attr = Attr.instance(context);
   115         deferredAttr = DeferredAttr.instance(context);
   116         chk = Check.instance(context);
   117         infer = Infer.instance(context);
   118         reader = ClassReader.instance(context);
   119         treeinfo = TreeInfo.instance(context);
   120         types = Types.instance(context);
   121         diags = JCDiagnostic.Factory.instance(context);
   122         Source source = Source.instance(context);
   123         boxingEnabled = source.allowBoxing();
   124         varargsEnabled = source.allowVarargs();
   125         Options options = Options.instance(context);
   126         debugResolve = options.isSet("debugresolve");
   127         verboseResolutionMode = VerboseResolutionMode.getVerboseResolutionMode(options);
   128         Target target = Target.instance(context);
   129         allowMethodHandles = target.hasMethodHandles();
   130         allowDefaultMethods = source.allowDefaultMethods();
   131         allowStructuralMostSpecific = source.allowStructuralMostSpecific();
   132         polymorphicSignatureScope = new Scope(syms.noSymbol);
   134         inapplicableMethodException = new InapplicableMethodException(diags);
   135     }
   137     /** error symbols, which are returned when resolution fails
   138      */
   139     private final SymbolNotFoundError varNotFound;
   140     private final SymbolNotFoundError methodNotFound;
   141     private final SymbolNotFoundError typeNotFound;
   143     public static Resolve instance(Context context) {
   144         Resolve instance = context.get(resolveKey);
   145         if (instance == null)
   146             instance = new Resolve(context);
   147         return instance;
   148     }
   150     // <editor-fold defaultstate="collapsed" desc="Verbose resolution diagnostics support">
   151     enum VerboseResolutionMode {
   152         SUCCESS("success"),
   153         FAILURE("failure"),
   154         APPLICABLE("applicable"),
   155         INAPPLICABLE("inapplicable"),
   156         DEFERRED_INST("deferred-inference"),
   157         PREDEF("predef"),
   158         OBJECT_INIT("object-init"),
   159         INTERNAL("internal");
   161         final String opt;
   163         private VerboseResolutionMode(String opt) {
   164             this.opt = opt;
   165         }
   167         static EnumSet<VerboseResolutionMode> getVerboseResolutionMode(Options opts) {
   168             String s = opts.get("verboseResolution");
   169             EnumSet<VerboseResolutionMode> res = EnumSet.noneOf(VerboseResolutionMode.class);
   170             if (s == null) return res;
   171             if (s.contains("all")) {
   172                 res = EnumSet.allOf(VerboseResolutionMode.class);
   173             }
   174             Collection<String> args = Arrays.asList(s.split(","));
   175             for (VerboseResolutionMode mode : values()) {
   176                 if (args.contains(mode.opt)) {
   177                     res.add(mode);
   178                 } else if (args.contains("-" + mode.opt)) {
   179                     res.remove(mode);
   180                 }
   181             }
   182             return res;
   183         }
   184     }
   186     void reportVerboseResolutionDiagnostic(DiagnosticPosition dpos, Name name, Type site,
   187             List<Type> argtypes, List<Type> typeargtypes, Symbol bestSoFar) {
   188         boolean success = bestSoFar.kind < ERRONEOUS;
   190         if (success && !verboseResolutionMode.contains(VerboseResolutionMode.SUCCESS)) {
   191             return;
   192         } else if (!success && !verboseResolutionMode.contains(VerboseResolutionMode.FAILURE)) {
   193             return;
   194         }
   196         if (bestSoFar.name == names.init &&
   197                 bestSoFar.owner == syms.objectType.tsym &&
   198                 !verboseResolutionMode.contains(VerboseResolutionMode.OBJECT_INIT)) {
   199             return; //skip diags for Object constructor resolution
   200         } else if (site == syms.predefClass.type &&
   201                 !verboseResolutionMode.contains(VerboseResolutionMode.PREDEF)) {
   202             return; //skip spurious diags for predef symbols (i.e. operators)
   203         } else if (currentResolutionContext.internalResolution &&
   204                 !verboseResolutionMode.contains(VerboseResolutionMode.INTERNAL)) {
   205             return;
   206         }
   208         int pos = 0;
   209         int mostSpecificPos = -1;
   210         ListBuffer<JCDiagnostic> subDiags = ListBuffer.lb();
   211         for (Candidate c : currentResolutionContext.candidates) {
   212             if (currentResolutionContext.step != c.step ||
   213                     (c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.APPLICABLE)) ||
   214                     (!c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.INAPPLICABLE))) {
   215                 continue;
   216             } else {
   217                 subDiags.append(c.isApplicable() ?
   218                         getVerboseApplicableCandidateDiag(pos, c.sym, c.mtype) :
   219                         getVerboseInapplicableCandidateDiag(pos, c.sym, c.details));
   220                 if (c.sym == bestSoFar)
   221                     mostSpecificPos = pos;
   222                 pos++;
   223             }
   224         }
   225         String key = success ? "verbose.resolve.multi" : "verbose.resolve.multi.1";
   226         List<Type> argtypes2 = Type.map(argtypes,
   227                     deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, bestSoFar, currentResolutionContext.step));
   228         JCDiagnostic main = diags.note(log.currentSource(), dpos, key, name,
   229                 site.tsym, mostSpecificPos, currentResolutionContext.step,
   230                 methodArguments(argtypes2),
   231                 methodArguments(typeargtypes));
   232         JCDiagnostic d = new JCDiagnostic.MultilineDiagnostic(main, subDiags.toList());
   233         log.report(d);
   234     }
   236     JCDiagnostic getVerboseApplicableCandidateDiag(int pos, Symbol sym, Type inst) {
   237         JCDiagnostic subDiag = null;
   238         if (sym.type.hasTag(FORALL)) {
   239             subDiag = diags.fragment("partial.inst.sig", inst);
   240         }
   242         String key = subDiag == null ?
   243                 "applicable.method.found" :
   244                 "applicable.method.found.1";
   246         return diags.fragment(key, pos, sym, subDiag);
   247     }
   249     JCDiagnostic getVerboseInapplicableCandidateDiag(int pos, Symbol sym, JCDiagnostic subDiag) {
   250         return diags.fragment("not.applicable.method.found", pos, sym, subDiag);
   251     }
   252     // </editor-fold>
   254 /* ************************************************************************
   255  * Identifier resolution
   256  *************************************************************************/
   258     /** An environment is "static" if its static level is greater than
   259      *  the one of its outer environment
   260      */
   261     protected static boolean isStatic(Env<AttrContext> env) {
   262         return env.info.staticLevel > env.outer.info.staticLevel;
   263     }
   265     /** An environment is an "initializer" if it is a constructor or
   266      *  an instance initializer.
   267      */
   268     static boolean isInitializer(Env<AttrContext> env) {
   269         Symbol owner = env.info.scope.owner;
   270         return owner.isConstructor() ||
   271             owner.owner.kind == TYP &&
   272             (owner.kind == VAR ||
   273              owner.kind == MTH && (owner.flags() & BLOCK) != 0) &&
   274             (owner.flags() & STATIC) == 0;
   275     }
   277     /** Is class accessible in given evironment?
   278      *  @param env    The current environment.
   279      *  @param c      The class whose accessibility is checked.
   280      */
   281     public boolean isAccessible(Env<AttrContext> env, TypeSymbol c) {
   282         return isAccessible(env, c, false);
   283     }
   285     public boolean isAccessible(Env<AttrContext> env, TypeSymbol c, boolean checkInner) {
   286         boolean isAccessible = false;
   287         switch ((short)(c.flags() & AccessFlags)) {
   288             case PRIVATE:
   289                 isAccessible =
   290                     env.enclClass.sym.outermostClass() ==
   291                     c.owner.outermostClass();
   292                 break;
   293             case 0:
   294                 isAccessible =
   295                     env.toplevel.packge == c.owner // fast special case
   296                     ||
   297                     env.toplevel.packge == c.packge()
   298                     ||
   299                     // Hack: this case is added since synthesized default constructors
   300                     // of anonymous classes should be allowed to access
   301                     // classes which would be inaccessible otherwise.
   302                     env.enclMethod != null &&
   303                     (env.enclMethod.mods.flags & ANONCONSTR) != 0;
   304                 break;
   305             default: // error recovery
   306             case PUBLIC:
   307                 isAccessible = true;
   308                 break;
   309             case PROTECTED:
   310                 isAccessible =
   311                     env.toplevel.packge == c.owner // fast special case
   312                     ||
   313                     env.toplevel.packge == c.packge()
   314                     ||
   315                     isInnerSubClass(env.enclClass.sym, c.owner);
   316                 break;
   317         }
   318         return (checkInner == false || c.type.getEnclosingType() == Type.noType) ?
   319             isAccessible :
   320             isAccessible && isAccessible(env, c.type.getEnclosingType(), checkInner);
   321     }
   322     //where
   323         /** Is given class a subclass of given base class, or an inner class
   324          *  of a subclass?
   325          *  Return null if no such class exists.
   326          *  @param c     The class which is the subclass or is contained in it.
   327          *  @param base  The base class
   328          */
   329         private boolean isInnerSubClass(ClassSymbol c, Symbol base) {
   330             while (c != null && !c.isSubClass(base, types)) {
   331                 c = c.owner.enclClass();
   332             }
   333             return c != null;
   334         }
   336     boolean isAccessible(Env<AttrContext> env, Type t) {
   337         return isAccessible(env, t, false);
   338     }
   340     boolean isAccessible(Env<AttrContext> env, Type t, boolean checkInner) {
   341         return (t.hasTag(ARRAY))
   342             ? isAccessible(env, types.elemtype(t))
   343             : isAccessible(env, t.tsym, checkInner);
   344     }
   346     /** Is symbol accessible as a member of given type in given evironment?
   347      *  @param env    The current environment.
   348      *  @param site   The type of which the tested symbol is regarded
   349      *                as a member.
   350      *  @param sym    The symbol.
   351      */
   352     public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym) {
   353         return isAccessible(env, site, sym, false);
   354     }
   355     public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym, boolean checkInner) {
   356         if (sym.name == names.init && sym.owner != site.tsym) return false;
   357         switch ((short)(sym.flags() & AccessFlags)) {
   358         case PRIVATE:
   359             return
   360                 (env.enclClass.sym == sym.owner // fast special case
   361                  ||
   362                  env.enclClass.sym.outermostClass() ==
   363                  sym.owner.outermostClass())
   364                 &&
   365                 sym.isInheritedIn(site.tsym, types);
   366         case 0:
   367             return
   368                 (env.toplevel.packge == sym.owner.owner // fast special case
   369                  ||
   370                  env.toplevel.packge == sym.packge())
   371                 &&
   372                 isAccessible(env, site, checkInner)
   373                 &&
   374                 sym.isInheritedIn(site.tsym, types)
   375                 &&
   376                 notOverriddenIn(site, sym);
   377         case PROTECTED:
   378             return
   379                 (env.toplevel.packge == sym.owner.owner // fast special case
   380                  ||
   381                  env.toplevel.packge == sym.packge()
   382                  ||
   383                  isProtectedAccessible(sym, env.enclClass.sym, site)
   384                  ||
   385                  // OK to select instance method or field from 'super' or type name
   386                  // (but type names should be disallowed elsewhere!)
   387                  env.info.selectSuper && (sym.flags() & STATIC) == 0 && sym.kind != TYP)
   388                 &&
   389                 isAccessible(env, site, checkInner)
   390                 &&
   391                 notOverriddenIn(site, sym);
   392         default: // this case includes erroneous combinations as well
   393             return isAccessible(env, site, checkInner) && notOverriddenIn(site, sym);
   394         }
   395     }
   396     //where
   397     /* `sym' is accessible only if not overridden by
   398      * another symbol which is a member of `site'
   399      * (because, if it is overridden, `sym' is not strictly
   400      * speaking a member of `site'). A polymorphic signature method
   401      * cannot be overridden (e.g. MH.invokeExact(Object[])).
   402      */
   403     private boolean notOverriddenIn(Type site, Symbol sym) {
   404         if (sym.kind != MTH || sym.isConstructor() || sym.isStatic())
   405             return true;
   406         else {
   407             Symbol s2 = ((MethodSymbol)sym).implementation(site.tsym, types, true);
   408             return (s2 == null || s2 == sym || sym.owner == s2.owner ||
   409                     !types.isSubSignature(types.memberType(site, s2), types.memberType(site, sym)));
   410         }
   411     }
   412     //where
   413         /** Is given protected symbol accessible if it is selected from given site
   414          *  and the selection takes place in given class?
   415          *  @param sym     The symbol with protected access
   416          *  @param c       The class where the access takes place
   417          *  @site          The type of the qualifier
   418          */
   419         private
   420         boolean isProtectedAccessible(Symbol sym, ClassSymbol c, Type site) {
   421             while (c != null &&
   422                    !(c.isSubClass(sym.owner, types) &&
   423                      (c.flags() & INTERFACE) == 0 &&
   424                      // In JLS 2e 6.6.2.1, the subclass restriction applies
   425                      // only to instance fields and methods -- types are excluded
   426                      // regardless of whether they are declared 'static' or not.
   427                      ((sym.flags() & STATIC) != 0 || sym.kind == TYP || site.tsym.isSubClass(c, types))))
   428                 c = c.owner.enclClass();
   429             return c != null;
   430         }
   432     /**
   433      * Performs a recursive scan of a type looking for accessibility problems
   434      * from current attribution environment
   435      */
   436     void checkAccessibleType(Env<AttrContext> env, Type t) {
   437         accessibilityChecker.visit(t, env);
   438     }
   440     /**
   441      * Accessibility type-visitor
   442      */
   443     Types.SimpleVisitor<Void, Env<AttrContext>> accessibilityChecker =
   444             new Types.SimpleVisitor<Void, Env<AttrContext>>() {
   446         void visit(List<Type> ts, Env<AttrContext> env) {
   447             for (Type t : ts) {
   448                 visit(t, env);
   449             }
   450         }
   452         public Void visitType(Type t, Env<AttrContext> env) {
   453             return null;
   454         }
   456         @Override
   457         public Void visitArrayType(ArrayType t, Env<AttrContext> env) {
   458             visit(t.elemtype, env);
   459             return null;
   460         }
   462         @Override
   463         public Void visitClassType(ClassType t, Env<AttrContext> env) {
   464             visit(t.getTypeArguments(), env);
   465             if (!isAccessible(env, t, true)) {
   466                 accessBase(new AccessError(t.tsym), env.tree.pos(), env.enclClass.sym, t, t.tsym.name, true);
   467             }
   468             return null;
   469         }
   471         @Override
   472         public Void visitWildcardType(WildcardType t, Env<AttrContext> env) {
   473             visit(t.type, env);
   474             return null;
   475         }
   477         @Override
   478         public Void visitMethodType(MethodType t, Env<AttrContext> env) {
   479             visit(t.getParameterTypes(), env);
   480             visit(t.getReturnType(), env);
   481             visit(t.getThrownTypes(), env);
   482             return null;
   483         }
   484     };
   486     /** Try to instantiate the type of a method so that it fits
   487      *  given type arguments and argument types. If succesful, return
   488      *  the method's instantiated type, else return null.
   489      *  The instantiation will take into account an additional leading
   490      *  formal parameter if the method is an instance method seen as a member
   491      *  of un underdetermined site In this case, we treat site as an additional
   492      *  parameter and the parameters of the class containing the method as
   493      *  additional type variables that get instantiated.
   494      *
   495      *  @param env         The current environment
   496      *  @param site        The type of which the method is a member.
   497      *  @param m           The method symbol.
   498      *  @param argtypes    The invocation's given value arguments.
   499      *  @param typeargtypes    The invocation's given type arguments.
   500      *  @param allowBoxing Allow boxing conversions of arguments.
   501      *  @param useVarargs Box trailing arguments into an array for varargs.
   502      */
   503     Type rawInstantiate(Env<AttrContext> env,
   504                         Type site,
   505                         Symbol m,
   506                         ResultInfo resultInfo,
   507                         List<Type> argtypes,
   508                         List<Type> typeargtypes,
   509                         boolean allowBoxing,
   510                         boolean useVarargs,
   511                         MethodCheck methodCheck,
   512                         Warner warn) throws Infer.InferenceException {
   514         Type mt = types.memberType(site, m);
   515         // tvars is the list of formal type variables for which type arguments
   516         // need to inferred.
   517         List<Type> tvars = List.nil();
   518         if (typeargtypes == null) typeargtypes = List.nil();
   519         if (!mt.hasTag(FORALL) && typeargtypes.nonEmpty()) {
   520             // This is not a polymorphic method, but typeargs are supplied
   521             // which is fine, see JLS 15.12.2.1
   522         } else if (mt.hasTag(FORALL) && typeargtypes.nonEmpty()) {
   523             ForAll pmt = (ForAll) mt;
   524             if (typeargtypes.length() != pmt.tvars.length())
   525                 throw inapplicableMethodException.setMessage("arg.length.mismatch"); // not enough args
   526             // Check type arguments are within bounds
   527             List<Type> formals = pmt.tvars;
   528             List<Type> actuals = typeargtypes;
   529             while (formals.nonEmpty() && actuals.nonEmpty()) {
   530                 List<Type> bounds = types.subst(types.getBounds((TypeVar)formals.head),
   531                                                 pmt.tvars, typeargtypes);
   532                 for (; bounds.nonEmpty(); bounds = bounds.tail)
   533                     if (!types.isSubtypeUnchecked(actuals.head, bounds.head, warn))
   534                         throw inapplicableMethodException.setMessage("explicit.param.do.not.conform.to.bounds",actuals.head, bounds);
   535                 formals = formals.tail;
   536                 actuals = actuals.tail;
   537             }
   538             mt = types.subst(pmt.qtype, pmt.tvars, typeargtypes);
   539         } else if (mt.hasTag(FORALL)) {
   540             ForAll pmt = (ForAll) mt;
   541             List<Type> tvars1 = types.newInstances(pmt.tvars);
   542             tvars = tvars.appendList(tvars1);
   543             mt = types.subst(pmt.qtype, pmt.tvars, tvars1);
   544         }
   546         // find out whether we need to go the slow route via infer
   547         boolean instNeeded = tvars.tail != null; /*inlined: tvars.nonEmpty()*/
   548         for (List<Type> l = argtypes;
   549              l.tail != null/*inlined: l.nonEmpty()*/ && !instNeeded;
   550              l = l.tail) {
   551             if (l.head.hasTag(FORALL)) instNeeded = true;
   552         }
   554         if (instNeeded)
   555             return infer.instantiateMethod(env,
   556                                     tvars,
   557                                     (MethodType)mt,
   558                                     resultInfo,
   559                                     m,
   560                                     argtypes,
   561                                     allowBoxing,
   562                                     useVarargs,
   563                                     currentResolutionContext,
   564                                     methodCheck,
   565                                     warn);
   567         methodCheck.argumentsAcceptable(env, currentResolutionContext.deferredAttrContext(m, infer.emptyContext, resultInfo, warn),
   568                                 argtypes, mt.getParameterTypes(), warn);
   569         return mt;
   570     }
   572     Type checkMethod(Env<AttrContext> env,
   573                      Type site,
   574                      Symbol m,
   575                      ResultInfo resultInfo,
   576                      List<Type> argtypes,
   577                      List<Type> typeargtypes,
   578                      Warner warn) {
   579         MethodResolutionContext prevContext = currentResolutionContext;
   580         try {
   581             currentResolutionContext = new MethodResolutionContext();
   582             currentResolutionContext.attrMode = DeferredAttr.AttrMode.CHECK;
   583             MethodResolutionPhase step = currentResolutionContext.step = env.info.pendingResolutionPhase;
   584             return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
   585                     step.isBoxingRequired(), step.isVarargsRequired(), resolveMethodCheck, warn);
   586         }
   587         finally {
   588             currentResolutionContext = prevContext;
   589         }
   590     }
   592     /** Same but returns null instead throwing a NoInstanceException
   593      */
   594     Type instantiate(Env<AttrContext> env,
   595                      Type site,
   596                      Symbol m,
   597                      ResultInfo resultInfo,
   598                      List<Type> argtypes,
   599                      List<Type> typeargtypes,
   600                      boolean allowBoxing,
   601                      boolean useVarargs,
   602                      MethodCheck methodCheck,
   603                      Warner warn) {
   604         try {
   605             return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
   606                                   allowBoxing, useVarargs, methodCheck, warn);
   607         } catch (InapplicableMethodException ex) {
   608             return null;
   609         }
   610     }
   612     /**
   613      * This interface defines an entry point that should be used to perform a
   614      * method check. A method check usually consist in determining as to whether
   615      * a set of types (actuals) is compatible with another set of types (formals).
   616      * Since the notion of compatibility can vary depending on the circumstances,
   617      * this interfaces allows to easily add new pluggable method check routines.
   618      */
   619     interface MethodCheck {
   620         /**
   621          * Main method check routine. A method check usually consist in determining
   622          * as to whether a set of types (actuals) is compatible with another set of
   623          * types (formals). If an incompatibility is found, an unchecked exception
   624          * is assumed to be thrown.
   625          */
   626         void argumentsAcceptable(Env<AttrContext> env,
   627                                 DeferredAttrContext deferredAttrContext,
   628                                 List<Type> argtypes,
   629                                 List<Type> formals,
   630                                 Warner warn);
   631     }
   633     /**
   634      * Helper enum defining all method check diagnostics (used by resolveMethodCheck).
   635      */
   636     enum MethodCheckDiag {
   637         /**
   638          * Actuals and formals differs in length.
   639          */
   640         ARITY_MISMATCH("arg.length.mismatch", "infer.arg.length.mismatch"),
   641         /**
   642          * An actual is incompatible with a formal.
   643          */
   644         ARG_MISMATCH("no.conforming.assignment.exists", "infer.no.conforming.assignment.exists"),
   645         /**
   646          * An actual is incompatible with the varargs element type.
   647          */
   648         VARARG_MISMATCH("varargs.argument.mismatch", "infer.varargs.argument.mismatch"),
   649         /**
   650          * The varargs element type is inaccessible.
   651          */
   652         INACCESSIBLE_VARARGS("inaccessible.varargs.type", "inaccessible.varargs.type");
   654         final String basicKey;
   655         final String inferKey;
   657         MethodCheckDiag(String basicKey, String inferKey) {
   658             this.basicKey = basicKey;
   659             this.inferKey = inferKey;
   660         }
   661     }
   663     /**
   664      * Main method applicability routine. Given a list of actual types A,
   665      * a list of formal types F, determines whether the types in A are
   666      * compatible (by method invocation conversion) with the types in F.
   667      *
   668      * Since this routine is shared between overload resolution and method
   669      * type-inference, a (possibly empty) inference context is used to convert
   670      * formal types to the corresponding 'undet' form ahead of a compatibility
   671      * check so that constraints can be propagated and collected.
   672      *
   673      * Moreover, if one or more types in A is a deferred type, this routine uses
   674      * DeferredAttr in order to perform deferred attribution. If one or more actual
   675      * deferred types are stuck, they are placed in a queue and revisited later
   676      * after the remainder of the arguments have been seen. If this is not sufficient
   677      * to 'unstuck' the argument, a cyclic inference error is called out.
   678      *
   679      * A method check handler (see above) is used in order to report errors.
   680      */
   681     MethodCheck resolveMethodCheck = new MethodCheck() {
   682         @Override
   683         public void argumentsAcceptable(final Env<AttrContext> env,
   684                                     DeferredAttrContext deferredAttrContext,
   685                                     List<Type> argtypes,
   686                                     List<Type> formals,
   687                                     Warner warn) {
   688             //should we expand formals?
   689             boolean useVarargs = deferredAttrContext.phase.isVarargsRequired();
   691             //inference context used during this method check
   692             InferenceContext inferenceContext = deferredAttrContext.inferenceContext;
   694             Type varargsFormal = useVarargs ? formals.last() : null;
   696             if (varargsFormal == null &&
   697                     argtypes.size() != formals.size()) {
   698                 reportMC(MethodCheckDiag.ARITY_MISMATCH, inferenceContext); // not enough args
   699             }
   701             while (argtypes.nonEmpty() && formals.head != varargsFormal) {
   702                 ResultInfo mresult = methodCheckResult(false, formals.head, deferredAttrContext, warn);
   703                 mresult.check(null, argtypes.head);
   704                 argtypes = argtypes.tail;
   705                 formals = formals.tail;
   706             }
   708             if (formals.head != varargsFormal) {
   709                 reportMC(MethodCheckDiag.ARITY_MISMATCH, inferenceContext); // not enough args
   710             }
   712             if (useVarargs) {
   713                 //note: if applicability check is triggered by most specific test,
   714                 //the last argument of a varargs is _not_ an array type (see JLS 15.12.2.5)
   715                 final Type elt = types.elemtype(varargsFormal);
   716                 ResultInfo mresult = methodCheckResult(true, elt, deferredAttrContext, warn);
   717                 while (argtypes.nonEmpty()) {
   718                     mresult.check(null, argtypes.head);
   719                     argtypes = argtypes.tail;
   720                 }
   721                 //check varargs element type accessibility
   722                 varargsAccessible(env, elt, inferenceContext);
   723             }
   724         }
   726         private void reportMC(MethodCheckDiag diag, InferenceContext inferenceContext, Object... args) {
   727             boolean inferDiag = inferenceContext != infer.emptyContext;
   728             InapplicableMethodException ex = inferDiag ?
   729                     infer.inferenceException : inapplicableMethodException;
   730             if (inferDiag && (!diag.inferKey.equals(diag.basicKey))) {
   731                 Object[] args2 = new Object[args.length + 1];
   732                 System.arraycopy(args, 0, args2, 1, args.length);
   733                 args2[0] = inferenceContext.inferenceVars();
   734                 args = args2;
   735             }
   736             throw ex.setMessage(inferDiag ? diag.inferKey : diag.basicKey, args);
   737         }
   739         private void varargsAccessible(final Env<AttrContext> env, final Type t, final InferenceContext inferenceContext) {
   740             if (inferenceContext.free(t)) {
   741                 inferenceContext.addFreeTypeListener(List.of(t), new FreeTypeListener() {
   742                     @Override
   743                     public void typesInferred(InferenceContext inferenceContext) {
   744                         varargsAccessible(env, inferenceContext.asInstType(t), inferenceContext);
   745                     }
   746                 });
   747             } else {
   748                 if (!isAccessible(env, t)) {
   749                     Symbol location = env.enclClass.sym;
   750                     reportMC(MethodCheckDiag.INACCESSIBLE_VARARGS, inferenceContext, t, Kinds.kindName(location), location);
   751                 }
   752             }
   753         }
   755         private ResultInfo methodCheckResult(final boolean varargsCheck, Type to,
   756                 final DeferredAttr.DeferredAttrContext deferredAttrContext, Warner rsWarner) {
   757             CheckContext checkContext = new MethodCheckContext(!deferredAttrContext.phase.isBoxingRequired(), deferredAttrContext, rsWarner) {
   758                 MethodCheckDiag methodDiag = varargsCheck ?
   759                                  MethodCheckDiag.VARARG_MISMATCH : MethodCheckDiag.ARG_MISMATCH;
   761                 @Override
   762                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
   763                     reportMC(methodDiag, deferredAttrContext.inferenceContext, details);
   764                 }
   765             };
   766             return new MethodResultInfo(to, checkContext);
   767         }
   768     };
   770     /**
   771      * Check context to be used during method applicability checks. A method check
   772      * context might contain inference variables.
   773      */
   774     abstract class MethodCheckContext implements CheckContext {
   776         boolean strict;
   777         DeferredAttrContext deferredAttrContext;
   778         Warner rsWarner;
   780         public MethodCheckContext(boolean strict, DeferredAttrContext deferredAttrContext, Warner rsWarner) {
   781            this.strict = strict;
   782            this.deferredAttrContext = deferredAttrContext;
   783            this.rsWarner = rsWarner;
   784         }
   786         public boolean compatible(Type found, Type req, Warner warn) {
   787             return strict ?
   788                     types.isSubtypeUnchecked(found, deferredAttrContext.inferenceContext.asFree(req), warn) :
   789                     types.isConvertible(found, deferredAttrContext.inferenceContext.asFree(req), warn);
   790         }
   792         public void report(DiagnosticPosition pos, JCDiagnostic details) {
   793             throw inapplicableMethodException.setMessage(details);
   794         }
   796         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
   797             return rsWarner;
   798         }
   800         public InferenceContext inferenceContext() {
   801             return deferredAttrContext.inferenceContext;
   802         }
   804         public DeferredAttrContext deferredAttrContext() {
   805             return deferredAttrContext;
   806         }
   807     }
   809     /**
   810      * ResultInfo class to be used during method applicability checks. Check
   811      * for deferred types goes through special path.
   812      */
   813     class MethodResultInfo extends ResultInfo {
   815         public MethodResultInfo(Type pt, CheckContext checkContext) {
   816             attr.super(VAL, pt, checkContext);
   817         }
   819         @Override
   820         protected Type check(DiagnosticPosition pos, Type found) {
   821             if (found.hasTag(DEFERRED)) {
   822                 DeferredType dt = (DeferredType)found;
   823                 return dt.check(this);
   824             } else {
   825                 return super.check(pos, chk.checkNonVoid(pos, types.capture(types.upperBound(found.baseType()))));
   826             }
   827         }
   829         @Override
   830         protected MethodResultInfo dup(Type newPt) {
   831             return new MethodResultInfo(newPt, checkContext);
   832         }
   834         @Override
   835         protected ResultInfo dup(CheckContext newContext) {
   836             return new MethodResultInfo(pt, newContext);
   837         }
   838     }
   840     /**
   841      * Most specific method applicability routine. Given a list of actual types A,
   842      * a list of formal types F1, and a list of formal types F2, the routine determines
   843      * as to whether the types in F1 can be considered more specific than those in F2 w.r.t.
   844      * argument types A.
   845      */
   846     class MostSpecificCheck implements MethodCheck {
   848         boolean strict;
   849         List<Type> actuals;
   851         MostSpecificCheck(boolean strict, List<Type> actuals) {
   852             this.strict = strict;
   853             this.actuals = actuals;
   854         }
   856         @Override
   857         public void argumentsAcceptable(final Env<AttrContext> env,
   858                                     DeferredAttrContext deferredAttrContext,
   859                                     List<Type> formals1,
   860                                     List<Type> formals2,
   861                                     Warner warn) {
   862             formals2 = adjustArgs(formals2, deferredAttrContext.msym, formals1.length(), deferredAttrContext.phase.isVarargsRequired());
   863             while (formals2.nonEmpty()) {
   864                 ResultInfo mresult = methodCheckResult(formals2.head, deferredAttrContext, warn, actuals.head);
   865                 mresult.check(null, formals1.head);
   866                 formals1 = formals1.tail;
   867                 formals2 = formals2.tail;
   868                 actuals = actuals.isEmpty() ? actuals : actuals.tail;
   869             }
   870         }
   872        /**
   873         * Create a method check context to be used during the most specific applicability check
   874         */
   875         ResultInfo methodCheckResult(Type to, DeferredAttr.DeferredAttrContext deferredAttrContext,
   876                Warner rsWarner, Type actual) {
   877            return attr.new ResultInfo(Kinds.VAL, to,
   878                    new MostSpecificCheckContext(strict, deferredAttrContext, rsWarner, actual));
   879         }
   881         /**
   882          * Subclass of method check context class that implements most specific
   883          * method conversion. If the actual type under analysis is a deferred type
   884          * a full blown structural analysis is carried out.
   885          */
   886         class MostSpecificCheckContext extends MethodCheckContext {
   888             Type actual;
   890             public MostSpecificCheckContext(boolean strict, DeferredAttrContext deferredAttrContext, Warner rsWarner, Type actual) {
   891                 super(strict, deferredAttrContext, rsWarner);
   892                 this.actual = actual;
   893             }
   895             public boolean compatible(Type found, Type req, Warner warn) {
   896                 if (!allowStructuralMostSpecific || actual == null) {
   897                     return super.compatible(found, req, warn);
   898                 } else {
   899                     switch (actual.getTag()) {
   900                         case DEFERRED:
   901                             DeferredType dt = (DeferredType) actual;
   902                             DeferredType.SpeculativeCache.Entry e = dt.speculativeCache.get(deferredAttrContext.msym, deferredAttrContext.phase);
   903                             return (e == null || e.speculativeTree == deferredAttr.stuckTree)
   904                                     ? false : mostSpecific(found, req, e.speculativeTree, warn);
   905                         default:
   906                             return standaloneMostSpecific(found, req, actual, warn);
   907                     }
   908                 }
   909             }
   911             private boolean mostSpecific(Type t, Type s, JCTree tree, Warner warn) {
   912                 MostSpecificChecker msc = new MostSpecificChecker(t, s, warn);
   913                 msc.scan(tree);
   914                 return msc.result;
   915             }
   917             boolean polyMostSpecific(Type t1, Type t2, Warner warn) {
   918                 return (!t1.isPrimitive() && t2.isPrimitive())
   919                         ? true : super.compatible(t1, t2, warn);
   920             }
   922             boolean standaloneMostSpecific(Type t1, Type t2, Type exprType, Warner warn) {
   923                 return (exprType.isPrimitive() == t1.isPrimitive()
   924                         && exprType.isPrimitive() != t2.isPrimitive())
   925                         ? true : super.compatible(t1, t2, warn);
   926             }
   928             /**
   929              * Structural checker for most specific.
   930              */
   931             class MostSpecificChecker extends DeferredAttr.PolyScanner {
   933                 final Type t;
   934                 final Type s;
   935                 final Warner warn;
   936                 boolean result;
   938                 MostSpecificChecker(Type t, Type s, Warner warn) {
   939                     this.t = t;
   940                     this.s = s;
   941                     this.warn = warn;
   942                     result = true;
   943                 }
   945                 @Override
   946                 void skip(JCTree tree) {
   947                     result &= standaloneMostSpecific(t, s, tree.type, warn);
   948                 }
   950                 @Override
   951                 public void visitConditional(JCConditional tree) {
   952                     if (tree.polyKind == PolyKind.STANDALONE) {
   953                         result &= standaloneMostSpecific(t, s, tree.type, warn);
   954                     } else {
   955                         super.visitConditional(tree);
   956                     }
   957                 }
   959                 @Override
   960                 public void visitApply(JCMethodInvocation tree) {
   961                     result &= (tree.polyKind == PolyKind.STANDALONE)
   962                             ? standaloneMostSpecific(t, s, tree.type, warn)
   963                             : polyMostSpecific(t, s, warn);
   964                 }
   966                 @Override
   967                 public void visitNewClass(JCNewClass tree) {
   968                     result &= (tree.polyKind == PolyKind.STANDALONE)
   969                             ? standaloneMostSpecific(t, s, tree.type, warn)
   970                             : polyMostSpecific(t, s, warn);
   971                 }
   973                 @Override
   974                 public void visitReference(JCMemberReference tree) {
   975                     if (types.isFunctionalInterface(t.tsym) &&
   976                             types.isFunctionalInterface(s.tsym) &&
   977                             types.asSuper(t, s.tsym) == null &&
   978                             types.asSuper(s, t.tsym) == null) {
   979                         Type desc_t = types.findDescriptorType(t);
   980                         Type desc_s = types.findDescriptorType(s);
   981                         if (types.isSameTypes(desc_t.getParameterTypes(), desc_s.getParameterTypes())) {
   982                             if (!desc_s.getReturnType().hasTag(VOID)) {
   983                                 //perform structural comparison
   984                                 Type ret_t = desc_t.getReturnType();
   985                                 Type ret_s = desc_s.getReturnType();
   986                                 result &= ((tree.refPolyKind == PolyKind.STANDALONE)
   987                                         ? standaloneMostSpecific(ret_t, ret_s, tree.type, warn)
   988                                         : polyMostSpecific(ret_t, ret_s, warn));
   989                             } else {
   990                                 return;
   991                             }
   992                         } else {
   993                             result &= false;
   994                         }
   995                     } else {
   996                         result &= MostSpecificCheckContext.super.compatible(t, s, warn);
   997                     }
   998                 }
  1000                 @Override
  1001                 public void visitLambda(JCLambda tree) {
  1002                     if (types.isFunctionalInterface(t.tsym) &&
  1003                             types.isFunctionalInterface(s.tsym) &&
  1004                             types.asSuper(t, s.tsym) == null &&
  1005                             types.asSuper(s, t.tsym) == null) {
  1006                         Type desc_t = types.findDescriptorType(t);
  1007                         Type desc_s = types.findDescriptorType(s);
  1008                         if (tree.paramKind == JCLambda.ParameterKind.EXPLICIT
  1009                                 || types.isSameTypes(desc_t.getParameterTypes(), desc_s.getParameterTypes())) {
  1010                             if (!desc_s.getReturnType().hasTag(VOID)) {
  1011                                 //perform structural comparison
  1012                                 Type ret_t = desc_t.getReturnType();
  1013                                 Type ret_s = desc_s.getReturnType();
  1014                                 scanLambdaBody(tree, ret_t, ret_s);
  1015                             } else {
  1016                                 return;
  1018                         } else {
  1019                             result &= false;
  1021                     } else {
  1022                         result &= MostSpecificCheckContext.super.compatible(t, s, warn);
  1025                 //where
  1027                 void scanLambdaBody(JCLambda lambda, final Type t, final Type s) {
  1028                     if (lambda.getBodyKind() == JCTree.JCLambda.BodyKind.EXPRESSION) {
  1029                         result &= MostSpecificCheckContext.this.mostSpecific(t, s, lambda.body, warn);
  1030                     } else {
  1031                         DeferredAttr.LambdaReturnScanner lambdaScanner =
  1032                                 new DeferredAttr.LambdaReturnScanner() {
  1033                                     @Override
  1034                                     public void visitReturn(JCReturn tree) {
  1035                                         if (tree.expr != null) {
  1036                                             result &= MostSpecificCheckContext.this.mostSpecific(t, s, tree.expr, warn);
  1039                                 };
  1040                         lambdaScanner.scan(lambda.body);
  1047     public static class InapplicableMethodException extends RuntimeException {
  1048         private static final long serialVersionUID = 0;
  1050         JCDiagnostic diagnostic;
  1051         JCDiagnostic.Factory diags;
  1053         InapplicableMethodException(JCDiagnostic.Factory diags) {
  1054             this.diagnostic = null;
  1055             this.diags = diags;
  1057         InapplicableMethodException setMessage() {
  1058             return setMessage((JCDiagnostic)null);
  1060         InapplicableMethodException setMessage(String key) {
  1061             return setMessage(key != null ? diags.fragment(key) : null);
  1063         InapplicableMethodException setMessage(String key, Object... args) {
  1064             return setMessage(key != null ? diags.fragment(key, args) : null);
  1066         InapplicableMethodException setMessage(JCDiagnostic diag) {
  1067             this.diagnostic = diag;
  1068             return this;
  1071         public JCDiagnostic getDiagnostic() {
  1072             return diagnostic;
  1075     private final InapplicableMethodException inapplicableMethodException;
  1077 /* ***************************************************************************
  1078  *  Symbol lookup
  1079  *  the following naming conventions for arguments are used
  1081  *       env      is the environment where the symbol was mentioned
  1082  *       site     is the type of which the symbol is a member
  1083  *       name     is the symbol's name
  1084  *                if no arguments are given
  1085  *       argtypes are the value arguments, if we search for a method
  1087  *  If no symbol was found, a ResolveError detailing the problem is returned.
  1088  ****************************************************************************/
  1090     /** Find field. Synthetic fields are always skipped.
  1091      *  @param env     The current environment.
  1092      *  @param site    The original type from where the selection takes place.
  1093      *  @param name    The name of the field.
  1094      *  @param c       The class to search for the field. This is always
  1095      *                 a superclass or implemented interface of site's class.
  1096      */
  1097     Symbol findField(Env<AttrContext> env,
  1098                      Type site,
  1099                      Name name,
  1100                      TypeSymbol c) {
  1101         while (c.type.hasTag(TYPEVAR))
  1102             c = c.type.getUpperBound().tsym;
  1103         Symbol bestSoFar = varNotFound;
  1104         Symbol sym;
  1105         Scope.Entry e = c.members().lookup(name);
  1106         while (e.scope != null) {
  1107             if (e.sym.kind == VAR && (e.sym.flags_field & SYNTHETIC) == 0) {
  1108                 return isAccessible(env, site, e.sym)
  1109                     ? e.sym : new AccessError(env, site, e.sym);
  1111             e = e.next();
  1113         Type st = types.supertype(c.type);
  1114         if (st != null && (st.hasTag(CLASS) || st.hasTag(TYPEVAR))) {
  1115             sym = findField(env, site, name, st.tsym);
  1116             if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1118         for (List<Type> l = types.interfaces(c.type);
  1119              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
  1120              l = l.tail) {
  1121             sym = findField(env, site, name, l.head.tsym);
  1122             if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
  1123                 sym.owner != bestSoFar.owner)
  1124                 bestSoFar = new AmbiguityError(bestSoFar, sym);
  1125             else if (sym.kind < bestSoFar.kind)
  1126                 bestSoFar = sym;
  1128         return bestSoFar;
  1131     /** Resolve a field identifier, throw a fatal error if not found.
  1132      *  @param pos       The position to use for error reporting.
  1133      *  @param env       The environment current at the method invocation.
  1134      *  @param site      The type of the qualifying expression, in which
  1135      *                   identifier is searched.
  1136      *  @param name      The identifier's name.
  1137      */
  1138     public VarSymbol resolveInternalField(DiagnosticPosition pos, Env<AttrContext> env,
  1139                                           Type site, Name name) {
  1140         Symbol sym = findField(env, site, name, site.tsym);
  1141         if (sym.kind == VAR) return (VarSymbol)sym;
  1142         else throw new FatalError(
  1143                  diags.fragment("fatal.err.cant.locate.field",
  1144                                 name));
  1147     /** Find unqualified variable or field with given name.
  1148      *  Synthetic fields always skipped.
  1149      *  @param env     The current environment.
  1150      *  @param name    The name of the variable or field.
  1151      */
  1152     Symbol findVar(Env<AttrContext> env, Name name) {
  1153         Symbol bestSoFar = varNotFound;
  1154         Symbol sym;
  1155         Env<AttrContext> env1 = env;
  1156         boolean staticOnly = false;
  1157         while (env1.outer != null) {
  1158             if (isStatic(env1)) staticOnly = true;
  1159             Scope.Entry e = env1.info.scope.lookup(name);
  1160             while (e.scope != null &&
  1161                    (e.sym.kind != VAR ||
  1162                     (e.sym.flags_field & SYNTHETIC) != 0))
  1163                 e = e.next();
  1164             sym = (e.scope != null)
  1165                 ? e.sym
  1166                 : findField(
  1167                     env1, env1.enclClass.sym.type, name, env1.enclClass.sym);
  1168             if (sym.exists()) {
  1169                 if (staticOnly &&
  1170                     sym.kind == VAR &&
  1171                     sym.owner.kind == TYP &&
  1172                     (sym.flags() & STATIC) == 0)
  1173                     return new StaticError(sym);
  1174                 else
  1175                     return sym;
  1176             } else if (sym.kind < bestSoFar.kind) {
  1177                 bestSoFar = sym;
  1180             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  1181             env1 = env1.outer;
  1184         sym = findField(env, syms.predefClass.type, name, syms.predefClass);
  1185         if (sym.exists())
  1186             return sym;
  1187         if (bestSoFar.exists())
  1188             return bestSoFar;
  1190         Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
  1191         for (; e.scope != null; e = e.next()) {
  1192             sym = e.sym;
  1193             Type origin = e.getOrigin().owner.type;
  1194             if (sym.kind == VAR) {
  1195                 if (e.sym.owner.type != origin)
  1196                     sym = sym.clone(e.getOrigin().owner);
  1197                 return isAccessible(env, origin, sym)
  1198                     ? sym : new AccessError(env, origin, sym);
  1202         Symbol origin = null;
  1203         e = env.toplevel.starImportScope.lookup(name);
  1204         for (; e.scope != null; e = e.next()) {
  1205             sym = e.sym;
  1206             if (sym.kind != VAR)
  1207                 continue;
  1208             // invariant: sym.kind == VAR
  1209             if (bestSoFar.kind < AMBIGUOUS && sym.owner != bestSoFar.owner)
  1210                 return new AmbiguityError(bestSoFar, sym);
  1211             else if (bestSoFar.kind >= VAR) {
  1212                 origin = e.getOrigin().owner;
  1213                 bestSoFar = isAccessible(env, origin.type, sym)
  1214                     ? sym : new AccessError(env, origin.type, sym);
  1217         if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type)
  1218             return bestSoFar.clone(origin);
  1219         else
  1220             return bestSoFar;
  1223     Warner noteWarner = new Warner();
  1225     /** Select the best method for a call site among two choices.
  1226      *  @param env              The current environment.
  1227      *  @param site             The original type from where the
  1228      *                          selection takes place.
  1229      *  @param argtypes         The invocation's value arguments,
  1230      *  @param typeargtypes     The invocation's type arguments,
  1231      *  @param sym              Proposed new best match.
  1232      *  @param bestSoFar        Previously found best match.
  1233      *  @param allowBoxing Allow boxing conversions of arguments.
  1234      *  @param useVarargs Box trailing arguments into an array for varargs.
  1235      */
  1236     @SuppressWarnings("fallthrough")
  1237     Symbol selectBest(Env<AttrContext> env,
  1238                       Type site,
  1239                       List<Type> argtypes,
  1240                       List<Type> typeargtypes,
  1241                       Symbol sym,
  1242                       Symbol bestSoFar,
  1243                       boolean allowBoxing,
  1244                       boolean useVarargs,
  1245                       boolean operator) {
  1246         if (sym.kind == ERR ||
  1247                 !sym.isInheritedIn(site.tsym, types) ||
  1248                 (useVarargs && (sym.flags() & VARARGS) == 0)) {
  1249             return bestSoFar;
  1251         Assert.check(sym.kind < AMBIGUOUS);
  1252         try {
  1253             Type mt = rawInstantiate(env, site, sym, null, argtypes, typeargtypes,
  1254                                allowBoxing, useVarargs, resolveMethodCheck, types.noWarnings);
  1255             if (!operator)
  1256                 currentResolutionContext.addApplicableCandidate(sym, mt);
  1257         } catch (InapplicableMethodException ex) {
  1258             if (!operator)
  1259                 currentResolutionContext.addInapplicableCandidate(sym, ex.getDiagnostic());
  1260             switch (bestSoFar.kind) {
  1261                 case ABSENT_MTH:
  1262                     return new InapplicableSymbolError(currentResolutionContext);
  1263                 case WRONG_MTH:
  1264                     if (operator) return bestSoFar;
  1265                     bestSoFar = new InapplicableSymbolsError(currentResolutionContext);
  1266                 default:
  1267                     return bestSoFar;
  1270         if (!isAccessible(env, site, sym)) {
  1271             return (bestSoFar.kind == ABSENT_MTH)
  1272                 ? new AccessError(env, site, sym)
  1273                 : bestSoFar;
  1275         return (bestSoFar.kind > AMBIGUOUS)
  1276             ? sym
  1277             : mostSpecific(argtypes, sym, bestSoFar, env, site,
  1278                            allowBoxing && operator, useVarargs);
  1281     /* Return the most specific of the two methods for a call,
  1282      *  given that both are accessible and applicable.
  1283      *  @param m1               A new candidate for most specific.
  1284      *  @param m2               The previous most specific candidate.
  1285      *  @param env              The current environment.
  1286      *  @param site             The original type from where the selection
  1287      *                          takes place.
  1288      *  @param allowBoxing Allow boxing conversions of arguments.
  1289      *  @param useVarargs Box trailing arguments into an array for varargs.
  1290      */
  1291     Symbol mostSpecific(List<Type> argtypes, Symbol m1,
  1292                         Symbol m2,
  1293                         Env<AttrContext> env,
  1294                         final Type site,
  1295                         boolean allowBoxing,
  1296                         boolean useVarargs) {
  1297         switch (m2.kind) {
  1298         case MTH:
  1299             if (m1 == m2) return m1;
  1300             boolean m1SignatureMoreSpecific =
  1301                     signatureMoreSpecific(argtypes, env, site, m1, m2, allowBoxing, useVarargs);
  1302             boolean m2SignatureMoreSpecific =
  1303                     signatureMoreSpecific(argtypes, env, site, m2, m1, allowBoxing, useVarargs);
  1304             if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) {
  1305                 Type mt1 = types.memberType(site, m1);
  1306                 Type mt2 = types.memberType(site, m2);
  1307                 if (!types.overrideEquivalent(mt1, mt2))
  1308                     return ambiguityError(m1, m2);
  1310                 // same signature; select (a) the non-bridge method, or
  1311                 // (b) the one that overrides the other, or (c) the concrete
  1312                 // one, or (d) merge both abstract signatures
  1313                 if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE))
  1314                     return ((m1.flags() & BRIDGE) != 0) ? m2 : m1;
  1316                 // if one overrides or hides the other, use it
  1317                 TypeSymbol m1Owner = (TypeSymbol)m1.owner;
  1318                 TypeSymbol m2Owner = (TypeSymbol)m2.owner;
  1319                 if (types.asSuper(m1Owner.type, m2Owner) != null &&
  1320                     ((m1.owner.flags_field & INTERFACE) == 0 ||
  1321                      (m2.owner.flags_field & INTERFACE) != 0) &&
  1322                     m1.overrides(m2, m1Owner, types, false))
  1323                     return m1;
  1324                 if (types.asSuper(m2Owner.type, m1Owner) != null &&
  1325                     ((m2.owner.flags_field & INTERFACE) == 0 ||
  1326                      (m1.owner.flags_field & INTERFACE) != 0) &&
  1327                     m2.overrides(m1, m2Owner, types, false))
  1328                     return m2;
  1329                 boolean m1Abstract = (m1.flags() & ABSTRACT) != 0;
  1330                 boolean m2Abstract = (m2.flags() & ABSTRACT) != 0;
  1331                 if (m1Abstract && !m2Abstract) return m2;
  1332                 if (m2Abstract && !m1Abstract) return m1;
  1333                 // both abstract or both concrete
  1334                 return ambiguityError(m1, m2);
  1336             if (m1SignatureMoreSpecific) return m1;
  1337             if (m2SignatureMoreSpecific) return m2;
  1338             return ambiguityError(m1, m2);
  1339         case AMBIGUOUS:
  1340             //check if m1 is more specific than all ambiguous methods in m2
  1341             AmbiguityError e = (AmbiguityError)m2;
  1342             for (Symbol s : e.ambiguousSyms) {
  1343                 if (mostSpecific(argtypes, m1, s, env, site, allowBoxing, useVarargs) != m1) {
  1344                     return e.addAmbiguousSymbol(m1);
  1347             return m1;
  1348         default:
  1349             throw new AssertionError();
  1352     //where
  1353     private boolean signatureMoreSpecific(List<Type> actuals, Env<AttrContext> env, Type site, Symbol m1, Symbol m2, boolean allowBoxing, boolean useVarargs) {
  1354         noteWarner.clear();
  1355         int maxLength = Math.max(
  1356                             Math.max(m1.type.getParameterTypes().length(), actuals.length()),
  1357                             m2.type.getParameterTypes().length());
  1358         Type mst = instantiate(env, site, m2, null,
  1359                 adjustArgs(types.lowerBounds(types.memberType(site, m1).getParameterTypes()), m1, maxLength, useVarargs), null,
  1360                 allowBoxing, useVarargs, new MostSpecificCheck(!allowBoxing, actuals), noteWarner);
  1361         return mst != null &&
  1362                 !noteWarner.hasLint(Lint.LintCategory.UNCHECKED);
  1364     private List<Type> adjustArgs(List<Type> args, Symbol msym, int length, boolean allowVarargs) {
  1365         if ((msym.flags() & VARARGS) != 0 && allowVarargs) {
  1366             Type varargsElem = types.elemtype(args.last());
  1367             if (varargsElem == null) {
  1368                 Assert.error("Bad varargs = " + args.last() + " " + msym);
  1370             List<Type> newArgs = args.reverse().tail.prepend(varargsElem).reverse();
  1371             while (newArgs.length() < length) {
  1372                 newArgs = newArgs.append(newArgs.last());
  1374             return newArgs;
  1375         } else {
  1376             return args;
  1379     //where
  1380     Type mostSpecificReturnType(Type mt1, Type mt2) {
  1381         Type rt1 = mt1.getReturnType();
  1382         Type rt2 = mt2.getReturnType();
  1384         if (mt1.hasTag(FORALL) && mt2.hasTag(FORALL)) {
  1385             //if both are generic methods, adjust return type ahead of subtyping check
  1386             rt1 = types.subst(rt1, mt1.getTypeArguments(), mt2.getTypeArguments());
  1388         //first use subtyping, then return type substitutability
  1389         if (types.isSubtype(rt1, rt2)) {
  1390             return mt1;
  1391         } else if (types.isSubtype(rt2, rt1)) {
  1392             return mt2;
  1393         } else if (types.returnTypeSubstitutable(mt1, mt2)) {
  1394             return mt1;
  1395         } else if (types.returnTypeSubstitutable(mt2, mt1)) {
  1396             return mt2;
  1397         } else {
  1398             return null;
  1401     //where
  1402     Symbol ambiguityError(Symbol m1, Symbol m2) {
  1403         if (((m1.flags() | m2.flags()) & CLASH) != 0) {
  1404             return (m1.flags() & CLASH) == 0 ? m1 : m2;
  1405         } else {
  1406             return new AmbiguityError(m1, m2);
  1410     Symbol findMethodInScope(Env<AttrContext> env,
  1411             Type site,
  1412             Name name,
  1413             List<Type> argtypes,
  1414             List<Type> typeargtypes,
  1415             Scope sc,
  1416             Symbol bestSoFar,
  1417             boolean allowBoxing,
  1418             boolean useVarargs,
  1419             boolean operator,
  1420             boolean abstractok) {
  1421         for (Symbol s : sc.getElementsByName(name, new LookupFilter(abstractok))) {
  1422             bestSoFar = selectBest(env, site, argtypes, typeargtypes, s,
  1423                     bestSoFar, allowBoxing, useVarargs, operator);
  1425         return bestSoFar;
  1427     //where
  1428         class LookupFilter implements Filter<Symbol> {
  1430             boolean abstractOk;
  1432             LookupFilter(boolean abstractOk) {
  1433                 this.abstractOk = abstractOk;
  1436             public boolean accepts(Symbol s) {
  1437                 long flags = s.flags();
  1438                 return s.kind == MTH &&
  1439                         (flags & SYNTHETIC) == 0 &&
  1440                         (abstractOk ||
  1441                         (flags & DEFAULT) != 0 ||
  1442                         (flags & ABSTRACT) == 0);
  1444         };
  1446     /** Find best qualified method matching given name, type and value
  1447      *  arguments.
  1448      *  @param env       The current environment.
  1449      *  @param site      The original type from where the selection
  1450      *                   takes place.
  1451      *  @param name      The method's name.
  1452      *  @param argtypes  The method's value arguments.
  1453      *  @param typeargtypes The method's type arguments
  1454      *  @param allowBoxing Allow boxing conversions of arguments.
  1455      *  @param useVarargs Box trailing arguments into an array for varargs.
  1456      */
  1457     Symbol findMethod(Env<AttrContext> env,
  1458                       Type site,
  1459                       Name name,
  1460                       List<Type> argtypes,
  1461                       List<Type> typeargtypes,
  1462                       boolean allowBoxing,
  1463                       boolean useVarargs,
  1464                       boolean operator) {
  1465         Symbol bestSoFar = methodNotFound;
  1466         bestSoFar = findMethod(env,
  1467                           site,
  1468                           name,
  1469                           argtypes,
  1470                           typeargtypes,
  1471                           site.tsym.type,
  1472                           bestSoFar,
  1473                           allowBoxing,
  1474                           useVarargs,
  1475                           operator);
  1476         reportVerboseResolutionDiagnostic(env.tree.pos(), name, site, argtypes, typeargtypes, bestSoFar);
  1477         return bestSoFar;
  1479     // where
  1480     private Symbol findMethod(Env<AttrContext> env,
  1481                               Type site,
  1482                               Name name,
  1483                               List<Type> argtypes,
  1484                               List<Type> typeargtypes,
  1485                               Type intype,
  1486                               Symbol bestSoFar,
  1487                               boolean allowBoxing,
  1488                               boolean useVarargs,
  1489                               boolean operator) {
  1490         @SuppressWarnings({"unchecked","rawtypes"})
  1491         List<Type>[] itypes = (List<Type>[])new List[] { List.<Type>nil(), List.<Type>nil() };
  1492         InterfaceLookupPhase iphase = InterfaceLookupPhase.ABSTRACT_OK;
  1493         for (TypeSymbol s : superclasses(intype)) {
  1494             bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
  1495                     s.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
  1496             if (name == names.init) return bestSoFar;
  1497             iphase = (iphase == null) ? null : iphase.update(s, this);
  1498             if (iphase != null) {
  1499                 for (Type itype : types.interfaces(s.type)) {
  1500                     itypes[iphase.ordinal()] = types.union(types.closure(itype), itypes[iphase.ordinal()]);
  1505         Symbol concrete = bestSoFar.kind < ERR &&
  1506                 (bestSoFar.flags() & ABSTRACT) == 0 ?
  1507                 bestSoFar : methodNotFound;
  1509         for (InterfaceLookupPhase iphase2 : InterfaceLookupPhase.values()) {
  1510             if (iphase2 == InterfaceLookupPhase.DEFAULT_OK && !allowDefaultMethods) break;
  1511             //keep searching for abstract methods
  1512             for (Type itype : itypes[iphase2.ordinal()]) {
  1513                 if (!itype.isInterface()) continue; //skip j.l.Object (included by Types.closure())
  1514                 if (iphase2 == InterfaceLookupPhase.DEFAULT_OK &&
  1515                         (itype.tsym.flags() & DEFAULT) == 0) continue;
  1516                 bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
  1517                         itype.tsym.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
  1518                 if (concrete != bestSoFar &&
  1519                         concrete.kind < ERR  && bestSoFar.kind < ERR &&
  1520                         types.isSubSignature(concrete.type, bestSoFar.type)) {
  1521                     //this is an hack - as javac does not do full membership checks
  1522                     //most specific ends up comparing abstract methods that might have
  1523                     //been implemented by some concrete method in a subclass and,
  1524                     //because of raw override, it is possible for an abstract method
  1525                     //to be more specific than the concrete method - so we need
  1526                     //to explicitly call that out (see CR 6178365)
  1527                     bestSoFar = concrete;
  1531         return bestSoFar;
  1534     enum InterfaceLookupPhase {
  1535         ABSTRACT_OK() {
  1536             @Override
  1537             InterfaceLookupPhase update(Symbol s, Resolve rs) {
  1538                 //We should not look for abstract methods if receiver is a concrete class
  1539                 //(as concrete classes are expected to implement all abstracts coming
  1540                 //from superinterfaces)
  1541                 if ((s.flags() & (ABSTRACT | INTERFACE | ENUM)) != 0) {
  1542                     return this;
  1543                 } else if (rs.allowDefaultMethods) {
  1544                     return DEFAULT_OK;
  1545                 } else {
  1546                     return null;
  1549         },
  1550         DEFAULT_OK() {
  1551             @Override
  1552             InterfaceLookupPhase update(Symbol s, Resolve rs) {
  1553                 return this;
  1555         };
  1557         abstract InterfaceLookupPhase update(Symbol s, Resolve rs);
  1560     /**
  1561      * Return an Iterable object to scan the superclasses of a given type.
  1562      * It's crucial that the scan is done lazily, as we don't want to accidentally
  1563      * access more supertypes than strictly needed (as this could trigger completion
  1564      * errors if some of the not-needed supertypes are missing/ill-formed).
  1565      */
  1566     Iterable<TypeSymbol> superclasses(final Type intype) {
  1567         return new Iterable<TypeSymbol>() {
  1568             public Iterator<TypeSymbol> iterator() {
  1569                 return new Iterator<TypeSymbol>() {
  1571                     List<TypeSymbol> seen = List.nil();
  1572                     TypeSymbol currentSym = symbolFor(intype);
  1573                     TypeSymbol prevSym = null;
  1575                     public boolean hasNext() {
  1576                         if (currentSym == syms.noSymbol) {
  1577                             currentSym = symbolFor(types.supertype(prevSym.type));
  1579                         return currentSym != null;
  1582                     public TypeSymbol next() {
  1583                         prevSym = currentSym;
  1584                         currentSym = syms.noSymbol;
  1585                         Assert.check(prevSym != null || prevSym != syms.noSymbol);
  1586                         return prevSym;
  1589                     public void remove() {
  1590                         throw new UnsupportedOperationException();
  1593                     TypeSymbol symbolFor(Type t) {
  1594                         if (!t.hasTag(CLASS) &&
  1595                                 !t.hasTag(TYPEVAR)) {
  1596                             return null;
  1598                         while (t.hasTag(TYPEVAR))
  1599                             t = t.getUpperBound();
  1600                         if (seen.contains(t.tsym)) {
  1601                             //degenerate case in which we have a circular
  1602                             //class hierarchy - because of ill-formed classfiles
  1603                             return null;
  1605                         seen = seen.prepend(t.tsym);
  1606                         return t.tsym;
  1608                 };
  1610         };
  1613     /** Find unqualified method matching given name, type and value arguments.
  1614      *  @param env       The current environment.
  1615      *  @param name      The method's name.
  1616      *  @param argtypes  The method's value arguments.
  1617      *  @param typeargtypes  The method's type arguments.
  1618      *  @param allowBoxing Allow boxing conversions of arguments.
  1619      *  @param useVarargs Box trailing arguments into an array for varargs.
  1620      */
  1621     Symbol findFun(Env<AttrContext> env, Name name,
  1622                    List<Type> argtypes, List<Type> typeargtypes,
  1623                    boolean allowBoxing, boolean useVarargs) {
  1624         Symbol bestSoFar = methodNotFound;
  1625         Symbol sym;
  1626         Env<AttrContext> env1 = env;
  1627         boolean staticOnly = false;
  1628         while (env1.outer != null) {
  1629             if (isStatic(env1)) staticOnly = true;
  1630             sym = findMethod(
  1631                 env1, env1.enclClass.sym.type, name, argtypes, typeargtypes,
  1632                 allowBoxing, useVarargs, false);
  1633             if (sym.exists()) {
  1634                 if (staticOnly &&
  1635                     sym.kind == MTH &&
  1636                     sym.owner.kind == TYP &&
  1637                     (sym.flags() & STATIC) == 0) return new StaticError(sym);
  1638                 else return sym;
  1639             } else if (sym.kind < bestSoFar.kind) {
  1640                 bestSoFar = sym;
  1642             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  1643             env1 = env1.outer;
  1646         sym = findMethod(env, syms.predefClass.type, name, argtypes,
  1647                          typeargtypes, allowBoxing, useVarargs, false);
  1648         if (sym.exists())
  1649             return sym;
  1651         Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
  1652         for (; e.scope != null; e = e.next()) {
  1653             sym = e.sym;
  1654             Type origin = e.getOrigin().owner.type;
  1655             if (sym.kind == MTH) {
  1656                 if (e.sym.owner.type != origin)
  1657                     sym = sym.clone(e.getOrigin().owner);
  1658                 if (!isAccessible(env, origin, sym))
  1659                     sym = new AccessError(env, origin, sym);
  1660                 bestSoFar = selectBest(env, origin,
  1661                                        argtypes, typeargtypes,
  1662                                        sym, bestSoFar,
  1663                                        allowBoxing, useVarargs, false);
  1666         if (bestSoFar.exists())
  1667             return bestSoFar;
  1669         e = env.toplevel.starImportScope.lookup(name);
  1670         for (; e.scope != null; e = e.next()) {
  1671             sym = e.sym;
  1672             Type origin = e.getOrigin().owner.type;
  1673             if (sym.kind == MTH) {
  1674                 if (e.sym.owner.type != origin)
  1675                     sym = sym.clone(e.getOrigin().owner);
  1676                 if (!isAccessible(env, origin, sym))
  1677                     sym = new AccessError(env, origin, sym);
  1678                 bestSoFar = selectBest(env, origin,
  1679                                        argtypes, typeargtypes,
  1680                                        sym, bestSoFar,
  1681                                        allowBoxing, useVarargs, false);
  1684         return bestSoFar;
  1687     /** Load toplevel or member class with given fully qualified name and
  1688      *  verify that it is accessible.
  1689      *  @param env       The current environment.
  1690      *  @param name      The fully qualified name of the class to be loaded.
  1691      */
  1692     Symbol loadClass(Env<AttrContext> env, Name name) {
  1693         try {
  1694             ClassSymbol c = reader.loadClass(name);
  1695             return isAccessible(env, c) ? c : new AccessError(c);
  1696         } catch (ClassReader.BadClassFile err) {
  1697             throw err;
  1698         } catch (CompletionFailure ex) {
  1699             return typeNotFound;
  1703     /** Find qualified member type.
  1704      *  @param env       The current environment.
  1705      *  @param site      The original type from where the selection takes
  1706      *                   place.
  1707      *  @param name      The type's name.
  1708      *  @param c         The class to search for the member type. This is
  1709      *                   always a superclass or implemented interface of
  1710      *                   site's class.
  1711      */
  1712     Symbol findMemberType(Env<AttrContext> env,
  1713                           Type site,
  1714                           Name name,
  1715                           TypeSymbol c) {
  1716         Symbol bestSoFar = typeNotFound;
  1717         Symbol sym;
  1718         Scope.Entry e = c.members().lookup(name);
  1719         while (e.scope != null) {
  1720             if (e.sym.kind == TYP) {
  1721                 return isAccessible(env, site, e.sym)
  1722                     ? e.sym
  1723                     : new AccessError(env, site, e.sym);
  1725             e = e.next();
  1727         Type st = types.supertype(c.type);
  1728         if (st != null && st.hasTag(CLASS)) {
  1729             sym = findMemberType(env, site, name, st.tsym);
  1730             if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1732         for (List<Type> l = types.interfaces(c.type);
  1733              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
  1734              l = l.tail) {
  1735             sym = findMemberType(env, site, name, l.head.tsym);
  1736             if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
  1737                 sym.owner != bestSoFar.owner)
  1738                 bestSoFar = new AmbiguityError(bestSoFar, sym);
  1739             else if (sym.kind < bestSoFar.kind)
  1740                 bestSoFar = sym;
  1742         return bestSoFar;
  1745     /** Find a global type in given scope and load corresponding class.
  1746      *  @param env       The current environment.
  1747      *  @param scope     The scope in which to look for the type.
  1748      *  @param name      The type's name.
  1749      */
  1750     Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name) {
  1751         Symbol bestSoFar = typeNotFound;
  1752         for (Scope.Entry e = scope.lookup(name); e.scope != null; e = e.next()) {
  1753             Symbol sym = loadClass(env, e.sym.flatName());
  1754             if (bestSoFar.kind == TYP && sym.kind == TYP &&
  1755                 bestSoFar != sym)
  1756                 return new AmbiguityError(bestSoFar, sym);
  1757             else if (sym.kind < bestSoFar.kind)
  1758                 bestSoFar = sym;
  1760         return bestSoFar;
  1763     /** Find an unqualified type symbol.
  1764      *  @param env       The current environment.
  1765      *  @param name      The type's name.
  1766      */
  1767     Symbol findType(Env<AttrContext> env, Name name) {
  1768         Symbol bestSoFar = typeNotFound;
  1769         Symbol sym;
  1770         boolean staticOnly = false;
  1771         for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
  1772             if (isStatic(env1)) staticOnly = true;
  1773             for (Scope.Entry e = env1.info.scope.lookup(name);
  1774                  e.scope != null;
  1775                  e = e.next()) {
  1776                 if (e.sym.kind == TYP) {
  1777                     if (staticOnly &&
  1778                         e.sym.type.hasTag(TYPEVAR) &&
  1779                         e.sym.owner.kind == TYP) return new StaticError(e.sym);
  1780                     return e.sym;
  1784             sym = findMemberType(env1, env1.enclClass.sym.type, name,
  1785                                  env1.enclClass.sym);
  1786             if (staticOnly && sym.kind == TYP &&
  1787                 sym.type.hasTag(CLASS) &&
  1788                 sym.type.getEnclosingType().hasTag(CLASS) &&
  1789                 env1.enclClass.sym.type.isParameterized() &&
  1790                 sym.type.getEnclosingType().isParameterized())
  1791                 return new StaticError(sym);
  1792             else if (sym.exists()) return sym;
  1793             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1795             JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass;
  1796             if ((encl.sym.flags() & STATIC) != 0)
  1797                 staticOnly = true;
  1800         if (!env.tree.hasTag(IMPORT)) {
  1801             sym = findGlobalType(env, env.toplevel.namedImportScope, name);
  1802             if (sym.exists()) return sym;
  1803             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1805             sym = findGlobalType(env, env.toplevel.packge.members(), name);
  1806             if (sym.exists()) return sym;
  1807             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1809             sym = findGlobalType(env, env.toplevel.starImportScope, name);
  1810             if (sym.exists()) return sym;
  1811             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1814         return bestSoFar;
  1817     /** Find an unqualified identifier which matches a specified kind set.
  1818      *  @param env       The current environment.
  1819      *  @param name      The identifier's name.
  1820      *  @param kind      Indicates the possible symbol kinds
  1821      *                   (a subset of VAL, TYP, PCK).
  1822      */
  1823     Symbol findIdent(Env<AttrContext> env, Name name, int kind) {
  1824         Symbol bestSoFar = typeNotFound;
  1825         Symbol sym;
  1827         if ((kind & VAR) != 0) {
  1828             sym = findVar(env, name);
  1829             if (sym.exists()) return sym;
  1830             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1833         if ((kind & TYP) != 0) {
  1834             sym = findType(env, name);
  1835             if (sym.kind==TYP) {
  1836                  reportDependence(env.enclClass.sym, sym);
  1838             if (sym.exists()) return sym;
  1839             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1842         if ((kind & PCK) != 0) return reader.enterPackage(name);
  1843         else return bestSoFar;
  1846     /** Report dependencies.
  1847      * @param from The enclosing class sym
  1848      * @param to   The found identifier that the class depends on.
  1849      */
  1850     public void reportDependence(Symbol from, Symbol to) {
  1851         // Override if you want to collect the reported dependencies.
  1854     /** Find an identifier in a package which matches a specified kind set.
  1855      *  @param env       The current environment.
  1856      *  @param name      The identifier's name.
  1857      *  @param kind      Indicates the possible symbol kinds
  1858      *                   (a nonempty subset of TYP, PCK).
  1859      */
  1860     Symbol findIdentInPackage(Env<AttrContext> env, TypeSymbol pck,
  1861                               Name name, int kind) {
  1862         Name fullname = TypeSymbol.formFullName(name, pck);
  1863         Symbol bestSoFar = typeNotFound;
  1864         PackageSymbol pack = null;
  1865         if ((kind & PCK) != 0) {
  1866             pack = reader.enterPackage(fullname);
  1867             if (pack.exists()) return pack;
  1869         if ((kind & TYP) != 0) {
  1870             Symbol sym = loadClass(env, fullname);
  1871             if (sym.exists()) {
  1872                 // don't allow programs to use flatnames
  1873                 if (name == sym.name) return sym;
  1875             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1877         return (pack != null) ? pack : bestSoFar;
  1880     /** Find an identifier among the members of a given type `site'.
  1881      *  @param env       The current environment.
  1882      *  @param site      The type containing the symbol to be found.
  1883      *  @param name      The identifier's name.
  1884      *  @param kind      Indicates the possible symbol kinds
  1885      *                   (a subset of VAL, TYP).
  1886      */
  1887     Symbol findIdentInType(Env<AttrContext> env, Type site,
  1888                            Name name, int kind) {
  1889         Symbol bestSoFar = typeNotFound;
  1890         Symbol sym;
  1891         if ((kind & VAR) != 0) {
  1892             sym = findField(env, site, name, site.tsym);
  1893             if (sym.exists()) return sym;
  1894             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1897         if ((kind & TYP) != 0) {
  1898             sym = findMemberType(env, site, name, site.tsym);
  1899             if (sym.exists()) return sym;
  1900             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1902         return bestSoFar;
  1905 /* ***************************************************************************
  1906  *  Access checking
  1907  *  The following methods convert ResolveErrors to ErrorSymbols, issuing
  1908  *  an error message in the process
  1909  ****************************************************************************/
  1911     /** If `sym' is a bad symbol: report error and return errSymbol
  1912      *  else pass through unchanged,
  1913      *  additional arguments duplicate what has been used in trying to find the
  1914      *  symbol {@literal (--> flyweight pattern)}. This improves performance since we
  1915      *  expect misses to happen frequently.
  1917      *  @param sym       The symbol that was found, or a ResolveError.
  1918      *  @param pos       The position to use for error reporting.
  1919      *  @param location  The symbol the served as a context for this lookup
  1920      *  @param site      The original type from where the selection took place.
  1921      *  @param name      The symbol's name.
  1922      *  @param qualified Did we get here through a qualified expression resolution?
  1923      *  @param argtypes  The invocation's value arguments,
  1924      *                   if we looked for a method.
  1925      *  @param typeargtypes  The invocation's type arguments,
  1926      *                   if we looked for a method.
  1927      *  @param logResolveHelper helper class used to log resolve errors
  1928      */
  1929     Symbol accessInternal(Symbol sym,
  1930                   DiagnosticPosition pos,
  1931                   Symbol location,
  1932                   Type site,
  1933                   Name name,
  1934                   boolean qualified,
  1935                   List<Type> argtypes,
  1936                   List<Type> typeargtypes,
  1937                   LogResolveHelper logResolveHelper) {
  1938         if (sym.kind >= AMBIGUOUS) {
  1939             ResolveError errSym = (ResolveError)sym;
  1940             sym = errSym.access(name, qualified ? site.tsym : syms.noSymbol);
  1941             argtypes = logResolveHelper.getArgumentTypes(errSym, sym, name, argtypes);
  1942             if (logResolveHelper.resolveDiagnosticNeeded(site, argtypes, typeargtypes)) {
  1943                 logResolveError(errSym, pos, location, site, name, argtypes, typeargtypes);
  1946         return sym;
  1949     /**
  1950      * Variant of the generalized access routine, to be used for generating method
  1951      * resolution diagnostics
  1952      */
  1953     Symbol accessMethod(Symbol sym,
  1954                   DiagnosticPosition pos,
  1955                   Symbol location,
  1956                   Type site,
  1957                   Name name,
  1958                   boolean qualified,
  1959                   List<Type> argtypes,
  1960                   List<Type> typeargtypes) {
  1961         return accessInternal(sym, pos, location, site, name, qualified, argtypes, typeargtypes, methodLogResolveHelper);
  1964     /** Same as original accessMethod(), but without location.
  1965      */
  1966     Symbol accessMethod(Symbol sym,
  1967                   DiagnosticPosition pos,
  1968                   Type site,
  1969                   Name name,
  1970                   boolean qualified,
  1971                   List<Type> argtypes,
  1972                   List<Type> typeargtypes) {
  1973         return accessMethod(sym, pos, site.tsym, site, name, qualified, argtypes, typeargtypes);
  1976     /**
  1977      * Variant of the generalized access routine, to be used for generating variable,
  1978      * type resolution diagnostics
  1979      */
  1980     Symbol accessBase(Symbol sym,
  1981                   DiagnosticPosition pos,
  1982                   Symbol location,
  1983                   Type site,
  1984                   Name name,
  1985                   boolean qualified) {
  1986         return accessInternal(sym, pos, location, site, name, qualified, List.<Type>nil(), null, basicLogResolveHelper);
  1989     /** Same as original accessBase(), but without location.
  1990      */
  1991     Symbol accessBase(Symbol sym,
  1992                   DiagnosticPosition pos,
  1993                   Type site,
  1994                   Name name,
  1995                   boolean qualified) {
  1996         return accessBase(sym, pos, site.tsym, site, name, qualified);
  1999     interface LogResolveHelper {
  2000         boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes);
  2001         List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes);
  2004     LogResolveHelper basicLogResolveHelper = new LogResolveHelper() {
  2005         public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
  2006             return !site.isErroneous();
  2008         public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
  2009             return argtypes;
  2011     };
  2013     LogResolveHelper methodLogResolveHelper = new LogResolveHelper() {
  2014         public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
  2015             return !site.isErroneous() &&
  2016                         !Type.isErroneous(argtypes) &&
  2017                         (typeargtypes == null || !Type.isErroneous(typeargtypes));
  2019         public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
  2020             return (syms.operatorNames.contains(name)) ?
  2021                     argtypes :
  2022                     Type.map(argtypes, new ResolveDeferredRecoveryMap(accessedSym));
  2025         class ResolveDeferredRecoveryMap extends DeferredAttr.RecoveryDeferredTypeMap {
  2027             public ResolveDeferredRecoveryMap(Symbol msym) {
  2028                 deferredAttr.super(AttrMode.SPECULATIVE, msym, currentResolutionContext.step);
  2031             @Override
  2032             protected Type typeOf(DeferredType dt) {
  2033                 Type res = super.typeOf(dt);
  2034                 if (!res.isErroneous()) {
  2035                     switch (TreeInfo.skipParens(dt.tree).getTag()) {
  2036                         case LAMBDA:
  2037                         case REFERENCE:
  2038                             return dt;
  2039                         case CONDEXPR:
  2040                             return res == Type.recoveryType ?
  2041                                     dt : res;
  2044                 return res;
  2047     };
  2049     /** Check that sym is not an abstract method.
  2050      */
  2051     void checkNonAbstract(DiagnosticPosition pos, Symbol sym) {
  2052         if ((sym.flags() & ABSTRACT) != 0 && (sym.flags() & DEFAULT) == 0)
  2053             log.error(pos, "abstract.cant.be.accessed.directly",
  2054                       kindName(sym), sym, sym.location());
  2057 /* ***************************************************************************
  2058  *  Debugging
  2059  ****************************************************************************/
  2061     /** print all scopes starting with scope s and proceeding outwards.
  2062      *  used for debugging.
  2063      */
  2064     public void printscopes(Scope s) {
  2065         while (s != null) {
  2066             if (s.owner != null)
  2067                 System.err.print(s.owner + ": ");
  2068             for (Scope.Entry e = s.elems; e != null; e = e.sibling) {
  2069                 if ((e.sym.flags() & ABSTRACT) != 0)
  2070                     System.err.print("abstract ");
  2071                 System.err.print(e.sym + " ");
  2073             System.err.println();
  2074             s = s.next;
  2078     void printscopes(Env<AttrContext> env) {
  2079         while (env.outer != null) {
  2080             System.err.println("------------------------------");
  2081             printscopes(env.info.scope);
  2082             env = env.outer;
  2086     public void printscopes(Type t) {
  2087         while (t.hasTag(CLASS)) {
  2088             printscopes(t.tsym.members());
  2089             t = types.supertype(t);
  2093 /* ***************************************************************************
  2094  *  Name resolution
  2095  *  Naming conventions are as for symbol lookup
  2096  *  Unlike the find... methods these methods will report access errors
  2097  ****************************************************************************/
  2099     /** Resolve an unqualified (non-method) identifier.
  2100      *  @param pos       The position to use for error reporting.
  2101      *  @param env       The environment current at the identifier use.
  2102      *  @param name      The identifier's name.
  2103      *  @param kind      The set of admissible symbol kinds for the identifier.
  2104      */
  2105     Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env,
  2106                         Name name, int kind) {
  2107         return accessBase(
  2108             findIdent(env, name, kind),
  2109             pos, env.enclClass.sym.type, name, false);
  2112     /** Resolve an unqualified method identifier.
  2113      *  @param pos       The position to use for error reporting.
  2114      *  @param env       The environment current at the method invocation.
  2115      *  @param name      The identifier's name.
  2116      *  @param argtypes  The types of the invocation's value arguments.
  2117      *  @param typeargtypes  The types of the invocation's type arguments.
  2118      */
  2119     Symbol resolveMethod(DiagnosticPosition pos,
  2120                          Env<AttrContext> env,
  2121                          Name name,
  2122                          List<Type> argtypes,
  2123                          List<Type> typeargtypes) {
  2124         return lookupMethod(env, pos, env.enclClass.sym, new BasicLookupHelper(name, env.enclClass.sym.type, argtypes, typeargtypes) {
  2125             @Override
  2126             Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2127                 return findFun(env, name, argtypes, typeargtypes,
  2128                         phase.isBoxingRequired(),
  2129                         phase.isVarargsRequired());
  2131         });
  2134     /** Resolve a qualified method identifier
  2135      *  @param pos       The position to use for error reporting.
  2136      *  @param env       The environment current at the method invocation.
  2137      *  @param site      The type of the qualifying expression, in which
  2138      *                   identifier is searched.
  2139      *  @param name      The identifier's name.
  2140      *  @param argtypes  The types of the invocation's value arguments.
  2141      *  @param typeargtypes  The types of the invocation's type arguments.
  2142      */
  2143     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
  2144                                   Type site, Name name, List<Type> argtypes,
  2145                                   List<Type> typeargtypes) {
  2146         return resolveQualifiedMethod(pos, env, site.tsym, site, name, argtypes, typeargtypes);
  2148     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
  2149                                   Symbol location, Type site, Name name, List<Type> argtypes,
  2150                                   List<Type> typeargtypes) {
  2151         return resolveQualifiedMethod(new MethodResolutionContext(), pos, env, location, site, name, argtypes, typeargtypes);
  2153     private Symbol resolveQualifiedMethod(MethodResolutionContext resolveContext,
  2154                                   DiagnosticPosition pos, Env<AttrContext> env,
  2155                                   Symbol location, Type site, Name name, List<Type> argtypes,
  2156                                   List<Type> typeargtypes) {
  2157         return lookupMethod(env, pos, location, resolveContext, new BasicLookupHelper(name, site, argtypes, typeargtypes) {
  2158             @Override
  2159             Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2160                 return findMethod(env, site, name, argtypes, typeargtypes,
  2161                         phase.isBoxingRequired(),
  2162                         phase.isVarargsRequired(), false);
  2164             @Override
  2165             Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2166                 if (sym.kind >= AMBIGUOUS) {
  2167                     sym = super.access(env, pos, location, sym);
  2168                 } else if (allowMethodHandles) {
  2169                     MethodSymbol msym = (MethodSymbol)sym;
  2170                     if (msym.isSignaturePolymorphic(types)) {
  2171                         return findPolymorphicSignatureInstance(env, sym, argtypes);
  2174                 return sym;
  2176         });
  2179     /** Find or create an implicit method of exactly the given type (after erasure).
  2180      *  Searches in a side table, not the main scope of the site.
  2181      *  This emulates the lookup process required by JSR 292 in JVM.
  2182      *  @param env       Attribution environment
  2183      *  @param spMethod  signature polymorphic method - i.e. MH.invokeExact
  2184      *  @param argtypes  The required argument types
  2185      */
  2186     Symbol findPolymorphicSignatureInstance(Env<AttrContext> env,
  2187                                             final Symbol spMethod,
  2188                                             List<Type> argtypes) {
  2189         Type mtype = infer.instantiatePolymorphicSignatureInstance(env,
  2190                 (MethodSymbol)spMethod, currentResolutionContext, argtypes);
  2191         for (Symbol sym : polymorphicSignatureScope.getElementsByName(spMethod.name)) {
  2192             if (types.isSameType(mtype, sym.type)) {
  2193                return sym;
  2197         // create the desired method
  2198         long flags = ABSTRACT | HYPOTHETICAL | spMethod.flags() & Flags.AccessFlags;
  2199         Symbol msym = new MethodSymbol(flags, spMethod.name, mtype, spMethod.owner) {
  2200             @Override
  2201             public Symbol baseSymbol() {
  2202                 return spMethod;
  2204         };
  2205         polymorphicSignatureScope.enter(msym);
  2206         return msym;
  2209     /** Resolve a qualified method identifier, throw a fatal error if not
  2210      *  found.
  2211      *  @param pos       The position to use for error reporting.
  2212      *  @param env       The environment current at the method invocation.
  2213      *  @param site      The type of the qualifying expression, in which
  2214      *                   identifier is searched.
  2215      *  @param name      The identifier's name.
  2216      *  @param argtypes  The types of the invocation's value arguments.
  2217      *  @param typeargtypes  The types of the invocation's type arguments.
  2218      */
  2219     public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env,
  2220                                         Type site, Name name,
  2221                                         List<Type> argtypes,
  2222                                         List<Type> typeargtypes) {
  2223         MethodResolutionContext resolveContext = new MethodResolutionContext();
  2224         resolveContext.internalResolution = true;
  2225         Symbol sym = resolveQualifiedMethod(resolveContext, pos, env, site.tsym,
  2226                 site, name, argtypes, typeargtypes);
  2227         if (sym.kind == MTH) return (MethodSymbol)sym;
  2228         else throw new FatalError(
  2229                  diags.fragment("fatal.err.cant.locate.meth",
  2230                                 name));
  2233     /** Resolve constructor.
  2234      *  @param pos       The position to use for error reporting.
  2235      *  @param env       The environment current at the constructor invocation.
  2236      *  @param site      The type of class for which a constructor is searched.
  2237      *  @param argtypes  The types of the constructor invocation's value
  2238      *                   arguments.
  2239      *  @param typeargtypes  The types of the constructor invocation's type
  2240      *                   arguments.
  2241      */
  2242     Symbol resolveConstructor(DiagnosticPosition pos,
  2243                               Env<AttrContext> env,
  2244                               Type site,
  2245                               List<Type> argtypes,
  2246                               List<Type> typeargtypes) {
  2247         return resolveConstructor(new MethodResolutionContext(), pos, env, site, argtypes, typeargtypes);
  2250     private Symbol resolveConstructor(MethodResolutionContext resolveContext,
  2251                               final DiagnosticPosition pos,
  2252                               Env<AttrContext> env,
  2253                               Type site,
  2254                               List<Type> argtypes,
  2255                               List<Type> typeargtypes) {
  2256         return lookupMethod(env, pos, site.tsym, resolveContext, new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
  2257             @Override
  2258             Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2259                 return findConstructor(pos, env, site, argtypes, typeargtypes,
  2260                         phase.isBoxingRequired(),
  2261                         phase.isVarargsRequired());
  2263         });
  2266     /** Resolve a constructor, throw a fatal error if not found.
  2267      *  @param pos       The position to use for error reporting.
  2268      *  @param env       The environment current at the method invocation.
  2269      *  @param site      The type to be constructed.
  2270      *  @param argtypes  The types of the invocation's value arguments.
  2271      *  @param typeargtypes  The types of the invocation's type arguments.
  2272      */
  2273     public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  2274                                         Type site,
  2275                                         List<Type> argtypes,
  2276                                         List<Type> typeargtypes) {
  2277         MethodResolutionContext resolveContext = new MethodResolutionContext();
  2278         resolveContext.internalResolution = true;
  2279         Symbol sym = resolveConstructor(resolveContext, pos, env, site, argtypes, typeargtypes);
  2280         if (sym.kind == MTH) return (MethodSymbol)sym;
  2281         else throw new FatalError(
  2282                  diags.fragment("fatal.err.cant.locate.ctor", site));
  2285     Symbol findConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  2286                               Type site, List<Type> argtypes,
  2287                               List<Type> typeargtypes,
  2288                               boolean allowBoxing,
  2289                               boolean useVarargs) {
  2290         Symbol sym = findMethod(env, site,
  2291                                     names.init, argtypes,
  2292                                     typeargtypes, allowBoxing,
  2293                                     useVarargs, false);
  2294         chk.checkDeprecated(pos, env.info.scope.owner, sym);
  2295         return sym;
  2298     /** Resolve constructor using diamond inference.
  2299      *  @param pos       The position to use for error reporting.
  2300      *  @param env       The environment current at the constructor invocation.
  2301      *  @param site      The type of class for which a constructor is searched.
  2302      *                   The scope of this class has been touched in attribution.
  2303      *  @param argtypes  The types of the constructor invocation's value
  2304      *                   arguments.
  2305      *  @param typeargtypes  The types of the constructor invocation's type
  2306      *                   arguments.
  2307      */
  2308     Symbol resolveDiamond(DiagnosticPosition pos,
  2309                               Env<AttrContext> env,
  2310                               Type site,
  2311                               List<Type> argtypes,
  2312                               List<Type> typeargtypes) {
  2313         return lookupMethod(env, pos, site.tsym, new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
  2314             @Override
  2315             Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2316                 return findDiamond(env, site, argtypes, typeargtypes,
  2317                         phase.isBoxingRequired(),
  2318                         phase.isVarargsRequired());
  2320             @Override
  2321             Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2322                 if (sym.kind >= AMBIGUOUS) {
  2323                     final JCDiagnostic details = sym.kind == WRONG_MTH ?
  2324                                     ((InapplicableSymbolError)sym).errCandidate().details :
  2325                                     null;
  2326                     sym = new InapplicableSymbolError(sym.kind, "diamondError", currentResolutionContext) {
  2327                         @Override
  2328                         JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos,
  2329                                 Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
  2330                             String key = details == null ?
  2331                                 "cant.apply.diamond" :
  2332                                 "cant.apply.diamond.1";
  2333                             return diags.create(dkind, log.currentSource(), pos, key,
  2334                                     diags.fragment("diamond", site.tsym), details);
  2336                     };
  2337                     sym = accessMethod(sym, pos, site, names.init, true, argtypes, typeargtypes);
  2338                     env.info.pendingResolutionPhase = currentResolutionContext.step;
  2340                 return sym;
  2342         });
  2345     /** This method scans all the constructor symbol in a given class scope -
  2346      *  assuming that the original scope contains a constructor of the kind:
  2347      *  {@code Foo(X x, Y y)}, where X,Y are class type-variables declared in Foo,
  2348      *  a method check is executed against the modified constructor type:
  2349      *  {@code <X,Y>Foo<X,Y>(X x, Y y)}. This is crucial in order to enable diamond
  2350      *  inference. The inferred return type of the synthetic constructor IS
  2351      *  the inferred type for the diamond operator.
  2352      */
  2353     private Symbol findDiamond(Env<AttrContext> env,
  2354                               Type site,
  2355                               List<Type> argtypes,
  2356                               List<Type> typeargtypes,
  2357                               boolean allowBoxing,
  2358                               boolean useVarargs) {
  2359         Symbol bestSoFar = methodNotFound;
  2360         for (Scope.Entry e = site.tsym.members().lookup(names.init);
  2361              e.scope != null;
  2362              e = e.next()) {
  2363             final Symbol sym = e.sym;
  2364             //- System.out.println(" e " + e.sym);
  2365             if (sym.kind == MTH &&
  2366                 (sym.flags_field & SYNTHETIC) == 0) {
  2367                     List<Type> oldParams = e.sym.type.hasTag(FORALL) ?
  2368                             ((ForAll)sym.type).tvars :
  2369                             List.<Type>nil();
  2370                     Type constrType = new ForAll(site.tsym.type.getTypeArguments().appendList(oldParams),
  2371                             types.createMethodTypeWithReturn(sym.type.asMethodType(), site));
  2372                     MethodSymbol newConstr = new MethodSymbol(sym.flags(), names.init, constrType, site.tsym) {
  2373                         @Override
  2374                         public Symbol baseSymbol() {
  2375                             return sym;
  2377                     };
  2378                     bestSoFar = selectBest(env, site, argtypes, typeargtypes,
  2379                             newConstr,
  2380                             bestSoFar,
  2381                             allowBoxing,
  2382                             useVarargs,
  2383                             false);
  2386         return bestSoFar;
  2391     /** Resolve operator.
  2392      *  @param pos       The position to use for error reporting.
  2393      *  @param optag     The tag of the operation tree.
  2394      *  @param env       The environment current at the operation.
  2395      *  @param argtypes  The types of the operands.
  2396      */
  2397     Symbol resolveOperator(DiagnosticPosition pos, JCTree.Tag optag,
  2398                            Env<AttrContext> env, List<Type> argtypes) {
  2399         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  2400         try {
  2401             currentResolutionContext = new MethodResolutionContext();
  2402             Name name = treeinfo.operatorName(optag);
  2403             env.info.pendingResolutionPhase = currentResolutionContext.step = BASIC;
  2404             Symbol sym = findMethod(env, syms.predefClass.type, name, argtypes,
  2405                                     null, false, false, true);
  2406             if (boxingEnabled && sym.kind >= WRONG_MTHS)
  2407                 env.info.pendingResolutionPhase = currentResolutionContext.step = BOX;
  2408                 sym = findMethod(env, syms.predefClass.type, name, argtypes,
  2409                                  null, true, false, true);
  2410             return accessMethod(sym, pos, env.enclClass.sym.type, name,
  2411                           false, argtypes, null);
  2413         finally {
  2414             currentResolutionContext = prevResolutionContext;
  2418     /** Resolve operator.
  2419      *  @param pos       The position to use for error reporting.
  2420      *  @param optag     The tag of the operation tree.
  2421      *  @param env       The environment current at the operation.
  2422      *  @param arg       The type of the operand.
  2423      */
  2424     Symbol resolveUnaryOperator(DiagnosticPosition pos, JCTree.Tag optag, Env<AttrContext> env, Type arg) {
  2425         return resolveOperator(pos, optag, env, List.of(arg));
  2428     /** Resolve binary operator.
  2429      *  @param pos       The position to use for error reporting.
  2430      *  @param optag     The tag of the operation tree.
  2431      *  @param env       The environment current at the operation.
  2432      *  @param left      The types of the left operand.
  2433      *  @param right     The types of the right operand.
  2434      */
  2435     Symbol resolveBinaryOperator(DiagnosticPosition pos,
  2436                                  JCTree.Tag optag,
  2437                                  Env<AttrContext> env,
  2438                                  Type left,
  2439                                  Type right) {
  2440         return resolveOperator(pos, optag, env, List.of(left, right));
  2443     /**
  2444      * Resolution of member references is typically done as a single
  2445      * overload resolution step, where the argument types A are inferred from
  2446      * the target functional descriptor.
  2448      * If the member reference is a method reference with a type qualifier,
  2449      * a two-step lookup process is performed. The first step uses the
  2450      * expected argument list A, while the second step discards the first
  2451      * type from A (which is treated as a receiver type).
  2453      * There are two cases in which inference is performed: (i) if the member
  2454      * reference is a constructor reference and the qualifier type is raw - in
  2455      * which case diamond inference is used to infer a parameterization for the
  2456      * type qualifier; (ii) if the member reference is an unbound reference
  2457      * where the type qualifier is raw - in that case, during the unbound lookup
  2458      * the receiver argument type is used to infer an instantiation for the raw
  2459      * qualifier type.
  2461      * When a multi-step resolution process is exploited, it is an error
  2462      * if two candidates are found (ambiguity).
  2464      * This routine returns a pair (T,S), where S is the member reference symbol,
  2465      * and T is the type of the class in which S is defined. This is necessary as
  2466      * the type T might be dynamically inferred (i.e. if constructor reference
  2467      * has a raw qualifier).
  2468      */
  2469     Pair<Symbol, ReferenceLookupHelper> resolveMemberReference(DiagnosticPosition pos,
  2470                                   Env<AttrContext> env,
  2471                                   JCMemberReference referenceTree,
  2472                                   Type site,
  2473                                   Name name, List<Type> argtypes,
  2474                                   List<Type> typeargtypes,
  2475                                   boolean boxingAllowed) {
  2476         MethodResolutionPhase maxPhase = boxingAllowed ? VARARITY : BASIC;
  2478         ReferenceLookupHelper boundLookupHelper;
  2479         if (!name.equals(names.init)) {
  2480             //method reference
  2481             boundLookupHelper =
  2482                     new MethodReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
  2483         } else if (site.hasTag(ARRAY)) {
  2484             //array constructor reference
  2485             boundLookupHelper =
  2486                     new ArrayConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase);
  2487         } else {
  2488             //class constructor reference
  2489             boundLookupHelper =
  2490                     new ConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase);
  2493         //step 1 - bound lookup
  2494         Env<AttrContext> boundEnv = env.dup(env.tree, env.info.dup());
  2495         Symbol boundSym = lookupMethod(boundEnv, env.tree.pos(), site.tsym, boundLookupHelper);
  2497         //step 2 - unbound lookup
  2498         ReferenceLookupHelper unboundLookupHelper = boundLookupHelper.unboundLookup();
  2499         Env<AttrContext> unboundEnv = env.dup(env.tree, env.info.dup());
  2500         Symbol unboundSym = lookupMethod(unboundEnv, env.tree.pos(), site.tsym, unboundLookupHelper);
  2502         //merge results
  2503         Pair<Symbol, ReferenceLookupHelper> res;
  2504         if (!lookupSuccess(unboundSym)) {
  2505             res = new Pair<Symbol, ReferenceLookupHelper>(boundSym, boundLookupHelper);
  2506             env.info.pendingResolutionPhase = boundEnv.info.pendingResolutionPhase;
  2507         } else if (lookupSuccess(boundSym)) {
  2508             res = new Pair<Symbol, ReferenceLookupHelper>(ambiguityError(boundSym, unboundSym), boundLookupHelper);
  2509             env.info.pendingResolutionPhase = boundEnv.info.pendingResolutionPhase;
  2510         } else {
  2511             res = new Pair<Symbol, ReferenceLookupHelper>(unboundSym, unboundLookupHelper);
  2512             env.info.pendingResolutionPhase = unboundEnv.info.pendingResolutionPhase;
  2515         return res;
  2517     //private
  2518         boolean lookupSuccess(Symbol s) {
  2519             return s.kind == MTH || s.kind == AMBIGUOUS;
  2522     /**
  2523      * Helper for defining custom method-like lookup logic; a lookup helper
  2524      * provides hooks for (i) the actual lookup logic and (ii) accessing the
  2525      * lookup result (this step might result in compiler diagnostics to be generated)
  2526      */
  2527     abstract class LookupHelper {
  2529         /** name of the symbol to lookup */
  2530         Name name;
  2532         /** location in which the lookup takes place */
  2533         Type site;
  2535         /** actual types used during the lookup */
  2536         List<Type> argtypes;
  2538         /** type arguments used during the lookup */
  2539         List<Type> typeargtypes;
  2541         /** Max overload resolution phase handled by this helper */
  2542         MethodResolutionPhase maxPhase;
  2544         LookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2545             this.name = name;
  2546             this.site = site;
  2547             this.argtypes = argtypes;
  2548             this.typeargtypes = typeargtypes;
  2549             this.maxPhase = maxPhase;
  2552         /**
  2553          * Should lookup stop at given phase with given result
  2554          */
  2555         protected boolean shouldStop(Symbol sym, MethodResolutionPhase phase) {
  2556             return phase.ordinal() > maxPhase.ordinal() ||
  2557                     sym.kind < ERRONEOUS || sym.kind == AMBIGUOUS;
  2560         /**
  2561          * Search for a symbol under a given overload resolution phase - this method
  2562          * is usually called several times, once per each overload resolution phase
  2563          */
  2564         abstract Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase);
  2566         /**
  2567          * Validate the result of the lookup
  2568          */
  2569         abstract Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym);
  2572     abstract class BasicLookupHelper extends LookupHelper {
  2574         BasicLookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes) {
  2575             super(name, site, argtypes, typeargtypes, MethodResolutionPhase.VARARITY);
  2578         @Override
  2579         Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2580             if (sym.kind == AMBIGUOUS) {
  2581                 AmbiguityError a_err = (AmbiguityError)sym;
  2582                 sym = a_err.mergeAbstracts(site);
  2584             if (sym.kind >= AMBIGUOUS) {
  2585                 //if nothing is found return the 'first' error
  2586                 sym = accessMethod(sym, pos, location, site, name, true, argtypes, typeargtypes);
  2588             return sym;
  2592     /**
  2593      * Helper class for member reference lookup. A reference lookup helper
  2594      * defines the basic logic for member reference lookup; a method gives
  2595      * access to an 'unbound' helper used to perform an unbound member
  2596      * reference lookup.
  2597      */
  2598     abstract class ReferenceLookupHelper extends LookupHelper {
  2600         /** The member reference tree */
  2601         JCMemberReference referenceTree;
  2603         ReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
  2604                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2605             super(name, site, argtypes, typeargtypes, maxPhase);
  2606             this.referenceTree = referenceTree;
  2610         /**
  2611          * Returns an unbound version of this lookup helper. By default, this
  2612          * method returns an dummy lookup helper.
  2613          */
  2614         ReferenceLookupHelper unboundLookup() {
  2615             //dummy loopkup helper that always return 'methodNotFound'
  2616             return new ReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase) {
  2617                 @Override
  2618                 ReferenceLookupHelper unboundLookup() {
  2619                     return this;
  2621                 @Override
  2622                 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2623                     return methodNotFound;
  2625                 @Override
  2626                 ReferenceKind referenceKind(Symbol sym) {
  2627                     Assert.error();
  2628                     return null;
  2630             };
  2633         /**
  2634          * Get the kind of the member reference
  2635          */
  2636         abstract JCMemberReference.ReferenceKind referenceKind(Symbol sym);
  2638         Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2639             if (sym.kind == AMBIGUOUS) {
  2640                 AmbiguityError a_err = (AmbiguityError)sym;
  2641                 sym = a_err.mergeAbstracts(site);
  2643             //skip error reporting
  2644             return sym;
  2648     /**
  2649      * Helper class for method reference lookup. The lookup logic is based
  2650      * upon Resolve.findMethod; in certain cases, this helper class has a
  2651      * corresponding unbound helper class (see UnboundMethodReferenceLookupHelper).
  2652      * In such cases, non-static lookup results are thrown away.
  2653      */
  2654     class MethodReferenceLookupHelper extends ReferenceLookupHelper {
  2656         MethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
  2657                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2658             super(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
  2661         protected Symbol lookupReferenceInternal(Env<AttrContext> env, MethodResolutionPhase phase) {
  2662             return findMethod(env, site, name, argtypes, typeargtypes,
  2663                     phase.isBoxingRequired(), phase.isVarargsRequired(), syms.operatorNames.contains(name));
  2666         protected Symbol adjustLookupResult(Env<AttrContext> env, Symbol sym) {
  2667             return !TreeInfo.isStaticSelector(referenceTree.expr, names) ||
  2668                         sym.kind != MTH ||
  2669                         sym.isStatic() ? sym : new StaticError(sym);
  2672         @Override
  2673         final Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2674             return adjustLookupResult(env, lookupReferenceInternal(env, phase));
  2677         @Override
  2678         ReferenceLookupHelper unboundLookup() {
  2679             if (TreeInfo.isStaticSelector(referenceTree.expr, names) &&
  2680                     argtypes.nonEmpty() &&
  2681                     types.isSubtypeUnchecked(argtypes.head, site)) {
  2682                 return new UnboundMethodReferenceLookupHelper(referenceTree, name,
  2683                         site, argtypes, typeargtypes, maxPhase);
  2684             } else {
  2685                 return super.unboundLookup();
  2689         @Override
  2690         ReferenceKind referenceKind(Symbol sym) {
  2691             if (sym.isStatic()) {
  2692                 return ReferenceKind.STATIC;
  2693             } else {
  2694                 Name selName = TreeInfo.name(referenceTree.getQualifierExpression());
  2695                 return selName != null && selName == names._super ?
  2696                         ReferenceKind.SUPER :
  2697                         ReferenceKind.BOUND;
  2702     /**
  2703      * Helper class for unbound method reference lookup. Essentially the same
  2704      * as the basic method reference lookup helper; main difference is that static
  2705      * lookup results are thrown away. If qualifier type is raw, an attempt to
  2706      * infer a parameterized type is made using the first actual argument (that
  2707      * would otherwise be ignored during the lookup).
  2708      */
  2709     class UnboundMethodReferenceLookupHelper extends MethodReferenceLookupHelper {
  2711         UnboundMethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
  2712                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2713             super(referenceTree, name, site, argtypes.tail, typeargtypes, maxPhase);
  2714             Type asSuperSite = types.asSuper(argtypes.head, site.tsym);
  2715             if (site.isRaw() && !asSuperSite.isErroneous()) {
  2716                 this.site = asSuperSite;
  2720         @Override
  2721         protected Symbol adjustLookupResult(Env<AttrContext> env, Symbol sym) {
  2722             return sym.kind != MTH || !sym.isStatic() ? sym : new StaticError(sym);
  2725         @Override
  2726         ReferenceLookupHelper unboundLookup() {
  2727             return this;
  2730         @Override
  2731         ReferenceKind referenceKind(Symbol sym) {
  2732             return ReferenceKind.UNBOUND;
  2736     /**
  2737      * Helper class for array constructor lookup; an array constructor lookup
  2738      * is simulated by looking up a method that returns the array type specified
  2739      * as qualifier, and that accepts a single int parameter (size of the array).
  2740      */
  2741     class ArrayConstructorReferenceLookupHelper extends ReferenceLookupHelper {
  2743         ArrayConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
  2744                 List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2745             super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase);
  2748         @Override
  2749         protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2750             Scope sc = new Scope(syms.arrayClass);
  2751             MethodSymbol arrayConstr = new MethodSymbol(PUBLIC, name, null, site.tsym);
  2752             arrayConstr.type = new MethodType(List.of(syms.intType), site, List.<Type>nil(), syms.methodClass);
  2753             sc.enter(arrayConstr);
  2754             return findMethodInScope(env, site, name, argtypes, typeargtypes, sc, methodNotFound, phase.isBoxingRequired(), phase.isVarargsRequired(), false, false);
  2757         @Override
  2758         ReferenceKind referenceKind(Symbol sym) {
  2759             return ReferenceKind.ARRAY_CTOR;
  2763     /**
  2764      * Helper class for constructor reference lookup. The lookup logic is based
  2765      * upon either Resolve.findMethod or Resolve.findDiamond - depending on
  2766      * whether the constructor reference needs diamond inference (this is the case
  2767      * if the qualifier type is raw). A special erroneous symbol is returned
  2768      * if the lookup returns the constructor of an inner class and there's no
  2769      * enclosing instance in scope.
  2770      */
  2771     class ConstructorReferenceLookupHelper extends ReferenceLookupHelper {
  2773         boolean needsInference;
  2775         ConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
  2776                 List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2777             super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase);
  2778             if (site.isRaw()) {
  2779                 this.site = new ClassType(site.getEnclosingType(), site.tsym.type.getTypeArguments(), site.tsym);
  2780                 needsInference = true;
  2784         @Override
  2785         protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2786             Symbol sym = needsInference ?
  2787                 findDiamond(env, site, argtypes, typeargtypes, phase.isBoxingRequired(), phase.isVarargsRequired()) :
  2788                 findMethod(env, site, name, argtypes, typeargtypes,
  2789                         phase.isBoxingRequired(), phase.isVarargsRequired(), syms.operatorNames.contains(name));
  2790             return sym.kind != MTH ||
  2791                           site.getEnclosingType().hasTag(NONE) ||
  2792                           hasEnclosingInstance(env, site) ?
  2793                           sym : new InvalidSymbolError(Kinds.MISSING_ENCL, sym, null) {
  2794                     @Override
  2795                     JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
  2796                        return diags.create(dkind, log.currentSource(), pos,
  2797                             "cant.access.inner.cls.constr", site.tsym.name, argtypes, site.getEnclosingType());
  2799                 };
  2802         @Override
  2803         ReferenceKind referenceKind(Symbol sym) {
  2804             return site.getEnclosingType().hasTag(NONE) ?
  2805                     ReferenceKind.TOPLEVEL : ReferenceKind.IMPLICIT_INNER;
  2809     /**
  2810      * Main overload resolution routine. On each overload resolution step, a
  2811      * lookup helper class is used to perform the method/constructor lookup;
  2812      * at the end of the lookup, the helper is used to validate the results
  2813      * (this last step might trigger overload resolution diagnostics).
  2814      */
  2815     Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, LookupHelper lookupHelper) {
  2816         return lookupMethod(env, pos, location, new MethodResolutionContext(), lookupHelper);
  2819     Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location,
  2820             MethodResolutionContext resolveContext, LookupHelper lookupHelper) {
  2821         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  2822         try {
  2823             Symbol bestSoFar = methodNotFound;
  2824             currentResolutionContext = resolveContext;
  2825             for (MethodResolutionPhase phase : methodResolutionSteps) {
  2826                 if (!phase.isApplicable(boxingEnabled, varargsEnabled) ||
  2827                         lookupHelper.shouldStop(bestSoFar, phase)) break;
  2828                 MethodResolutionPhase prevPhase = currentResolutionContext.step;
  2829                 Symbol prevBest = bestSoFar;
  2830                 currentResolutionContext.step = phase;
  2831                 bestSoFar = phase.mergeResults(bestSoFar, lookupHelper.lookup(env, phase));
  2832                 env.info.pendingResolutionPhase = (prevBest == bestSoFar) ? prevPhase : phase;
  2834             return lookupHelper.access(env, pos, location, bestSoFar);
  2835         } finally {
  2836             currentResolutionContext = prevResolutionContext;
  2840     /**
  2841      * Resolve `c.name' where name == this or name == super.
  2842      * @param pos           The position to use for error reporting.
  2843      * @param env           The environment current at the expression.
  2844      * @param c             The qualifier.
  2845      * @param name          The identifier's name.
  2846      */
  2847     Symbol resolveSelf(DiagnosticPosition pos,
  2848                        Env<AttrContext> env,
  2849                        TypeSymbol c,
  2850                        Name name) {
  2851         Env<AttrContext> env1 = env;
  2852         boolean staticOnly = false;
  2853         while (env1.outer != null) {
  2854             if (isStatic(env1)) staticOnly = true;
  2855             if (env1.enclClass.sym == c) {
  2856                 Symbol sym = env1.info.scope.lookup(name).sym;
  2857                 if (sym != null) {
  2858                     if (staticOnly) sym = new StaticError(sym);
  2859                     return accessBase(sym, pos, env.enclClass.sym.type,
  2860                                   name, true);
  2863             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  2864             env1 = env1.outer;
  2866         if (allowDefaultMethods && c.isInterface() &&
  2867                 name == names._super && !isStatic(env) &&
  2868                 types.isDirectSuperInterface(c, env.enclClass.sym)) {
  2869             //this might be a default super call if one of the superinterfaces is 'c'
  2870             for (Type t : pruneInterfaces(env.enclClass.type)) {
  2871                 if (t.tsym == c) {
  2872                     env.info.defaultSuperCallSite = t;
  2873                     return new VarSymbol(0, names._super,
  2874                             types.asSuper(env.enclClass.type, c), env.enclClass.sym);
  2877             //find a direct superinterface that is a subtype of 'c'
  2878             for (Type i : types.interfaces(env.enclClass.type)) {
  2879                 if (i.tsym.isSubClass(c, types) && i.tsym != c) {
  2880                     log.error(pos, "illegal.default.super.call", c,
  2881                             diags.fragment("redundant.supertype", c, i));
  2882                     return syms.errSymbol;
  2885             Assert.error();
  2887         log.error(pos, "not.encl.class", c);
  2888         return syms.errSymbol;
  2890     //where
  2891     private List<Type> pruneInterfaces(Type t) {
  2892         ListBuffer<Type> result = ListBuffer.lb();
  2893         for (Type t1 : types.interfaces(t)) {
  2894             boolean shouldAdd = true;
  2895             for (Type t2 : types.interfaces(t)) {
  2896                 if (t1 != t2 && types.isSubtypeNoCapture(t2, t1)) {
  2897                     shouldAdd = false;
  2900             if (shouldAdd) {
  2901                 result.append(t1);
  2904         return result.toList();
  2908     /**
  2909      * Resolve `c.this' for an enclosing class c that contains the
  2910      * named member.
  2911      * @param pos           The position to use for error reporting.
  2912      * @param env           The environment current at the expression.
  2913      * @param member        The member that must be contained in the result.
  2914      */
  2915     Symbol resolveSelfContaining(DiagnosticPosition pos,
  2916                                  Env<AttrContext> env,
  2917                                  Symbol member,
  2918                                  boolean isSuperCall) {
  2919         Symbol sym = resolveSelfContainingInternal(env, member, isSuperCall);
  2920         if (sym == null) {
  2921             log.error(pos, "encl.class.required", member);
  2922             return syms.errSymbol;
  2923         } else {
  2924             return accessBase(sym, pos, env.enclClass.sym.type, sym.name, true);
  2928     boolean hasEnclosingInstance(Env<AttrContext> env, Type type) {
  2929         Symbol encl = resolveSelfContainingInternal(env, type.tsym, false);
  2930         return encl != null && encl.kind < ERRONEOUS;
  2933     private Symbol resolveSelfContainingInternal(Env<AttrContext> env,
  2934                                  Symbol member,
  2935                                  boolean isSuperCall) {
  2936         Name name = names._this;
  2937         Env<AttrContext> env1 = isSuperCall ? env.outer : env;
  2938         boolean staticOnly = false;
  2939         if (env1 != null) {
  2940             while (env1 != null && env1.outer != null) {
  2941                 if (isStatic(env1)) staticOnly = true;
  2942                 if (env1.enclClass.sym.isSubClass(member.owner, types)) {
  2943                     Symbol sym = env1.info.scope.lookup(name).sym;
  2944                     if (sym != null) {
  2945                         if (staticOnly) sym = new StaticError(sym);
  2946                         return sym;
  2949                 if ((env1.enclClass.sym.flags() & STATIC) != 0)
  2950                     staticOnly = true;
  2951                 env1 = env1.outer;
  2954         return null;
  2957     /**
  2958      * Resolve an appropriate implicit this instance for t's container.
  2959      * JLS 8.8.5.1 and 15.9.2
  2960      */
  2961     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
  2962         return resolveImplicitThis(pos, env, t, false);
  2965     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t, boolean isSuperCall) {
  2966         Type thisType = (((t.tsym.owner.kind & (MTH|VAR)) != 0)
  2967                          ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
  2968                          : resolveSelfContaining(pos, env, t.tsym, isSuperCall)).type;
  2969         if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
  2970             log.error(pos, "cant.ref.before.ctor.called", "this");
  2971         return thisType;
  2974 /* ***************************************************************************
  2975  *  ResolveError classes, indicating error situations when accessing symbols
  2976  ****************************************************************************/
  2978     //used by TransTypes when checking target type of synthetic cast
  2979     public void logAccessErrorInternal(Env<AttrContext> env, JCTree tree, Type type) {
  2980         AccessError error = new AccessError(env, env.enclClass.type, type.tsym);
  2981         logResolveError(error, tree.pos(), env.enclClass.sym, env.enclClass.type, null, null, null);
  2983     //where
  2984     private void logResolveError(ResolveError error,
  2985             DiagnosticPosition pos,
  2986             Symbol location,
  2987             Type site,
  2988             Name name,
  2989             List<Type> argtypes,
  2990             List<Type> typeargtypes) {
  2991         JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
  2992                 pos, location, site, name, argtypes, typeargtypes);
  2993         if (d != null) {
  2994             d.setFlag(DiagnosticFlag.RESOLVE_ERROR);
  2995             log.report(d);
  2999     private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
  3001     public Object methodArguments(List<Type> argtypes) {
  3002         if (argtypes == null || argtypes.isEmpty()) {
  3003             return noArgs;
  3004         } else {
  3005             ListBuffer<Object> diagArgs = ListBuffer.lb();
  3006             for (Type t : argtypes) {
  3007                 if (t.hasTag(DEFERRED)) {
  3008                     diagArgs.append(((DeferredAttr.DeferredType)t).tree);
  3009                 } else {
  3010                     diagArgs.append(t);
  3013             return diagArgs;
  3017     /**
  3018      * Root class for resolution errors. Subclass of ResolveError
  3019      * represent a different kinds of resolution error - as such they must
  3020      * specify how they map into concrete compiler diagnostics.
  3021      */
  3022     abstract class ResolveError extends Symbol {
  3024         /** The name of the kind of error, for debugging only. */
  3025         final String debugName;
  3027         ResolveError(int kind, String debugName) {
  3028             super(kind, 0, null, null, null);
  3029             this.debugName = debugName;
  3032         @Override
  3033         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
  3034             throw new AssertionError();
  3037         @Override
  3038         public String toString() {
  3039             return debugName;
  3042         @Override
  3043         public boolean exists() {
  3044             return false;
  3047         /**
  3048          * Create an external representation for this erroneous symbol to be
  3049          * used during attribution - by default this returns the symbol of a
  3050          * brand new error type which stores the original type found
  3051          * during resolution.
  3053          * @param name     the name used during resolution
  3054          * @param location the location from which the symbol is accessed
  3055          */
  3056         protected Symbol access(Name name, TypeSymbol location) {
  3057             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  3060         /**
  3061          * Create a diagnostic representing this resolution error.
  3063          * @param dkind     The kind of the diagnostic to be created (e.g error).
  3064          * @param pos       The position to be used for error reporting.
  3065          * @param site      The original type from where the selection took place.
  3066          * @param name      The name of the symbol to be resolved.
  3067          * @param argtypes  The invocation's value arguments,
  3068          *                  if we looked for a method.
  3069          * @param typeargtypes  The invocation's type arguments,
  3070          *                      if we looked for a method.
  3071          */
  3072         abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3073                 DiagnosticPosition pos,
  3074                 Symbol location,
  3075                 Type site,
  3076                 Name name,
  3077                 List<Type> argtypes,
  3078                 List<Type> typeargtypes);
  3081     /**
  3082      * This class is the root class of all resolution errors caused by
  3083      * an invalid symbol being found during resolution.
  3084      */
  3085     abstract class InvalidSymbolError extends ResolveError {
  3087         /** The invalid symbol found during resolution */
  3088         Symbol sym;
  3090         InvalidSymbolError(int kind, Symbol sym, String debugName) {
  3091             super(kind, debugName);
  3092             this.sym = sym;
  3095         @Override
  3096         public boolean exists() {
  3097             return true;
  3100         @Override
  3101         public String toString() {
  3102              return super.toString() + " wrongSym=" + sym;
  3105         @Override
  3106         public Symbol access(Name name, TypeSymbol location) {
  3107             if ((sym.kind & ERRONEOUS) == 0 && (sym.kind & TYP) != 0)
  3108                 return types.createErrorType(name, location, sym.type).tsym;
  3109             else
  3110                 return sym;
  3114     /**
  3115      * InvalidSymbolError error class indicating that a symbol matching a
  3116      * given name does not exists in a given site.
  3117      */
  3118     class SymbolNotFoundError extends ResolveError {
  3120         SymbolNotFoundError(int kind) {
  3121             super(kind, "symbol not found error");
  3124         @Override
  3125         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3126                 DiagnosticPosition pos,
  3127                 Symbol location,
  3128                 Type site,
  3129                 Name name,
  3130                 List<Type> argtypes,
  3131                 List<Type> typeargtypes) {
  3132             argtypes = argtypes == null ? List.<Type>nil() : argtypes;
  3133             typeargtypes = typeargtypes == null ? List.<Type>nil() : typeargtypes;
  3134             if (name == names.error)
  3135                 return null;
  3137             if (syms.operatorNames.contains(name)) {
  3138                 boolean isUnaryOp = argtypes.size() == 1;
  3139                 String key = argtypes.size() == 1 ?
  3140                     "operator.cant.be.applied" :
  3141                     "operator.cant.be.applied.1";
  3142                 Type first = argtypes.head;
  3143                 Type second = !isUnaryOp ? argtypes.tail.head : null;
  3144                 return diags.create(dkind, log.currentSource(), pos,
  3145                         key, name, first, second);
  3147             boolean hasLocation = false;
  3148             if (location == null) {
  3149                 location = site.tsym;
  3151             if (!location.name.isEmpty()) {
  3152                 if (location.kind == PCK && !site.tsym.exists()) {
  3153                     return diags.create(dkind, log.currentSource(), pos,
  3154                         "doesnt.exist", location);
  3156                 hasLocation = !location.name.equals(names._this) &&
  3157                         !location.name.equals(names._super);
  3159             boolean isConstructor = kind == ABSENT_MTH && name == names.init;
  3160             KindName kindname = isConstructor ? KindName.CONSTRUCTOR : absentKind(kind);
  3161             Name idname = isConstructor ? site.tsym.name : name;
  3162             String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation);
  3163             if (hasLocation) {
  3164                 return diags.create(dkind, log.currentSource(), pos,
  3165                         errKey, kindname, idname, //symbol kindname, name
  3166                         typeargtypes, args(argtypes), //type parameters and arguments (if any)
  3167                         getLocationDiag(location, site)); //location kindname, type
  3169             else {
  3170                 return diags.create(dkind, log.currentSource(), pos,
  3171                         errKey, kindname, idname, //symbol kindname, name
  3172                         typeargtypes, args(argtypes)); //type parameters and arguments (if any)
  3175         //where
  3176         private Object args(List<Type> args) {
  3177             return args.isEmpty() ? args : methodArguments(args);
  3180         private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) {
  3181             String key = "cant.resolve";
  3182             String suffix = hasLocation ? ".location" : "";
  3183             switch (kindname) {
  3184                 case METHOD:
  3185                 case CONSTRUCTOR: {
  3186                     suffix += ".args";
  3187                     suffix += hasTypeArgs ? ".params" : "";
  3190             return key + suffix;
  3192         private JCDiagnostic getLocationDiag(Symbol location, Type site) {
  3193             if (location.kind == VAR) {
  3194                 return diags.fragment("location.1",
  3195                     kindName(location),
  3196                     location,
  3197                     location.type);
  3198             } else {
  3199                 return diags.fragment("location",
  3200                     typeKindName(site),
  3201                     site,
  3202                     null);
  3207     /**
  3208      * InvalidSymbolError error class indicating that a given symbol
  3209      * (either a method, a constructor or an operand) is not applicable
  3210      * given an actual arguments/type argument list.
  3211      */
  3212     class InapplicableSymbolError extends ResolveError {
  3214         protected MethodResolutionContext resolveContext;
  3216         InapplicableSymbolError(MethodResolutionContext context) {
  3217             this(WRONG_MTH, "inapplicable symbol error", context);
  3220         protected InapplicableSymbolError(int kind, String debugName, MethodResolutionContext context) {
  3221             super(kind, debugName);
  3222             this.resolveContext = context;
  3225         @Override
  3226         public String toString() {
  3227             return super.toString();
  3230         @Override
  3231         public boolean exists() {
  3232             return true;
  3235         @Override
  3236         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3237                 DiagnosticPosition pos,
  3238                 Symbol location,
  3239                 Type site,
  3240                 Name name,
  3241                 List<Type> argtypes,
  3242                 List<Type> typeargtypes) {
  3243             if (name == names.error)
  3244                 return null;
  3246             if (syms.operatorNames.contains(name)) {
  3247                 boolean isUnaryOp = argtypes.size() == 1;
  3248                 String key = argtypes.size() == 1 ?
  3249                     "operator.cant.be.applied" :
  3250                     "operator.cant.be.applied.1";
  3251                 Type first = argtypes.head;
  3252                 Type second = !isUnaryOp ? argtypes.tail.head : null;
  3253                 return diags.create(dkind, log.currentSource(), pos,
  3254                         key, name, first, second);
  3256             else {
  3257                 Candidate c = errCandidate();
  3258                 Symbol ws = c.sym.asMemberOf(site, types);
  3259                 return diags.create(dkind, log.currentSource(), pos,
  3260                           "cant.apply.symbol",
  3261                           kindName(ws),
  3262                           ws.name == names.init ? ws.owner.name : ws.name,
  3263                           methodArguments(ws.type.getParameterTypes()),
  3264                           methodArguments(argtypes),
  3265                           kindName(ws.owner),
  3266                           ws.owner.type,
  3267                           c.details);
  3271         @Override
  3272         public Symbol access(Name name, TypeSymbol location) {
  3273             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  3276         private Candidate errCandidate() {
  3277             Candidate bestSoFar = null;
  3278             for (Candidate c : resolveContext.candidates) {
  3279                 if (c.isApplicable()) continue;
  3280                 bestSoFar = c;
  3282             Assert.checkNonNull(bestSoFar);
  3283             return bestSoFar;
  3287     /**
  3288      * ResolveError error class indicating that a set of symbols
  3289      * (either methods, constructors or operands) is not applicable
  3290      * given an actual arguments/type argument list.
  3291      */
  3292     class InapplicableSymbolsError extends InapplicableSymbolError {
  3294         InapplicableSymbolsError(MethodResolutionContext context) {
  3295             super(WRONG_MTHS, "inapplicable symbols", context);
  3298         @Override
  3299         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3300                 DiagnosticPosition pos,
  3301                 Symbol location,
  3302                 Type site,
  3303                 Name name,
  3304                 List<Type> argtypes,
  3305                 List<Type> typeargtypes) {
  3306             if (!resolveContext.candidates.isEmpty()) {
  3307                 JCDiagnostic err = diags.create(dkind,
  3308                         log.currentSource(),
  3309                         pos,
  3310                         "cant.apply.symbols",
  3311                         name == names.init ? KindName.CONSTRUCTOR : absentKind(kind),
  3312                         name == names.init ? site.tsym.name : name,
  3313                         methodArguments(argtypes));
  3314                 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(site));
  3315             } else {
  3316                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
  3317                     location, site, name, argtypes, typeargtypes);
  3321         //where
  3322         List<JCDiagnostic> candidateDetails(Type site) {
  3323             Map<Symbol, JCDiagnostic> details = new LinkedHashMap<Symbol, JCDiagnostic>();
  3324             for (Candidate c : resolveContext.candidates) {
  3325                 if (c.isApplicable()) continue;
  3326                 JCDiagnostic detailDiag = diags.fragment("inapplicable.method",
  3327                         Kinds.kindName(c.sym),
  3328                         c.sym.location(site, types),
  3329                         c.sym.asMemberOf(site, types),
  3330                         c.details);
  3331                 details.put(c.sym, detailDiag);
  3333             return List.from(details.values());
  3337     /**
  3338      * An InvalidSymbolError error class indicating that a symbol is not
  3339      * accessible from a given site
  3340      */
  3341     class AccessError extends InvalidSymbolError {
  3343         private Env<AttrContext> env;
  3344         private Type site;
  3346         AccessError(Symbol sym) {
  3347             this(null, null, sym);
  3350         AccessError(Env<AttrContext> env, Type site, Symbol sym) {
  3351             super(HIDDEN, sym, "access error");
  3352             this.env = env;
  3353             this.site = site;
  3354             if (debugResolve)
  3355                 log.error("proc.messager", sym + " @ " + site + " is inaccessible.");
  3358         @Override
  3359         public boolean exists() {
  3360             return false;
  3363         @Override
  3364         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3365                 DiagnosticPosition pos,
  3366                 Symbol location,
  3367                 Type site,
  3368                 Name name,
  3369                 List<Type> argtypes,
  3370                 List<Type> typeargtypes) {
  3371             if (sym.owner.type.hasTag(ERROR))
  3372                 return null;
  3374             if (sym.name == names.init && sym.owner != site.tsym) {
  3375                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
  3376                         pos, location, site, name, argtypes, typeargtypes);
  3378             else if ((sym.flags() & PUBLIC) != 0
  3379                 || (env != null && this.site != null
  3380                     && !isAccessible(env, this.site))) {
  3381                 return diags.create(dkind, log.currentSource(),
  3382                         pos, "not.def.access.class.intf.cant.access",
  3383                     sym, sym.location());
  3385             else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) {
  3386                 return diags.create(dkind, log.currentSource(),
  3387                         pos, "report.access", sym,
  3388                         asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
  3389                         sym.location());
  3391             else {
  3392                 return diags.create(dkind, log.currentSource(),
  3393                         pos, "not.def.public.cant.access", sym, sym.location());
  3398     /**
  3399      * InvalidSymbolError error class indicating that an instance member
  3400      * has erroneously been accessed from a static context.
  3401      */
  3402     class StaticError extends InvalidSymbolError {
  3404         StaticError(Symbol sym) {
  3405             super(STATICERR, sym, "static 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             Symbol errSym = ((sym.kind == TYP && sym.type.hasTag(CLASS))
  3417                 ? types.erasure(sym.type).tsym
  3418                 : sym);
  3419             return diags.create(dkind, log.currentSource(), pos,
  3420                     "non-static.cant.be.ref", kindName(sym), errSym);
  3424     /**
  3425      * InvalidSymbolError error class indicating that a pair of symbols
  3426      * (either methods, constructors or operands) are ambiguous
  3427      * given an actual arguments/type argument list.
  3428      */
  3429     class AmbiguityError extends ResolveError {
  3431         /** The other maximally specific symbol */
  3432         List<Symbol> ambiguousSyms = List.nil();
  3434         @Override
  3435         public boolean exists() {
  3436             return true;
  3439         AmbiguityError(Symbol sym1, Symbol sym2) {
  3440             super(AMBIGUOUS, "ambiguity error");
  3441             ambiguousSyms = flatten(sym2).appendList(flatten(sym1));
  3444         private List<Symbol> flatten(Symbol sym) {
  3445             if (sym.kind == AMBIGUOUS) {
  3446                 return ((AmbiguityError)sym).ambiguousSyms;
  3447             } else {
  3448                 return List.of(sym);
  3452         AmbiguityError addAmbiguousSymbol(Symbol s) {
  3453             ambiguousSyms = ambiguousSyms.prepend(s);
  3454             return this;
  3457         @Override
  3458         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3459                 DiagnosticPosition pos,
  3460                 Symbol location,
  3461                 Type site,
  3462                 Name name,
  3463                 List<Type> argtypes,
  3464                 List<Type> typeargtypes) {
  3465             List<Symbol> diagSyms = ambiguousSyms.reverse();
  3466             Symbol s1 = diagSyms.head;
  3467             Symbol s2 = diagSyms.tail.head;
  3468             Name sname = s1.name;
  3469             if (sname == names.init) sname = s1.owner.name;
  3470             return diags.create(dkind, log.currentSource(),
  3471                       pos, "ref.ambiguous", sname,
  3472                       kindName(s1),
  3473                       s1,
  3474                       s1.location(site, types),
  3475                       kindName(s2),
  3476                       s2,
  3477                       s2.location(site, types));
  3480         /**
  3481          * If multiple applicable methods are found during overload and none of them
  3482          * is more specific than the others, attempt to merge their signatures.
  3483          */
  3484         Symbol mergeAbstracts(Type site) {
  3485             Symbol fst = ambiguousSyms.last();
  3486             Symbol res = fst;
  3487             for (Symbol s : ambiguousSyms.reverse()) {
  3488                 Type mt1 = types.memberType(site, res);
  3489                 Type mt2 = types.memberType(site, s);
  3490                 if ((s.flags() & ABSTRACT) == 0 ||
  3491                         !types.overrideEquivalent(mt1, mt2) ||
  3492                         !types.isSameTypes(fst.erasure(types).getParameterTypes(),
  3493                                        s.erasure(types).getParameterTypes())) {
  3494                     //ambiguity cannot be resolved
  3495                     return this;
  3496                 } else {
  3497                     Type mst = mostSpecificReturnType(mt1, mt2);
  3498                     if (mst == null) {
  3499                         // Theoretically, this can't happen, but it is possible
  3500                         // due to error recovery or mixing incompatible class files
  3501                         return this;
  3503                     Symbol mostSpecific = mst == mt1 ? res : s;
  3504                     List<Type> allThrown = chk.intersect(mt1.getThrownTypes(), mt2.getThrownTypes());
  3505                     Type newSig = types.createMethodTypeWithThrown(mostSpecific.type, allThrown);
  3506                     res = new MethodSymbol(
  3507                             mostSpecific.flags(),
  3508                             mostSpecific.name,
  3509                             newSig,
  3510                             mostSpecific.owner);
  3513             return res;
  3516         @Override
  3517         protected Symbol access(Name name, TypeSymbol location) {
  3518             Symbol firstAmbiguity = ambiguousSyms.last();
  3519             return firstAmbiguity.kind == TYP ?
  3520                     types.createErrorType(name, location, firstAmbiguity.type).tsym :
  3521                     firstAmbiguity;
  3525     enum MethodResolutionPhase {
  3526         BASIC(false, false),
  3527         BOX(true, false),
  3528         VARARITY(true, true) {
  3529             @Override
  3530             public Symbol mergeResults(Symbol bestSoFar, Symbol sym) {
  3531                 switch (sym.kind) {
  3532                     case WRONG_MTH:
  3533                         return (bestSoFar.kind == WRONG_MTH || bestSoFar.kind == WRONG_MTHS) ?
  3534                             bestSoFar :
  3535                             sym;
  3536                     case ABSENT_MTH:
  3537                         return bestSoFar;
  3538                     default:
  3539                         return sym;
  3542         };
  3544         final boolean isBoxingRequired;
  3545         final boolean isVarargsRequired;
  3547         MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) {
  3548            this.isBoxingRequired = isBoxingRequired;
  3549            this.isVarargsRequired = isVarargsRequired;
  3552         public boolean isBoxingRequired() {
  3553             return isBoxingRequired;
  3556         public boolean isVarargsRequired() {
  3557             return isVarargsRequired;
  3560         public boolean isApplicable(boolean boxingEnabled, boolean varargsEnabled) {
  3561             return (varargsEnabled || !isVarargsRequired) &&
  3562                    (boxingEnabled || !isBoxingRequired);
  3565         public Symbol mergeResults(Symbol prev, Symbol sym) {
  3566             return sym;
  3570     final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
  3572     /**
  3573      * A resolution context is used to keep track of intermediate results of
  3574      * overload resolution, such as list of method that are not applicable
  3575      * (used to generate more precise diagnostics) and so on. Resolution contexts
  3576      * can be nested - this means that when each overload resolution routine should
  3577      * work within the resolution context it created.
  3578      */
  3579     class MethodResolutionContext {
  3581         private List<Candidate> candidates = List.nil();
  3583         MethodResolutionPhase step = null;
  3585         private boolean internalResolution = false;
  3586         private DeferredAttr.AttrMode attrMode = DeferredAttr.AttrMode.SPECULATIVE;
  3588         void addInapplicableCandidate(Symbol sym, JCDiagnostic details) {
  3589             Candidate c = new Candidate(currentResolutionContext.step, sym, details, null);
  3590             candidates = candidates.append(c);
  3593         void addApplicableCandidate(Symbol sym, Type mtype) {
  3594             Candidate c = new Candidate(currentResolutionContext.step, sym, null, mtype);
  3595             candidates = candidates.append(c);
  3598         DeferredAttrContext deferredAttrContext(Symbol sym, InferenceContext inferenceContext, ResultInfo pendingResult, Warner warn) {
  3599             return deferredAttr.new DeferredAttrContext(attrMode, sym, step, inferenceContext, pendingResult != null ? pendingResult.checkContext.deferredAttrContext() : deferredAttr.emptyDeferredAttrContext, warn);
  3602         /**
  3603          * This class represents an overload resolution candidate. There are two
  3604          * kinds of candidates: applicable methods and inapplicable methods;
  3605          * applicable methods have a pointer to the instantiated method type,
  3606          * while inapplicable candidates contain further details about the
  3607          * reason why the method has been considered inapplicable.
  3608          */
  3609         class Candidate {
  3611             final MethodResolutionPhase step;
  3612             final Symbol sym;
  3613             final JCDiagnostic details;
  3614             final Type mtype;
  3616             private Candidate(MethodResolutionPhase step, Symbol sym, JCDiagnostic details, Type mtype) {
  3617                 this.step = step;
  3618                 this.sym = sym;
  3619                 this.details = details;
  3620                 this.mtype = mtype;
  3623             @Override
  3624             public boolean equals(Object o) {
  3625                 if (o instanceof Candidate) {
  3626                     Symbol s1 = this.sym;
  3627                     Symbol s2 = ((Candidate)o).sym;
  3628                     if  ((s1 != s2 &&
  3629                             (s1.overrides(s2, s1.owner.type.tsym, types, false) ||
  3630                             (s2.overrides(s1, s2.owner.type.tsym, types, false)))) ||
  3631                             ((s1.isConstructor() || s2.isConstructor()) && s1.owner != s2.owner))
  3632                         return true;
  3634                 return false;
  3637             boolean isApplicable() {
  3638                 return mtype != null;
  3642         DeferredAttr.AttrMode attrMode() {
  3643             return attrMode;
  3646         boolean internal() {
  3647             return internalResolution;
  3651     MethodResolutionContext currentResolutionContext = null;

mercurial