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

Mon, 21 Jan 2013 20:13:56 +0000

author
mcimadamore
date
Mon, 21 Jan 2013 20:13:56 +0000
changeset 1510
7873d37f5b37
parent 1498
1afdf1f1472b
child 1521
71f35e4b93a5
permissions
-rw-r--r--

8005244: Implement overload resolution as per latest spec EDR
Summary: Add support for stuck expressions and provisional applicability
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 1999, 2012, 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.InferenceContext.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;
    58 import java.util.Set;
    60 import javax.lang.model.element.ElementVisitor;
    62 import static com.sun.tools.javac.code.Flags.*;
    63 import static com.sun.tools.javac.code.Flags.BLOCK;
    64 import static com.sun.tools.javac.code.Kinds.*;
    65 import static com.sun.tools.javac.code.Kinds.ERRONEOUS;
    66 import static com.sun.tools.javac.code.TypeTag.*;
    67 import static com.sun.tools.javac.comp.Resolve.MethodResolutionPhase.*;
    68 import static com.sun.tools.javac.tree.JCTree.Tag.*;
    70 /** Helper class for name resolution, used mostly by the attribution phase.
    71  *
    72  *  <p><b>This is NOT part of any supported API.
    73  *  If you write code that depends on this, you do so at your own risk.
    74  *  This code and its internal interfaces are subject to change or
    75  *  deletion without notice.</b>
    76  */
    77 public class Resolve {
    78     protected static final Context.Key<Resolve> resolveKey =
    79         new Context.Key<Resolve>();
    81     Names names;
    82     Log log;
    83     Symtab syms;
    84     Attr attr;
    85     DeferredAttr deferredAttr;
    86     Check chk;
    87     Infer infer;
    88     ClassReader reader;
    89     TreeInfo treeinfo;
    90     Types types;
    91     JCDiagnostic.Factory diags;
    92     public final boolean boxingEnabled; // = source.allowBoxing();
    93     public final boolean varargsEnabled; // = source.allowVarargs();
    94     public final boolean allowMethodHandles;
    95     public final boolean allowDefaultMethods;
    96     public final boolean allowStructuralMostSpecific;
    97     private final boolean debugResolve;
    98     final EnumSet<VerboseResolutionMode> verboseResolutionMode;
   100     Scope polymorphicSignatureScope;
   102     protected Resolve(Context context) {
   103         context.put(resolveKey, this);
   104         syms = Symtab.instance(context);
   106         varNotFound = new
   107             SymbolNotFoundError(ABSENT_VAR);
   108         methodNotFound = new
   109             SymbolNotFoundError(ABSENT_MTH);
   110         typeNotFound = new
   111             SymbolNotFoundError(ABSENT_TYP);
   113         names = Names.instance(context);
   114         log = Log.instance(context);
   115         attr = Attr.instance(context);
   116         deferredAttr = DeferredAttr.instance(context);
   117         chk = Check.instance(context);
   118         infer = Infer.instance(context);
   119         reader = ClassReader.instance(context);
   120         treeinfo = TreeInfo.instance(context);
   121         types = Types.instance(context);
   122         diags = JCDiagnostic.Factory.instance(context);
   123         Source source = Source.instance(context);
   124         boxingEnabled = source.allowBoxing();
   125         varargsEnabled = source.allowVarargs();
   126         Options options = Options.instance(context);
   127         debugResolve = options.isSet("debugresolve");
   128         verboseResolutionMode = VerboseResolutionMode.getVerboseResolutionMode(options);
   129         Target target = Target.instance(context);
   130         allowMethodHandles = target.hasMethodHandles();
   131         allowDefaultMethods = source.allowDefaultMethods();
   132         allowStructuralMostSpecific = source.allowStructuralMostSpecific();
   133         polymorphicSignatureScope = new Scope(syms.noSymbol);
   135         inapplicableMethodException = new InapplicableMethodException(diags);
   136     }
   138     /** error symbols, which are returned when resolution fails
   139      */
   140     private final SymbolNotFoundError varNotFound;
   141     private final SymbolNotFoundError methodNotFound;
   142     private final SymbolNotFoundError typeNotFound;
   144     public static Resolve instance(Context context) {
   145         Resolve instance = context.get(resolveKey);
   146         if (instance == null)
   147             instance = new Resolve(context);
   148         return instance;
   149     }
   151     // <editor-fold defaultstate="collapsed" desc="Verbose resolution diagnostics support">
   152     enum VerboseResolutionMode {
   153         SUCCESS("success"),
   154         FAILURE("failure"),
   155         APPLICABLE("applicable"),
   156         INAPPLICABLE("inapplicable"),
   157         DEFERRED_INST("deferred-inference"),
   158         PREDEF("predef"),
   159         OBJECT_INIT("object-init"),
   160         INTERNAL("internal");
   162         final String opt;
   164         private VerboseResolutionMode(String opt) {
   165             this.opt = opt;
   166         }
   168         static EnumSet<VerboseResolutionMode> getVerboseResolutionMode(Options opts) {
   169             String s = opts.get("verboseResolution");
   170             EnumSet<VerboseResolutionMode> res = EnumSet.noneOf(VerboseResolutionMode.class);
   171             if (s == null) return res;
   172             if (s.contains("all")) {
   173                 res = EnumSet.allOf(VerboseResolutionMode.class);
   174             }
   175             Collection<String> args = Arrays.asList(s.split(","));
   176             for (VerboseResolutionMode mode : values()) {
   177                 if (args.contains(mode.opt)) {
   178                     res.add(mode);
   179                 } else if (args.contains("-" + mode.opt)) {
   180                     res.remove(mode);
   181                 }
   182             }
   183             return res;
   184         }
   185     }
   187     void reportVerboseResolutionDiagnostic(DiagnosticPosition dpos, Name name, Type site,
   188             List<Type> argtypes, List<Type> typeargtypes, Symbol bestSoFar) {
   189         boolean success = bestSoFar.kind < ERRONEOUS;
   191         if (success && !verboseResolutionMode.contains(VerboseResolutionMode.SUCCESS)) {
   192             return;
   193         } else if (!success && !verboseResolutionMode.contains(VerboseResolutionMode.FAILURE)) {
   194             return;
   195         }
   197         if (bestSoFar.name == names.init &&
   198                 bestSoFar.owner == syms.objectType.tsym &&
   199                 !verboseResolutionMode.contains(VerboseResolutionMode.OBJECT_INIT)) {
   200             return; //skip diags for Object constructor resolution
   201         } else if (site == syms.predefClass.type &&
   202                 !verboseResolutionMode.contains(VerboseResolutionMode.PREDEF)) {
   203             return; //skip spurious diags for predef symbols (i.e. operators)
   204         } else if (currentResolutionContext.internalResolution &&
   205                 !verboseResolutionMode.contains(VerboseResolutionMode.INTERNAL)) {
   206             return;
   207         }
   209         int pos = 0;
   210         int mostSpecificPos = -1;
   211         ListBuffer<JCDiagnostic> subDiags = ListBuffer.lb();
   212         for (Candidate c : currentResolutionContext.candidates) {
   213             if (currentResolutionContext.step != c.step ||
   214                     (c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.APPLICABLE)) ||
   215                     (!c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.INAPPLICABLE))) {
   216                 continue;
   217             } else {
   218                 subDiags.append(c.isApplicable() ?
   219                         getVerboseApplicableCandidateDiag(pos, c.sym, c.mtype) :
   220                         getVerboseInapplicableCandidateDiag(pos, c.sym, c.details));
   221                 if (c.sym == bestSoFar)
   222                     mostSpecificPos = pos;
   223                 pos++;
   224             }
   225         }
   226         String key = success ? "verbose.resolve.multi" : "verbose.resolve.multi.1";
   227         List<Type> argtypes2 = Type.map(argtypes,
   228                     deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, bestSoFar, currentResolutionContext.step));
   229         JCDiagnostic main = diags.note(log.currentSource(), dpos, key, name,
   230                 site.tsym, mostSpecificPos, currentResolutionContext.step,
   231                 methodArguments(argtypes2),
   232                 methodArguments(typeargtypes));
   233         JCDiagnostic d = new JCDiagnostic.MultilineDiagnostic(main, subDiags.toList());
   234         log.report(d);
   235     }
   237     JCDiagnostic getVerboseApplicableCandidateDiag(int pos, Symbol sym, Type inst) {
   238         JCDiagnostic subDiag = null;
   239         if (sym.type.hasTag(FORALL)) {
   240             subDiag = diags.fragment("partial.inst.sig", inst);
   241         }
   243         String key = subDiag == null ?
   244                 "applicable.method.found" :
   245                 "applicable.method.found.1";
   247         return diags.fragment(key, pos, sym, subDiag);
   248     }
   250     JCDiagnostic getVerboseInapplicableCandidateDiag(int pos, Symbol sym, JCDiagnostic subDiag) {
   251         return diags.fragment("not.applicable.method.found", pos, sym, subDiag);
   252     }
   253     // </editor-fold>
   255 /* ************************************************************************
   256  * Identifier resolution
   257  *************************************************************************/
   259     /** An environment is "static" if its static level is greater than
   260      *  the one of its outer environment
   261      */
   262     protected static boolean isStatic(Env<AttrContext> env) {
   263         return env.info.staticLevel > env.outer.info.staticLevel;
   264     }
   266     /** An environment is an "initializer" if it is a constructor or
   267      *  an instance initializer.
   268      */
   269     static boolean isInitializer(Env<AttrContext> env) {
   270         Symbol owner = env.info.scope.owner;
   271         return owner.isConstructor() ||
   272             owner.owner.kind == TYP &&
   273             (owner.kind == VAR ||
   274              owner.kind == MTH && (owner.flags() & BLOCK) != 0) &&
   275             (owner.flags() & STATIC) == 0;
   276     }
   278     /** Is class accessible in given evironment?
   279      *  @param env    The current environment.
   280      *  @param c      The class whose accessibility is checked.
   281      */
   282     public boolean isAccessible(Env<AttrContext> env, TypeSymbol c) {
   283         return isAccessible(env, c, false);
   284     }
   286     public boolean isAccessible(Env<AttrContext> env, TypeSymbol c, boolean checkInner) {
   287         boolean isAccessible = false;
   288         switch ((short)(c.flags() & AccessFlags)) {
   289             case PRIVATE:
   290                 isAccessible =
   291                     env.enclClass.sym.outermostClass() ==
   292                     c.owner.outermostClass();
   293                 break;
   294             case 0:
   295                 isAccessible =
   296                     env.toplevel.packge == c.owner // fast special case
   297                     ||
   298                     env.toplevel.packge == c.packge()
   299                     ||
   300                     // Hack: this case is added since synthesized default constructors
   301                     // of anonymous classes should be allowed to access
   302                     // classes which would be inaccessible otherwise.
   303                     env.enclMethod != null &&
   304                     (env.enclMethod.mods.flags & ANONCONSTR) != 0;
   305                 break;
   306             default: // error recovery
   307             case PUBLIC:
   308                 isAccessible = true;
   309                 break;
   310             case PROTECTED:
   311                 isAccessible =
   312                     env.toplevel.packge == c.owner // fast special case
   313                     ||
   314                     env.toplevel.packge == c.packge()
   315                     ||
   316                     isInnerSubClass(env.enclClass.sym, c.owner);
   317                 break;
   318         }
   319         return (checkInner == false || c.type.getEnclosingType() == Type.noType) ?
   320             isAccessible :
   321             isAccessible && isAccessible(env, c.type.getEnclosingType(), checkInner);
   322     }
   323     //where
   324         /** Is given class a subclass of given base class, or an inner class
   325          *  of a subclass?
   326          *  Return null if no such class exists.
   327          *  @param c     The class which is the subclass or is contained in it.
   328          *  @param base  The base class
   329          */
   330         private boolean isInnerSubClass(ClassSymbol c, Symbol base) {
   331             while (c != null && !c.isSubClass(base, types)) {
   332                 c = c.owner.enclClass();
   333             }
   334             return c != null;
   335         }
   337     boolean isAccessible(Env<AttrContext> env, Type t) {
   338         return isAccessible(env, t, false);
   339     }
   341     boolean isAccessible(Env<AttrContext> env, Type t, boolean checkInner) {
   342         return (t.hasTag(ARRAY))
   343             ? isAccessible(env, types.elemtype(t))
   344             : isAccessible(env, t.tsym, checkInner);
   345     }
   347     /** Is symbol accessible as a member of given type in given evironment?
   348      *  @param env    The current environment.
   349      *  @param site   The type of which the tested symbol is regarded
   350      *                as a member.
   351      *  @param sym    The symbol.
   352      */
   353     public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym) {
   354         return isAccessible(env, site, sym, false);
   355     }
   356     public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym, boolean checkInner) {
   357         if (sym.name == names.init && sym.owner != site.tsym) return false;
   358         switch ((short)(sym.flags() & AccessFlags)) {
   359         case PRIVATE:
   360             return
   361                 (env.enclClass.sym == sym.owner // fast special case
   362                  ||
   363                  env.enclClass.sym.outermostClass() ==
   364                  sym.owner.outermostClass())
   365                 &&
   366                 sym.isInheritedIn(site.tsym, types);
   367         case 0:
   368             return
   369                 (env.toplevel.packge == sym.owner.owner // fast special case
   370                  ||
   371                  env.toplevel.packge == sym.packge())
   372                 &&
   373                 isAccessible(env, site, checkInner)
   374                 &&
   375                 sym.isInheritedIn(site.tsym, types)
   376                 &&
   377                 notOverriddenIn(site, sym);
   378         case PROTECTED:
   379             return
   380                 (env.toplevel.packge == sym.owner.owner // fast special case
   381                  ||
   382                  env.toplevel.packge == sym.packge()
   383                  ||
   384                  isProtectedAccessible(sym, env.enclClass.sym, site)
   385                  ||
   386                  // OK to select instance method or field from 'super' or type name
   387                  // (but type names should be disallowed elsewhere!)
   388                  env.info.selectSuper && (sym.flags() & STATIC) == 0 && sym.kind != TYP)
   389                 &&
   390                 isAccessible(env, site, checkInner)
   391                 &&
   392                 notOverriddenIn(site, sym);
   393         default: // this case includes erroneous combinations as well
   394             return isAccessible(env, site, checkInner) && notOverriddenIn(site, sym);
   395         }
   396     }
   397     //where
   398     /* `sym' is accessible only if not overridden by
   399      * another symbol which is a member of `site'
   400      * (because, if it is overridden, `sym' is not strictly
   401      * speaking a member of `site'). A polymorphic signature method
   402      * cannot be overridden (e.g. MH.invokeExact(Object[])).
   403      */
   404     private boolean notOverriddenIn(Type site, Symbol sym) {
   405         if (sym.kind != MTH || sym.isConstructor() || sym.isStatic())
   406             return true;
   407         else {
   408             Symbol s2 = ((MethodSymbol)sym).implementation(site.tsym, types, true);
   409             return (s2 == null || s2 == sym || sym.owner == s2.owner ||
   410                     !types.isSubSignature(types.memberType(site, s2), types.memberType(site, sym)));
   411         }
   412     }
   413     //where
   414         /** Is given protected symbol accessible if it is selected from given site
   415          *  and the selection takes place in given class?
   416          *  @param sym     The symbol with protected access
   417          *  @param c       The class where the access takes place
   418          *  @site          The type of the qualifier
   419          */
   420         private
   421         boolean isProtectedAccessible(Symbol sym, ClassSymbol c, Type site) {
   422             while (c != null &&
   423                    !(c.isSubClass(sym.owner, types) &&
   424                      (c.flags() & INTERFACE) == 0 &&
   425                      // In JLS 2e 6.6.2.1, the subclass restriction applies
   426                      // only to instance fields and methods -- types are excluded
   427                      // regardless of whether they are declared 'static' or not.
   428                      ((sym.flags() & STATIC) != 0 || sym.kind == TYP || site.tsym.isSubClass(c, types))))
   429                 c = c.owner.enclClass();
   430             return c != null;
   431         }
   433     /**
   434      * Performs a recursive scan of a type looking for accessibility problems
   435      * from current attribution environment
   436      */
   437     void checkAccessibleType(Env<AttrContext> env, Type t) {
   438         accessibilityChecker.visit(t, env);
   439     }
   441     /**
   442      * Accessibility type-visitor
   443      */
   444     Types.SimpleVisitor<Void, Env<AttrContext>> accessibilityChecker =
   445             new Types.SimpleVisitor<Void, Env<AttrContext>>() {
   447         void visit(List<Type> ts, Env<AttrContext> env) {
   448             for (Type t : ts) {
   449                 visit(t, env);
   450             }
   451         }
   453         public Void visitType(Type t, Env<AttrContext> env) {
   454             return null;
   455         }
   457         @Override
   458         public Void visitArrayType(ArrayType t, Env<AttrContext> env) {
   459             visit(t.elemtype, env);
   460             return null;
   461         }
   463         @Override
   464         public Void visitClassType(ClassType t, Env<AttrContext> env) {
   465             visit(t.getTypeArguments(), env);
   466             if (!isAccessible(env, t, true)) {
   467                 accessBase(new AccessError(t.tsym), env.tree.pos(), env.enclClass.sym, t, t.tsym.name, true);
   468             }
   469             return null;
   470         }
   472         @Override
   473         public Void visitWildcardType(WildcardType t, Env<AttrContext> env) {
   474             visit(t.type, env);
   475             return null;
   476         }
   478         @Override
   479         public Void visitMethodType(MethodType t, Env<AttrContext> env) {
   480             visit(t.getParameterTypes(), env);
   481             visit(t.getReturnType(), env);
   482             visit(t.getThrownTypes(), env);
   483             return null;
   484         }
   485     };
   487     /** Try to instantiate the type of a method so that it fits
   488      *  given type arguments and argument types. If succesful, return
   489      *  the method's instantiated type, else return null.
   490      *  The instantiation will take into account an additional leading
   491      *  formal parameter if the method is an instance method seen as a member
   492      *  of un underdetermined site In this case, we treat site as an additional
   493      *  parameter and the parameters of the class containing the method as
   494      *  additional type variables that get instantiated.
   495      *
   496      *  @param env         The current environment
   497      *  @param site        The type of which the method is a member.
   498      *  @param m           The method symbol.
   499      *  @param argtypes    The invocation's given value arguments.
   500      *  @param typeargtypes    The invocation's given type arguments.
   501      *  @param allowBoxing Allow boxing conversions of arguments.
   502      *  @param useVarargs Box trailing arguments into an array for varargs.
   503      */
   504     Type rawInstantiate(Env<AttrContext> env,
   505                         Type site,
   506                         Symbol m,
   507                         ResultInfo resultInfo,
   508                         List<Type> argtypes,
   509                         List<Type> typeargtypes,
   510                         boolean allowBoxing,
   511                         boolean useVarargs,
   512                         MethodCheck methodCheck,
   513                         Warner warn) throws Infer.InferenceException {
   515         Type mt = types.memberType(site, m);
   516         // tvars is the list of formal type variables for which type arguments
   517         // need to inferred.
   518         List<Type> tvars = List.nil();
   519         if (typeargtypes == null) typeargtypes = List.nil();
   520         if (!mt.hasTag(FORALL) && typeargtypes.nonEmpty()) {
   521             // This is not a polymorphic method, but typeargs are supplied
   522             // which is fine, see JLS 15.12.2.1
   523         } else if (mt.hasTag(FORALL) && typeargtypes.nonEmpty()) {
   524             ForAll pmt = (ForAll) mt;
   525             if (typeargtypes.length() != pmt.tvars.length())
   526                 throw inapplicableMethodException.setMessage("arg.length.mismatch"); // not enough args
   527             // Check type arguments are within bounds
   528             List<Type> formals = pmt.tvars;
   529             List<Type> actuals = typeargtypes;
   530             while (formals.nonEmpty() && actuals.nonEmpty()) {
   531                 List<Type> bounds = types.subst(types.getBounds((TypeVar)formals.head),
   532                                                 pmt.tvars, typeargtypes);
   533                 for (; bounds.nonEmpty(); bounds = bounds.tail)
   534                     if (!types.isSubtypeUnchecked(actuals.head, bounds.head, warn))
   535                         throw inapplicableMethodException.setMessage("explicit.param.do.not.conform.to.bounds",actuals.head, bounds);
   536                 formals = formals.tail;
   537                 actuals = actuals.tail;
   538             }
   539             mt = types.subst(pmt.qtype, pmt.tvars, typeargtypes);
   540         } else if (mt.hasTag(FORALL)) {
   541             ForAll pmt = (ForAll) mt;
   542             List<Type> tvars1 = types.newInstances(pmt.tvars);
   543             tvars = tvars.appendList(tvars1);
   544             mt = types.subst(pmt.qtype, pmt.tvars, tvars1);
   545         }
   547         // find out whether we need to go the slow route via infer
   548         boolean instNeeded = tvars.tail != null; /*inlined: tvars.nonEmpty()*/
   549         for (List<Type> l = argtypes;
   550              l.tail != null/*inlined: l.nonEmpty()*/ && !instNeeded;
   551              l = l.tail) {
   552             if (l.head.hasTag(FORALL)) instNeeded = true;
   553         }
   555         if (instNeeded)
   556             return infer.instantiateMethod(env,
   557                                     tvars,
   558                                     (MethodType)mt,
   559                                     resultInfo,
   560                                     m,
   561                                     argtypes,
   562                                     allowBoxing,
   563                                     useVarargs,
   564                                     currentResolutionContext,
   565                                     methodCheck,
   566                                     warn);
   568         methodCheck.argumentsAcceptable(env, currentResolutionContext.deferredAttrContext(m, infer.emptyContext),
   569                                 argtypes, mt.getParameterTypes(), warn);
   570         return mt;
   571     }
   573     Type checkMethod(Env<AttrContext> env,
   574                      Type site,
   575                      Symbol m,
   576                      ResultInfo resultInfo,
   577                      List<Type> argtypes,
   578                      List<Type> typeargtypes,
   579                      Warner warn) {
   580         MethodResolutionContext prevContext = currentResolutionContext;
   581         try {
   582             currentResolutionContext = new MethodResolutionContext();
   583             currentResolutionContext.attrMode = DeferredAttr.AttrMode.CHECK;
   584             MethodResolutionPhase step = currentResolutionContext.step = env.info.pendingResolutionPhase;
   585             return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
   586                     step.isBoxingRequired(), step.isVarargsRequired(), resolveMethodCheck, warn);
   587         }
   588         finally {
   589             currentResolutionContext = prevContext;
   590         }
   591     }
   593     /** Same but returns null instead throwing a NoInstanceException
   594      */
   595     Type instantiate(Env<AttrContext> env,
   596                      Type site,
   597                      Symbol m,
   598                      ResultInfo resultInfo,
   599                      List<Type> argtypes,
   600                      List<Type> typeargtypes,
   601                      boolean allowBoxing,
   602                      boolean useVarargs,
   603                      MethodCheck methodCheck,
   604                      Warner warn) {
   605         try {
   606             return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
   607                                   allowBoxing, useVarargs, methodCheck, warn);
   608         } catch (InapplicableMethodException ex) {
   609             return null;
   610         }
   611     }
   613     /**
   614      * This interface defines an entry point that should be used to perform a
   615      * method check. A method check usually consist in determining as to whether
   616      * a set of types (actuals) is compatible with another set of types (formals).
   617      * Since the notion of compatibility can vary depending on the circumstances,
   618      * this interfaces allows to easily add new pluggable method check routines.
   619      */
   620     interface MethodCheck {
   621         /**
   622          * Main method check routine. A method check usually consist in determining
   623          * as to whether a set of types (actuals) is compatible with another set of
   624          * types (formals). If an incompatibility is found, an unchecked exception
   625          * is assumed to be thrown.
   626          */
   627         void argumentsAcceptable(Env<AttrContext> env,
   628                                 DeferredAttrContext deferredAttrContext,
   629                                 List<Type> argtypes,
   630                                 List<Type> formals,
   631                                 Warner warn);
   632     }
   634     /**
   635      * Helper enum defining all method check diagnostics (used by resolveMethodCheck).
   636      */
   637     enum MethodCheckDiag {
   638         /**
   639          * Actuals and formals differs in length.
   640          */
   641         ARITY_MISMATCH("arg.length.mismatch", "infer.arg.length.mismatch"),
   642         /**
   643          * An actual is incompatible with a formal.
   644          */
   645         ARG_MISMATCH("no.conforming.assignment.exists", "infer.no.conforming.assignment.exists"),
   646         /**
   647          * An actual is incompatible with the varargs element type.
   648          */
   649         VARARG_MISMATCH("varargs.argument.mismatch", "infer.varargs.argument.mismatch"),
   650         /**
   651          * The varargs element type is inaccessible.
   652          */
   653         INACCESSIBLE_VARARGS("inaccessible.varargs.type", "inaccessible.varargs.type");
   655         final String basicKey;
   656         final String inferKey;
   658         MethodCheckDiag(String basicKey, String inferKey) {
   659             this.basicKey = basicKey;
   660             this.inferKey = inferKey;
   661         }
   662     }
   664     /**
   665      * Main method applicability routine. Given a list of actual types A,
   666      * a list of formal types F, determines whether the types in A are
   667      * compatible (by method invocation conversion) with the types in F.
   668      *
   669      * Since this routine is shared between overload resolution and method
   670      * type-inference, a (possibly empty) inference context is used to convert
   671      * formal types to the corresponding 'undet' form ahead of a compatibility
   672      * check so that constraints can be propagated and collected.
   673      *
   674      * Moreover, if one or more types in A is a deferred type, this routine uses
   675      * DeferredAttr in order to perform deferred attribution. If one or more actual
   676      * deferred types are stuck, they are placed in a queue and revisited later
   677      * after the remainder of the arguments have been seen. If this is not sufficient
   678      * to 'unstuck' the argument, a cyclic inference error is called out.
   679      *
   680      * A method check handler (see above) is used in order to report errors.
   681      */
   682     MethodCheck resolveMethodCheck = new MethodCheck() {
   683         @Override
   684         public void argumentsAcceptable(final Env<AttrContext> env,
   685                                     DeferredAttrContext deferredAttrContext,
   686                                     List<Type> argtypes,
   687                                     List<Type> formals,
   688                                     Warner warn) {
   689             //should we expand formals?
   690             boolean useVarargs = deferredAttrContext.phase.isVarargsRequired();
   692             //inference context used during this method check
   693             InferenceContext inferenceContext = deferredAttrContext.inferenceContext;
   695             Type varargsFormal = useVarargs ? formals.last() : null;
   697             if (varargsFormal == null &&
   698                     argtypes.size() != formals.size()) {
   699                 report(MethodCheckDiag.ARITY_MISMATCH, inferenceContext); // not enough args
   700             }
   702             while (argtypes.nonEmpty() && formals.head != varargsFormal) {
   703                 ResultInfo mresult = methodCheckResult(false, formals.head, deferredAttrContext, warn);
   704                 mresult.check(null, argtypes.head);
   705                 argtypes = argtypes.tail;
   706                 formals = formals.tail;
   707             }
   709             if (formals.head != varargsFormal) {
   710                 report(MethodCheckDiag.ARITY_MISMATCH, inferenceContext); // not enough args
   711             }
   713             if (useVarargs) {
   714                 //note: if applicability check is triggered by most specific test,
   715                 //the last argument of a varargs is _not_ an array type (see JLS 15.12.2.5)
   716                 final Type elt = types.elemtype(varargsFormal);
   717                 ResultInfo mresult = methodCheckResult(true, elt, deferredAttrContext, warn);
   718                 while (argtypes.nonEmpty()) {
   719                     mresult.check(null, argtypes.head);
   720                     argtypes = argtypes.tail;
   721                 }
   722                 //check varargs element type accessibility
   723                 varargsAccessible(env, elt, inferenceContext);
   724             }
   725         }
   727         private void report(MethodCheckDiag diag, InferenceContext inferenceContext, Object... args) {
   728             boolean inferDiag = inferenceContext != infer.emptyContext;
   729             InapplicableMethodException ex = inferDiag ?
   730                     infer.inferenceException : inapplicableMethodException;
   731             if (inferDiag && (!diag.inferKey.equals(diag.basicKey))) {
   732                 Object[] args2 = new Object[args.length + 1];
   733                 System.arraycopy(args, 0, args2, 1, args.length);
   734                 args2[0] = inferenceContext.inferenceVars();
   735                 args = args2;
   736             }
   737             throw ex.setMessage(inferDiag ? diag.inferKey : diag.basicKey, args);
   738         }
   740         private void varargsAccessible(final Env<AttrContext> env, final Type t, final InferenceContext inferenceContext) {
   741             if (inferenceContext.free(t)) {
   742                 inferenceContext.addFreeTypeListener(List.of(t), new FreeTypeListener() {
   743                     @Override
   744                     public void typesInferred(InferenceContext inferenceContext) {
   745                         varargsAccessible(env, inferenceContext.asInstType(t, types), inferenceContext);
   746                     }
   747                 });
   748             } else {
   749                 if (!isAccessible(env, t)) {
   750                     Symbol location = env.enclClass.sym;
   751                     report(MethodCheckDiag.INACCESSIBLE_VARARGS, inferenceContext, t, Kinds.kindName(location), location);
   752                 }
   753             }
   754         }
   756         private ResultInfo methodCheckResult(final boolean varargsCheck, Type to,
   757                 final DeferredAttr.DeferredAttrContext deferredAttrContext, Warner rsWarner) {
   758             CheckContext checkContext = new MethodCheckContext(!deferredAttrContext.phase.isBoxingRequired(), deferredAttrContext, rsWarner) {
   759                 MethodCheckDiag methodDiag = varargsCheck ?
   760                                  MethodCheckDiag.VARARG_MISMATCH : MethodCheckDiag.ARG_MISMATCH;
   762                 @Override
   763                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
   764                     report(methodDiag, deferredAttrContext.inferenceContext, details);
   765                 }
   766             };
   767             return new MethodResultInfo(to, checkContext);
   768         }
   769     };
   771     /**
   772      * Check context to be used during method applicability checks. A method check
   773      * context might contain inference variables.
   774      */
   775     abstract class MethodCheckContext implements CheckContext {
   777         boolean strict;
   778         DeferredAttrContext deferredAttrContext;
   779         Warner rsWarner;
   781         public MethodCheckContext(boolean strict, DeferredAttrContext deferredAttrContext, Warner rsWarner) {
   782            this.strict = strict;
   783            this.deferredAttrContext = deferredAttrContext;
   784            this.rsWarner = rsWarner;
   785         }
   787         public boolean compatible(Type found, Type req, Warner warn) {
   788             return strict ?
   789                     types.isSubtypeUnchecked(found, deferredAttrContext.inferenceContext.asFree(req, types), warn) :
   790                     types.isConvertible(found, deferredAttrContext.inferenceContext.asFree(req, types), warn);
   791         }
   793         public void report(DiagnosticPosition pos, JCDiagnostic details) {
   794             throw inapplicableMethodException.setMessage(details);
   795         }
   797         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
   798             return rsWarner;
   799         }
   801         public InferenceContext inferenceContext() {
   802             return deferredAttrContext.inferenceContext;
   803         }
   805         public DeferredAttrContext deferredAttrContext() {
   806             return deferredAttrContext;
   807         }
   808     }
   810     /**
   811      * ResultInfo class to be used during method applicability checks. Check
   812      * for deferred types goes through special path.
   813      */
   814     class MethodResultInfo extends ResultInfo {
   816         public MethodResultInfo(Type pt, CheckContext checkContext) {
   817             attr.super(VAL, pt, checkContext);
   818         }
   820         @Override
   821         protected Type check(DiagnosticPosition pos, Type found) {
   822             if (found.hasTag(DEFERRED)) {
   823                 DeferredType dt = (DeferredType)found;
   824                 return dt.check(this);
   825             } else {
   826                 return super.check(pos, chk.checkNonVoid(pos, types.capture(types.upperBound(found.baseType()))));
   827             }
   828         }
   830         @Override
   831         protected MethodResultInfo dup(Type newPt) {
   832             return new MethodResultInfo(newPt, checkContext);
   833         }
   835         @Override
   836         protected ResultInfo dup(CheckContext newContext) {
   837             return new MethodResultInfo(pt, newContext);
   838         }
   839     }
   841     /**
   842      * Most specific method applicability routine. Given a list of actual types A,
   843      * a list of formal types F1, and a list of formal types F2, the routine determines
   844      * as to whether the types in F1 can be considered more specific than those in F2 w.r.t.
   845      * argument types A.
   846      */
   847     class MostSpecificCheck implements MethodCheck {
   849         boolean strict;
   850         List<Type> actuals;
   852         MostSpecificCheck(boolean strict, List<Type> actuals) {
   853             this.strict = strict;
   854             this.actuals = actuals;
   855         }
   857         @Override
   858         public void argumentsAcceptable(final Env<AttrContext> env,
   859                                     DeferredAttrContext deferredAttrContext,
   860                                     List<Type> formals1,
   861                                     List<Type> formals2,
   862                                     Warner warn) {
   863             formals2 = adjustArgs(formals2, deferredAttrContext.msym, formals1.length(), deferredAttrContext.phase.isVarargsRequired());
   864             while (formals2.nonEmpty()) {
   865                 ResultInfo mresult = methodCheckResult(formals2.head, deferredAttrContext, warn, actuals.head);
   866                 mresult.check(null, formals1.head);
   867                 formals1 = formals1.tail;
   868                 formals2 = formals2.tail;
   869                 actuals = actuals.isEmpty() ? actuals : actuals.tail;
   870             }
   871         }
   873        /**
   874         * Create a method check context to be used during the most specific applicability check
   875         */
   876         ResultInfo methodCheckResult(Type to, DeferredAttr.DeferredAttrContext deferredAttrContext,
   877                Warner rsWarner, Type actual) {
   878            return attr.new ResultInfo(Kinds.VAL, to,
   879                    new MostSpecificCheckContext(strict, deferredAttrContext, rsWarner, actual));
   880         }
   882         /**
   883          * Subclass of method check context class that implements most specific
   884          * method conversion. If the actual type under analysis is a deferred type
   885          * a full blown structural analysis is carried out.
   886          */
   887         class MostSpecificCheckContext extends MethodCheckContext {
   889             Type actual;
   891             public MostSpecificCheckContext(boolean strict, DeferredAttrContext deferredAttrContext, Warner rsWarner, Type actual) {
   892                 super(strict, deferredAttrContext, rsWarner);
   893                 this.actual = actual;
   894             }
   896             public boolean compatible(Type found, Type req, Warner warn) {
   897                 if (!allowStructuralMostSpecific || actual == null) {
   898                     return super.compatible(found, req, warn);
   899                 } else {
   900                     switch (actual.getTag()) {
   901                         case DEFERRED:
   902                             DeferredType dt = (DeferredType) actual;
   903                             DeferredType.SpeculativeCache.Entry e = dt.speculativeCache.get(deferredAttrContext.msym, deferredAttrContext.phase);
   904                             return (e == null || e.speculativeTree == deferredAttr.stuckTree)
   905                                     ? false : mostSpecific(found, req, e.speculativeTree, warn);
   906                         default:
   907                             return standaloneMostSpecific(found, req, actual, warn);
   908                     }
   909                 }
   910             }
   912             private boolean mostSpecific(Type t, Type s, JCTree tree, Warner warn) {
   913                 MostSpecificChecker msc = new MostSpecificChecker(t, s, warn);
   914                 msc.scan(tree);
   915                 return msc.result;
   916             }
   918             boolean polyMostSpecific(Type t1, Type t2, Warner warn) {
   919                 return (!t1.isPrimitive() && t2.isPrimitive())
   920                         ? true : super.compatible(t1, t2, warn);
   921             }
   923             boolean standaloneMostSpecific(Type t1, Type t2, Type exprType, Warner warn) {
   924                 return (exprType.isPrimitive() == t1.isPrimitive()
   925                         && exprType.isPrimitive() != t2.isPrimitive())
   926                         ? true : super.compatible(t1, t2, warn);
   927             }
   929             /**
   930              * Structural checker for most specific.
   931              */
   932             class MostSpecificChecker extends DeferredAttr.PolyScanner {
   934                 final Type t;
   935                 final Type s;
   936                 final Warner warn;
   937                 boolean result;
   939                 MostSpecificChecker(Type t, Type s, Warner warn) {
   940                     this.t = t;
   941                     this.s = s;
   942                     this.warn = warn;
   943                     result = true;
   944                 }
   946                 @Override
   947                 void skip(JCTree tree) {
   948                     result &= standaloneMostSpecific(t, s, tree.type, warn);
   949                 }
   951                 @Override
   952                 public void visitConditional(JCConditional tree) {
   953                     if (tree.polyKind == PolyKind.STANDALONE) {
   954                         result &= standaloneMostSpecific(t, s, tree.type, warn);
   955                     } else {
   956                         super.visitConditional(tree);
   957                     }
   958                 }
   960                 @Override
   961                 public void visitApply(JCMethodInvocation tree) {
   962                     result &= (tree.polyKind == PolyKind.STANDALONE)
   963                             ? standaloneMostSpecific(t, s, tree.type, warn)
   964                             : polyMostSpecific(t, s, warn);
   965                 }
   967                 @Override
   968                 public void visitNewClass(JCNewClass tree) {
   969                     result &= (tree.polyKind == PolyKind.STANDALONE)
   970                             ? standaloneMostSpecific(t, s, tree.type, warn)
   971                             : polyMostSpecific(t, s, warn);
   972                 }
   974                 @Override
   975                 public void visitReference(JCMemberReference tree) {
   976                     if (types.isFunctionalInterface(t.tsym) &&
   977                             types.isFunctionalInterface(s.tsym) &&
   978                             types.asSuper(t, s.tsym) == null &&
   979                             types.asSuper(s, t.tsym) == null) {
   980                         Type desc_t = types.findDescriptorType(t);
   981                         Type desc_s = types.findDescriptorType(s);
   982                         if (types.isSameTypes(desc_t.getParameterTypes(), desc_s.getParameterTypes())) {
   983                             if (!desc_s.getReturnType().hasTag(VOID)) {
   984                                 //perform structural comparison
   985                                 Type ret_t = desc_t.getReturnType();
   986                                 Type ret_s = desc_s.getReturnType();
   987                                 result &= ((tree.refPolyKind == PolyKind.STANDALONE)
   988                                         ? standaloneMostSpecific(ret_t, ret_s, tree.type, warn)
   989                                         : polyMostSpecific(ret_t, ret_s, warn));
   990                             } else {
   991                                 return;
   992                             }
   993                         } else {
   994                             result &= false;
   995                         }
   996                     } else {
   997                         result &= MostSpecificCheckContext.super.compatible(t, s, warn);
   998                     }
   999                 }
  1001                 @Override
  1002                 public void visitLambda(JCLambda tree) {
  1003                     if (types.isFunctionalInterface(t.tsym) &&
  1004                             types.isFunctionalInterface(s.tsym) &&
  1005                             types.asSuper(t, s.tsym) == null &&
  1006                             types.asSuper(s, t.tsym) == null) {
  1007                         Type desc_t = types.findDescriptorType(t);
  1008                         Type desc_s = types.findDescriptorType(s);
  1009                         if (tree.paramKind == JCLambda.ParameterKind.EXPLICIT
  1010                                 || types.isSameTypes(desc_t.getParameterTypes(), desc_s.getParameterTypes())) {
  1011                             if (!desc_s.getReturnType().hasTag(VOID)) {
  1012                                 //perform structural comparison
  1013                                 Type ret_t = desc_t.getReturnType();
  1014                                 Type ret_s = desc_s.getReturnType();
  1015                                 scanLambdaBody(tree, ret_t, ret_s);
  1016                             } else {
  1017                                 return;
  1019                         } else {
  1020                             result &= false;
  1022                     } else {
  1023                         result &= MostSpecificCheckContext.super.compatible(t, s, warn);
  1026                 //where
  1028                 void scanLambdaBody(JCLambda lambda, final Type t, final Type s) {
  1029                     if (lambda.getBodyKind() == JCTree.JCLambda.BodyKind.EXPRESSION) {
  1030                         result &= MostSpecificCheckContext.this.mostSpecific(t, s, lambda.body, warn);
  1031                     } else {
  1032                         DeferredAttr.LambdaReturnScanner lambdaScanner =
  1033                                 new DeferredAttr.LambdaReturnScanner() {
  1034                                     @Override
  1035                                     public void visitReturn(JCReturn tree) {
  1036                                         if (tree.expr != null) {
  1037                                             result &= MostSpecificCheckContext.this.mostSpecific(t, s, tree.expr, warn);
  1040                                 };
  1041                         lambdaScanner.scan(lambda.body);
  1048     public static class InapplicableMethodException extends RuntimeException {
  1049         private static final long serialVersionUID = 0;
  1051         JCDiagnostic diagnostic;
  1052         JCDiagnostic.Factory diags;
  1054         InapplicableMethodException(JCDiagnostic.Factory diags) {
  1055             this.diagnostic = null;
  1056             this.diags = diags;
  1058         InapplicableMethodException setMessage() {
  1059             return setMessage((JCDiagnostic)null);
  1061         InapplicableMethodException setMessage(String key) {
  1062             return setMessage(key != null ? diags.fragment(key) : null);
  1064         InapplicableMethodException setMessage(String key, Object... args) {
  1065             return setMessage(key != null ? diags.fragment(key, args) : null);
  1067         InapplicableMethodException setMessage(JCDiagnostic diag) {
  1068             this.diagnostic = diag;
  1069             return this;
  1072         public JCDiagnostic getDiagnostic() {
  1073             return diagnostic;
  1076     private final InapplicableMethodException inapplicableMethodException;
  1078 /* ***************************************************************************
  1079  *  Symbol lookup
  1080  *  the following naming conventions for arguments are used
  1082  *       env      is the environment where the symbol was mentioned
  1083  *       site     is the type of which the symbol is a member
  1084  *       name     is the symbol's name
  1085  *                if no arguments are given
  1086  *       argtypes are the value arguments, if we search for a method
  1088  *  If no symbol was found, a ResolveError detailing the problem is returned.
  1089  ****************************************************************************/
  1091     /** Find field. Synthetic fields are always skipped.
  1092      *  @param env     The current environment.
  1093      *  @param site    The original type from where the selection takes place.
  1094      *  @param name    The name of the field.
  1095      *  @param c       The class to search for the field. This is always
  1096      *                 a superclass or implemented interface of site's class.
  1097      */
  1098     Symbol findField(Env<AttrContext> env,
  1099                      Type site,
  1100                      Name name,
  1101                      TypeSymbol c) {
  1102         while (c.type.hasTag(TYPEVAR))
  1103             c = c.type.getUpperBound().tsym;
  1104         Symbol bestSoFar = varNotFound;
  1105         Symbol sym;
  1106         Scope.Entry e = c.members().lookup(name);
  1107         while (e.scope != null) {
  1108             if (e.sym.kind == VAR && (e.sym.flags_field & SYNTHETIC) == 0) {
  1109                 return isAccessible(env, site, e.sym)
  1110                     ? e.sym : new AccessError(env, site, e.sym);
  1112             e = e.next();
  1114         Type st = types.supertype(c.type);
  1115         if (st != null && (st.hasTag(CLASS) || st.hasTag(TYPEVAR))) {
  1116             sym = findField(env, site, name, st.tsym);
  1117             if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1119         for (List<Type> l = types.interfaces(c.type);
  1120              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
  1121              l = l.tail) {
  1122             sym = findField(env, site, name, l.head.tsym);
  1123             if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
  1124                 sym.owner != bestSoFar.owner)
  1125                 bestSoFar = new AmbiguityError(bestSoFar, sym);
  1126             else if (sym.kind < bestSoFar.kind)
  1127                 bestSoFar = sym;
  1129         return bestSoFar;
  1132     /** Resolve a field identifier, throw a fatal error if not found.
  1133      *  @param pos       The position to use for error reporting.
  1134      *  @param env       The environment current at the method invocation.
  1135      *  @param site      The type of the qualifying expression, in which
  1136      *                   identifier is searched.
  1137      *  @param name      The identifier's name.
  1138      */
  1139     public VarSymbol resolveInternalField(DiagnosticPosition pos, Env<AttrContext> env,
  1140                                           Type site, Name name) {
  1141         Symbol sym = findField(env, site, name, site.tsym);
  1142         if (sym.kind == VAR) return (VarSymbol)sym;
  1143         else throw new FatalError(
  1144                  diags.fragment("fatal.err.cant.locate.field",
  1145                                 name));
  1148     /** Find unqualified variable or field with given name.
  1149      *  Synthetic fields always skipped.
  1150      *  @param env     The current environment.
  1151      *  @param name    The name of the variable or field.
  1152      */
  1153     Symbol findVar(Env<AttrContext> env, Name name) {
  1154         Symbol bestSoFar = varNotFound;
  1155         Symbol sym;
  1156         Env<AttrContext> env1 = env;
  1157         boolean staticOnly = false;
  1158         while (env1.outer != null) {
  1159             if (isStatic(env1)) staticOnly = true;
  1160             Scope.Entry e = env1.info.scope.lookup(name);
  1161             while (e.scope != null &&
  1162                    (e.sym.kind != VAR ||
  1163                     (e.sym.flags_field & SYNTHETIC) != 0))
  1164                 e = e.next();
  1165             sym = (e.scope != null)
  1166                 ? e.sym
  1167                 : findField(
  1168                     env1, env1.enclClass.sym.type, name, env1.enclClass.sym);
  1169             if (sym.exists()) {
  1170                 if (staticOnly &&
  1171                     sym.kind == VAR &&
  1172                     sym.owner.kind == TYP &&
  1173                     (sym.flags() & STATIC) == 0)
  1174                     return new StaticError(sym);
  1175                 else
  1176                     return sym;
  1177             } else if (sym.kind < bestSoFar.kind) {
  1178                 bestSoFar = sym;
  1181             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  1182             env1 = env1.outer;
  1185         sym = findField(env, syms.predefClass.type, name, syms.predefClass);
  1186         if (sym.exists())
  1187             return sym;
  1188         if (bestSoFar.exists())
  1189             return bestSoFar;
  1191         Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
  1192         for (; e.scope != null; e = e.next()) {
  1193             sym = e.sym;
  1194             Type origin = e.getOrigin().owner.type;
  1195             if (sym.kind == VAR) {
  1196                 if (e.sym.owner.type != origin)
  1197                     sym = sym.clone(e.getOrigin().owner);
  1198                 return isAccessible(env, origin, sym)
  1199                     ? sym : new AccessError(env, origin, sym);
  1203         Symbol origin = null;
  1204         e = env.toplevel.starImportScope.lookup(name);
  1205         for (; e.scope != null; e = e.next()) {
  1206             sym = e.sym;
  1207             if (sym.kind != VAR)
  1208                 continue;
  1209             // invariant: sym.kind == VAR
  1210             if (bestSoFar.kind < AMBIGUOUS && sym.owner != bestSoFar.owner)
  1211                 return new AmbiguityError(bestSoFar, sym);
  1212             else if (bestSoFar.kind >= VAR) {
  1213                 origin = e.getOrigin().owner;
  1214                 bestSoFar = isAccessible(env, origin.type, sym)
  1215                     ? sym : new AccessError(env, origin.type, sym);
  1218         if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type)
  1219             return bestSoFar.clone(origin);
  1220         else
  1221             return bestSoFar;
  1224     Warner noteWarner = new Warner();
  1226     /** Select the best method for a call site among two choices.
  1227      *  @param env              The current environment.
  1228      *  @param site             The original type from where the
  1229      *                          selection takes place.
  1230      *  @param argtypes         The invocation's value arguments,
  1231      *  @param typeargtypes     The invocation's type arguments,
  1232      *  @param sym              Proposed new best match.
  1233      *  @param bestSoFar        Previously found best match.
  1234      *  @param allowBoxing Allow boxing conversions of arguments.
  1235      *  @param useVarargs Box trailing arguments into an array for varargs.
  1236      */
  1237     @SuppressWarnings("fallthrough")
  1238     Symbol selectBest(Env<AttrContext> env,
  1239                       Type site,
  1240                       List<Type> argtypes,
  1241                       List<Type> typeargtypes,
  1242                       Symbol sym,
  1243                       Symbol bestSoFar,
  1244                       boolean allowBoxing,
  1245                       boolean useVarargs,
  1246                       boolean operator) {
  1247         if (sym.kind == ERR ||
  1248                 !sym.isInheritedIn(site.tsym, types) ||
  1249                 (useVarargs && (sym.flags() & VARARGS) == 0)) {
  1250             return bestSoFar;
  1252         Assert.check(sym.kind < AMBIGUOUS);
  1253         try {
  1254             Type mt = rawInstantiate(env, site, sym, null, argtypes, typeargtypes,
  1255                                allowBoxing, useVarargs, resolveMethodCheck, types.noWarnings);
  1256             if (!operator)
  1257                 currentResolutionContext.addApplicableCandidate(sym, mt);
  1258         } catch (InapplicableMethodException ex) {
  1259             if (!operator)
  1260                 currentResolutionContext.addInapplicableCandidate(sym, ex.getDiagnostic());
  1261             switch (bestSoFar.kind) {
  1262                 case ABSENT_MTH:
  1263                     return new InapplicableSymbolError(currentResolutionContext);
  1264                 case WRONG_MTH:
  1265                     if (operator) return bestSoFar;
  1266                     bestSoFar = new InapplicableSymbolsError(currentResolutionContext);
  1267                 default:
  1268                     return bestSoFar;
  1271         if (!isAccessible(env, site, sym)) {
  1272             return (bestSoFar.kind == ABSENT_MTH)
  1273                 ? new AccessError(env, site, sym)
  1274                 : bestSoFar;
  1276         return (bestSoFar.kind > AMBIGUOUS)
  1277             ? sym
  1278             : mostSpecific(argtypes, sym, bestSoFar, env, site,
  1279                            allowBoxing && operator, useVarargs);
  1282     /* Return the most specific of the two methods for a call,
  1283      *  given that both are accessible and applicable.
  1284      *  @param m1               A new candidate for most specific.
  1285      *  @param m2               The previous most specific candidate.
  1286      *  @param env              The current environment.
  1287      *  @param site             The original type from where the selection
  1288      *                          takes place.
  1289      *  @param allowBoxing Allow boxing conversions of arguments.
  1290      *  @param useVarargs Box trailing arguments into an array for varargs.
  1291      */
  1292     Symbol mostSpecific(List<Type> argtypes, Symbol m1,
  1293                         Symbol m2,
  1294                         Env<AttrContext> env,
  1295                         final Type site,
  1296                         boolean allowBoxing,
  1297                         boolean useVarargs) {
  1298         switch (m2.kind) {
  1299         case MTH:
  1300             if (m1 == m2) return m1;
  1301             boolean m1SignatureMoreSpecific =
  1302                     signatureMoreSpecific(argtypes, env, site, m1, m2, allowBoxing, useVarargs);
  1303             boolean m2SignatureMoreSpecific =
  1304                     signatureMoreSpecific(argtypes, env, site, m2, m1, allowBoxing, useVarargs);
  1305             if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) {
  1306                 Type mt1 = types.memberType(site, m1);
  1307                 Type mt2 = types.memberType(site, m2);
  1308                 if (!types.overrideEquivalent(mt1, mt2))
  1309                     return ambiguityError(m1, m2);
  1311                 // same signature; select (a) the non-bridge method, or
  1312                 // (b) the one that overrides the other, or (c) the concrete
  1313                 // one, or (d) merge both abstract signatures
  1314                 if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE))
  1315                     return ((m1.flags() & BRIDGE) != 0) ? m2 : m1;
  1317                 // if one overrides or hides the other, use it
  1318                 TypeSymbol m1Owner = (TypeSymbol)m1.owner;
  1319                 TypeSymbol m2Owner = (TypeSymbol)m2.owner;
  1320                 if (types.asSuper(m1Owner.type, m2Owner) != null &&
  1321                     ((m1.owner.flags_field & INTERFACE) == 0 ||
  1322                      (m2.owner.flags_field & INTERFACE) != 0) &&
  1323                     m1.overrides(m2, m1Owner, types, false))
  1324                     return m1;
  1325                 if (types.asSuper(m2Owner.type, m1Owner) != null &&
  1326                     ((m2.owner.flags_field & INTERFACE) == 0 ||
  1327                      (m1.owner.flags_field & INTERFACE) != 0) &&
  1328                     m2.overrides(m1, m2Owner, types, false))
  1329                     return m2;
  1330                 boolean m1Abstract = (m1.flags() & ABSTRACT) != 0;
  1331                 boolean m2Abstract = (m2.flags() & ABSTRACT) != 0;
  1332                 if (m1Abstract && !m2Abstract) return m2;
  1333                 if (m2Abstract && !m1Abstract) return m1;
  1334                 // both abstract or both concrete
  1335                 return ambiguityError(m1, m2);
  1337             if (m1SignatureMoreSpecific) return m1;
  1338             if (m2SignatureMoreSpecific) return m2;
  1339             return ambiguityError(m1, m2);
  1340         case AMBIGUOUS:
  1341             //check if m1 is more specific than all ambiguous methods in m2
  1342             AmbiguityError e = (AmbiguityError)m2;
  1343             for (Symbol s : e.ambiguousSyms) {
  1344                 if (mostSpecific(argtypes, m1, s, env, site, allowBoxing, useVarargs) != m1) {
  1345                     return e.addAmbiguousSymbol(m1);
  1348             return m1;
  1349         default:
  1350             throw new AssertionError();
  1353     //where
  1354     private boolean signatureMoreSpecific(List<Type> actuals, Env<AttrContext> env, Type site, Symbol m1, Symbol m2, boolean allowBoxing, boolean useVarargs) {
  1355         noteWarner.clear();
  1356         int maxLength = Math.max(
  1357                             Math.max(m1.type.getParameterTypes().length(), actuals.length()),
  1358                             m2.type.getParameterTypes().length());
  1359         Type mst = instantiate(env, site, m2, null,
  1360                 adjustArgs(types.lowerBounds(types.memberType(site, m1).getParameterTypes()), m1, maxLength, useVarargs), null,
  1361                 allowBoxing, useVarargs, new MostSpecificCheck(!allowBoxing, actuals), noteWarner);
  1362         return mst != null &&
  1363                 !noteWarner.hasLint(Lint.LintCategory.UNCHECKED);
  1365     private List<Type> adjustArgs(List<Type> args, Symbol msym, int length, boolean allowVarargs) {
  1366         if ((msym.flags() & VARARGS) != 0 && allowVarargs) {
  1367             Type varargsElem = types.elemtype(args.last());
  1368             if (varargsElem == null) {
  1369                 Assert.error("Bad varargs = " + args.last() + " " + msym);
  1371             List<Type> newArgs = args.reverse().tail.prepend(varargsElem).reverse();
  1372             while (newArgs.length() < length) {
  1373                 newArgs = newArgs.append(newArgs.last());
  1375             return newArgs;
  1376         } else {
  1377             return args;
  1380     //where
  1381     Type mostSpecificReturnType(Type mt1, Type mt2) {
  1382         Type rt1 = mt1.getReturnType();
  1383         Type rt2 = mt2.getReturnType();
  1385         if (mt1.hasTag(FORALL) && mt2.hasTag(FORALL)) {
  1386             //if both are generic methods, adjust return type ahead of subtyping check
  1387             rt1 = types.subst(rt1, mt1.getTypeArguments(), mt2.getTypeArguments());
  1389         //first use subtyping, then return type substitutability
  1390         if (types.isSubtype(rt1, rt2)) {
  1391             return mt1;
  1392         } else if (types.isSubtype(rt2, rt1)) {
  1393             return mt2;
  1394         } else if (types.returnTypeSubstitutable(mt1, mt2)) {
  1395             return mt1;
  1396         } else if (types.returnTypeSubstitutable(mt2, mt1)) {
  1397             return mt2;
  1398         } else {
  1399             return null;
  1402     //where
  1403     Symbol ambiguityError(Symbol m1, Symbol m2) {
  1404         if (((m1.flags() | m2.flags()) & CLASH) != 0) {
  1405             return (m1.flags() & CLASH) == 0 ? m1 : m2;
  1406         } else {
  1407             return new AmbiguityError(m1, m2);
  1411     Symbol findMethodInScope(Env<AttrContext> env,
  1412             Type site,
  1413             Name name,
  1414             List<Type> argtypes,
  1415             List<Type> typeargtypes,
  1416             Scope sc,
  1417             Symbol bestSoFar,
  1418             boolean allowBoxing,
  1419             boolean useVarargs,
  1420             boolean operator,
  1421             boolean abstractok) {
  1422         for (Symbol s : sc.getElementsByName(name, new LookupFilter(abstractok))) {
  1423             bestSoFar = selectBest(env, site, argtypes, typeargtypes, s,
  1424                     bestSoFar, allowBoxing, useVarargs, operator);
  1426         return bestSoFar;
  1428     //where
  1429         class LookupFilter implements Filter<Symbol> {
  1431             boolean abstractOk;
  1433             LookupFilter(boolean abstractOk) {
  1434                 this.abstractOk = abstractOk;
  1437             public boolean accepts(Symbol s) {
  1438                 long flags = s.flags();
  1439                 return s.kind == MTH &&
  1440                         (flags & SYNTHETIC) == 0 &&
  1441                         (abstractOk ||
  1442                         (flags & DEFAULT) != 0 ||
  1443                         (flags & ABSTRACT) == 0);
  1445         };
  1447     /** Find best qualified method matching given name, type and value
  1448      *  arguments.
  1449      *  @param env       The current environment.
  1450      *  @param site      The original type from where the selection
  1451      *                   takes place.
  1452      *  @param name      The method's name.
  1453      *  @param argtypes  The method's value arguments.
  1454      *  @param typeargtypes The method's type arguments
  1455      *  @param allowBoxing Allow boxing conversions of arguments.
  1456      *  @param useVarargs Box trailing arguments into an array for varargs.
  1457      */
  1458     Symbol findMethod(Env<AttrContext> env,
  1459                       Type site,
  1460                       Name name,
  1461                       List<Type> argtypes,
  1462                       List<Type> typeargtypes,
  1463                       boolean allowBoxing,
  1464                       boolean useVarargs,
  1465                       boolean operator) {
  1466         Symbol bestSoFar = methodNotFound;
  1467         bestSoFar = findMethod(env,
  1468                           site,
  1469                           name,
  1470                           argtypes,
  1471                           typeargtypes,
  1472                           site.tsym.type,
  1473                           bestSoFar,
  1474                           allowBoxing,
  1475                           useVarargs,
  1476                           operator);
  1477         reportVerboseResolutionDiagnostic(env.tree.pos(), name, site, argtypes, typeargtypes, bestSoFar);
  1478         return bestSoFar;
  1480     // where
  1481     private Symbol findMethod(Env<AttrContext> env,
  1482                               Type site,
  1483                               Name name,
  1484                               List<Type> argtypes,
  1485                               List<Type> typeargtypes,
  1486                               Type intype,
  1487                               Symbol bestSoFar,
  1488                               boolean allowBoxing,
  1489                               boolean useVarargs,
  1490                               boolean operator) {
  1491         @SuppressWarnings({"unchecked","rawtypes"})
  1492         List<Type>[] itypes = (List<Type>[])new List[] { List.<Type>nil(), List.<Type>nil() };
  1493         InterfaceLookupPhase iphase = InterfaceLookupPhase.ABSTRACT_OK;
  1494         for (TypeSymbol s : superclasses(intype)) {
  1495             bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
  1496                     s.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
  1497             if (name == names.init) return bestSoFar;
  1498             iphase = (iphase == null) ? null : iphase.update(s, this);
  1499             if (iphase != null) {
  1500                 for (Type itype : types.interfaces(s.type)) {
  1501                     itypes[iphase.ordinal()] = types.union(types.closure(itype), itypes[iphase.ordinal()]);
  1506         Symbol concrete = bestSoFar.kind < ERR &&
  1507                 (bestSoFar.flags() & ABSTRACT) == 0 ?
  1508                 bestSoFar : methodNotFound;
  1510         for (InterfaceLookupPhase iphase2 : InterfaceLookupPhase.values()) {
  1511             if (iphase2 == InterfaceLookupPhase.DEFAULT_OK && !allowDefaultMethods) break;
  1512             //keep searching for abstract methods
  1513             for (Type itype : itypes[iphase2.ordinal()]) {
  1514                 if (!itype.isInterface()) continue; //skip j.l.Object (included by Types.closure())
  1515                 if (iphase2 == InterfaceLookupPhase.DEFAULT_OK &&
  1516                         (itype.tsym.flags() & DEFAULT) == 0) continue;
  1517                 bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
  1518                         itype.tsym.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
  1519                 if (concrete != bestSoFar &&
  1520                         concrete.kind < ERR  && bestSoFar.kind < ERR &&
  1521                         types.isSubSignature(concrete.type, bestSoFar.type)) {
  1522                     //this is an hack - as javac does not do full membership checks
  1523                     //most specific ends up comparing abstract methods that might have
  1524                     //been implemented by some concrete method in a subclass and,
  1525                     //because of raw override, it is possible for an abstract method
  1526                     //to be more specific than the concrete method - so we need
  1527                     //to explicitly call that out (see CR 6178365)
  1528                     bestSoFar = concrete;
  1532         return bestSoFar;
  1535     enum InterfaceLookupPhase {
  1536         ABSTRACT_OK() {
  1537             @Override
  1538             InterfaceLookupPhase update(Symbol s, Resolve rs) {
  1539                 //We should not look for abstract methods if receiver is a concrete class
  1540                 //(as concrete classes are expected to implement all abstracts coming
  1541                 //from superinterfaces)
  1542                 if ((s.flags() & (ABSTRACT | INTERFACE | ENUM)) != 0) {
  1543                     return this;
  1544                 } else if (rs.allowDefaultMethods) {
  1545                     return DEFAULT_OK;
  1546                 } else {
  1547                     return null;
  1550         },
  1551         DEFAULT_OK() {
  1552             @Override
  1553             InterfaceLookupPhase update(Symbol s, Resolve rs) {
  1554                 return this;
  1556         };
  1558         abstract InterfaceLookupPhase update(Symbol s, Resolve rs);
  1561     /**
  1562      * Return an Iterable object to scan the superclasses of a given type.
  1563      * It's crucial that the scan is done lazily, as we don't want to accidentally
  1564      * access more supertypes than strictly needed (as this could trigger completion
  1565      * errors if some of the not-needed supertypes are missing/ill-formed).
  1566      */
  1567     Iterable<TypeSymbol> superclasses(final Type intype) {
  1568         return new Iterable<TypeSymbol>() {
  1569             public Iterator<TypeSymbol> iterator() {
  1570                 return new Iterator<TypeSymbol>() {
  1572                     List<TypeSymbol> seen = List.nil();
  1573                     TypeSymbol currentSym = symbolFor(intype);
  1574                     TypeSymbol prevSym = null;
  1576                     public boolean hasNext() {
  1577                         if (currentSym == syms.noSymbol) {
  1578                             currentSym = symbolFor(types.supertype(prevSym.type));
  1580                         return currentSym != null;
  1583                     public TypeSymbol next() {
  1584                         prevSym = currentSym;
  1585                         currentSym = syms.noSymbol;
  1586                         Assert.check(prevSym != null || prevSym != syms.noSymbol);
  1587                         return prevSym;
  1590                     public void remove() {
  1591                         throw new UnsupportedOperationException();
  1594                     TypeSymbol symbolFor(Type t) {
  1595                         if (!t.hasTag(CLASS) &&
  1596                                 !t.hasTag(TYPEVAR)) {
  1597                             return null;
  1599                         while (t.hasTag(TYPEVAR))
  1600                             t = t.getUpperBound();
  1601                         if (seen.contains(t.tsym)) {
  1602                             //degenerate case in which we have a circular
  1603                             //class hierarchy - because of ill-formed classfiles
  1604                             return null;
  1606                         seen = seen.prepend(t.tsym);
  1607                         return t.tsym;
  1609                 };
  1611         };
  1614     /** Find unqualified method matching given name, type and value arguments.
  1615      *  @param env       The current environment.
  1616      *  @param name      The method's name.
  1617      *  @param argtypes  The method's value arguments.
  1618      *  @param typeargtypes  The method's type arguments.
  1619      *  @param allowBoxing Allow boxing conversions of arguments.
  1620      *  @param useVarargs Box trailing arguments into an array for varargs.
  1621      */
  1622     Symbol findFun(Env<AttrContext> env, Name name,
  1623                    List<Type> argtypes, List<Type> typeargtypes,
  1624                    boolean allowBoxing, boolean useVarargs) {
  1625         Symbol bestSoFar = methodNotFound;
  1626         Symbol sym;
  1627         Env<AttrContext> env1 = env;
  1628         boolean staticOnly = false;
  1629         while (env1.outer != null) {
  1630             if (isStatic(env1)) staticOnly = true;
  1631             sym = findMethod(
  1632                 env1, env1.enclClass.sym.type, name, argtypes, typeargtypes,
  1633                 allowBoxing, useVarargs, false);
  1634             if (sym.exists()) {
  1635                 if (staticOnly &&
  1636                     sym.kind == MTH &&
  1637                     sym.owner.kind == TYP &&
  1638                     (sym.flags() & STATIC) == 0) return new StaticError(sym);
  1639                 else return sym;
  1640             } else if (sym.kind < bestSoFar.kind) {
  1641                 bestSoFar = sym;
  1643             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  1644             env1 = env1.outer;
  1647         sym = findMethod(env, syms.predefClass.type, name, argtypes,
  1648                          typeargtypes, allowBoxing, useVarargs, false);
  1649         if (sym.exists())
  1650             return sym;
  1652         Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
  1653         for (; e.scope != null; e = e.next()) {
  1654             sym = e.sym;
  1655             Type origin = e.getOrigin().owner.type;
  1656             if (sym.kind == MTH) {
  1657                 if (e.sym.owner.type != origin)
  1658                     sym = sym.clone(e.getOrigin().owner);
  1659                 if (!isAccessible(env, origin, sym))
  1660                     sym = new AccessError(env, origin, sym);
  1661                 bestSoFar = selectBest(env, origin,
  1662                                        argtypes, typeargtypes,
  1663                                        sym, bestSoFar,
  1664                                        allowBoxing, useVarargs, false);
  1667         if (bestSoFar.exists())
  1668             return bestSoFar;
  1670         e = env.toplevel.starImportScope.lookup(name);
  1671         for (; e.scope != null; e = e.next()) {
  1672             sym = e.sym;
  1673             Type origin = e.getOrigin().owner.type;
  1674             if (sym.kind == MTH) {
  1675                 if (e.sym.owner.type != origin)
  1676                     sym = sym.clone(e.getOrigin().owner);
  1677                 if (!isAccessible(env, origin, sym))
  1678                     sym = new AccessError(env, origin, sym);
  1679                 bestSoFar = selectBest(env, origin,
  1680                                        argtypes, typeargtypes,
  1681                                        sym, bestSoFar,
  1682                                        allowBoxing, useVarargs, false);
  1685         return bestSoFar;
  1688     /** Load toplevel or member class with given fully qualified name and
  1689      *  verify that it is accessible.
  1690      *  @param env       The current environment.
  1691      *  @param name      The fully qualified name of the class to be loaded.
  1692      */
  1693     Symbol loadClass(Env<AttrContext> env, Name name) {
  1694         try {
  1695             ClassSymbol c = reader.loadClass(name);
  1696             return isAccessible(env, c) ? c : new AccessError(c);
  1697         } catch (ClassReader.BadClassFile err) {
  1698             throw err;
  1699         } catch (CompletionFailure ex) {
  1700             return typeNotFound;
  1704     /** Find qualified member type.
  1705      *  @param env       The current environment.
  1706      *  @param site      The original type from where the selection takes
  1707      *                   place.
  1708      *  @param name      The type's name.
  1709      *  @param c         The class to search for the member type. This is
  1710      *                   always a superclass or implemented interface of
  1711      *                   site's class.
  1712      */
  1713     Symbol findMemberType(Env<AttrContext> env,
  1714                           Type site,
  1715                           Name name,
  1716                           TypeSymbol c) {
  1717         Symbol bestSoFar = typeNotFound;
  1718         Symbol sym;
  1719         Scope.Entry e = c.members().lookup(name);
  1720         while (e.scope != null) {
  1721             if (e.sym.kind == TYP) {
  1722                 return isAccessible(env, site, e.sym)
  1723                     ? e.sym
  1724                     : new AccessError(env, site, e.sym);
  1726             e = e.next();
  1728         Type st = types.supertype(c.type);
  1729         if (st != null && st.hasTag(CLASS)) {
  1730             sym = findMemberType(env, site, name, st.tsym);
  1731             if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1733         for (List<Type> l = types.interfaces(c.type);
  1734              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
  1735              l = l.tail) {
  1736             sym = findMemberType(env, site, name, l.head.tsym);
  1737             if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
  1738                 sym.owner != bestSoFar.owner)
  1739                 bestSoFar = new AmbiguityError(bestSoFar, sym);
  1740             else if (sym.kind < bestSoFar.kind)
  1741                 bestSoFar = sym;
  1743         return bestSoFar;
  1746     /** Find a global type in given scope and load corresponding class.
  1747      *  @param env       The current environment.
  1748      *  @param scope     The scope in which to look for the type.
  1749      *  @param name      The type's name.
  1750      */
  1751     Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name) {
  1752         Symbol bestSoFar = typeNotFound;
  1753         for (Scope.Entry e = scope.lookup(name); e.scope != null; e = e.next()) {
  1754             Symbol sym = loadClass(env, e.sym.flatName());
  1755             if (bestSoFar.kind == TYP && sym.kind == TYP &&
  1756                 bestSoFar != sym)
  1757                 return new AmbiguityError(bestSoFar, sym);
  1758             else if (sym.kind < bestSoFar.kind)
  1759                 bestSoFar = sym;
  1761         return bestSoFar;
  1764     /** Find an unqualified type symbol.
  1765      *  @param env       The current environment.
  1766      *  @param name      The type's name.
  1767      */
  1768     Symbol findType(Env<AttrContext> env, Name name) {
  1769         Symbol bestSoFar = typeNotFound;
  1770         Symbol sym;
  1771         boolean staticOnly = false;
  1772         for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
  1773             if (isStatic(env1)) staticOnly = true;
  1774             for (Scope.Entry e = env1.info.scope.lookup(name);
  1775                  e.scope != null;
  1776                  e = e.next()) {
  1777                 if (e.sym.kind == TYP) {
  1778                     if (staticOnly &&
  1779                         e.sym.type.hasTag(TYPEVAR) &&
  1780                         e.sym.owner.kind == TYP) return new StaticError(e.sym);
  1781                     return e.sym;
  1785             sym = findMemberType(env1, env1.enclClass.sym.type, name,
  1786                                  env1.enclClass.sym);
  1787             if (staticOnly && sym.kind == TYP &&
  1788                 sym.type.hasTag(CLASS) &&
  1789                 sym.type.getEnclosingType().hasTag(CLASS) &&
  1790                 env1.enclClass.sym.type.isParameterized() &&
  1791                 sym.type.getEnclosingType().isParameterized())
  1792                 return new StaticError(sym);
  1793             else if (sym.exists()) return sym;
  1794             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1796             JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass;
  1797             if ((encl.sym.flags() & STATIC) != 0)
  1798                 staticOnly = true;
  1801         if (!env.tree.hasTag(IMPORT)) {
  1802             sym = findGlobalType(env, env.toplevel.namedImportScope, name);
  1803             if (sym.exists()) return sym;
  1804             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1806             sym = findGlobalType(env, env.toplevel.packge.members(), name);
  1807             if (sym.exists()) return sym;
  1808             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1810             sym = findGlobalType(env, env.toplevel.starImportScope, name);
  1811             if (sym.exists()) return sym;
  1812             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1815         return bestSoFar;
  1818     /** Find an unqualified identifier which matches a specified kind set.
  1819      *  @param env       The current environment.
  1820      *  @param name      The identifier's name.
  1821      *  @param kind      Indicates the possible symbol kinds
  1822      *                   (a subset of VAL, TYP, PCK).
  1823      */
  1824     Symbol findIdent(Env<AttrContext> env, Name name, int kind) {
  1825         Symbol bestSoFar = typeNotFound;
  1826         Symbol sym;
  1828         if ((kind & VAR) != 0) {
  1829             sym = findVar(env, name);
  1830             if (sym.exists()) return sym;
  1831             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1834         if ((kind & TYP) != 0) {
  1835             sym = findType(env, name);
  1836             if (sym.kind==TYP) {
  1837                  reportDependence(env.enclClass.sym, sym);
  1839             if (sym.exists()) return sym;
  1840             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1843         if ((kind & PCK) != 0) return reader.enterPackage(name);
  1844         else return bestSoFar;
  1847     /** Report dependencies.
  1848      * @param from The enclosing class sym
  1849      * @param to   The found identifier that the class depends on.
  1850      */
  1851     public void reportDependence(Symbol from, Symbol to) {
  1852         // Override if you want to collect the reported dependencies.
  1855     /** Find an identifier in a package which matches a specified kind set.
  1856      *  @param env       The current environment.
  1857      *  @param name      The identifier's name.
  1858      *  @param kind      Indicates the possible symbol kinds
  1859      *                   (a nonempty subset of TYP, PCK).
  1860      */
  1861     Symbol findIdentInPackage(Env<AttrContext> env, TypeSymbol pck,
  1862                               Name name, int kind) {
  1863         Name fullname = TypeSymbol.formFullName(name, pck);
  1864         Symbol bestSoFar = typeNotFound;
  1865         PackageSymbol pack = null;
  1866         if ((kind & PCK) != 0) {
  1867             pack = reader.enterPackage(fullname);
  1868             if (pack.exists()) return pack;
  1870         if ((kind & TYP) != 0) {
  1871             Symbol sym = loadClass(env, fullname);
  1872             if (sym.exists()) {
  1873                 // don't allow programs to use flatnames
  1874                 if (name == sym.name) return sym;
  1876             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1878         return (pack != null) ? pack : bestSoFar;
  1881     /** Find an identifier among the members of a given type `site'.
  1882      *  @param env       The current environment.
  1883      *  @param site      The type containing the symbol to be found.
  1884      *  @param name      The identifier's name.
  1885      *  @param kind      Indicates the possible symbol kinds
  1886      *                   (a subset of VAL, TYP).
  1887      */
  1888     Symbol findIdentInType(Env<AttrContext> env, Type site,
  1889                            Name name, int kind) {
  1890         Symbol bestSoFar = typeNotFound;
  1891         Symbol sym;
  1892         if ((kind & VAR) != 0) {
  1893             sym = findField(env, site, name, site.tsym);
  1894             if (sym.exists()) return sym;
  1895             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1898         if ((kind & TYP) != 0) {
  1899             sym = findMemberType(env, site, name, site.tsym);
  1900             if (sym.exists()) return sym;
  1901             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1903         return bestSoFar;
  1906 /* ***************************************************************************
  1907  *  Access checking
  1908  *  The following methods convert ResolveErrors to ErrorSymbols, issuing
  1909  *  an error message in the process
  1910  ****************************************************************************/
  1912     /** If `sym' is a bad symbol: report error and return errSymbol
  1913      *  else pass through unchanged,
  1914      *  additional arguments duplicate what has been used in trying to find the
  1915      *  symbol {@literal (--> flyweight pattern)}. This improves performance since we
  1916      *  expect misses to happen frequently.
  1918      *  @param sym       The symbol that was found, or a ResolveError.
  1919      *  @param pos       The position to use for error reporting.
  1920      *  @param location  The symbol the served as a context for this lookup
  1921      *  @param site      The original type from where the selection took place.
  1922      *  @param name      The symbol's name.
  1923      *  @param qualified Did we get here through a qualified expression resolution?
  1924      *  @param argtypes  The invocation's value arguments,
  1925      *                   if we looked for a method.
  1926      *  @param typeargtypes  The invocation's type arguments,
  1927      *                   if we looked for a method.
  1928      *  @param logResolveHelper helper class used to log resolve errors
  1929      */
  1930     Symbol accessInternal(Symbol sym,
  1931                   DiagnosticPosition pos,
  1932                   Symbol location,
  1933                   Type site,
  1934                   Name name,
  1935                   boolean qualified,
  1936                   List<Type> argtypes,
  1937                   List<Type> typeargtypes,
  1938                   LogResolveHelper logResolveHelper) {
  1939         if (sym.kind >= AMBIGUOUS) {
  1940             ResolveError errSym = (ResolveError)sym;
  1941             sym = errSym.access(name, qualified ? site.tsym : syms.noSymbol);
  1942             argtypes = logResolveHelper.getArgumentTypes(errSym, sym, name, argtypes);
  1943             if (logResolveHelper.resolveDiagnosticNeeded(site, argtypes, typeargtypes)) {
  1944                 logResolveError(errSym, pos, location, site, name, argtypes, typeargtypes);
  1947         return sym;
  1950     /**
  1951      * Variant of the generalized access routine, to be used for generating method
  1952      * resolution diagnostics
  1953      */
  1954     Symbol accessMethod(Symbol sym,
  1955                   DiagnosticPosition pos,
  1956                   Symbol location,
  1957                   Type site,
  1958                   Name name,
  1959                   boolean qualified,
  1960                   List<Type> argtypes,
  1961                   List<Type> typeargtypes) {
  1962         return accessInternal(sym, pos, location, site, name, qualified, argtypes, typeargtypes, methodLogResolveHelper);
  1965     /** Same as original accessMethod(), but without location.
  1966      */
  1967     Symbol accessMethod(Symbol sym,
  1968                   DiagnosticPosition pos,
  1969                   Type site,
  1970                   Name name,
  1971                   boolean qualified,
  1972                   List<Type> argtypes,
  1973                   List<Type> typeargtypes) {
  1974         return accessMethod(sym, pos, site.tsym, site, name, qualified, argtypes, typeargtypes);
  1977     /**
  1978      * Variant of the generalized access routine, to be used for generating variable,
  1979      * type resolution diagnostics
  1980      */
  1981     Symbol accessBase(Symbol sym,
  1982                   DiagnosticPosition pos,
  1983                   Symbol location,
  1984                   Type site,
  1985                   Name name,
  1986                   boolean qualified) {
  1987         return accessInternal(sym, pos, location, site, name, qualified, List.<Type>nil(), null, basicLogResolveHelper);
  1990     /** Same as original accessBase(), but without location.
  1991      */
  1992     Symbol accessBase(Symbol sym,
  1993                   DiagnosticPosition pos,
  1994                   Type site,
  1995                   Name name,
  1996                   boolean qualified) {
  1997         return accessBase(sym, pos, site.tsym, site, name, qualified);
  2000     interface LogResolveHelper {
  2001         boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes);
  2002         List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes);
  2005     LogResolveHelper basicLogResolveHelper = new LogResolveHelper() {
  2006         public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
  2007             return !site.isErroneous();
  2009         public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
  2010             return argtypes;
  2012     };
  2014     LogResolveHelper methodLogResolveHelper = new LogResolveHelper() {
  2015         public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
  2016             return !site.isErroneous() &&
  2017                         !Type.isErroneous(argtypes) &&
  2018                         (typeargtypes == null || !Type.isErroneous(typeargtypes));
  2020         public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
  2021             return (syms.operatorNames.contains(name)) ?
  2022                     argtypes :
  2023                     Type.map(argtypes, new ResolveDeferredRecoveryMap(accessedSym));
  2026         class ResolveDeferredRecoveryMap extends DeferredAttr.RecoveryDeferredTypeMap {
  2028             public ResolveDeferredRecoveryMap(Symbol msym) {
  2029                 deferredAttr.super(AttrMode.SPECULATIVE, msym, currentResolutionContext.step);
  2032             @Override
  2033             protected Type typeOf(DeferredType dt) {
  2034                 Type res = super.typeOf(dt);
  2035                 if (!res.isErroneous()) {
  2036                     switch (TreeInfo.skipParens(dt.tree).getTag()) {
  2037                         case LAMBDA:
  2038                         case REFERENCE:
  2039                             return dt;
  2040                         case CONDEXPR:
  2041                             return res == Type.recoveryType ?
  2042                                     dt : res;
  2045                 return res;
  2048     };
  2050     /** Check that sym is not an abstract method.
  2051      */
  2052     void checkNonAbstract(DiagnosticPosition pos, Symbol sym) {
  2053         if ((sym.flags() & ABSTRACT) != 0 && (sym.flags() & DEFAULT) == 0)
  2054             log.error(pos, "abstract.cant.be.accessed.directly",
  2055                       kindName(sym), sym, sym.location());
  2058 /* ***************************************************************************
  2059  *  Debugging
  2060  ****************************************************************************/
  2062     /** print all scopes starting with scope s and proceeding outwards.
  2063      *  used for debugging.
  2064      */
  2065     public void printscopes(Scope s) {
  2066         while (s != null) {
  2067             if (s.owner != null)
  2068                 System.err.print(s.owner + ": ");
  2069             for (Scope.Entry e = s.elems; e != null; e = e.sibling) {
  2070                 if ((e.sym.flags() & ABSTRACT) != 0)
  2071                     System.err.print("abstract ");
  2072                 System.err.print(e.sym + " ");
  2074             System.err.println();
  2075             s = s.next;
  2079     void printscopes(Env<AttrContext> env) {
  2080         while (env.outer != null) {
  2081             System.err.println("------------------------------");
  2082             printscopes(env.info.scope);
  2083             env = env.outer;
  2087     public void printscopes(Type t) {
  2088         while (t.hasTag(CLASS)) {
  2089             printscopes(t.tsym.members());
  2090             t = types.supertype(t);
  2094 /* ***************************************************************************
  2095  *  Name resolution
  2096  *  Naming conventions are as for symbol lookup
  2097  *  Unlike the find... methods these methods will report access errors
  2098  ****************************************************************************/
  2100     /** Resolve an unqualified (non-method) identifier.
  2101      *  @param pos       The position to use for error reporting.
  2102      *  @param env       The environment current at the identifier use.
  2103      *  @param name      The identifier's name.
  2104      *  @param kind      The set of admissible symbol kinds for the identifier.
  2105      */
  2106     Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env,
  2107                         Name name, int kind) {
  2108         return accessBase(
  2109             findIdent(env, name, kind),
  2110             pos, env.enclClass.sym.type, name, false);
  2113     /** Resolve an unqualified method identifier.
  2114      *  @param pos       The position to use for error reporting.
  2115      *  @param env       The environment current at the method invocation.
  2116      *  @param name      The identifier's name.
  2117      *  @param argtypes  The types of the invocation's value arguments.
  2118      *  @param typeargtypes  The types of the invocation's type arguments.
  2119      */
  2120     Symbol resolveMethod(DiagnosticPosition pos,
  2121                          Env<AttrContext> env,
  2122                          Name name,
  2123                          List<Type> argtypes,
  2124                          List<Type> typeargtypes) {
  2125         return lookupMethod(env, pos, env.enclClass.sym, new BasicLookupHelper(name, env.enclClass.sym.type, argtypes, typeargtypes) {
  2126             @Override
  2127             Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2128                 return findFun(env, name, argtypes, typeargtypes,
  2129                         phase.isBoxingRequired(),
  2130                         phase.isVarargsRequired());
  2132         });
  2135     /** Resolve a qualified method identifier
  2136      *  @param pos       The position to use for error reporting.
  2137      *  @param env       The environment current at the method invocation.
  2138      *  @param site      The type of the qualifying expression, in which
  2139      *                   identifier is searched.
  2140      *  @param name      The identifier's name.
  2141      *  @param argtypes  The types of the invocation's value arguments.
  2142      *  @param typeargtypes  The types of the invocation's type arguments.
  2143      */
  2144     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
  2145                                   Type site, Name name, List<Type> argtypes,
  2146                                   List<Type> typeargtypes) {
  2147         return resolveQualifiedMethod(pos, env, site.tsym, site, name, argtypes, typeargtypes);
  2149     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
  2150                                   Symbol location, Type site, Name name, List<Type> argtypes,
  2151                                   List<Type> typeargtypes) {
  2152         return resolveQualifiedMethod(new MethodResolutionContext(), pos, env, location, site, name, argtypes, typeargtypes);
  2154     private Symbol resolveQualifiedMethod(MethodResolutionContext resolveContext,
  2155                                   DiagnosticPosition pos, Env<AttrContext> env,
  2156                                   Symbol location, Type site, Name name, List<Type> argtypes,
  2157                                   List<Type> typeargtypes) {
  2158         return lookupMethod(env, pos, location, resolveContext, new BasicLookupHelper(name, site, argtypes, typeargtypes) {
  2159             @Override
  2160             Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2161                 return findMethod(env, site, name, argtypes, typeargtypes,
  2162                         phase.isBoxingRequired(),
  2163                         phase.isVarargsRequired(), false);
  2165             @Override
  2166             Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2167                 if (sym.kind >= AMBIGUOUS) {
  2168                     sym = super.access(env, pos, location, sym);
  2169                 } else if (allowMethodHandles) {
  2170                     MethodSymbol msym = (MethodSymbol)sym;
  2171                     if (msym.isSignaturePolymorphic(types)) {
  2172                         return findPolymorphicSignatureInstance(env, sym, argtypes);
  2175                 return sym;
  2177         });
  2180     /** Find or create an implicit method of exactly the given type (after erasure).
  2181      *  Searches in a side table, not the main scope of the site.
  2182      *  This emulates the lookup process required by JSR 292 in JVM.
  2183      *  @param env       Attribution environment
  2184      *  @param spMethod  signature polymorphic method - i.e. MH.invokeExact
  2185      *  @param argtypes  The required argument types
  2186      */
  2187     Symbol findPolymorphicSignatureInstance(Env<AttrContext> env,
  2188                                             final Symbol spMethod,
  2189                                             List<Type> argtypes) {
  2190         Type mtype = infer.instantiatePolymorphicSignatureInstance(env,
  2191                 (MethodSymbol)spMethod, currentResolutionContext, argtypes);
  2192         for (Symbol sym : polymorphicSignatureScope.getElementsByName(spMethod.name)) {
  2193             if (types.isSameType(mtype, sym.type)) {
  2194                return sym;
  2198         // create the desired method
  2199         long flags = ABSTRACT | HYPOTHETICAL | spMethod.flags() & Flags.AccessFlags;
  2200         Symbol msym = new MethodSymbol(flags, spMethod.name, mtype, spMethod.owner) {
  2201             @Override
  2202             public Symbol baseSymbol() {
  2203                 return spMethod;
  2205         };
  2206         polymorphicSignatureScope.enter(msym);
  2207         return msym;
  2210     /** Resolve a qualified method identifier, throw a fatal error if not
  2211      *  found.
  2212      *  @param pos       The position to use for error reporting.
  2213      *  @param env       The environment current at the method invocation.
  2214      *  @param site      The type of the qualifying expression, in which
  2215      *                   identifier is searched.
  2216      *  @param name      The identifier's name.
  2217      *  @param argtypes  The types of the invocation's value arguments.
  2218      *  @param typeargtypes  The types of the invocation's type arguments.
  2219      */
  2220     public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env,
  2221                                         Type site, Name name,
  2222                                         List<Type> argtypes,
  2223                                         List<Type> typeargtypes) {
  2224         MethodResolutionContext resolveContext = new MethodResolutionContext();
  2225         resolveContext.internalResolution = true;
  2226         Symbol sym = resolveQualifiedMethod(resolveContext, pos, env, site.tsym,
  2227                 site, name, argtypes, typeargtypes);
  2228         if (sym.kind == MTH) return (MethodSymbol)sym;
  2229         else throw new FatalError(
  2230                  diags.fragment("fatal.err.cant.locate.meth",
  2231                                 name));
  2234     /** Resolve constructor.
  2235      *  @param pos       The position to use for error reporting.
  2236      *  @param env       The environment current at the constructor invocation.
  2237      *  @param site      The type of class for which a constructor is searched.
  2238      *  @param argtypes  The types of the constructor invocation's value
  2239      *                   arguments.
  2240      *  @param typeargtypes  The types of the constructor invocation's type
  2241      *                   arguments.
  2242      */
  2243     Symbol resolveConstructor(DiagnosticPosition pos,
  2244                               Env<AttrContext> env,
  2245                               Type site,
  2246                               List<Type> argtypes,
  2247                               List<Type> typeargtypes) {
  2248         return resolveConstructor(new MethodResolutionContext(), pos, env, site, argtypes, typeargtypes);
  2251     private Symbol resolveConstructor(MethodResolutionContext resolveContext,
  2252                               final DiagnosticPosition pos,
  2253                               Env<AttrContext> env,
  2254                               Type site,
  2255                               List<Type> argtypes,
  2256                               List<Type> typeargtypes) {
  2257         return lookupMethod(env, pos, site.tsym, resolveContext, new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
  2258             @Override
  2259             Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2260                 return findConstructor(pos, env, site, argtypes, typeargtypes,
  2261                         phase.isBoxingRequired(),
  2262                         phase.isVarargsRequired());
  2264         });
  2267     /** Resolve a constructor, throw a fatal error if not found.
  2268      *  @param pos       The position to use for error reporting.
  2269      *  @param env       The environment current at the method invocation.
  2270      *  @param site      The type to be constructed.
  2271      *  @param argtypes  The types of the invocation's value arguments.
  2272      *  @param typeargtypes  The types of the invocation's type arguments.
  2273      */
  2274     public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  2275                                         Type site,
  2276                                         List<Type> argtypes,
  2277                                         List<Type> typeargtypes) {
  2278         MethodResolutionContext resolveContext = new MethodResolutionContext();
  2279         resolveContext.internalResolution = true;
  2280         Symbol sym = resolveConstructor(resolveContext, pos, env, site, argtypes, typeargtypes);
  2281         if (sym.kind == MTH) return (MethodSymbol)sym;
  2282         else throw new FatalError(
  2283                  diags.fragment("fatal.err.cant.locate.ctor", site));
  2286     Symbol findConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  2287                               Type site, List<Type> argtypes,
  2288                               List<Type> typeargtypes,
  2289                               boolean allowBoxing,
  2290                               boolean useVarargs) {
  2291         Symbol sym = findMethod(env, site,
  2292                                     names.init, argtypes,
  2293                                     typeargtypes, allowBoxing,
  2294                                     useVarargs, false);
  2295         chk.checkDeprecated(pos, env.info.scope.owner, sym);
  2296         return sym;
  2299     /** Resolve constructor using diamond inference.
  2300      *  @param pos       The position to use for error reporting.
  2301      *  @param env       The environment current at the constructor invocation.
  2302      *  @param site      The type of class for which a constructor is searched.
  2303      *                   The scope of this class has been touched in attribution.
  2304      *  @param argtypes  The types of the constructor invocation's value
  2305      *                   arguments.
  2306      *  @param typeargtypes  The types of the constructor invocation's type
  2307      *                   arguments.
  2308      */
  2309     Symbol resolveDiamond(DiagnosticPosition pos,
  2310                               Env<AttrContext> env,
  2311                               Type site,
  2312                               List<Type> argtypes,
  2313                               List<Type> typeargtypes) {
  2314         return lookupMethod(env, pos, site.tsym, new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
  2315             @Override
  2316             Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2317                 return findDiamond(env, site, argtypes, typeargtypes,
  2318                         phase.isBoxingRequired(),
  2319                         phase.isVarargsRequired());
  2321             @Override
  2322             Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2323                 if (sym.kind >= AMBIGUOUS) {
  2324                     final JCDiagnostic details = sym.kind == WRONG_MTH ?
  2325                                     ((InapplicableSymbolError)sym).errCandidate().details :
  2326                                     null;
  2327                     sym = new InapplicableSymbolError(sym.kind, "diamondError", currentResolutionContext) {
  2328                         @Override
  2329                         JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos,
  2330                                 Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
  2331                             String key = details == null ?
  2332                                 "cant.apply.diamond" :
  2333                                 "cant.apply.diamond.1";
  2334                             return diags.create(dkind, log.currentSource(), pos, key,
  2335                                     diags.fragment("diamond", site.tsym), details);
  2337                     };
  2338                     sym = accessMethod(sym, pos, site, names.init, true, argtypes, typeargtypes);
  2339                     env.info.pendingResolutionPhase = currentResolutionContext.step;
  2341                 return sym;
  2343         });
  2346     /** This method scans all the constructor symbol in a given class scope -
  2347      *  assuming that the original scope contains a constructor of the kind:
  2348      *  {@code Foo(X x, Y y)}, where X,Y are class type-variables declared in Foo,
  2349      *  a method check is executed against the modified constructor type:
  2350      *  {@code <X,Y>Foo<X,Y>(X x, Y y)}. This is crucial in order to enable diamond
  2351      *  inference. The inferred return type of the synthetic constructor IS
  2352      *  the inferred type for the diamond operator.
  2353      */
  2354     private Symbol findDiamond(Env<AttrContext> env,
  2355                               Type site,
  2356                               List<Type> argtypes,
  2357                               List<Type> typeargtypes,
  2358                               boolean allowBoxing,
  2359                               boolean useVarargs) {
  2360         Symbol bestSoFar = methodNotFound;
  2361         for (Scope.Entry e = site.tsym.members().lookup(names.init);
  2362              e.scope != null;
  2363              e = e.next()) {
  2364             final Symbol sym = e.sym;
  2365             //- System.out.println(" e " + e.sym);
  2366             if (sym.kind == MTH &&
  2367                 (sym.flags_field & SYNTHETIC) == 0) {
  2368                     List<Type> oldParams = e.sym.type.hasTag(FORALL) ?
  2369                             ((ForAll)sym.type).tvars :
  2370                             List.<Type>nil();
  2371                     Type constrType = new ForAll(site.tsym.type.getTypeArguments().appendList(oldParams),
  2372                             types.createMethodTypeWithReturn(sym.type.asMethodType(), site));
  2373                     MethodSymbol newConstr = new MethodSymbol(sym.flags(), names.init, constrType, site.tsym) {
  2374                         @Override
  2375                         public Symbol baseSymbol() {
  2376                             return sym;
  2378                     };
  2379                     bestSoFar = selectBest(env, site, argtypes, typeargtypes,
  2380                             newConstr,
  2381                             bestSoFar,
  2382                             allowBoxing,
  2383                             useVarargs,
  2384                             false);
  2387         return bestSoFar;
  2392     /** Resolve operator.
  2393      *  @param pos       The position to use for error reporting.
  2394      *  @param optag     The tag of the operation tree.
  2395      *  @param env       The environment current at the operation.
  2396      *  @param argtypes  The types of the operands.
  2397      */
  2398     Symbol resolveOperator(DiagnosticPosition pos, JCTree.Tag optag,
  2399                            Env<AttrContext> env, List<Type> argtypes) {
  2400         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  2401         try {
  2402             currentResolutionContext = new MethodResolutionContext();
  2403             Name name = treeinfo.operatorName(optag);
  2404             env.info.pendingResolutionPhase = currentResolutionContext.step = BASIC;
  2405             Symbol sym = findMethod(env, syms.predefClass.type, name, argtypes,
  2406                                     null, false, false, true);
  2407             if (boxingEnabled && sym.kind >= WRONG_MTHS)
  2408                 env.info.pendingResolutionPhase = currentResolutionContext.step = BOX;
  2409                 sym = findMethod(env, syms.predefClass.type, name, argtypes,
  2410                                  null, true, false, true);
  2411             return accessMethod(sym, pos, env.enclClass.sym.type, name,
  2412                           false, argtypes, null);
  2414         finally {
  2415             currentResolutionContext = prevResolutionContext;
  2419     /** Resolve operator.
  2420      *  @param pos       The position to use for error reporting.
  2421      *  @param optag     The tag of the operation tree.
  2422      *  @param env       The environment current at the operation.
  2423      *  @param arg       The type of the operand.
  2424      */
  2425     Symbol resolveUnaryOperator(DiagnosticPosition pos, JCTree.Tag optag, Env<AttrContext> env, Type arg) {
  2426         return resolveOperator(pos, optag, env, List.of(arg));
  2429     /** Resolve binary operator.
  2430      *  @param pos       The position to use for error reporting.
  2431      *  @param optag     The tag of the operation tree.
  2432      *  @param env       The environment current at the operation.
  2433      *  @param left      The types of the left operand.
  2434      *  @param right     The types of the right operand.
  2435      */
  2436     Symbol resolveBinaryOperator(DiagnosticPosition pos,
  2437                                  JCTree.Tag optag,
  2438                                  Env<AttrContext> env,
  2439                                  Type left,
  2440                                  Type right) {
  2441         return resolveOperator(pos, optag, env, List.of(left, right));
  2444     /**
  2445      * Resolution of member references is typically done as a single
  2446      * overload resolution step, where the argument types A are inferred from
  2447      * the target functional descriptor.
  2449      * If the member reference is a method reference with a type qualifier,
  2450      * a two-step lookup process is performed. The first step uses the
  2451      * expected argument list A, while the second step discards the first
  2452      * type from A (which is treated as a receiver type).
  2454      * There are two cases in which inference is performed: (i) if the member
  2455      * reference is a constructor reference and the qualifier type is raw - in
  2456      * which case diamond inference is used to infer a parameterization for the
  2457      * type qualifier; (ii) if the member reference is an unbound reference
  2458      * where the type qualifier is raw - in that case, during the unbound lookup
  2459      * the receiver argument type is used to infer an instantiation for the raw
  2460      * qualifier type.
  2462      * When a multi-step resolution process is exploited, it is an error
  2463      * if two candidates are found (ambiguity).
  2465      * This routine returns a pair (T,S), where S is the member reference symbol,
  2466      * and T is the type of the class in which S is defined. This is necessary as
  2467      * the type T might be dynamically inferred (i.e. if constructor reference
  2468      * has a raw qualifier).
  2469      */
  2470     Pair<Symbol, ReferenceLookupHelper> resolveMemberReference(DiagnosticPosition pos,
  2471                                   Env<AttrContext> env,
  2472                                   JCMemberReference referenceTree,
  2473                                   Type site,
  2474                                   Name name, List<Type> argtypes,
  2475                                   List<Type> typeargtypes,
  2476                                   boolean boxingAllowed) {
  2477         MethodResolutionPhase maxPhase = boxingAllowed ? VARARITY : BASIC;
  2479         ReferenceLookupHelper boundLookupHelper;
  2480         if (!name.equals(names.init)) {
  2481             //method reference
  2482             boundLookupHelper =
  2483                     new MethodReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
  2484         } else if (site.hasTag(ARRAY)) {
  2485             //array constructor reference
  2486             boundLookupHelper =
  2487                     new ArrayConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase);
  2488         } else {
  2489             //class constructor reference
  2490             boundLookupHelper =
  2491                     new ConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase);
  2494         //step 1 - bound lookup
  2495         Env<AttrContext> boundEnv = env.dup(env.tree, env.info.dup());
  2496         Symbol boundSym = lookupMethod(boundEnv, env.tree.pos(), site.tsym, boundLookupHelper);
  2498         //step 2 - unbound lookup
  2499         ReferenceLookupHelper unboundLookupHelper = boundLookupHelper.unboundLookup();
  2500         Env<AttrContext> unboundEnv = env.dup(env.tree, env.info.dup());
  2501         Symbol unboundSym = lookupMethod(unboundEnv, env.tree.pos(), site.tsym, unboundLookupHelper);
  2503         //merge results
  2504         Pair<Symbol, ReferenceLookupHelper> res;
  2505         if (unboundSym.kind != MTH) {
  2506             res = new Pair<Symbol, ReferenceLookupHelper>(boundSym, boundLookupHelper);
  2507             env.info.pendingResolutionPhase = boundEnv.info.pendingResolutionPhase;
  2508         } else if (boundSym.kind == MTH) {
  2509             res = new Pair<Symbol, ReferenceLookupHelper>(ambiguityError(boundSym, unboundSym), boundLookupHelper);
  2510             env.info.pendingResolutionPhase = boundEnv.info.pendingResolutionPhase;
  2511         } else {
  2512             res = new Pair<Symbol, ReferenceLookupHelper>(unboundSym, unboundLookupHelper);
  2513             env.info.pendingResolutionPhase = unboundEnv.info.pendingResolutionPhase;
  2516         return res;
  2519     /**
  2520      * Helper for defining custom method-like lookup logic; a lookup helper
  2521      * provides hooks for (i) the actual lookup logic and (ii) accessing the
  2522      * lookup result (this step might result in compiler diagnostics to be generated)
  2523      */
  2524     abstract class LookupHelper {
  2526         /** name of the symbol to lookup */
  2527         Name name;
  2529         /** location in which the lookup takes place */
  2530         Type site;
  2532         /** actual types used during the lookup */
  2533         List<Type> argtypes;
  2535         /** type arguments used during the lookup */
  2536         List<Type> typeargtypes;
  2538         /** Max overload resolution phase handled by this helper */
  2539         MethodResolutionPhase maxPhase;
  2541         LookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2542             this.name = name;
  2543             this.site = site;
  2544             this.argtypes = argtypes;
  2545             this.typeargtypes = typeargtypes;
  2546             this.maxPhase = maxPhase;
  2549         /**
  2550          * Should lookup stop at given phase with given result
  2551          */
  2552         protected boolean shouldStop(Symbol sym, MethodResolutionPhase phase) {
  2553             return phase.ordinal() > maxPhase.ordinal() ||
  2554                     sym.kind < ERRONEOUS || sym.kind == AMBIGUOUS;
  2557         /**
  2558          * Search for a symbol under a given overload resolution phase - this method
  2559          * is usually called several times, once per each overload resolution phase
  2560          */
  2561         abstract Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase);
  2563         /**
  2564          * Validate the result of the lookup
  2565          */
  2566         abstract Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym);
  2569     abstract class BasicLookupHelper extends LookupHelper {
  2571         BasicLookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes) {
  2572             super(name, site, argtypes, typeargtypes, MethodResolutionPhase.VARARITY);
  2575         @Override
  2576         Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2577             if (sym.kind == AMBIGUOUS) {
  2578                 AmbiguityError a_err = (AmbiguityError)sym;
  2579                 sym = a_err.mergeAbstracts(site);
  2581             if (sym.kind >= AMBIGUOUS) {
  2582                 //if nothing is found return the 'first' error
  2583                 sym = accessMethod(sym, pos, location, site, name, true, argtypes, typeargtypes);
  2585             return sym;
  2589     /**
  2590      * Helper class for member reference lookup. A reference lookup helper
  2591      * defines the basic logic for member reference lookup; a method gives
  2592      * access to an 'unbound' helper used to perform an unbound member
  2593      * reference lookup.
  2594      */
  2595     abstract class ReferenceLookupHelper extends LookupHelper {
  2597         /** The member reference tree */
  2598         JCMemberReference referenceTree;
  2600         ReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
  2601                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2602             super(name, site, argtypes, typeargtypes, maxPhase);
  2603             this.referenceTree = referenceTree;
  2607         /**
  2608          * Returns an unbound version of this lookup helper. By default, this
  2609          * method returns an dummy lookup helper.
  2610          */
  2611         ReferenceLookupHelper unboundLookup() {
  2612             //dummy loopkup helper that always return 'methodNotFound'
  2613             return new ReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase) {
  2614                 @Override
  2615                 ReferenceLookupHelper unboundLookup() {
  2616                     return this;
  2618                 @Override
  2619                 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2620                     return methodNotFound;
  2622                 @Override
  2623                 ReferenceKind referenceKind(Symbol sym) {
  2624                     Assert.error();
  2625                     return null;
  2627             };
  2630         /**
  2631          * Get the kind of the member reference
  2632          */
  2633         abstract JCMemberReference.ReferenceKind referenceKind(Symbol sym);
  2635         Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2636             if (sym.kind == AMBIGUOUS) {
  2637                 AmbiguityError a_err = (AmbiguityError)sym;
  2638                 sym = a_err.mergeAbstracts(site);
  2640             //skip error reporting
  2641             return sym;
  2645     /**
  2646      * Helper class for method reference lookup. The lookup logic is based
  2647      * upon Resolve.findMethod; in certain cases, this helper class has a
  2648      * corresponding unbound helper class (see UnboundMethodReferenceLookupHelper).
  2649      * In such cases, non-static lookup results are thrown away.
  2650      */
  2651     class MethodReferenceLookupHelper extends ReferenceLookupHelper {
  2653         MethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
  2654                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2655             super(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
  2658         protected Symbol lookupReferenceInternal(Env<AttrContext> env, MethodResolutionPhase phase) {
  2659             return findMethod(env, site, name, argtypes, typeargtypes,
  2660                     phase.isBoxingRequired(), phase.isVarargsRequired(), syms.operatorNames.contains(name));
  2663         protected Symbol adjustLookupResult(Env<AttrContext> env, Symbol sym) {
  2664             return !TreeInfo.isStaticSelector(referenceTree.expr, names) ||
  2665                         sym.kind != MTH ||
  2666                         sym.isStatic() ? sym : new StaticError(sym);
  2669         @Override
  2670         final Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2671             return adjustLookupResult(env, lookupReferenceInternal(env, phase));
  2674         @Override
  2675         ReferenceLookupHelper unboundLookup() {
  2676             if (TreeInfo.isStaticSelector(referenceTree.expr, names) &&
  2677                     argtypes.nonEmpty() &&
  2678                     types.isSubtypeUnchecked(argtypes.head, site)) {
  2679                 return new UnboundMethodReferenceLookupHelper(referenceTree, name,
  2680                         site, argtypes, typeargtypes, maxPhase);
  2681             } else {
  2682                 return super.unboundLookup();
  2686         @Override
  2687         ReferenceKind referenceKind(Symbol sym) {
  2688             if (sym.isStatic()) {
  2689                 return ReferenceKind.STATIC;
  2690             } else {
  2691                 Name selName = TreeInfo.name(referenceTree.getQualifierExpression());
  2692                 return selName != null && selName == names._super ?
  2693                         ReferenceKind.SUPER :
  2694                         ReferenceKind.BOUND;
  2699     /**
  2700      * Helper class for unbound method reference lookup. Essentially the same
  2701      * as the basic method reference lookup helper; main difference is that static
  2702      * lookup results are thrown away. If qualifier type is raw, an attempt to
  2703      * infer a parameterized type is made using the first actual argument (that
  2704      * would otherwise be ignored during the lookup).
  2705      */
  2706     class UnboundMethodReferenceLookupHelper extends MethodReferenceLookupHelper {
  2708         UnboundMethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
  2709                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2710             super(referenceTree, name,
  2711                     site.isRaw() ? types.asSuper(argtypes.head, site.tsym) : site,
  2712                     argtypes.tail, typeargtypes, maxPhase);
  2715         @Override
  2716         protected Symbol adjustLookupResult(Env<AttrContext> env, Symbol sym) {
  2717             return sym.kind != MTH || !sym.isStatic() ? sym : new StaticError(sym);
  2720         @Override
  2721         ReferenceLookupHelper unboundLookup() {
  2722             return this;
  2725         @Override
  2726         ReferenceKind referenceKind(Symbol sym) {
  2727             return ReferenceKind.UNBOUND;
  2731     /**
  2732      * Helper class for array constructor lookup; an array constructor lookup
  2733      * is simulated by looking up a method that returns the array type specified
  2734      * as qualifier, and that accepts a single int parameter (size of the array).
  2735      */
  2736     class ArrayConstructorReferenceLookupHelper extends ReferenceLookupHelper {
  2738         ArrayConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
  2739                 List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2740             super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase);
  2743         @Override
  2744         protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2745             Scope sc = new Scope(syms.arrayClass);
  2746             MethodSymbol arrayConstr = new MethodSymbol(PUBLIC, name, null, site.tsym);
  2747             arrayConstr.type = new MethodType(List.of(syms.intType), site, List.<Type>nil(), syms.methodClass);
  2748             sc.enter(arrayConstr);
  2749             return findMethodInScope(env, site, name, argtypes, typeargtypes, sc, methodNotFound, phase.isBoxingRequired(), phase.isVarargsRequired(), false, false);
  2752         @Override
  2753         ReferenceKind referenceKind(Symbol sym) {
  2754             return ReferenceKind.ARRAY_CTOR;
  2758     /**
  2759      * Helper class for constructor reference lookup. The lookup logic is based
  2760      * upon either Resolve.findMethod or Resolve.findDiamond - depending on
  2761      * whether the constructor reference needs diamond inference (this is the case
  2762      * if the qualifier type is raw). A special erroneous symbol is returned
  2763      * if the lookup returns the constructor of an inner class and there's no
  2764      * enclosing instance in scope.
  2765      */
  2766     class ConstructorReferenceLookupHelper extends ReferenceLookupHelper {
  2768         boolean needsInference;
  2770         ConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
  2771                 List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2772             super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase);
  2773             if (site.isRaw()) {
  2774                 this.site = new ClassType(site.getEnclosingType(), site.tsym.type.getTypeArguments(), site.tsym);
  2775                 needsInference = true;
  2779         @Override
  2780         protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2781             Symbol sym = needsInference ?
  2782                 findDiamond(env, site, argtypes, typeargtypes, phase.isBoxingRequired(), phase.isVarargsRequired()) :
  2783                 findMethod(env, site, name, argtypes, typeargtypes,
  2784                         phase.isBoxingRequired(), phase.isVarargsRequired(), syms.operatorNames.contains(name));
  2785             return sym.kind != MTH ||
  2786                           site.getEnclosingType().hasTag(NONE) ||
  2787                           hasEnclosingInstance(env, site) ?
  2788                           sym : new InvalidSymbolError(Kinds.MISSING_ENCL, sym, null) {
  2789                     @Override
  2790                     JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
  2791                        return diags.create(dkind, log.currentSource(), pos,
  2792                             "cant.access.inner.cls.constr", site.tsym.name, argtypes, site.getEnclosingType());
  2794                 };
  2797         @Override
  2798         ReferenceKind referenceKind(Symbol sym) {
  2799             return site.getEnclosingType().hasTag(NONE) ?
  2800                     ReferenceKind.TOPLEVEL : ReferenceKind.IMPLICIT_INNER;
  2804     /**
  2805      * Main overload resolution routine. On each overload resolution step, a
  2806      * lookup helper class is used to perform the method/constructor lookup;
  2807      * at the end of the lookup, the helper is used to validate the results
  2808      * (this last step might trigger overload resolution diagnostics).
  2809      */
  2810     Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, LookupHelper lookupHelper) {
  2811         return lookupMethod(env, pos, location, new MethodResolutionContext(), lookupHelper);
  2814     Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location,
  2815             MethodResolutionContext resolveContext, LookupHelper lookupHelper) {
  2816         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  2817         try {
  2818             Symbol bestSoFar = methodNotFound;
  2819             currentResolutionContext = resolveContext;
  2820             for (MethodResolutionPhase phase : methodResolutionSteps) {
  2821                 if (!phase.isApplicable(boxingEnabled, varargsEnabled) ||
  2822                         lookupHelper.shouldStop(bestSoFar, phase)) break;
  2823                 MethodResolutionPhase prevPhase = currentResolutionContext.step;
  2824                 Symbol prevBest = bestSoFar;
  2825                 currentResolutionContext.step = phase;
  2826                 bestSoFar = phase.mergeResults(bestSoFar, lookupHelper.lookup(env, phase));
  2827                 env.info.pendingResolutionPhase = (prevBest == bestSoFar) ? prevPhase : phase;
  2829             return lookupHelper.access(env, pos, location, bestSoFar);
  2830         } finally {
  2831             currentResolutionContext = prevResolutionContext;
  2835     /**
  2836      * Resolve `c.name' where name == this or name == super.
  2837      * @param pos           The position to use for error reporting.
  2838      * @param env           The environment current at the expression.
  2839      * @param c             The qualifier.
  2840      * @param name          The identifier's name.
  2841      */
  2842     Symbol resolveSelf(DiagnosticPosition pos,
  2843                        Env<AttrContext> env,
  2844                        TypeSymbol c,
  2845                        Name name) {
  2846         Env<AttrContext> env1 = env;
  2847         boolean staticOnly = false;
  2848         while (env1.outer != null) {
  2849             if (isStatic(env1)) staticOnly = true;
  2850             if (env1.enclClass.sym == c) {
  2851                 Symbol sym = env1.info.scope.lookup(name).sym;
  2852                 if (sym != null) {
  2853                     if (staticOnly) sym = new StaticError(sym);
  2854                     return accessBase(sym, pos, env.enclClass.sym.type,
  2855                                   name, true);
  2858             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  2859             env1 = env1.outer;
  2861         if (allowDefaultMethods && c.isInterface() &&
  2862                 name == names._super && !isStatic(env) &&
  2863                 types.isDirectSuperInterface(c, env.enclClass.sym)) {
  2864             //this might be a default super call if one of the superinterfaces is 'c'
  2865             for (Type t : pruneInterfaces(env.enclClass.type)) {
  2866                 if (t.tsym == c) {
  2867                     env.info.defaultSuperCallSite = t;
  2868                     return new VarSymbol(0, names._super,
  2869                             types.asSuper(env.enclClass.type, c), env.enclClass.sym);
  2872             //find a direct superinterface that is a subtype of 'c'
  2873             for (Type i : types.interfaces(env.enclClass.type)) {
  2874                 if (i.tsym.isSubClass(c, types) && i.tsym != c) {
  2875                     log.error(pos, "illegal.default.super.call", c,
  2876                             diags.fragment("redundant.supertype", c, i));
  2877                     return syms.errSymbol;
  2880             Assert.error();
  2882         log.error(pos, "not.encl.class", c);
  2883         return syms.errSymbol;
  2885     //where
  2886     private List<Type> pruneInterfaces(Type t) {
  2887         ListBuffer<Type> result = ListBuffer.lb();
  2888         for (Type t1 : types.interfaces(t)) {
  2889             boolean shouldAdd = true;
  2890             for (Type t2 : types.interfaces(t)) {
  2891                 if (t1 != t2 && types.isSubtypeNoCapture(t2, t1)) {
  2892                     shouldAdd = false;
  2895             if (shouldAdd) {
  2896                 result.append(t1);
  2899         return result.toList();
  2903     /**
  2904      * Resolve `c.this' for an enclosing class c that contains the
  2905      * named member.
  2906      * @param pos           The position to use for error reporting.
  2907      * @param env           The environment current at the expression.
  2908      * @param member        The member that must be contained in the result.
  2909      */
  2910     Symbol resolveSelfContaining(DiagnosticPosition pos,
  2911                                  Env<AttrContext> env,
  2912                                  Symbol member,
  2913                                  boolean isSuperCall) {
  2914         Symbol sym = resolveSelfContainingInternal(env, member, isSuperCall);
  2915         if (sym == null) {
  2916             log.error(pos, "encl.class.required", member);
  2917             return syms.errSymbol;
  2918         } else {
  2919             return accessBase(sym, pos, env.enclClass.sym.type, sym.name, true);
  2923     boolean hasEnclosingInstance(Env<AttrContext> env, Type type) {
  2924         Symbol encl = resolveSelfContainingInternal(env, type.tsym, false);
  2925         return encl != null && encl.kind < ERRONEOUS;
  2928     private Symbol resolveSelfContainingInternal(Env<AttrContext> env,
  2929                                  Symbol member,
  2930                                  boolean isSuperCall) {
  2931         Name name = names._this;
  2932         Env<AttrContext> env1 = isSuperCall ? env.outer : env;
  2933         boolean staticOnly = false;
  2934         if (env1 != null) {
  2935             while (env1 != null && env1.outer != null) {
  2936                 if (isStatic(env1)) staticOnly = true;
  2937                 if (env1.enclClass.sym.isSubClass(member.owner, types)) {
  2938                     Symbol sym = env1.info.scope.lookup(name).sym;
  2939                     if (sym != null) {
  2940                         if (staticOnly) sym = new StaticError(sym);
  2941                         return sym;
  2944                 if ((env1.enclClass.sym.flags() & STATIC) != 0)
  2945                     staticOnly = true;
  2946                 env1 = env1.outer;
  2949         return null;
  2952     /**
  2953      * Resolve an appropriate implicit this instance for t's container.
  2954      * JLS 8.8.5.1 and 15.9.2
  2955      */
  2956     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
  2957         return resolveImplicitThis(pos, env, t, false);
  2960     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t, boolean isSuperCall) {
  2961         Type thisType = (((t.tsym.owner.kind & (MTH|VAR)) != 0)
  2962                          ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
  2963                          : resolveSelfContaining(pos, env, t.tsym, isSuperCall)).type;
  2964         if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
  2965             log.error(pos, "cant.ref.before.ctor.called", "this");
  2966         return thisType;
  2969 /* ***************************************************************************
  2970  *  ResolveError classes, indicating error situations when accessing symbols
  2971  ****************************************************************************/
  2973     //used by TransTypes when checking target type of synthetic cast
  2974     public void logAccessErrorInternal(Env<AttrContext> env, JCTree tree, Type type) {
  2975         AccessError error = new AccessError(env, env.enclClass.type, type.tsym);
  2976         logResolveError(error, tree.pos(), env.enclClass.sym, env.enclClass.type, null, null, null);
  2978     //where
  2979     private void logResolveError(ResolveError error,
  2980             DiagnosticPosition pos,
  2981             Symbol location,
  2982             Type site,
  2983             Name name,
  2984             List<Type> argtypes,
  2985             List<Type> typeargtypes) {
  2986         JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
  2987                 pos, location, site, name, argtypes, typeargtypes);
  2988         if (d != null) {
  2989             d.setFlag(DiagnosticFlag.RESOLVE_ERROR);
  2990             log.report(d);
  2994     private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
  2996     public Object methodArguments(List<Type> argtypes) {
  2997         if (argtypes == null || argtypes.isEmpty()) {
  2998             return noArgs;
  2999         } else {
  3000             ListBuffer<Object> diagArgs = ListBuffer.lb();
  3001             for (Type t : argtypes) {
  3002                 if (t.hasTag(DEFERRED)) {
  3003                     diagArgs.append(((DeferredAttr.DeferredType)t).tree);
  3004                 } else {
  3005                     diagArgs.append(t);
  3008             return diagArgs;
  3012     /**
  3013      * Root class for resolution errors. Subclass of ResolveError
  3014      * represent a different kinds of resolution error - as such they must
  3015      * specify how they map into concrete compiler diagnostics.
  3016      */
  3017     abstract class ResolveError extends Symbol {
  3019         /** The name of the kind of error, for debugging only. */
  3020         final String debugName;
  3022         ResolveError(int kind, String debugName) {
  3023             super(kind, 0, null, null, null);
  3024             this.debugName = debugName;
  3027         @Override
  3028         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
  3029             throw new AssertionError();
  3032         @Override
  3033         public String toString() {
  3034             return debugName;
  3037         @Override
  3038         public boolean exists() {
  3039             return false;
  3042         /**
  3043          * Create an external representation for this erroneous symbol to be
  3044          * used during attribution - by default this returns the symbol of a
  3045          * brand new error type which stores the original type found
  3046          * during resolution.
  3048          * @param name     the name used during resolution
  3049          * @param location the location from which the symbol is accessed
  3050          */
  3051         protected Symbol access(Name name, TypeSymbol location) {
  3052             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  3055         /**
  3056          * Create a diagnostic representing this resolution error.
  3058          * @param dkind     The kind of the diagnostic to be created (e.g error).
  3059          * @param pos       The position to be used for error reporting.
  3060          * @param site      The original type from where the selection took place.
  3061          * @param name      The name of the symbol to be resolved.
  3062          * @param argtypes  The invocation's value arguments,
  3063          *                  if we looked for a method.
  3064          * @param typeargtypes  The invocation's type arguments,
  3065          *                      if we looked for a method.
  3066          */
  3067         abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3068                 DiagnosticPosition pos,
  3069                 Symbol location,
  3070                 Type site,
  3071                 Name name,
  3072                 List<Type> argtypes,
  3073                 List<Type> typeargtypes);
  3076     /**
  3077      * This class is the root class of all resolution errors caused by
  3078      * an invalid symbol being found during resolution.
  3079      */
  3080     abstract class InvalidSymbolError extends ResolveError {
  3082         /** The invalid symbol found during resolution */
  3083         Symbol sym;
  3085         InvalidSymbolError(int kind, Symbol sym, String debugName) {
  3086             super(kind, debugName);
  3087             this.sym = sym;
  3090         @Override
  3091         public boolean exists() {
  3092             return true;
  3095         @Override
  3096         public String toString() {
  3097              return super.toString() + " wrongSym=" + sym;
  3100         @Override
  3101         public Symbol access(Name name, TypeSymbol location) {
  3102             if ((sym.kind & ERRONEOUS) == 0 && (sym.kind & TYP) != 0)
  3103                 return types.createErrorType(name, location, sym.type).tsym;
  3104             else
  3105                 return sym;
  3109     /**
  3110      * InvalidSymbolError error class indicating that a symbol matching a
  3111      * given name does not exists in a given site.
  3112      */
  3113     class SymbolNotFoundError extends ResolveError {
  3115         SymbolNotFoundError(int kind) {
  3116             super(kind, "symbol not found error");
  3119         @Override
  3120         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3121                 DiagnosticPosition pos,
  3122                 Symbol location,
  3123                 Type site,
  3124                 Name name,
  3125                 List<Type> argtypes,
  3126                 List<Type> typeargtypes) {
  3127             argtypes = argtypes == null ? List.<Type>nil() : argtypes;
  3128             typeargtypes = typeargtypes == null ? List.<Type>nil() : typeargtypes;
  3129             if (name == names.error)
  3130                 return null;
  3132             if (syms.operatorNames.contains(name)) {
  3133                 boolean isUnaryOp = argtypes.size() == 1;
  3134                 String key = argtypes.size() == 1 ?
  3135                     "operator.cant.be.applied" :
  3136                     "operator.cant.be.applied.1";
  3137                 Type first = argtypes.head;
  3138                 Type second = !isUnaryOp ? argtypes.tail.head : null;
  3139                 return diags.create(dkind, log.currentSource(), pos,
  3140                         key, name, first, second);
  3142             boolean hasLocation = false;
  3143             if (location == null) {
  3144                 location = site.tsym;
  3146             if (!location.name.isEmpty()) {
  3147                 if (location.kind == PCK && !site.tsym.exists()) {
  3148                     return diags.create(dkind, log.currentSource(), pos,
  3149                         "doesnt.exist", location);
  3151                 hasLocation = !location.name.equals(names._this) &&
  3152                         !location.name.equals(names._super);
  3154             boolean isConstructor = kind == ABSENT_MTH && name == names.init;
  3155             KindName kindname = isConstructor ? KindName.CONSTRUCTOR : absentKind(kind);
  3156             Name idname = isConstructor ? site.tsym.name : name;
  3157             String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation);
  3158             if (hasLocation) {
  3159                 return diags.create(dkind, log.currentSource(), pos,
  3160                         errKey, kindname, idname, //symbol kindname, name
  3161                         typeargtypes, args(argtypes), //type parameters and arguments (if any)
  3162                         getLocationDiag(location, site)); //location kindname, type
  3164             else {
  3165                 return diags.create(dkind, log.currentSource(), pos,
  3166                         errKey, kindname, idname, //symbol kindname, name
  3167                         typeargtypes, args(argtypes)); //type parameters and arguments (if any)
  3170         //where
  3171         private Object args(List<Type> args) {
  3172             return args.isEmpty() ? args : methodArguments(args);
  3175         private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) {
  3176             String key = "cant.resolve";
  3177             String suffix = hasLocation ? ".location" : "";
  3178             switch (kindname) {
  3179                 case METHOD:
  3180                 case CONSTRUCTOR: {
  3181                     suffix += ".args";
  3182                     suffix += hasTypeArgs ? ".params" : "";
  3185             return key + suffix;
  3187         private JCDiagnostic getLocationDiag(Symbol location, Type site) {
  3188             if (location.kind == VAR) {
  3189                 return diags.fragment("location.1",
  3190                     kindName(location),
  3191                     location,
  3192                     location.type);
  3193             } else {
  3194                 return diags.fragment("location",
  3195                     typeKindName(site),
  3196                     site,
  3197                     null);
  3202     /**
  3203      * InvalidSymbolError error class indicating that a given symbol
  3204      * (either a method, a constructor or an operand) is not applicable
  3205      * given an actual arguments/type argument list.
  3206      */
  3207     class InapplicableSymbolError extends ResolveError {
  3209         protected MethodResolutionContext resolveContext;
  3211         InapplicableSymbolError(MethodResolutionContext context) {
  3212             this(WRONG_MTH, "inapplicable symbol error", context);
  3215         protected InapplicableSymbolError(int kind, String debugName, MethodResolutionContext context) {
  3216             super(kind, debugName);
  3217             this.resolveContext = context;
  3220         @Override
  3221         public String toString() {
  3222             return super.toString();
  3225         @Override
  3226         public boolean exists() {
  3227             return true;
  3230         @Override
  3231         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3232                 DiagnosticPosition pos,
  3233                 Symbol location,
  3234                 Type site,
  3235                 Name name,
  3236                 List<Type> argtypes,
  3237                 List<Type> typeargtypes) {
  3238             if (name == names.error)
  3239                 return null;
  3241             if (syms.operatorNames.contains(name)) {
  3242                 boolean isUnaryOp = argtypes.size() == 1;
  3243                 String key = argtypes.size() == 1 ?
  3244                     "operator.cant.be.applied" :
  3245                     "operator.cant.be.applied.1";
  3246                 Type first = argtypes.head;
  3247                 Type second = !isUnaryOp ? argtypes.tail.head : null;
  3248                 return diags.create(dkind, log.currentSource(), pos,
  3249                         key, name, first, second);
  3251             else {
  3252                 Candidate c = errCandidate();
  3253                 Symbol ws = c.sym.asMemberOf(site, types);
  3254                 return diags.create(dkind, log.currentSource(), pos,
  3255                           "cant.apply.symbol",
  3256                           kindName(ws),
  3257                           ws.name == names.init ? ws.owner.name : ws.name,
  3258                           methodArguments(ws.type.getParameterTypes()),
  3259                           methodArguments(argtypes),
  3260                           kindName(ws.owner),
  3261                           ws.owner.type,
  3262                           c.details);
  3266         @Override
  3267         public Symbol access(Name name, TypeSymbol location) {
  3268             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  3271         private Candidate errCandidate() {
  3272             Candidate bestSoFar = null;
  3273             for (Candidate c : resolveContext.candidates) {
  3274                 if (c.isApplicable()) continue;
  3275                 bestSoFar = c;
  3277             Assert.checkNonNull(bestSoFar);
  3278             return bestSoFar;
  3282     /**
  3283      * ResolveError error class indicating that a set of symbols
  3284      * (either methods, constructors or operands) is not applicable
  3285      * given an actual arguments/type argument list.
  3286      */
  3287     class InapplicableSymbolsError extends InapplicableSymbolError {
  3289         InapplicableSymbolsError(MethodResolutionContext context) {
  3290             super(WRONG_MTHS, "inapplicable symbols", context);
  3293         @Override
  3294         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3295                 DiagnosticPosition pos,
  3296                 Symbol location,
  3297                 Type site,
  3298                 Name name,
  3299                 List<Type> argtypes,
  3300                 List<Type> typeargtypes) {
  3301             if (!resolveContext.candidates.isEmpty()) {
  3302                 JCDiagnostic err = diags.create(dkind,
  3303                         log.currentSource(),
  3304                         pos,
  3305                         "cant.apply.symbols",
  3306                         name == names.init ? KindName.CONSTRUCTOR : absentKind(kind),
  3307                         name == names.init ? site.tsym.name : name,
  3308                         methodArguments(argtypes));
  3309                 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(site));
  3310             } else {
  3311                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
  3312                     location, site, name, argtypes, typeargtypes);
  3316         //where
  3317         List<JCDiagnostic> candidateDetails(Type site) {
  3318             Map<Symbol, JCDiagnostic> details = new LinkedHashMap<Symbol, JCDiagnostic>();
  3319             for (Candidate c : resolveContext.candidates) {
  3320                 if (c.isApplicable()) continue;
  3321                 JCDiagnostic detailDiag = diags.fragment("inapplicable.method",
  3322                         Kinds.kindName(c.sym),
  3323                         c.sym.location(site, types),
  3324                         c.sym.asMemberOf(site, types),
  3325                         c.details);
  3326                 details.put(c.sym, detailDiag);
  3328             return List.from(details.values());
  3332     /**
  3333      * An InvalidSymbolError error class indicating that a symbol is not
  3334      * accessible from a given site
  3335      */
  3336     class AccessError extends InvalidSymbolError {
  3338         private Env<AttrContext> env;
  3339         private Type site;
  3341         AccessError(Symbol sym) {
  3342             this(null, null, sym);
  3345         AccessError(Env<AttrContext> env, Type site, Symbol sym) {
  3346             super(HIDDEN, sym, "access error");
  3347             this.env = env;
  3348             this.site = site;
  3349             if (debugResolve)
  3350                 log.error("proc.messager", sym + " @ " + site + " is inaccessible.");
  3353         @Override
  3354         public boolean exists() {
  3355             return false;
  3358         @Override
  3359         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3360                 DiagnosticPosition pos,
  3361                 Symbol location,
  3362                 Type site,
  3363                 Name name,
  3364                 List<Type> argtypes,
  3365                 List<Type> typeargtypes) {
  3366             if (sym.owner.type.hasTag(ERROR))
  3367                 return null;
  3369             if (sym.name == names.init && sym.owner != site.tsym) {
  3370                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
  3371                         pos, location, site, name, argtypes, typeargtypes);
  3373             else if ((sym.flags() & PUBLIC) != 0
  3374                 || (env != null && this.site != null
  3375                     && !isAccessible(env, this.site))) {
  3376                 return diags.create(dkind, log.currentSource(),
  3377                         pos, "not.def.access.class.intf.cant.access",
  3378                     sym, sym.location());
  3380             else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) {
  3381                 return diags.create(dkind, log.currentSource(),
  3382                         pos, "report.access", sym,
  3383                         asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
  3384                         sym.location());
  3386             else {
  3387                 return diags.create(dkind, log.currentSource(),
  3388                         pos, "not.def.public.cant.access", sym, sym.location());
  3393     /**
  3394      * InvalidSymbolError error class indicating that an instance member
  3395      * has erroneously been accessed from a static context.
  3396      */
  3397     class StaticError extends InvalidSymbolError {
  3399         StaticError(Symbol sym) {
  3400             super(STATICERR, sym, "static error");
  3403         @Override
  3404         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3405                 DiagnosticPosition pos,
  3406                 Symbol location,
  3407                 Type site,
  3408                 Name name,
  3409                 List<Type> argtypes,
  3410                 List<Type> typeargtypes) {
  3411             Symbol errSym = ((sym.kind == TYP && sym.type.hasTag(CLASS))
  3412                 ? types.erasure(sym.type).tsym
  3413                 : sym);
  3414             return diags.create(dkind, log.currentSource(), pos,
  3415                     "non-static.cant.be.ref", kindName(sym), errSym);
  3419     /**
  3420      * InvalidSymbolError error class indicating that a pair of symbols
  3421      * (either methods, constructors or operands) are ambiguous
  3422      * given an actual arguments/type argument list.
  3423      */
  3424     class AmbiguityError extends ResolveError {
  3426         /** The other maximally specific symbol */
  3427         List<Symbol> ambiguousSyms = List.nil();
  3429         @Override
  3430         public boolean exists() {
  3431             return true;
  3434         AmbiguityError(Symbol sym1, Symbol sym2) {
  3435             super(AMBIGUOUS, "ambiguity error");
  3436             ambiguousSyms = flatten(sym2).appendList(flatten(sym1));
  3439         private List<Symbol> flatten(Symbol sym) {
  3440             if (sym.kind == AMBIGUOUS) {
  3441                 return ((AmbiguityError)sym).ambiguousSyms;
  3442             } else {
  3443                 return List.of(sym);
  3447         AmbiguityError addAmbiguousSymbol(Symbol s) {
  3448             ambiguousSyms = ambiguousSyms.prepend(s);
  3449             return this;
  3452         @Override
  3453         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3454                 DiagnosticPosition pos,
  3455                 Symbol location,
  3456                 Type site,
  3457                 Name name,
  3458                 List<Type> argtypes,
  3459                 List<Type> typeargtypes) {
  3460             List<Symbol> diagSyms = ambiguousSyms.reverse();
  3461             Symbol s1 = diagSyms.head;
  3462             Symbol s2 = diagSyms.tail.head;
  3463             Name sname = s1.name;
  3464             if (sname == names.init) sname = s1.owner.name;
  3465             return diags.create(dkind, log.currentSource(),
  3466                       pos, "ref.ambiguous", sname,
  3467                       kindName(s1),
  3468                       s1,
  3469                       s1.location(site, types),
  3470                       kindName(s2),
  3471                       s2,
  3472                       s2.location(site, types));
  3475         /**
  3476          * If multiple applicable methods are found during overload and none of them
  3477          * is more specific than the others, attempt to merge their signatures.
  3478          */
  3479         Symbol mergeAbstracts(Type site) {
  3480             Symbol fst = ambiguousSyms.last();
  3481             Symbol res = fst;
  3482             for (Symbol s : ambiguousSyms.reverse()) {
  3483                 Type mt1 = types.memberType(site, res);
  3484                 Type mt2 = types.memberType(site, s);
  3485                 if ((s.flags() & ABSTRACT) == 0 ||
  3486                         !types.overrideEquivalent(mt1, mt2) ||
  3487                         !types.isSameTypes(fst.erasure(types).getParameterTypes(),
  3488                                        s.erasure(types).getParameterTypes())) {
  3489                     //ambiguity cannot be resolved
  3490                     return this;
  3491                 } else {
  3492                     Type mst = mostSpecificReturnType(mt1, mt2);
  3493                     if (mst == null) {
  3494                         // Theoretically, this can't happen, but it is possible
  3495                         // due to error recovery or mixing incompatible class files
  3496                         return this;
  3498                     Symbol mostSpecific = mst == mt1 ? res : s;
  3499                     List<Type> allThrown = chk.intersect(mt1.getThrownTypes(), mt2.getThrownTypes());
  3500                     Type newSig = types.createMethodTypeWithThrown(mostSpecific.type, allThrown);
  3501                     res = new MethodSymbol(
  3502                             mostSpecific.flags(),
  3503                             mostSpecific.name,
  3504                             newSig,
  3505                             mostSpecific.owner);
  3508             return res;
  3511         @Override
  3512         protected Symbol access(Name name, TypeSymbol location) {
  3513             Symbol firstAmbiguity = ambiguousSyms.last();
  3514             return firstAmbiguity.kind == TYP ?
  3515                     types.createErrorType(name, location, firstAmbiguity.type).tsym :
  3516                     firstAmbiguity;
  3520     enum MethodResolutionPhase {
  3521         BASIC(false, false),
  3522         BOX(true, false),
  3523         VARARITY(true, true) {
  3524             @Override
  3525             public Symbol mergeResults(Symbol bestSoFar, Symbol sym) {
  3526                 switch (sym.kind) {
  3527                     case WRONG_MTH:
  3528                         return (bestSoFar.kind == WRONG_MTH || bestSoFar.kind == WRONG_MTHS) ?
  3529                             bestSoFar :
  3530                             sym;
  3531                     case ABSENT_MTH:
  3532                         return bestSoFar;
  3533                     default:
  3534                         return sym;
  3537         };
  3539         final boolean isBoxingRequired;
  3540         final boolean isVarargsRequired;
  3542         MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) {
  3543            this.isBoxingRequired = isBoxingRequired;
  3544            this.isVarargsRequired = isVarargsRequired;
  3547         public boolean isBoxingRequired() {
  3548             return isBoxingRequired;
  3551         public boolean isVarargsRequired() {
  3552             return isVarargsRequired;
  3555         public boolean isApplicable(boolean boxingEnabled, boolean varargsEnabled) {
  3556             return (varargsEnabled || !isVarargsRequired) &&
  3557                    (boxingEnabled || !isBoxingRequired);
  3560         public Symbol mergeResults(Symbol prev, Symbol sym) {
  3561             return sym;
  3565     final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
  3567     /**
  3568      * A resolution context is used to keep track of intermediate results of
  3569      * overload resolution, such as list of method that are not applicable
  3570      * (used to generate more precise diagnostics) and so on. Resolution contexts
  3571      * can be nested - this means that when each overload resolution routine should
  3572      * work within the resolution context it created.
  3573      */
  3574     class MethodResolutionContext {
  3576         private List<Candidate> candidates = List.nil();
  3578         MethodResolutionPhase step = null;
  3580         private boolean internalResolution = false;
  3581         private DeferredAttr.AttrMode attrMode = DeferredAttr.AttrMode.SPECULATIVE;
  3583         void addInapplicableCandidate(Symbol sym, JCDiagnostic details) {
  3584             Candidate c = new Candidate(currentResolutionContext.step, sym, details, null);
  3585             candidates = candidates.append(c);
  3588         void addApplicableCandidate(Symbol sym, Type mtype) {
  3589             Candidate c = new Candidate(currentResolutionContext.step, sym, null, mtype);
  3590             candidates = candidates.append(c);
  3593         DeferredAttrContext deferredAttrContext(Symbol sym, InferenceContext inferenceContext) {
  3594             return deferredAttr.new DeferredAttrContext(attrMode, sym, step, inferenceContext);
  3597         /**
  3598          * This class represents an overload resolution candidate. There are two
  3599          * kinds of candidates: applicable methods and inapplicable methods;
  3600          * applicable methods have a pointer to the instantiated method type,
  3601          * while inapplicable candidates contain further details about the
  3602          * reason why the method has been considered inapplicable.
  3603          */
  3604         class Candidate {
  3606             final MethodResolutionPhase step;
  3607             final Symbol sym;
  3608             final JCDiagnostic details;
  3609             final Type mtype;
  3611             private Candidate(MethodResolutionPhase step, Symbol sym, JCDiagnostic details, Type mtype) {
  3612                 this.step = step;
  3613                 this.sym = sym;
  3614                 this.details = details;
  3615                 this.mtype = mtype;
  3618             @Override
  3619             public boolean equals(Object o) {
  3620                 if (o instanceof Candidate) {
  3621                     Symbol s1 = this.sym;
  3622                     Symbol s2 = ((Candidate)o).sym;
  3623                     if  ((s1 != s2 &&
  3624                             (s1.overrides(s2, s1.owner.type.tsym, types, false) ||
  3625                             (s2.overrides(s1, s2.owner.type.tsym, types, false)))) ||
  3626                             ((s1.isConstructor() || s2.isConstructor()) && s1.owner != s2.owner))
  3627                         return true;
  3629                 return false;
  3632             boolean isApplicable() {
  3633                 return mtype != null;
  3637         DeferredAttr.AttrMode attrMode() {
  3638             return attrMode;
  3641         boolean internal() {
  3642             return internalResolution;
  3646     MethodResolutionContext currentResolutionContext = null;

mercurial