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

Thu, 07 Mar 2013 10:04:28 +0000

author
vromero
date
Thu, 07 Mar 2013 10:04:28 +0000
changeset 1620
3806171b52d8
parent 1610
08782b8b03ce
child 1674
b71a61d39cf7
permissions
-rw-r--r--

8009138: javac, equals-hashCode warning tuning
Reviewed-by: mcimadamore

     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.sym.type.getReturnType(), 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             return bestSoFar;
  1249         } else if (useVarargs && (sym.flags() & VARARGS) == 0) {
  1250             return bestSoFar.kind >= ERRONEOUS ?
  1251                     new BadVarargsMethod((ResolveError)bestSoFar) :
  1252                     bestSoFar;
  1254         Assert.check(sym.kind < AMBIGUOUS);
  1255         try {
  1256             Type mt = rawInstantiate(env, site, sym, null, argtypes, typeargtypes,
  1257                                allowBoxing, useVarargs, resolveMethodCheck, types.noWarnings);
  1258             if (!operator)
  1259                 currentResolutionContext.addApplicableCandidate(sym, mt);
  1260         } catch (InapplicableMethodException ex) {
  1261             if (!operator)
  1262                 currentResolutionContext.addInapplicableCandidate(sym, ex.getDiagnostic());
  1263             switch (bestSoFar.kind) {
  1264                 case ABSENT_MTH:
  1265                     return new InapplicableSymbolError(currentResolutionContext);
  1266                 case WRONG_MTH:
  1267                     if (operator) return bestSoFar;
  1268                     bestSoFar = new InapplicableSymbolsError(currentResolutionContext);
  1269                 default:
  1270                     return bestSoFar;
  1273         if (!isAccessible(env, site, sym)) {
  1274             return (bestSoFar.kind == ABSENT_MTH)
  1275                 ? new AccessError(env, site, sym)
  1276                 : bestSoFar;
  1278         return (bestSoFar.kind > AMBIGUOUS)
  1279             ? sym
  1280             : mostSpecific(argtypes, sym, bestSoFar, env, site,
  1281                            allowBoxing && operator, useVarargs);
  1284     /* Return the most specific of the two methods for a call,
  1285      *  given that both are accessible and applicable.
  1286      *  @param m1               A new candidate for most specific.
  1287      *  @param m2               The previous most specific candidate.
  1288      *  @param env              The current environment.
  1289      *  @param site             The original type from where the selection
  1290      *                          takes place.
  1291      *  @param allowBoxing Allow boxing conversions of arguments.
  1292      *  @param useVarargs Box trailing arguments into an array for varargs.
  1293      */
  1294     Symbol mostSpecific(List<Type> argtypes, Symbol m1,
  1295                         Symbol m2,
  1296                         Env<AttrContext> env,
  1297                         final Type site,
  1298                         boolean allowBoxing,
  1299                         boolean useVarargs) {
  1300         switch (m2.kind) {
  1301         case MTH:
  1302             if (m1 == m2) return m1;
  1303             boolean m1SignatureMoreSpecific =
  1304                     signatureMoreSpecific(argtypes, env, site, m1, m2, allowBoxing, useVarargs);
  1305             boolean m2SignatureMoreSpecific =
  1306                     signatureMoreSpecific(argtypes, env, site, m2, m1, allowBoxing, useVarargs);
  1307             if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) {
  1308                 Type mt1 = types.memberType(site, m1);
  1309                 Type mt2 = types.memberType(site, m2);
  1310                 if (!types.overrideEquivalent(mt1, mt2))
  1311                     return ambiguityError(m1, m2);
  1313                 // same signature; select (a) the non-bridge method, or
  1314                 // (b) the one that overrides the other, or (c) the concrete
  1315                 // one, or (d) merge both abstract signatures
  1316                 if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE))
  1317                     return ((m1.flags() & BRIDGE) != 0) ? m2 : m1;
  1319                 // if one overrides or hides the other, use it
  1320                 TypeSymbol m1Owner = (TypeSymbol)m1.owner;
  1321                 TypeSymbol m2Owner = (TypeSymbol)m2.owner;
  1322                 if (types.asSuper(m1Owner.type, m2Owner) != null &&
  1323                     ((m1.owner.flags_field & INTERFACE) == 0 ||
  1324                      (m2.owner.flags_field & INTERFACE) != 0) &&
  1325                     m1.overrides(m2, m1Owner, types, false))
  1326                     return m1;
  1327                 if (types.asSuper(m2Owner.type, m1Owner) != null &&
  1328                     ((m2.owner.flags_field & INTERFACE) == 0 ||
  1329                      (m1.owner.flags_field & INTERFACE) != 0) &&
  1330                     m2.overrides(m1, m2Owner, types, false))
  1331                     return m2;
  1332                 boolean m1Abstract = (m1.flags() & ABSTRACT) != 0;
  1333                 boolean m2Abstract = (m2.flags() & ABSTRACT) != 0;
  1334                 if (m1Abstract && !m2Abstract) return m2;
  1335                 if (m2Abstract && !m1Abstract) return m1;
  1336                 // both abstract or both concrete
  1337                 return ambiguityError(m1, m2);
  1339             if (m1SignatureMoreSpecific) return m1;
  1340             if (m2SignatureMoreSpecific) return m2;
  1341             return ambiguityError(m1, m2);
  1342         case AMBIGUOUS:
  1343             //check if m1 is more specific than all ambiguous methods in m2
  1344             AmbiguityError e = (AmbiguityError)m2;
  1345             for (Symbol s : e.ambiguousSyms) {
  1346                 if (mostSpecific(argtypes, m1, s, env, site, allowBoxing, useVarargs) != m1) {
  1347                     return e.addAmbiguousSymbol(m1);
  1350             return m1;
  1351         default:
  1352             throw new AssertionError();
  1355     //where
  1356     private boolean signatureMoreSpecific(List<Type> actuals, Env<AttrContext> env, Type site, Symbol m1, Symbol m2, boolean allowBoxing, boolean useVarargs) {
  1357         noteWarner.clear();
  1358         int maxLength = Math.max(
  1359                             Math.max(m1.type.getParameterTypes().length(), actuals.length()),
  1360                             m2.type.getParameterTypes().length());
  1361         Type mst = instantiate(env, site, m2, null,
  1362                 adjustArgs(types.lowerBounds(types.memberType(site, m1).getParameterTypes()), m1, maxLength, useVarargs), null,
  1363                 allowBoxing, useVarargs, new MostSpecificCheck(!allowBoxing, actuals), noteWarner);
  1364         return mst != null &&
  1365                 !noteWarner.hasLint(Lint.LintCategory.UNCHECKED);
  1367     private List<Type> adjustArgs(List<Type> args, Symbol msym, int length, boolean allowVarargs) {
  1368         if ((msym.flags() & VARARGS) != 0 && allowVarargs) {
  1369             Type varargsElem = types.elemtype(args.last());
  1370             if (varargsElem == null) {
  1371                 Assert.error("Bad varargs = " + args.last() + " " + msym);
  1373             List<Type> newArgs = args.reverse().tail.prepend(varargsElem).reverse();
  1374             while (newArgs.length() < length) {
  1375                 newArgs = newArgs.append(newArgs.last());
  1377             return newArgs;
  1378         } else {
  1379             return args;
  1382     //where
  1383     Type mostSpecificReturnType(Type mt1, Type mt2) {
  1384         Type rt1 = mt1.getReturnType();
  1385         Type rt2 = mt2.getReturnType();
  1387         if (mt1.hasTag(FORALL) && mt2.hasTag(FORALL)) {
  1388             //if both are generic methods, adjust return type ahead of subtyping check
  1389             rt1 = types.subst(rt1, mt1.getTypeArguments(), mt2.getTypeArguments());
  1391         //first use subtyping, then return type substitutability
  1392         if (types.isSubtype(rt1, rt2)) {
  1393             return mt1;
  1394         } else if (types.isSubtype(rt2, rt1)) {
  1395             return mt2;
  1396         } else if (types.returnTypeSubstitutable(mt1, mt2)) {
  1397             return mt1;
  1398         } else if (types.returnTypeSubstitutable(mt2, mt1)) {
  1399             return mt2;
  1400         } else {
  1401             return null;
  1404     //where
  1405     Symbol ambiguityError(Symbol m1, Symbol m2) {
  1406         if (((m1.flags() | m2.flags()) & CLASH) != 0) {
  1407             return (m1.flags() & CLASH) == 0 ? m1 : m2;
  1408         } else {
  1409             return new AmbiguityError(m1, m2);
  1413     Symbol findMethodInScope(Env<AttrContext> env,
  1414             Type site,
  1415             Name name,
  1416             List<Type> argtypes,
  1417             List<Type> typeargtypes,
  1418             Scope sc,
  1419             Symbol bestSoFar,
  1420             boolean allowBoxing,
  1421             boolean useVarargs,
  1422             boolean operator,
  1423             boolean abstractok) {
  1424         for (Symbol s : sc.getElementsByName(name, new LookupFilter(abstractok))) {
  1425             bestSoFar = selectBest(env, site, argtypes, typeargtypes, s,
  1426                     bestSoFar, allowBoxing, useVarargs, operator);
  1428         return bestSoFar;
  1430     //where
  1431         class LookupFilter implements Filter<Symbol> {
  1433             boolean abstractOk;
  1435             LookupFilter(boolean abstractOk) {
  1436                 this.abstractOk = abstractOk;
  1439             public boolean accepts(Symbol s) {
  1440                 long flags = s.flags();
  1441                 return s.kind == MTH &&
  1442                         (flags & SYNTHETIC) == 0 &&
  1443                         (abstractOk ||
  1444                         (flags & DEFAULT) != 0 ||
  1445                         (flags & ABSTRACT) == 0);
  1447         };
  1449     /** Find best qualified method matching given name, type and value
  1450      *  arguments.
  1451      *  @param env       The current environment.
  1452      *  @param site      The original type from where the selection
  1453      *                   takes place.
  1454      *  @param name      The method's name.
  1455      *  @param argtypes  The method's value arguments.
  1456      *  @param typeargtypes The method's type arguments
  1457      *  @param allowBoxing Allow boxing conversions of arguments.
  1458      *  @param useVarargs Box trailing arguments into an array for varargs.
  1459      */
  1460     Symbol findMethod(Env<AttrContext> env,
  1461                       Type site,
  1462                       Name name,
  1463                       List<Type> argtypes,
  1464                       List<Type> typeargtypes,
  1465                       boolean allowBoxing,
  1466                       boolean useVarargs,
  1467                       boolean operator) {
  1468         Symbol bestSoFar = methodNotFound;
  1469         bestSoFar = findMethod(env,
  1470                           site,
  1471                           name,
  1472                           argtypes,
  1473                           typeargtypes,
  1474                           site.tsym.type,
  1475                           bestSoFar,
  1476                           allowBoxing,
  1477                           useVarargs,
  1478                           operator);
  1479         reportVerboseResolutionDiagnostic(env.tree.pos(), name, site, argtypes, typeargtypes, bestSoFar);
  1480         return bestSoFar;
  1482     // where
  1483     private Symbol findMethod(Env<AttrContext> env,
  1484                               Type site,
  1485                               Name name,
  1486                               List<Type> argtypes,
  1487                               List<Type> typeargtypes,
  1488                               Type intype,
  1489                               Symbol bestSoFar,
  1490                               boolean allowBoxing,
  1491                               boolean useVarargs,
  1492                               boolean operator) {
  1493         @SuppressWarnings({"unchecked","rawtypes"})
  1494         List<Type>[] itypes = (List<Type>[])new List[] { List.<Type>nil(), List.<Type>nil() };
  1495         InterfaceLookupPhase iphase = InterfaceLookupPhase.ABSTRACT_OK;
  1496         for (TypeSymbol s : superclasses(intype)) {
  1497             bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
  1498                     s.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
  1499             if (name == names.init) return bestSoFar;
  1500             iphase = (iphase == null) ? null : iphase.update(s, this);
  1501             if (iphase != null) {
  1502                 for (Type itype : types.interfaces(s.type)) {
  1503                     itypes[iphase.ordinal()] = types.union(types.closure(itype), itypes[iphase.ordinal()]);
  1508         Symbol concrete = bestSoFar.kind < ERR &&
  1509                 (bestSoFar.flags() & ABSTRACT) == 0 ?
  1510                 bestSoFar : methodNotFound;
  1512         for (InterfaceLookupPhase iphase2 : InterfaceLookupPhase.values()) {
  1513             if (iphase2 == InterfaceLookupPhase.DEFAULT_OK && !allowDefaultMethods) break;
  1514             //keep searching for abstract methods
  1515             for (Type itype : itypes[iphase2.ordinal()]) {
  1516                 if (!itype.isInterface()) continue; //skip j.l.Object (included by Types.closure())
  1517                 if (iphase2 == InterfaceLookupPhase.DEFAULT_OK &&
  1518                         (itype.tsym.flags() & DEFAULT) == 0) continue;
  1519                 bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
  1520                         itype.tsym.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
  1521                 if (concrete != bestSoFar &&
  1522                         concrete.kind < ERR  && bestSoFar.kind < ERR &&
  1523                         types.isSubSignature(concrete.type, bestSoFar.type)) {
  1524                     //this is an hack - as javac does not do full membership checks
  1525                     //most specific ends up comparing abstract methods that might have
  1526                     //been implemented by some concrete method in a subclass and,
  1527                     //because of raw override, it is possible for an abstract method
  1528                     //to be more specific than the concrete method - so we need
  1529                     //to explicitly call that out (see CR 6178365)
  1530                     bestSoFar = concrete;
  1534         return bestSoFar;
  1537     enum InterfaceLookupPhase {
  1538         ABSTRACT_OK() {
  1539             @Override
  1540             InterfaceLookupPhase update(Symbol s, Resolve rs) {
  1541                 //We should not look for abstract methods if receiver is a concrete class
  1542                 //(as concrete classes are expected to implement all abstracts coming
  1543                 //from superinterfaces)
  1544                 if ((s.flags() & (ABSTRACT | INTERFACE | ENUM)) != 0) {
  1545                     return this;
  1546                 } else if (rs.allowDefaultMethods) {
  1547                     return DEFAULT_OK;
  1548                 } else {
  1549                     return null;
  1552         },
  1553         DEFAULT_OK() {
  1554             @Override
  1555             InterfaceLookupPhase update(Symbol s, Resolve rs) {
  1556                 return this;
  1558         };
  1560         abstract InterfaceLookupPhase update(Symbol s, Resolve rs);
  1563     /**
  1564      * Return an Iterable object to scan the superclasses of a given type.
  1565      * It's crucial that the scan is done lazily, as we don't want to accidentally
  1566      * access more supertypes than strictly needed (as this could trigger completion
  1567      * errors if some of the not-needed supertypes are missing/ill-formed).
  1568      */
  1569     Iterable<TypeSymbol> superclasses(final Type intype) {
  1570         return new Iterable<TypeSymbol>() {
  1571             public Iterator<TypeSymbol> iterator() {
  1572                 return new Iterator<TypeSymbol>() {
  1574                     List<TypeSymbol> seen = List.nil();
  1575                     TypeSymbol currentSym = symbolFor(intype);
  1576                     TypeSymbol prevSym = null;
  1578                     public boolean hasNext() {
  1579                         if (currentSym == syms.noSymbol) {
  1580                             currentSym = symbolFor(types.supertype(prevSym.type));
  1582                         return currentSym != null;
  1585                     public TypeSymbol next() {
  1586                         prevSym = currentSym;
  1587                         currentSym = syms.noSymbol;
  1588                         Assert.check(prevSym != null || prevSym != syms.noSymbol);
  1589                         return prevSym;
  1592                     public void remove() {
  1593                         throw new UnsupportedOperationException();
  1596                     TypeSymbol symbolFor(Type t) {
  1597                         if (!t.hasTag(CLASS) &&
  1598                                 !t.hasTag(TYPEVAR)) {
  1599                             return null;
  1601                         while (t.hasTag(TYPEVAR))
  1602                             t = t.getUpperBound();
  1603                         if (seen.contains(t.tsym)) {
  1604                             //degenerate case in which we have a circular
  1605                             //class hierarchy - because of ill-formed classfiles
  1606                             return null;
  1608                         seen = seen.prepend(t.tsym);
  1609                         return t.tsym;
  1611                 };
  1613         };
  1616     /** Find unqualified method matching given name, type and value arguments.
  1617      *  @param env       The current environment.
  1618      *  @param name      The method's name.
  1619      *  @param argtypes  The method's value arguments.
  1620      *  @param typeargtypes  The method's type arguments.
  1621      *  @param allowBoxing Allow boxing conversions of arguments.
  1622      *  @param useVarargs Box trailing arguments into an array for varargs.
  1623      */
  1624     Symbol findFun(Env<AttrContext> env, Name name,
  1625                    List<Type> argtypes, List<Type> typeargtypes,
  1626                    boolean allowBoxing, boolean useVarargs) {
  1627         Symbol bestSoFar = methodNotFound;
  1628         Symbol sym;
  1629         Env<AttrContext> env1 = env;
  1630         boolean staticOnly = false;
  1631         while (env1.outer != null) {
  1632             if (isStatic(env1)) staticOnly = true;
  1633             sym = findMethod(
  1634                 env1, env1.enclClass.sym.type, name, argtypes, typeargtypes,
  1635                 allowBoxing, useVarargs, false);
  1636             if (sym.exists()) {
  1637                 if (staticOnly &&
  1638                     sym.kind == MTH &&
  1639                     sym.owner.kind == TYP &&
  1640                     (sym.flags() & STATIC) == 0) return new StaticError(sym);
  1641                 else return sym;
  1642             } else if (sym.kind < bestSoFar.kind) {
  1643                 bestSoFar = sym;
  1645             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  1646             env1 = env1.outer;
  1649         sym = findMethod(env, syms.predefClass.type, name, argtypes,
  1650                          typeargtypes, allowBoxing, useVarargs, false);
  1651         if (sym.exists())
  1652             return sym;
  1654         Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
  1655         for (; e.scope != null; e = e.next()) {
  1656             sym = e.sym;
  1657             Type origin = e.getOrigin().owner.type;
  1658             if (sym.kind == MTH) {
  1659                 if (e.sym.owner.type != origin)
  1660                     sym = sym.clone(e.getOrigin().owner);
  1661                 if (!isAccessible(env, origin, sym))
  1662                     sym = new AccessError(env, origin, sym);
  1663                 bestSoFar = selectBest(env, origin,
  1664                                        argtypes, typeargtypes,
  1665                                        sym, bestSoFar,
  1666                                        allowBoxing, useVarargs, false);
  1669         if (bestSoFar.exists())
  1670             return bestSoFar;
  1672         e = env.toplevel.starImportScope.lookup(name);
  1673         for (; e.scope != null; e = e.next()) {
  1674             sym = e.sym;
  1675             Type origin = e.getOrigin().owner.type;
  1676             if (sym.kind == MTH) {
  1677                 if (e.sym.owner.type != origin)
  1678                     sym = sym.clone(e.getOrigin().owner);
  1679                 if (!isAccessible(env, origin, sym))
  1680                     sym = new AccessError(env, origin, sym);
  1681                 bestSoFar = selectBest(env, origin,
  1682                                        argtypes, typeargtypes,
  1683                                        sym, bestSoFar,
  1684                                        allowBoxing, useVarargs, false);
  1687         return bestSoFar;
  1690     /** Load toplevel or member class with given fully qualified name and
  1691      *  verify that it is accessible.
  1692      *  @param env       The current environment.
  1693      *  @param name      The fully qualified name of the class to be loaded.
  1694      */
  1695     Symbol loadClass(Env<AttrContext> env, Name name) {
  1696         try {
  1697             ClassSymbol c = reader.loadClass(name);
  1698             return isAccessible(env, c) ? c : new AccessError(c);
  1699         } catch (ClassReader.BadClassFile err) {
  1700             throw err;
  1701         } catch (CompletionFailure ex) {
  1702             return typeNotFound;
  1706     /** Find qualified member type.
  1707      *  @param env       The current environment.
  1708      *  @param site      The original type from where the selection takes
  1709      *                   place.
  1710      *  @param name      The type's name.
  1711      *  @param c         The class to search for the member type. This is
  1712      *                   always a superclass or implemented interface of
  1713      *                   site's class.
  1714      */
  1715     Symbol findMemberType(Env<AttrContext> env,
  1716                           Type site,
  1717                           Name name,
  1718                           TypeSymbol c) {
  1719         Symbol bestSoFar = typeNotFound;
  1720         Symbol sym;
  1721         Scope.Entry e = c.members().lookup(name);
  1722         while (e.scope != null) {
  1723             if (e.sym.kind == TYP) {
  1724                 return isAccessible(env, site, e.sym)
  1725                     ? e.sym
  1726                     : new AccessError(env, site, e.sym);
  1728             e = e.next();
  1730         Type st = types.supertype(c.type);
  1731         if (st != null && st.hasTag(CLASS)) {
  1732             sym = findMemberType(env, site, name, st.tsym);
  1733             if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1735         for (List<Type> l = types.interfaces(c.type);
  1736              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
  1737              l = l.tail) {
  1738             sym = findMemberType(env, site, name, l.head.tsym);
  1739             if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
  1740                 sym.owner != bestSoFar.owner)
  1741                 bestSoFar = new AmbiguityError(bestSoFar, sym);
  1742             else if (sym.kind < bestSoFar.kind)
  1743                 bestSoFar = sym;
  1745         return bestSoFar;
  1748     /** Find a global type in given scope and load corresponding class.
  1749      *  @param env       The current environment.
  1750      *  @param scope     The scope in which to look for the type.
  1751      *  @param name      The type's name.
  1752      */
  1753     Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name) {
  1754         Symbol bestSoFar = typeNotFound;
  1755         for (Scope.Entry e = scope.lookup(name); e.scope != null; e = e.next()) {
  1756             Symbol sym = loadClass(env, e.sym.flatName());
  1757             if (bestSoFar.kind == TYP && sym.kind == TYP &&
  1758                 bestSoFar != sym)
  1759                 return new AmbiguityError(bestSoFar, sym);
  1760             else if (sym.kind < bestSoFar.kind)
  1761                 bestSoFar = sym;
  1763         return bestSoFar;
  1766     /** Find an unqualified type symbol.
  1767      *  @param env       The current environment.
  1768      *  @param name      The type's name.
  1769      */
  1770     Symbol findType(Env<AttrContext> env, Name name) {
  1771         Symbol bestSoFar = typeNotFound;
  1772         Symbol sym;
  1773         boolean staticOnly = false;
  1774         for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
  1775             if (isStatic(env1)) staticOnly = true;
  1776             for (Scope.Entry e = env1.info.scope.lookup(name);
  1777                  e.scope != null;
  1778                  e = e.next()) {
  1779                 if (e.sym.kind == TYP) {
  1780                     if (staticOnly &&
  1781                         e.sym.type.hasTag(TYPEVAR) &&
  1782                         e.sym.owner.kind == TYP) return new StaticError(e.sym);
  1783                     return e.sym;
  1787             sym = findMemberType(env1, env1.enclClass.sym.type, name,
  1788                                  env1.enclClass.sym);
  1789             if (staticOnly && sym.kind == TYP &&
  1790                 sym.type.hasTag(CLASS) &&
  1791                 sym.type.getEnclosingType().hasTag(CLASS) &&
  1792                 env1.enclClass.sym.type.isParameterized() &&
  1793                 sym.type.getEnclosingType().isParameterized())
  1794                 return new StaticError(sym);
  1795             else if (sym.exists()) return sym;
  1796             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1798             JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass;
  1799             if ((encl.sym.flags() & STATIC) != 0)
  1800                 staticOnly = true;
  1803         if (!env.tree.hasTag(IMPORT)) {
  1804             sym = findGlobalType(env, env.toplevel.namedImportScope, name);
  1805             if (sym.exists()) return sym;
  1806             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1808             sym = findGlobalType(env, env.toplevel.packge.members(), name);
  1809             if (sym.exists()) return sym;
  1810             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1812             sym = findGlobalType(env, env.toplevel.starImportScope, name);
  1813             if (sym.exists()) return sym;
  1814             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1817         return bestSoFar;
  1820     /** Find an unqualified identifier which matches a specified kind set.
  1821      *  @param env       The current environment.
  1822      *  @param name      The identifier's name.
  1823      *  @param kind      Indicates the possible symbol kinds
  1824      *                   (a subset of VAL, TYP, PCK).
  1825      */
  1826     Symbol findIdent(Env<AttrContext> env, Name name, int kind) {
  1827         Symbol bestSoFar = typeNotFound;
  1828         Symbol sym;
  1830         if ((kind & VAR) != 0) {
  1831             sym = findVar(env, name);
  1832             if (sym.exists()) return sym;
  1833             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1836         if ((kind & TYP) != 0) {
  1837             sym = findType(env, name);
  1838             if (sym.kind==TYP) {
  1839                  reportDependence(env.enclClass.sym, sym);
  1841             if (sym.exists()) return sym;
  1842             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1845         if ((kind & PCK) != 0) return reader.enterPackage(name);
  1846         else return bestSoFar;
  1849     /** Report dependencies.
  1850      * @param from The enclosing class sym
  1851      * @param to   The found identifier that the class depends on.
  1852      */
  1853     public void reportDependence(Symbol from, Symbol to) {
  1854         // Override if you want to collect the reported dependencies.
  1857     /** Find an identifier in a package which matches a specified kind set.
  1858      *  @param env       The current environment.
  1859      *  @param name      The identifier's name.
  1860      *  @param kind      Indicates the possible symbol kinds
  1861      *                   (a nonempty subset of TYP, PCK).
  1862      */
  1863     Symbol findIdentInPackage(Env<AttrContext> env, TypeSymbol pck,
  1864                               Name name, int kind) {
  1865         Name fullname = TypeSymbol.formFullName(name, pck);
  1866         Symbol bestSoFar = typeNotFound;
  1867         PackageSymbol pack = null;
  1868         if ((kind & PCK) != 0) {
  1869             pack = reader.enterPackage(fullname);
  1870             if (pack.exists()) return pack;
  1872         if ((kind & TYP) != 0) {
  1873             Symbol sym = loadClass(env, fullname);
  1874             if (sym.exists()) {
  1875                 // don't allow programs to use flatnames
  1876                 if (name == sym.name) return sym;
  1878             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1880         return (pack != null) ? pack : bestSoFar;
  1883     /** Find an identifier among the members of a given type `site'.
  1884      *  @param env       The current environment.
  1885      *  @param site      The type containing the symbol to be found.
  1886      *  @param name      The identifier's name.
  1887      *  @param kind      Indicates the possible symbol kinds
  1888      *                   (a subset of VAL, TYP).
  1889      */
  1890     Symbol findIdentInType(Env<AttrContext> env, Type site,
  1891                            Name name, int kind) {
  1892         Symbol bestSoFar = typeNotFound;
  1893         Symbol sym;
  1894         if ((kind & VAR) != 0) {
  1895             sym = findField(env, site, name, site.tsym);
  1896             if (sym.exists()) return sym;
  1897             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1900         if ((kind & TYP) != 0) {
  1901             sym = findMemberType(env, site, name, site.tsym);
  1902             if (sym.exists()) return sym;
  1903             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1905         return bestSoFar;
  1908 /* ***************************************************************************
  1909  *  Access checking
  1910  *  The following methods convert ResolveErrors to ErrorSymbols, issuing
  1911  *  an error message in the process
  1912  ****************************************************************************/
  1914     /** If `sym' is a bad symbol: report error and return errSymbol
  1915      *  else pass through unchanged,
  1916      *  additional arguments duplicate what has been used in trying to find the
  1917      *  symbol {@literal (--> flyweight pattern)}. This improves performance since we
  1918      *  expect misses to happen frequently.
  1920      *  @param sym       The symbol that was found, or a ResolveError.
  1921      *  @param pos       The position to use for error reporting.
  1922      *  @param location  The symbol the served as a context for this lookup
  1923      *  @param site      The original type from where the selection took place.
  1924      *  @param name      The symbol's name.
  1925      *  @param qualified Did we get here through a qualified expression resolution?
  1926      *  @param argtypes  The invocation's value arguments,
  1927      *                   if we looked for a method.
  1928      *  @param typeargtypes  The invocation's type arguments,
  1929      *                   if we looked for a method.
  1930      *  @param logResolveHelper helper class used to log resolve errors
  1931      */
  1932     Symbol accessInternal(Symbol sym,
  1933                   DiagnosticPosition pos,
  1934                   Symbol location,
  1935                   Type site,
  1936                   Name name,
  1937                   boolean qualified,
  1938                   List<Type> argtypes,
  1939                   List<Type> typeargtypes,
  1940                   LogResolveHelper logResolveHelper) {
  1941         if (sym.kind >= AMBIGUOUS) {
  1942             ResolveError errSym = (ResolveError)sym;
  1943             sym = errSym.access(name, qualified ? site.tsym : syms.noSymbol);
  1944             argtypes = logResolveHelper.getArgumentTypes(errSym, sym, name, argtypes);
  1945             if (logResolveHelper.resolveDiagnosticNeeded(site, argtypes, typeargtypes)) {
  1946                 logResolveError(errSym, pos, location, site, name, argtypes, typeargtypes);
  1949         return sym;
  1952     /**
  1953      * Variant of the generalized access routine, to be used for generating method
  1954      * resolution diagnostics
  1955      */
  1956     Symbol accessMethod(Symbol sym,
  1957                   DiagnosticPosition pos,
  1958                   Symbol location,
  1959                   Type site,
  1960                   Name name,
  1961                   boolean qualified,
  1962                   List<Type> argtypes,
  1963                   List<Type> typeargtypes) {
  1964         return accessInternal(sym, pos, location, site, name, qualified, argtypes, typeargtypes, methodLogResolveHelper);
  1967     /** Same as original accessMethod(), but without location.
  1968      */
  1969     Symbol accessMethod(Symbol sym,
  1970                   DiagnosticPosition pos,
  1971                   Type site,
  1972                   Name name,
  1973                   boolean qualified,
  1974                   List<Type> argtypes,
  1975                   List<Type> typeargtypes) {
  1976         return accessMethod(sym, pos, site.tsym, site, name, qualified, argtypes, typeargtypes);
  1979     /**
  1980      * Variant of the generalized access routine, to be used for generating variable,
  1981      * type resolution diagnostics
  1982      */
  1983     Symbol accessBase(Symbol sym,
  1984                   DiagnosticPosition pos,
  1985                   Symbol location,
  1986                   Type site,
  1987                   Name name,
  1988                   boolean qualified) {
  1989         return accessInternal(sym, pos, location, site, name, qualified, List.<Type>nil(), null, basicLogResolveHelper);
  1992     /** Same as original accessBase(), but without location.
  1993      */
  1994     Symbol accessBase(Symbol sym,
  1995                   DiagnosticPosition pos,
  1996                   Type site,
  1997                   Name name,
  1998                   boolean qualified) {
  1999         return accessBase(sym, pos, site.tsym, site, name, qualified);
  2002     interface LogResolveHelper {
  2003         boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes);
  2004         List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes);
  2007     LogResolveHelper basicLogResolveHelper = new LogResolveHelper() {
  2008         public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
  2009             return !site.isErroneous();
  2011         public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
  2012             return argtypes;
  2014     };
  2016     LogResolveHelper methodLogResolveHelper = new LogResolveHelper() {
  2017         public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
  2018             return !site.isErroneous() &&
  2019                         !Type.isErroneous(argtypes) &&
  2020                         (typeargtypes == null || !Type.isErroneous(typeargtypes));
  2022         public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
  2023             return (syms.operatorNames.contains(name)) ?
  2024                     argtypes :
  2025                     Type.map(argtypes, new ResolveDeferredRecoveryMap(accessedSym));
  2028         class ResolveDeferredRecoveryMap extends DeferredAttr.RecoveryDeferredTypeMap {
  2030             public ResolveDeferredRecoveryMap(Symbol msym) {
  2031                 deferredAttr.super(AttrMode.SPECULATIVE, msym, currentResolutionContext.step);
  2034             @Override
  2035             protected Type typeOf(DeferredType dt) {
  2036                 Type res = super.typeOf(dt);
  2037                 if (!res.isErroneous()) {
  2038                     switch (TreeInfo.skipParens(dt.tree).getTag()) {
  2039                         case LAMBDA:
  2040                         case REFERENCE:
  2041                             return dt;
  2042                         case CONDEXPR:
  2043                             return res == Type.recoveryType ?
  2044                                     dt : res;
  2047                 return res;
  2050     };
  2052     /** Check that sym is not an abstract method.
  2053      */
  2054     void checkNonAbstract(DiagnosticPosition pos, Symbol sym) {
  2055         if ((sym.flags() & ABSTRACT) != 0 && (sym.flags() & DEFAULT) == 0)
  2056             log.error(pos, "abstract.cant.be.accessed.directly",
  2057                       kindName(sym), sym, sym.location());
  2060 /* ***************************************************************************
  2061  *  Debugging
  2062  ****************************************************************************/
  2064     /** print all scopes starting with scope s and proceeding outwards.
  2065      *  used for debugging.
  2066      */
  2067     public void printscopes(Scope s) {
  2068         while (s != null) {
  2069             if (s.owner != null)
  2070                 System.err.print(s.owner + ": ");
  2071             for (Scope.Entry e = s.elems; e != null; e = e.sibling) {
  2072                 if ((e.sym.flags() & ABSTRACT) != 0)
  2073                     System.err.print("abstract ");
  2074                 System.err.print(e.sym + " ");
  2076             System.err.println();
  2077             s = s.next;
  2081     void printscopes(Env<AttrContext> env) {
  2082         while (env.outer != null) {
  2083             System.err.println("------------------------------");
  2084             printscopes(env.info.scope);
  2085             env = env.outer;
  2089     public void printscopes(Type t) {
  2090         while (t.hasTag(CLASS)) {
  2091             printscopes(t.tsym.members());
  2092             t = types.supertype(t);
  2096 /* ***************************************************************************
  2097  *  Name resolution
  2098  *  Naming conventions are as for symbol lookup
  2099  *  Unlike the find... methods these methods will report access errors
  2100  ****************************************************************************/
  2102     /** Resolve an unqualified (non-method) identifier.
  2103      *  @param pos       The position to use for error reporting.
  2104      *  @param env       The environment current at the identifier use.
  2105      *  @param name      The identifier's name.
  2106      *  @param kind      The set of admissible symbol kinds for the identifier.
  2107      */
  2108     Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env,
  2109                         Name name, int kind) {
  2110         return accessBase(
  2111             findIdent(env, name, kind),
  2112             pos, env.enclClass.sym.type, name, false);
  2115     /** Resolve an unqualified method identifier.
  2116      *  @param pos       The position to use for error reporting.
  2117      *  @param env       The environment current at the method invocation.
  2118      *  @param name      The identifier's name.
  2119      *  @param argtypes  The types of the invocation's value arguments.
  2120      *  @param typeargtypes  The types of the invocation's type arguments.
  2121      */
  2122     Symbol resolveMethod(DiagnosticPosition pos,
  2123                          Env<AttrContext> env,
  2124                          Name name,
  2125                          List<Type> argtypes,
  2126                          List<Type> typeargtypes) {
  2127         return lookupMethod(env, pos, env.enclClass.sym, new BasicLookupHelper(name, env.enclClass.sym.type, argtypes, typeargtypes) {
  2128             @Override
  2129             Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2130                 return findFun(env, name, argtypes, typeargtypes,
  2131                         phase.isBoxingRequired(),
  2132                         phase.isVarargsRequired());
  2134         });
  2137     /** Resolve a qualified method identifier
  2138      *  @param pos       The position to use for error reporting.
  2139      *  @param env       The environment current at the method invocation.
  2140      *  @param site      The type of the qualifying expression, in which
  2141      *                   identifier is searched.
  2142      *  @param name      The identifier's name.
  2143      *  @param argtypes  The types of the invocation's value arguments.
  2144      *  @param typeargtypes  The types of the invocation's type arguments.
  2145      */
  2146     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
  2147                                   Type site, Name name, List<Type> argtypes,
  2148                                   List<Type> typeargtypes) {
  2149         return resolveQualifiedMethod(pos, env, site.tsym, site, name, argtypes, typeargtypes);
  2151     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
  2152                                   Symbol location, Type site, Name name, List<Type> argtypes,
  2153                                   List<Type> typeargtypes) {
  2154         return resolveQualifiedMethod(new MethodResolutionContext(), pos, env, location, site, name, argtypes, typeargtypes);
  2156     private Symbol resolveQualifiedMethod(MethodResolutionContext resolveContext,
  2157                                   DiagnosticPosition pos, Env<AttrContext> env,
  2158                                   Symbol location, Type site, Name name, List<Type> argtypes,
  2159                                   List<Type> typeargtypes) {
  2160         return lookupMethod(env, pos, location, resolveContext, new BasicLookupHelper(name, site, argtypes, typeargtypes) {
  2161             @Override
  2162             Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2163                 return findMethod(env, site, name, argtypes, typeargtypes,
  2164                         phase.isBoxingRequired(),
  2165                         phase.isVarargsRequired(), false);
  2167             @Override
  2168             Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2169                 if (sym.kind >= AMBIGUOUS) {
  2170                     sym = super.access(env, pos, location, sym);
  2171                 } else if (allowMethodHandles) {
  2172                     MethodSymbol msym = (MethodSymbol)sym;
  2173                     if (msym.isSignaturePolymorphic(types)) {
  2174                         return findPolymorphicSignatureInstance(env, sym, argtypes);
  2177                 return sym;
  2179         });
  2182     /** Find or create an implicit method of exactly the given type (after erasure).
  2183      *  Searches in a side table, not the main scope of the site.
  2184      *  This emulates the lookup process required by JSR 292 in JVM.
  2185      *  @param env       Attribution environment
  2186      *  @param spMethod  signature polymorphic method - i.e. MH.invokeExact
  2187      *  @param argtypes  The required argument types
  2188      */
  2189     Symbol findPolymorphicSignatureInstance(Env<AttrContext> env,
  2190                                             final Symbol spMethod,
  2191                                             List<Type> argtypes) {
  2192         Type mtype = infer.instantiatePolymorphicSignatureInstance(env,
  2193                 (MethodSymbol)spMethod, currentResolutionContext, argtypes);
  2194         for (Symbol sym : polymorphicSignatureScope.getElementsByName(spMethod.name)) {
  2195             if (types.isSameType(mtype, sym.type)) {
  2196                return sym;
  2200         // create the desired method
  2201         long flags = ABSTRACT | HYPOTHETICAL | spMethod.flags() & Flags.AccessFlags;
  2202         Symbol msym = new MethodSymbol(flags, spMethod.name, mtype, spMethod.owner) {
  2203             @Override
  2204             public Symbol baseSymbol() {
  2205                 return spMethod;
  2207         };
  2208         polymorphicSignatureScope.enter(msym);
  2209         return msym;
  2212     /** Resolve a qualified method identifier, throw a fatal error if not
  2213      *  found.
  2214      *  @param pos       The position to use for error reporting.
  2215      *  @param env       The environment current at the method invocation.
  2216      *  @param site      The type of the qualifying expression, in which
  2217      *                   identifier is searched.
  2218      *  @param name      The identifier's name.
  2219      *  @param argtypes  The types of the invocation's value arguments.
  2220      *  @param typeargtypes  The types of the invocation's type arguments.
  2221      */
  2222     public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env,
  2223                                         Type site, Name name,
  2224                                         List<Type> argtypes,
  2225                                         List<Type> typeargtypes) {
  2226         MethodResolutionContext resolveContext = new MethodResolutionContext();
  2227         resolveContext.internalResolution = true;
  2228         Symbol sym = resolveQualifiedMethod(resolveContext, pos, env, site.tsym,
  2229                 site, name, argtypes, typeargtypes);
  2230         if (sym.kind == MTH) return (MethodSymbol)sym;
  2231         else throw new FatalError(
  2232                  diags.fragment("fatal.err.cant.locate.meth",
  2233                                 name));
  2236     /** Resolve constructor.
  2237      *  @param pos       The position to use for error reporting.
  2238      *  @param env       The environment current at the constructor invocation.
  2239      *  @param site      The type of class for which a constructor is searched.
  2240      *  @param argtypes  The types of the constructor invocation's value
  2241      *                   arguments.
  2242      *  @param typeargtypes  The types of the constructor invocation's type
  2243      *                   arguments.
  2244      */
  2245     Symbol resolveConstructor(DiagnosticPosition pos,
  2246                               Env<AttrContext> env,
  2247                               Type site,
  2248                               List<Type> argtypes,
  2249                               List<Type> typeargtypes) {
  2250         return resolveConstructor(new MethodResolutionContext(), pos, env, site, argtypes, typeargtypes);
  2253     private Symbol resolveConstructor(MethodResolutionContext resolveContext,
  2254                               final DiagnosticPosition pos,
  2255                               Env<AttrContext> env,
  2256                               Type site,
  2257                               List<Type> argtypes,
  2258                               List<Type> typeargtypes) {
  2259         return lookupMethod(env, pos, site.tsym, resolveContext, new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
  2260             @Override
  2261             Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2262                 return findConstructor(pos, env, site, argtypes, typeargtypes,
  2263                         phase.isBoxingRequired(),
  2264                         phase.isVarargsRequired());
  2266         });
  2269     /** Resolve a constructor, throw a fatal error if not found.
  2270      *  @param pos       The position to use for error reporting.
  2271      *  @param env       The environment current at the method invocation.
  2272      *  @param site      The type to be constructed.
  2273      *  @param argtypes  The types of the invocation's value arguments.
  2274      *  @param typeargtypes  The types of the invocation's type arguments.
  2275      */
  2276     public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  2277                                         Type site,
  2278                                         List<Type> argtypes,
  2279                                         List<Type> typeargtypes) {
  2280         MethodResolutionContext resolveContext = new MethodResolutionContext();
  2281         resolveContext.internalResolution = true;
  2282         Symbol sym = resolveConstructor(resolveContext, pos, env, site, argtypes, typeargtypes);
  2283         if (sym.kind == MTH) return (MethodSymbol)sym;
  2284         else throw new FatalError(
  2285                  diags.fragment("fatal.err.cant.locate.ctor", site));
  2288     Symbol findConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  2289                               Type site, List<Type> argtypes,
  2290                               List<Type> typeargtypes,
  2291                               boolean allowBoxing,
  2292                               boolean useVarargs) {
  2293         Symbol sym = findMethod(env, site,
  2294                                     names.init, argtypes,
  2295                                     typeargtypes, allowBoxing,
  2296                                     useVarargs, false);
  2297         chk.checkDeprecated(pos, env.info.scope.owner, sym);
  2298         return sym;
  2301     /** Resolve constructor using diamond inference.
  2302      *  @param pos       The position to use for error reporting.
  2303      *  @param env       The environment current at the constructor invocation.
  2304      *  @param site      The type of class for which a constructor is searched.
  2305      *                   The scope of this class has been touched in attribution.
  2306      *  @param argtypes  The types of the constructor invocation's value
  2307      *                   arguments.
  2308      *  @param typeargtypes  The types of the constructor invocation's type
  2309      *                   arguments.
  2310      */
  2311     Symbol resolveDiamond(DiagnosticPosition pos,
  2312                               Env<AttrContext> env,
  2313                               Type site,
  2314                               List<Type> argtypes,
  2315                               List<Type> typeargtypes) {
  2316         return lookupMethod(env, pos, site.tsym, new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
  2317             @Override
  2318             Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2319                 return findDiamond(env, site, argtypes, typeargtypes,
  2320                         phase.isBoxingRequired(),
  2321                         phase.isVarargsRequired());
  2323             @Override
  2324             Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2325                 if (sym.kind >= AMBIGUOUS) {
  2326                     final JCDiagnostic details = sym.kind == WRONG_MTH ?
  2327                                     ((InapplicableSymbolError)sym).errCandidate().details :
  2328                                     null;
  2329                     sym = new InapplicableSymbolError(sym.kind, "diamondError", currentResolutionContext) {
  2330                         @Override
  2331                         JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos,
  2332                                 Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
  2333                             String key = details == null ?
  2334                                 "cant.apply.diamond" :
  2335                                 "cant.apply.diamond.1";
  2336                             return diags.create(dkind, log.currentSource(), pos, key,
  2337                                     diags.fragment("diamond", site.tsym), details);
  2339                     };
  2340                     sym = accessMethod(sym, pos, site, names.init, true, argtypes, typeargtypes);
  2341                     env.info.pendingResolutionPhase = currentResolutionContext.step;
  2343                 return sym;
  2345         });
  2348     /** This method scans all the constructor symbol in a given class scope -
  2349      *  assuming that the original scope contains a constructor of the kind:
  2350      *  {@code Foo(X x, Y y)}, where X,Y are class type-variables declared in Foo,
  2351      *  a method check is executed against the modified constructor type:
  2352      *  {@code <X,Y>Foo<X,Y>(X x, Y y)}. This is crucial in order to enable diamond
  2353      *  inference. The inferred return type of the synthetic constructor IS
  2354      *  the inferred type for the diamond operator.
  2355      */
  2356     private Symbol findDiamond(Env<AttrContext> env,
  2357                               Type site,
  2358                               List<Type> argtypes,
  2359                               List<Type> typeargtypes,
  2360                               boolean allowBoxing,
  2361                               boolean useVarargs) {
  2362         Symbol bestSoFar = methodNotFound;
  2363         for (Scope.Entry e = site.tsym.members().lookup(names.init);
  2364              e.scope != null;
  2365              e = e.next()) {
  2366             final Symbol sym = e.sym;
  2367             //- System.out.println(" e " + e.sym);
  2368             if (sym.kind == MTH &&
  2369                 (sym.flags_field & SYNTHETIC) == 0) {
  2370                     List<Type> oldParams = e.sym.type.hasTag(FORALL) ?
  2371                             ((ForAll)sym.type).tvars :
  2372                             List.<Type>nil();
  2373                     Type constrType = new ForAll(site.tsym.type.getTypeArguments().appendList(oldParams),
  2374                             types.createMethodTypeWithReturn(sym.type.asMethodType(), site));
  2375                     MethodSymbol newConstr = new MethodSymbol(sym.flags(), names.init, constrType, site.tsym) {
  2376                         @Override
  2377                         public Symbol baseSymbol() {
  2378                             return sym;
  2380                     };
  2381                     bestSoFar = selectBest(env, site, argtypes, typeargtypes,
  2382                             newConstr,
  2383                             bestSoFar,
  2384                             allowBoxing,
  2385                             useVarargs,
  2386                             false);
  2389         return bestSoFar;
  2394     /** Resolve operator.
  2395      *  @param pos       The position to use for error reporting.
  2396      *  @param optag     The tag of the operation tree.
  2397      *  @param env       The environment current at the operation.
  2398      *  @param argtypes  The types of the operands.
  2399      */
  2400     Symbol resolveOperator(DiagnosticPosition pos, JCTree.Tag optag,
  2401                            Env<AttrContext> env, List<Type> argtypes) {
  2402         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  2403         try {
  2404             currentResolutionContext = new MethodResolutionContext();
  2405             Name name = treeinfo.operatorName(optag);
  2406             env.info.pendingResolutionPhase = currentResolutionContext.step = BASIC;
  2407             Symbol sym = findMethod(env, syms.predefClass.type, name, argtypes,
  2408                                     null, false, false, true);
  2409             if (boxingEnabled && sym.kind >= WRONG_MTHS)
  2410                 env.info.pendingResolutionPhase = currentResolutionContext.step = BOX;
  2411                 sym = findMethod(env, syms.predefClass.type, name, argtypes,
  2412                                  null, true, false, true);
  2413             return accessMethod(sym, pos, env.enclClass.sym.type, name,
  2414                           false, argtypes, null);
  2416         finally {
  2417             currentResolutionContext = prevResolutionContext;
  2421     /** Resolve operator.
  2422      *  @param pos       The position to use for error reporting.
  2423      *  @param optag     The tag of the operation tree.
  2424      *  @param env       The environment current at the operation.
  2425      *  @param arg       The type of the operand.
  2426      */
  2427     Symbol resolveUnaryOperator(DiagnosticPosition pos, JCTree.Tag optag, Env<AttrContext> env, Type arg) {
  2428         return resolveOperator(pos, optag, env, List.of(arg));
  2431     /** Resolve binary operator.
  2432      *  @param pos       The position to use for error reporting.
  2433      *  @param optag     The tag of the operation tree.
  2434      *  @param env       The environment current at the operation.
  2435      *  @param left      The types of the left operand.
  2436      *  @param right     The types of the right operand.
  2437      */
  2438     Symbol resolveBinaryOperator(DiagnosticPosition pos,
  2439                                  JCTree.Tag optag,
  2440                                  Env<AttrContext> env,
  2441                                  Type left,
  2442                                  Type right) {
  2443         return resolveOperator(pos, optag, env, List.of(left, right));
  2446     /**
  2447      * Resolution of member references is typically done as a single
  2448      * overload resolution step, where the argument types A are inferred from
  2449      * the target functional descriptor.
  2451      * If the member reference is a method reference with a type qualifier,
  2452      * a two-step lookup process is performed. The first step uses the
  2453      * expected argument list A, while the second step discards the first
  2454      * type from A (which is treated as a receiver type).
  2456      * There are two cases in which inference is performed: (i) if the member
  2457      * reference is a constructor reference and the qualifier type is raw - in
  2458      * which case diamond inference is used to infer a parameterization for the
  2459      * type qualifier; (ii) if the member reference is an unbound reference
  2460      * where the type qualifier is raw - in that case, during the unbound lookup
  2461      * the receiver argument type is used to infer an instantiation for the raw
  2462      * qualifier type.
  2464      * When a multi-step resolution process is exploited, it is an error
  2465      * if two candidates are found (ambiguity).
  2467      * This routine returns a pair (T,S), where S is the member reference symbol,
  2468      * and T is the type of the class in which S is defined. This is necessary as
  2469      * the type T might be dynamically inferred (i.e. if constructor reference
  2470      * has a raw qualifier).
  2471      */
  2472     Pair<Symbol, ReferenceLookupHelper> resolveMemberReference(DiagnosticPosition pos,
  2473                                   Env<AttrContext> env,
  2474                                   JCMemberReference referenceTree,
  2475                                   Type site,
  2476                                   Name name, List<Type> argtypes,
  2477                                   List<Type> typeargtypes,
  2478                                   boolean boxingAllowed) {
  2479         MethodResolutionPhase maxPhase = boxingAllowed ? VARARITY : BASIC;
  2481         ReferenceLookupHelper boundLookupHelper;
  2482         if (!name.equals(names.init)) {
  2483             //method reference
  2484             boundLookupHelper =
  2485                     new MethodReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
  2486         } else if (site.hasTag(ARRAY)) {
  2487             //array constructor reference
  2488             boundLookupHelper =
  2489                     new ArrayConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase);
  2490         } else {
  2491             //class constructor reference
  2492             boundLookupHelper =
  2493                     new ConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase);
  2496         //step 1 - bound lookup
  2497         Env<AttrContext> boundEnv = env.dup(env.tree, env.info.dup());
  2498         Symbol boundSym = lookupMethod(boundEnv, env.tree.pos(), site.tsym, boundLookupHelper);
  2500         //step 2 - unbound lookup
  2501         ReferenceLookupHelper unboundLookupHelper = boundLookupHelper.unboundLookup();
  2502         Env<AttrContext> unboundEnv = env.dup(env.tree, env.info.dup());
  2503         Symbol unboundSym = lookupMethod(unboundEnv, env.tree.pos(), site.tsym, unboundLookupHelper);
  2505         //merge results
  2506         Pair<Symbol, ReferenceLookupHelper> res;
  2507         if (!lookupSuccess(unboundSym)) {
  2508             res = new Pair<Symbol, ReferenceLookupHelper>(boundSym, boundLookupHelper);
  2509             env.info.pendingResolutionPhase = boundEnv.info.pendingResolutionPhase;
  2510         } else if (lookupSuccess(boundSym)) {
  2511             res = new Pair<Symbol, ReferenceLookupHelper>(ambiguityError(boundSym, unboundSym), boundLookupHelper);
  2512             env.info.pendingResolutionPhase = boundEnv.info.pendingResolutionPhase;
  2513         } else {
  2514             res = new Pair<Symbol, ReferenceLookupHelper>(unboundSym, unboundLookupHelper);
  2515             env.info.pendingResolutionPhase = unboundEnv.info.pendingResolutionPhase;
  2518         return res;
  2520     //private
  2521         boolean lookupSuccess(Symbol s) {
  2522             return s.kind == MTH || s.kind == AMBIGUOUS;
  2525     /**
  2526      * Helper for defining custom method-like lookup logic; a lookup helper
  2527      * provides hooks for (i) the actual lookup logic and (ii) accessing the
  2528      * lookup result (this step might result in compiler diagnostics to be generated)
  2529      */
  2530     abstract class LookupHelper {
  2532         /** name of the symbol to lookup */
  2533         Name name;
  2535         /** location in which the lookup takes place */
  2536         Type site;
  2538         /** actual types used during the lookup */
  2539         List<Type> argtypes;
  2541         /** type arguments used during the lookup */
  2542         List<Type> typeargtypes;
  2544         /** Max overload resolution phase handled by this helper */
  2545         MethodResolutionPhase maxPhase;
  2547         LookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2548             this.name = name;
  2549             this.site = site;
  2550             this.argtypes = argtypes;
  2551             this.typeargtypes = typeargtypes;
  2552             this.maxPhase = maxPhase;
  2555         /**
  2556          * Should lookup stop at given phase with given result
  2557          */
  2558         protected boolean shouldStop(Symbol sym, MethodResolutionPhase phase) {
  2559             return phase.ordinal() > maxPhase.ordinal() ||
  2560                     sym.kind < ERRONEOUS || sym.kind == AMBIGUOUS;
  2563         /**
  2564          * Search for a symbol under a given overload resolution phase - this method
  2565          * is usually called several times, once per each overload resolution phase
  2566          */
  2567         abstract Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase);
  2569         /**
  2570          * Validate the result of the lookup
  2571          */
  2572         abstract Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym);
  2575     abstract class BasicLookupHelper extends LookupHelper {
  2577         BasicLookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes) {
  2578             super(name, site, argtypes, typeargtypes, MethodResolutionPhase.VARARITY);
  2581         @Override
  2582         Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2583             if (sym.kind == AMBIGUOUS) {
  2584                 AmbiguityError a_err = (AmbiguityError)sym;
  2585                 sym = a_err.mergeAbstracts(site);
  2587             if (sym.kind >= AMBIGUOUS) {
  2588                 //if nothing is found return the 'first' error
  2589                 sym = accessMethod(sym, pos, location, site, name, true, argtypes, typeargtypes);
  2591             return sym;
  2595     /**
  2596      * Helper class for member reference lookup. A reference lookup helper
  2597      * defines the basic logic for member reference lookup; a method gives
  2598      * access to an 'unbound' helper used to perform an unbound member
  2599      * reference lookup.
  2600      */
  2601     abstract class ReferenceLookupHelper extends LookupHelper {
  2603         /** The member reference tree */
  2604         JCMemberReference referenceTree;
  2606         ReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
  2607                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2608             super(name, site, argtypes, typeargtypes, maxPhase);
  2609             this.referenceTree = referenceTree;
  2613         /**
  2614          * Returns an unbound version of this lookup helper. By default, this
  2615          * method returns an dummy lookup helper.
  2616          */
  2617         ReferenceLookupHelper unboundLookup() {
  2618             //dummy loopkup helper that always return 'methodNotFound'
  2619             return new ReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase) {
  2620                 @Override
  2621                 ReferenceLookupHelper unboundLookup() {
  2622                     return this;
  2624                 @Override
  2625                 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2626                     return methodNotFound;
  2628                 @Override
  2629                 ReferenceKind referenceKind(Symbol sym) {
  2630                     Assert.error();
  2631                     return null;
  2633             };
  2636         /**
  2637          * Get the kind of the member reference
  2638          */
  2639         abstract JCMemberReference.ReferenceKind referenceKind(Symbol sym);
  2641         Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2642             if (sym.kind == AMBIGUOUS) {
  2643                 AmbiguityError a_err = (AmbiguityError)sym;
  2644                 sym = a_err.mergeAbstracts(site);
  2646             //skip error reporting
  2647             return sym;
  2651     /**
  2652      * Helper class for method reference lookup. The lookup logic is based
  2653      * upon Resolve.findMethod; in certain cases, this helper class has a
  2654      * corresponding unbound helper class (see UnboundMethodReferenceLookupHelper).
  2655      * In such cases, non-static lookup results are thrown away.
  2656      */
  2657     class MethodReferenceLookupHelper extends ReferenceLookupHelper {
  2659         MethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
  2660                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2661             super(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
  2664         @Override
  2665         final Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2666             return findMethod(env, site, name, argtypes, typeargtypes,
  2667                     phase.isBoxingRequired(), phase.isVarargsRequired(), syms.operatorNames.contains(name));
  2670         @Override
  2671         ReferenceLookupHelper unboundLookup() {
  2672             if (TreeInfo.isStaticSelector(referenceTree.expr, names) &&
  2673                     argtypes.nonEmpty() &&
  2674                     types.isSubtypeUnchecked(argtypes.head, site)) {
  2675                 return new UnboundMethodReferenceLookupHelper(referenceTree, name,
  2676                         site, argtypes, typeargtypes, maxPhase);
  2677             } else {
  2678                 return super.unboundLookup();
  2682         @Override
  2683         ReferenceKind referenceKind(Symbol sym) {
  2684             if (sym.isStatic()) {
  2685                 return ReferenceKind.STATIC;
  2686             } else {
  2687                 Name selName = TreeInfo.name(referenceTree.getQualifierExpression());
  2688                 return selName != null && selName == names._super ?
  2689                         ReferenceKind.SUPER :
  2690                         ReferenceKind.BOUND;
  2695     /**
  2696      * Helper class for unbound method reference lookup. Essentially the same
  2697      * as the basic method reference lookup helper; main difference is that static
  2698      * lookup results are thrown away. If qualifier type is raw, an attempt to
  2699      * infer a parameterized type is made using the first actual argument (that
  2700      * would otherwise be ignored during the lookup).
  2701      */
  2702     class UnboundMethodReferenceLookupHelper extends MethodReferenceLookupHelper {
  2704         UnboundMethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
  2705                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2706             super(referenceTree, name, site, argtypes.tail, typeargtypes, maxPhase);
  2707             Type asSuperSite = types.asSuper(argtypes.head, site.tsym);
  2708             if (site.isRaw() && !asSuperSite.isErroneous()) {
  2709                 this.site = asSuperSite;
  2713         @Override
  2714         ReferenceLookupHelper unboundLookup() {
  2715             return this;
  2718         @Override
  2719         ReferenceKind referenceKind(Symbol sym) {
  2720             return ReferenceKind.UNBOUND;
  2724     /**
  2725      * Helper class for array constructor lookup; an array constructor lookup
  2726      * is simulated by looking up a method that returns the array type specified
  2727      * as qualifier, and that accepts a single int parameter (size of the array).
  2728      */
  2729     class ArrayConstructorReferenceLookupHelper extends ReferenceLookupHelper {
  2731         ArrayConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
  2732                 List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2733             super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase);
  2736         @Override
  2737         protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2738             Scope sc = new Scope(syms.arrayClass);
  2739             MethodSymbol arrayConstr = new MethodSymbol(PUBLIC, name, null, site.tsym);
  2740             arrayConstr.type = new MethodType(List.of(syms.intType), site, List.<Type>nil(), syms.methodClass);
  2741             sc.enter(arrayConstr);
  2742             return findMethodInScope(env, site, name, argtypes, typeargtypes, sc, methodNotFound, phase.isBoxingRequired(), phase.isVarargsRequired(), false, false);
  2745         @Override
  2746         ReferenceKind referenceKind(Symbol sym) {
  2747             return ReferenceKind.ARRAY_CTOR;
  2751     /**
  2752      * Helper class for constructor reference lookup. The lookup logic is based
  2753      * upon either Resolve.findMethod or Resolve.findDiamond - depending on
  2754      * whether the constructor reference needs diamond inference (this is the case
  2755      * if the qualifier type is raw). A special erroneous symbol is returned
  2756      * if the lookup returns the constructor of an inner class and there's no
  2757      * enclosing instance in scope.
  2758      */
  2759     class ConstructorReferenceLookupHelper extends ReferenceLookupHelper {
  2761         boolean needsInference;
  2763         ConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
  2764                 List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2765             super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase);
  2766             if (site.isRaw()) {
  2767                 this.site = new ClassType(site.getEnclosingType(), site.tsym.type.getTypeArguments(), site.tsym);
  2768                 needsInference = true;
  2772         @Override
  2773         protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2774             Symbol sym = needsInference ?
  2775                 findDiamond(env, site, argtypes, typeargtypes, phase.isBoxingRequired(), phase.isVarargsRequired()) :
  2776                 findMethod(env, site, name, argtypes, typeargtypes,
  2777                         phase.isBoxingRequired(), phase.isVarargsRequired(), syms.operatorNames.contains(name));
  2778             return sym.kind != MTH ||
  2779                           site.getEnclosingType().hasTag(NONE) ||
  2780                           hasEnclosingInstance(env, site) ?
  2781                           sym : new InvalidSymbolError(Kinds.MISSING_ENCL, sym, null) {
  2782                     @Override
  2783                     JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
  2784                        return diags.create(dkind, log.currentSource(), pos,
  2785                             "cant.access.inner.cls.constr", site.tsym.name, argtypes, site.getEnclosingType());
  2787                 };
  2790         @Override
  2791         ReferenceKind referenceKind(Symbol sym) {
  2792             return site.getEnclosingType().hasTag(NONE) ?
  2793                     ReferenceKind.TOPLEVEL : ReferenceKind.IMPLICIT_INNER;
  2797     /**
  2798      * Main overload resolution routine. On each overload resolution step, a
  2799      * lookup helper class is used to perform the method/constructor lookup;
  2800      * at the end of the lookup, the helper is used to validate the results
  2801      * (this last step might trigger overload resolution diagnostics).
  2802      */
  2803     Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, LookupHelper lookupHelper) {
  2804         return lookupMethod(env, pos, location, new MethodResolutionContext(), lookupHelper);
  2807     Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location,
  2808             MethodResolutionContext resolveContext, LookupHelper lookupHelper) {
  2809         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  2810         try {
  2811             Symbol bestSoFar = methodNotFound;
  2812             currentResolutionContext = resolveContext;
  2813             for (MethodResolutionPhase phase : methodResolutionSteps) {
  2814                 if (!phase.isApplicable(boxingEnabled, varargsEnabled) ||
  2815                         lookupHelper.shouldStop(bestSoFar, phase)) break;
  2816                 MethodResolutionPhase prevPhase = currentResolutionContext.step;
  2817                 Symbol prevBest = bestSoFar;
  2818                 currentResolutionContext.step = phase;
  2819                 bestSoFar = phase.mergeResults(bestSoFar, lookupHelper.lookup(env, phase));
  2820                 env.info.pendingResolutionPhase = (prevBest == bestSoFar) ? prevPhase : phase;
  2822             return lookupHelper.access(env, pos, location, bestSoFar);
  2823         } finally {
  2824             currentResolutionContext = prevResolutionContext;
  2828     /**
  2829      * Resolve `c.name' where name == this or name == super.
  2830      * @param pos           The position to use for error reporting.
  2831      * @param env           The environment current at the expression.
  2832      * @param c             The qualifier.
  2833      * @param name          The identifier's name.
  2834      */
  2835     Symbol resolveSelf(DiagnosticPosition pos,
  2836                        Env<AttrContext> env,
  2837                        TypeSymbol c,
  2838                        Name name) {
  2839         Env<AttrContext> env1 = env;
  2840         boolean staticOnly = false;
  2841         while (env1.outer != null) {
  2842             if (isStatic(env1)) staticOnly = true;
  2843             if (env1.enclClass.sym == c) {
  2844                 Symbol sym = env1.info.scope.lookup(name).sym;
  2845                 if (sym != null) {
  2846                     if (staticOnly) sym = new StaticError(sym);
  2847                     return accessBase(sym, pos, env.enclClass.sym.type,
  2848                                   name, true);
  2851             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  2852             env1 = env1.outer;
  2854         if (allowDefaultMethods && c.isInterface() &&
  2855                 name == names._super && !isStatic(env) &&
  2856                 types.isDirectSuperInterface(c, env.enclClass.sym)) {
  2857             //this might be a default super call if one of the superinterfaces is 'c'
  2858             for (Type t : pruneInterfaces(env.enclClass.type)) {
  2859                 if (t.tsym == c) {
  2860                     env.info.defaultSuperCallSite = t;
  2861                     return new VarSymbol(0, names._super,
  2862                             types.asSuper(env.enclClass.type, c), env.enclClass.sym);
  2865             //find a direct superinterface that is a subtype of 'c'
  2866             for (Type i : types.interfaces(env.enclClass.type)) {
  2867                 if (i.tsym.isSubClass(c, types) && i.tsym != c) {
  2868                     log.error(pos, "illegal.default.super.call", c,
  2869                             diags.fragment("redundant.supertype", c, i));
  2870                     return syms.errSymbol;
  2873             Assert.error();
  2875         log.error(pos, "not.encl.class", c);
  2876         return syms.errSymbol;
  2878     //where
  2879     private List<Type> pruneInterfaces(Type t) {
  2880         ListBuffer<Type> result = ListBuffer.lb();
  2881         for (Type t1 : types.interfaces(t)) {
  2882             boolean shouldAdd = true;
  2883             for (Type t2 : types.interfaces(t)) {
  2884                 if (t1 != t2 && types.isSubtypeNoCapture(t2, t1)) {
  2885                     shouldAdd = false;
  2888             if (shouldAdd) {
  2889                 result.append(t1);
  2892         return result.toList();
  2896     /**
  2897      * Resolve `c.this' for an enclosing class c that contains the
  2898      * named member.
  2899      * @param pos           The position to use for error reporting.
  2900      * @param env           The environment current at the expression.
  2901      * @param member        The member that must be contained in the result.
  2902      */
  2903     Symbol resolveSelfContaining(DiagnosticPosition pos,
  2904                                  Env<AttrContext> env,
  2905                                  Symbol member,
  2906                                  boolean isSuperCall) {
  2907         Symbol sym = resolveSelfContainingInternal(env, member, isSuperCall);
  2908         if (sym == null) {
  2909             log.error(pos, "encl.class.required", member);
  2910             return syms.errSymbol;
  2911         } else {
  2912             return accessBase(sym, pos, env.enclClass.sym.type, sym.name, true);
  2916     boolean hasEnclosingInstance(Env<AttrContext> env, Type type) {
  2917         Symbol encl = resolveSelfContainingInternal(env, type.tsym, false);
  2918         return encl != null && encl.kind < ERRONEOUS;
  2921     private Symbol resolveSelfContainingInternal(Env<AttrContext> env,
  2922                                  Symbol member,
  2923                                  boolean isSuperCall) {
  2924         Name name = names._this;
  2925         Env<AttrContext> env1 = isSuperCall ? env.outer : env;
  2926         boolean staticOnly = false;
  2927         if (env1 != null) {
  2928             while (env1 != null && env1.outer != null) {
  2929                 if (isStatic(env1)) staticOnly = true;
  2930                 if (env1.enclClass.sym.isSubClass(member.owner, types)) {
  2931                     Symbol sym = env1.info.scope.lookup(name).sym;
  2932                     if (sym != null) {
  2933                         if (staticOnly) sym = new StaticError(sym);
  2934                         return sym;
  2937                 if ((env1.enclClass.sym.flags() & STATIC) != 0)
  2938                     staticOnly = true;
  2939                 env1 = env1.outer;
  2942         return null;
  2945     /**
  2946      * Resolve an appropriate implicit this instance for t's container.
  2947      * JLS 8.8.5.1 and 15.9.2
  2948      */
  2949     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
  2950         return resolveImplicitThis(pos, env, t, false);
  2953     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t, boolean isSuperCall) {
  2954         Type thisType = (((t.tsym.owner.kind & (MTH|VAR)) != 0)
  2955                          ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
  2956                          : resolveSelfContaining(pos, env, t.tsym, isSuperCall)).type;
  2957         if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
  2958             log.error(pos, "cant.ref.before.ctor.called", "this");
  2959         return thisType;
  2962 /* ***************************************************************************
  2963  *  ResolveError classes, indicating error situations when accessing symbols
  2964  ****************************************************************************/
  2966     //used by TransTypes when checking target type of synthetic cast
  2967     public void logAccessErrorInternal(Env<AttrContext> env, JCTree tree, Type type) {
  2968         AccessError error = new AccessError(env, env.enclClass.type, type.tsym);
  2969         logResolveError(error, tree.pos(), env.enclClass.sym, env.enclClass.type, null, null, null);
  2971     //where
  2972     private void logResolveError(ResolveError error,
  2973             DiagnosticPosition pos,
  2974             Symbol location,
  2975             Type site,
  2976             Name name,
  2977             List<Type> argtypes,
  2978             List<Type> typeargtypes) {
  2979         JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
  2980                 pos, location, site, name, argtypes, typeargtypes);
  2981         if (d != null) {
  2982             d.setFlag(DiagnosticFlag.RESOLVE_ERROR);
  2983             log.report(d);
  2987     private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
  2989     public Object methodArguments(List<Type> argtypes) {
  2990         if (argtypes == null || argtypes.isEmpty()) {
  2991             return noArgs;
  2992         } else {
  2993             ListBuffer<Object> diagArgs = ListBuffer.lb();
  2994             for (Type t : argtypes) {
  2995                 if (t.hasTag(DEFERRED)) {
  2996                     diagArgs.append(((DeferredAttr.DeferredType)t).tree);
  2997                 } else {
  2998                     diagArgs.append(t);
  3001             return diagArgs;
  3005     /**
  3006      * Root class for resolution errors. Subclass of ResolveError
  3007      * represent a different kinds of resolution error - as such they must
  3008      * specify how they map into concrete compiler diagnostics.
  3009      */
  3010     abstract class ResolveError extends Symbol {
  3012         /** The name of the kind of error, for debugging only. */
  3013         final String debugName;
  3015         ResolveError(int kind, String debugName) {
  3016             super(kind, 0, null, null, null);
  3017             this.debugName = debugName;
  3020         @Override
  3021         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
  3022             throw new AssertionError();
  3025         @Override
  3026         public String toString() {
  3027             return debugName;
  3030         @Override
  3031         public boolean exists() {
  3032             return false;
  3035         /**
  3036          * Create an external representation for this erroneous symbol to be
  3037          * used during attribution - by default this returns the symbol of a
  3038          * brand new error type which stores the original type found
  3039          * during resolution.
  3041          * @param name     the name used during resolution
  3042          * @param location the location from which the symbol is accessed
  3043          */
  3044         protected Symbol access(Name name, TypeSymbol location) {
  3045             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  3048         /**
  3049          * Create a diagnostic representing this resolution error.
  3051          * @param dkind     The kind of the diagnostic to be created (e.g error).
  3052          * @param pos       The position to be used for error reporting.
  3053          * @param site      The original type from where the selection took place.
  3054          * @param name      The name of the symbol to be resolved.
  3055          * @param argtypes  The invocation's value arguments,
  3056          *                  if we looked for a method.
  3057          * @param typeargtypes  The invocation's type arguments,
  3058          *                      if we looked for a method.
  3059          */
  3060         abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3061                 DiagnosticPosition pos,
  3062                 Symbol location,
  3063                 Type site,
  3064                 Name name,
  3065                 List<Type> argtypes,
  3066                 List<Type> typeargtypes);
  3069     /**
  3070      * This class is the root class of all resolution errors caused by
  3071      * an invalid symbol being found during resolution.
  3072      */
  3073     abstract class InvalidSymbolError extends ResolveError {
  3075         /** The invalid symbol found during resolution */
  3076         Symbol sym;
  3078         InvalidSymbolError(int kind, Symbol sym, String debugName) {
  3079             super(kind, debugName);
  3080             this.sym = sym;
  3083         @Override
  3084         public boolean exists() {
  3085             return true;
  3088         @Override
  3089         public String toString() {
  3090              return super.toString() + " wrongSym=" + sym;
  3093         @Override
  3094         public Symbol access(Name name, TypeSymbol location) {
  3095             if ((sym.kind & ERRONEOUS) == 0 && (sym.kind & TYP) != 0)
  3096                 return types.createErrorType(name, location, sym.type).tsym;
  3097             else
  3098                 return sym;
  3102     /**
  3103      * InvalidSymbolError error class indicating that a symbol matching a
  3104      * given name does not exists in a given site.
  3105      */
  3106     class SymbolNotFoundError extends ResolveError {
  3108         SymbolNotFoundError(int kind) {
  3109             super(kind, "symbol not found error");
  3112         @Override
  3113         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3114                 DiagnosticPosition pos,
  3115                 Symbol location,
  3116                 Type site,
  3117                 Name name,
  3118                 List<Type> argtypes,
  3119                 List<Type> typeargtypes) {
  3120             argtypes = argtypes == null ? List.<Type>nil() : argtypes;
  3121             typeargtypes = typeargtypes == null ? List.<Type>nil() : typeargtypes;
  3122             if (name == names.error)
  3123                 return null;
  3125             if (syms.operatorNames.contains(name)) {
  3126                 boolean isUnaryOp = argtypes.size() == 1;
  3127                 String key = argtypes.size() == 1 ?
  3128                     "operator.cant.be.applied" :
  3129                     "operator.cant.be.applied.1";
  3130                 Type first = argtypes.head;
  3131                 Type second = !isUnaryOp ? argtypes.tail.head : null;
  3132                 return diags.create(dkind, log.currentSource(), pos,
  3133                         key, name, first, second);
  3135             boolean hasLocation = false;
  3136             if (location == null) {
  3137                 location = site.tsym;
  3139             if (!location.name.isEmpty()) {
  3140                 if (location.kind == PCK && !site.tsym.exists()) {
  3141                     return diags.create(dkind, log.currentSource(), pos,
  3142                         "doesnt.exist", location);
  3144                 hasLocation = !location.name.equals(names._this) &&
  3145                         !location.name.equals(names._super);
  3147             boolean isConstructor = kind == ABSENT_MTH && name == names.init;
  3148             KindName kindname = isConstructor ? KindName.CONSTRUCTOR : absentKind(kind);
  3149             Name idname = isConstructor ? site.tsym.name : name;
  3150             String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation);
  3151             if (hasLocation) {
  3152                 return diags.create(dkind, log.currentSource(), pos,
  3153                         errKey, kindname, idname, //symbol kindname, name
  3154                         typeargtypes, args(argtypes), //type parameters and arguments (if any)
  3155                         getLocationDiag(location, site)); //location kindname, type
  3157             else {
  3158                 return diags.create(dkind, log.currentSource(), pos,
  3159                         errKey, kindname, idname, //symbol kindname, name
  3160                         typeargtypes, args(argtypes)); //type parameters and arguments (if any)
  3163         //where
  3164         private Object args(List<Type> args) {
  3165             return args.isEmpty() ? args : methodArguments(args);
  3168         private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) {
  3169             String key = "cant.resolve";
  3170             String suffix = hasLocation ? ".location" : "";
  3171             switch (kindname) {
  3172                 case METHOD:
  3173                 case CONSTRUCTOR: {
  3174                     suffix += ".args";
  3175                     suffix += hasTypeArgs ? ".params" : "";
  3178             return key + suffix;
  3180         private JCDiagnostic getLocationDiag(Symbol location, Type site) {
  3181             if (location.kind == VAR) {
  3182                 return diags.fragment("location.1",
  3183                     kindName(location),
  3184                     location,
  3185                     location.type);
  3186             } else {
  3187                 return diags.fragment("location",
  3188                     typeKindName(site),
  3189                     site,
  3190                     null);
  3195     /**
  3196      * InvalidSymbolError error class indicating that a given symbol
  3197      * (either a method, a constructor or an operand) is not applicable
  3198      * given an actual arguments/type argument list.
  3199      */
  3200     class InapplicableSymbolError extends ResolveError {
  3202         protected MethodResolutionContext resolveContext;
  3204         InapplicableSymbolError(MethodResolutionContext context) {
  3205             this(WRONG_MTH, "inapplicable symbol error", context);
  3208         protected InapplicableSymbolError(int kind, String debugName, MethodResolutionContext context) {
  3209             super(kind, debugName);
  3210             this.resolveContext = context;
  3213         @Override
  3214         public String toString() {
  3215             return super.toString();
  3218         @Override
  3219         public boolean exists() {
  3220             return true;
  3223         @Override
  3224         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3225                 DiagnosticPosition pos,
  3226                 Symbol location,
  3227                 Type site,
  3228                 Name name,
  3229                 List<Type> argtypes,
  3230                 List<Type> typeargtypes) {
  3231             if (name == names.error)
  3232                 return null;
  3234             if (syms.operatorNames.contains(name)) {
  3235                 boolean isUnaryOp = argtypes.size() == 1;
  3236                 String key = argtypes.size() == 1 ?
  3237                     "operator.cant.be.applied" :
  3238                     "operator.cant.be.applied.1";
  3239                 Type first = argtypes.head;
  3240                 Type second = !isUnaryOp ? argtypes.tail.head : null;
  3241                 return diags.create(dkind, log.currentSource(), pos,
  3242                         key, name, first, second);
  3244             else {
  3245                 Candidate c = errCandidate();
  3246                 Symbol ws = c.sym.asMemberOf(site, types);
  3247                 return diags.create(dkind, log.currentSource(), pos,
  3248                           "cant.apply.symbol",
  3249                           kindName(ws),
  3250                           ws.name == names.init ? ws.owner.name : ws.name,
  3251                           methodArguments(ws.type.getParameterTypes()),
  3252                           methodArguments(argtypes),
  3253                           kindName(ws.owner),
  3254                           ws.owner.type,
  3255                           c.details);
  3259         @Override
  3260         public Symbol access(Name name, TypeSymbol location) {
  3261             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  3264         private Candidate errCandidate() {
  3265             Candidate bestSoFar = null;
  3266             for (Candidate c : resolveContext.candidates) {
  3267                 if (c.isApplicable()) continue;
  3268                 bestSoFar = c;
  3270             Assert.checkNonNull(bestSoFar);
  3271             return bestSoFar;
  3275     /**
  3276      * ResolveError error class indicating that a set of symbols
  3277      * (either methods, constructors or operands) is not applicable
  3278      * given an actual arguments/type argument list.
  3279      */
  3280     class InapplicableSymbolsError extends InapplicableSymbolError {
  3282         InapplicableSymbolsError(MethodResolutionContext context) {
  3283             super(WRONG_MTHS, "inapplicable symbols", context);
  3286         @Override
  3287         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3288                 DiagnosticPosition pos,
  3289                 Symbol location,
  3290                 Type site,
  3291                 Name name,
  3292                 List<Type> argtypes,
  3293                 List<Type> typeargtypes) {
  3294             if (!resolveContext.candidates.isEmpty()) {
  3295                 JCDiagnostic err = diags.create(dkind,
  3296                         log.currentSource(),
  3297                         pos,
  3298                         "cant.apply.symbols",
  3299                         name == names.init ? KindName.CONSTRUCTOR : absentKind(kind),
  3300                         name == names.init ? site.tsym.name : name,
  3301                         methodArguments(argtypes));
  3302                 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(site));
  3303             } else {
  3304                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
  3305                     location, site, name, argtypes, typeargtypes);
  3309         //where
  3310         List<JCDiagnostic> candidateDetails(Type site) {
  3311             Map<Symbol, JCDiagnostic> details = new LinkedHashMap<Symbol, JCDiagnostic>();
  3312             for (Candidate c : resolveContext.candidates) {
  3313                 if (c.isApplicable()) continue;
  3314                 JCDiagnostic detailDiag = diags.fragment("inapplicable.method",
  3315                         Kinds.kindName(c.sym),
  3316                         c.sym.location(site, types),
  3317                         c.sym.asMemberOf(site, types),
  3318                         c.details);
  3319                 details.put(c.sym, detailDiag);
  3321             return List.from(details.values());
  3325     /**
  3326      * An InvalidSymbolError error class indicating that a symbol is not
  3327      * accessible from a given site
  3328      */
  3329     class AccessError extends InvalidSymbolError {
  3331         private Env<AttrContext> env;
  3332         private Type site;
  3334         AccessError(Symbol sym) {
  3335             this(null, null, sym);
  3338         AccessError(Env<AttrContext> env, Type site, Symbol sym) {
  3339             super(HIDDEN, sym, "access error");
  3340             this.env = env;
  3341             this.site = site;
  3342             if (debugResolve)
  3343                 log.error("proc.messager", sym + " @ " + site + " is inaccessible.");
  3346         @Override
  3347         public boolean exists() {
  3348             return false;
  3351         @Override
  3352         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3353                 DiagnosticPosition pos,
  3354                 Symbol location,
  3355                 Type site,
  3356                 Name name,
  3357                 List<Type> argtypes,
  3358                 List<Type> typeargtypes) {
  3359             if (sym.owner.type.hasTag(ERROR))
  3360                 return null;
  3362             if (sym.name == names.init && sym.owner != site.tsym) {
  3363                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
  3364                         pos, location, site, name, argtypes, typeargtypes);
  3366             else if ((sym.flags() & PUBLIC) != 0
  3367                 || (env != null && this.site != null
  3368                     && !isAccessible(env, this.site))) {
  3369                 return diags.create(dkind, log.currentSource(),
  3370                         pos, "not.def.access.class.intf.cant.access",
  3371                     sym, sym.location());
  3373             else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) {
  3374                 return diags.create(dkind, log.currentSource(),
  3375                         pos, "report.access", sym,
  3376                         asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
  3377                         sym.location());
  3379             else {
  3380                 return diags.create(dkind, log.currentSource(),
  3381                         pos, "not.def.public.cant.access", sym, sym.location());
  3386     /**
  3387      * InvalidSymbolError error class indicating that an instance member
  3388      * has erroneously been accessed from a static context.
  3389      */
  3390     class StaticError extends InvalidSymbolError {
  3392         StaticError(Symbol sym) {
  3393             super(STATICERR, sym, "static error");
  3396         @Override
  3397         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3398                 DiagnosticPosition pos,
  3399                 Symbol location,
  3400                 Type site,
  3401                 Name name,
  3402                 List<Type> argtypes,
  3403                 List<Type> typeargtypes) {
  3404             Symbol errSym = ((sym.kind == TYP && sym.type.hasTag(CLASS))
  3405                 ? types.erasure(sym.type).tsym
  3406                 : sym);
  3407             return diags.create(dkind, log.currentSource(), pos,
  3408                     "non-static.cant.be.ref", kindName(sym), errSym);
  3412     /**
  3413      * InvalidSymbolError error class indicating that a pair of symbols
  3414      * (either methods, constructors or operands) are ambiguous
  3415      * given an actual arguments/type argument list.
  3416      */
  3417     class AmbiguityError extends ResolveError {
  3419         /** The other maximally specific symbol */
  3420         List<Symbol> ambiguousSyms = List.nil();
  3422         @Override
  3423         public boolean exists() {
  3424             return true;
  3427         AmbiguityError(Symbol sym1, Symbol sym2) {
  3428             super(AMBIGUOUS, "ambiguity error");
  3429             ambiguousSyms = flatten(sym2).appendList(flatten(sym1));
  3432         private List<Symbol> flatten(Symbol sym) {
  3433             if (sym.kind == AMBIGUOUS) {
  3434                 return ((AmbiguityError)sym).ambiguousSyms;
  3435             } else {
  3436                 return List.of(sym);
  3440         AmbiguityError addAmbiguousSymbol(Symbol s) {
  3441             ambiguousSyms = ambiguousSyms.prepend(s);
  3442             return this;
  3445         @Override
  3446         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3447                 DiagnosticPosition pos,
  3448                 Symbol location,
  3449                 Type site,
  3450                 Name name,
  3451                 List<Type> argtypes,
  3452                 List<Type> typeargtypes) {
  3453             List<Symbol> diagSyms = ambiguousSyms.reverse();
  3454             Symbol s1 = diagSyms.head;
  3455             Symbol s2 = diagSyms.tail.head;
  3456             Name sname = s1.name;
  3457             if (sname == names.init) sname = s1.owner.name;
  3458             return diags.create(dkind, log.currentSource(),
  3459                       pos, "ref.ambiguous", sname,
  3460                       kindName(s1),
  3461                       s1,
  3462                       s1.location(site, types),
  3463                       kindName(s2),
  3464                       s2,
  3465                       s2.location(site, types));
  3468         /**
  3469          * If multiple applicable methods are found during overload and none of them
  3470          * is more specific than the others, attempt to merge their signatures.
  3471          */
  3472         Symbol mergeAbstracts(Type site) {
  3473             Symbol fst = ambiguousSyms.last();
  3474             Symbol res = fst;
  3475             for (Symbol s : ambiguousSyms.reverse()) {
  3476                 Type mt1 = types.memberType(site, res);
  3477                 Type mt2 = types.memberType(site, s);
  3478                 if ((s.flags() & ABSTRACT) == 0 ||
  3479                         !types.overrideEquivalent(mt1, mt2) ||
  3480                         !types.isSameTypes(fst.erasure(types).getParameterTypes(),
  3481                                        s.erasure(types).getParameterTypes())) {
  3482                     //ambiguity cannot be resolved
  3483                     return this;
  3484                 } else {
  3485                     Type mst = mostSpecificReturnType(mt1, mt2);
  3486                     if (mst == null) {
  3487                         // Theoretically, this can't happen, but it is possible
  3488                         // due to error recovery or mixing incompatible class files
  3489                         return this;
  3491                     Symbol mostSpecific = mst == mt1 ? res : s;
  3492                     List<Type> allThrown = chk.intersect(mt1.getThrownTypes(), mt2.getThrownTypes());
  3493                     Type newSig = types.createMethodTypeWithThrown(mostSpecific.type, allThrown);
  3494                     res = new MethodSymbol(
  3495                             mostSpecific.flags(),
  3496                             mostSpecific.name,
  3497                             newSig,
  3498                             mostSpecific.owner);
  3501             return res;
  3504         @Override
  3505         protected Symbol access(Name name, TypeSymbol location) {
  3506             Symbol firstAmbiguity = ambiguousSyms.last();
  3507             return firstAmbiguity.kind == TYP ?
  3508                     types.createErrorType(name, location, firstAmbiguity.type).tsym :
  3509                     firstAmbiguity;
  3513     class BadVarargsMethod extends ResolveError {
  3515         ResolveError delegatedError;
  3517         BadVarargsMethod(ResolveError delegatedError) {
  3518             super(delegatedError.kind, "badVarargs");
  3519             this.delegatedError = delegatedError;
  3522         @Override
  3523         protected Symbol access(Name name, TypeSymbol location) {
  3524             return delegatedError.access(name, location);
  3527         @Override
  3528         public boolean exists() {
  3529             return true;
  3532         @Override
  3533         JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
  3534             return delegatedError.getDiagnostic(dkind, pos, location, site, name, argtypes, typeargtypes);
  3538     enum MethodResolutionPhase {
  3539         BASIC(false, false),
  3540         BOX(true, false),
  3541         VARARITY(true, true) {
  3542             @Override
  3543             public Symbol mergeResults(Symbol bestSoFar, Symbol sym) {
  3544                 switch (sym.kind) {
  3545                     case WRONG_MTH:
  3546                         return (bestSoFar.kind == WRONG_MTH || bestSoFar.kind == WRONG_MTHS) ?
  3547                             bestSoFar :
  3548                             sym;
  3549                     case ABSENT_MTH:
  3550                         return bestSoFar;
  3551                     default:
  3552                         return sym;
  3555         };
  3557         final boolean isBoxingRequired;
  3558         final boolean isVarargsRequired;
  3560         MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) {
  3561            this.isBoxingRequired = isBoxingRequired;
  3562            this.isVarargsRequired = isVarargsRequired;
  3565         public boolean isBoxingRequired() {
  3566             return isBoxingRequired;
  3569         public boolean isVarargsRequired() {
  3570             return isVarargsRequired;
  3573         public boolean isApplicable(boolean boxingEnabled, boolean varargsEnabled) {
  3574             return (varargsEnabled || !isVarargsRequired) &&
  3575                    (boxingEnabled || !isBoxingRequired);
  3578         public Symbol mergeResults(Symbol prev, Symbol sym) {
  3579             return sym;
  3583     final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
  3585     /**
  3586      * A resolution context is used to keep track of intermediate results of
  3587      * overload resolution, such as list of method that are not applicable
  3588      * (used to generate more precise diagnostics) and so on. Resolution contexts
  3589      * can be nested - this means that when each overload resolution routine should
  3590      * work within the resolution context it created.
  3591      */
  3592     class MethodResolutionContext {
  3594         private List<Candidate> candidates = List.nil();
  3596         MethodResolutionPhase step = null;
  3598         private boolean internalResolution = false;
  3599         private DeferredAttr.AttrMode attrMode = DeferredAttr.AttrMode.SPECULATIVE;
  3601         void addInapplicableCandidate(Symbol sym, JCDiagnostic details) {
  3602             Candidate c = new Candidate(currentResolutionContext.step, sym, details, null);
  3603             candidates = candidates.append(c);
  3606         void addApplicableCandidate(Symbol sym, Type mtype) {
  3607             Candidate c = new Candidate(currentResolutionContext.step, sym, null, mtype);
  3608             candidates = candidates.append(c);
  3611         DeferredAttrContext deferredAttrContext(Symbol sym, InferenceContext inferenceContext, ResultInfo pendingResult, Warner warn) {
  3612             return deferredAttr.new DeferredAttrContext(attrMode, sym, step, inferenceContext, pendingResult != null ? pendingResult.checkContext.deferredAttrContext() : deferredAttr.emptyDeferredAttrContext, warn);
  3615         /**
  3616          * This class represents an overload resolution candidate. There are two
  3617          * kinds of candidates: applicable methods and inapplicable methods;
  3618          * applicable methods have a pointer to the instantiated method type,
  3619          * while inapplicable candidates contain further details about the
  3620          * reason why the method has been considered inapplicable.
  3621          */
  3622         @SuppressWarnings("overrides")
  3623         class Candidate {
  3625             final MethodResolutionPhase step;
  3626             final Symbol sym;
  3627             final JCDiagnostic details;
  3628             final Type mtype;
  3630             private Candidate(MethodResolutionPhase step, Symbol sym, JCDiagnostic details, Type mtype) {
  3631                 this.step = step;
  3632                 this.sym = sym;
  3633                 this.details = details;
  3634                 this.mtype = mtype;
  3637             @Override
  3638             public boolean equals(Object o) {
  3639                 if (o instanceof Candidate) {
  3640                     Symbol s1 = this.sym;
  3641                     Symbol s2 = ((Candidate)o).sym;
  3642                     if  ((s1 != s2 &&
  3643                             (s1.overrides(s2, s1.owner.type.tsym, types, false) ||
  3644                             (s2.overrides(s1, s2.owner.type.tsym, types, false)))) ||
  3645                             ((s1.isConstructor() || s2.isConstructor()) && s1.owner != s2.owner))
  3646                         return true;
  3648                 return false;
  3651             boolean isApplicable() {
  3652                 return mtype != null;
  3656         DeferredAttr.AttrMode attrMode() {
  3657             return attrMode;
  3660         boolean internal() {
  3661             return internalResolution;
  3665     MethodResolutionContext currentResolutionContext = null;

mercurial