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

Wed, 26 Sep 2012 14:22:41 +0100

author
mcimadamore
date
Wed, 26 Sep 2012 14:22:41 +0100
changeset 1341
db36841709e4
parent 1338
ad2ca2a4ab5e
child 1342
1a65d6565b45
permissions
-rw-r--r--

7188968: New instance creation expression using diamond is checked twice
Summary: Unify method and constructor check logic
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.Type.*;
    31 import com.sun.tools.javac.code.Symbol.*;
    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.Infer.InferenceContext;
    35 import com.sun.tools.javac.comp.Infer.InferenceContext.FreeTypeListener;
    36 import com.sun.tools.javac.comp.Resolve.MethodResolutionContext.Candidate;
    37 import com.sun.tools.javac.jvm.*;
    38 import com.sun.tools.javac.tree.*;
    39 import com.sun.tools.javac.tree.JCTree.*;
    40 import com.sun.tools.javac.util.*;
    41 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
    42 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    43 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType;
    45 import java.util.ArrayList;
    46 import java.util.Arrays;
    47 import java.util.Collection;
    48 import java.util.EnumMap;
    49 import java.util.EnumSet;
    50 import java.util.HashSet;
    51 import java.util.Map;
    52 import java.util.Set;
    54 import javax.lang.model.element.ElementVisitor;
    56 import static com.sun.tools.javac.code.Flags.*;
    57 import static com.sun.tools.javac.code.Flags.BLOCK;
    58 import static com.sun.tools.javac.code.Kinds.*;
    59 import static com.sun.tools.javac.code.Kinds.ERRONEOUS;
    60 import static com.sun.tools.javac.code.TypeTags.*;
    61 import static com.sun.tools.javac.comp.Resolve.MethodResolutionPhase.*;
    62 import static com.sun.tools.javac.tree.JCTree.Tag.*;
    63 import java.util.Iterator;
    65 /** Helper class for name resolution, used mostly by the attribution phase.
    66  *
    67  *  <p><b>This is NOT part of any supported API.
    68  *  If you write code that depends on this, you do so at your own risk.
    69  *  This code and its internal interfaces are subject to change or
    70  *  deletion without notice.</b>
    71  */
    72 public class Resolve {
    73     protected static final Context.Key<Resolve> resolveKey =
    74         new Context.Key<Resolve>();
    76     Names names;
    77     Log log;
    78     Symtab syms;
    79     Attr attr;
    80     Check chk;
    81     Infer infer;
    82     ClassReader reader;
    83     TreeInfo treeinfo;
    84     Types types;
    85     JCDiagnostic.Factory diags;
    86     public final boolean boxingEnabled; // = source.allowBoxing();
    87     public final boolean varargsEnabled; // = source.allowVarargs();
    88     public final boolean allowMethodHandles;
    89     private final boolean debugResolve;
    90     final EnumSet<VerboseResolutionMode> verboseResolutionMode;
    92     Scope polymorphicSignatureScope;
    94     protected Resolve(Context context) {
    95         context.put(resolveKey, this);
    96         syms = Symtab.instance(context);
    98         varNotFound = new
    99             SymbolNotFoundError(ABSENT_VAR);
   100         wrongMethod = new
   101             InapplicableSymbolError();
   102         wrongMethods = new
   103             InapplicableSymbolsError();
   104         methodNotFound = new
   105             SymbolNotFoundError(ABSENT_MTH);
   106         typeNotFound = new
   107             SymbolNotFoundError(ABSENT_TYP);
   109         names = Names.instance(context);
   110         log = Log.instance(context);
   111         attr = Attr.instance(context);
   112         chk = Check.instance(context);
   113         infer = Infer.instance(context);
   114         reader = ClassReader.instance(context);
   115         treeinfo = TreeInfo.instance(context);
   116         types = Types.instance(context);
   117         diags = JCDiagnostic.Factory.instance(context);
   118         Source source = Source.instance(context);
   119         boxingEnabled = source.allowBoxing();
   120         varargsEnabled = source.allowVarargs();
   121         Options options = Options.instance(context);
   122         debugResolve = options.isSet("debugresolve");
   123         verboseResolutionMode = VerboseResolutionMode.getVerboseResolutionMode(options);
   124         Target target = Target.instance(context);
   125         allowMethodHandles = target.hasMethodHandles();
   126         polymorphicSignatureScope = new Scope(syms.noSymbol);
   128         inapplicableMethodException = new InapplicableMethodException(diags);
   129     }
   131     /** error symbols, which are returned when resolution fails
   132      */
   133     private final SymbolNotFoundError varNotFound;
   134     private final InapplicableSymbolError wrongMethod;
   135     private final InapplicableSymbolsError wrongMethods;
   136     private final SymbolNotFoundError methodNotFound;
   137     private final SymbolNotFoundError typeNotFound;
   139     public static Resolve instance(Context context) {
   140         Resolve instance = context.get(resolveKey);
   141         if (instance == null)
   142             instance = new Resolve(context);
   143         return instance;
   144     }
   146     // <editor-fold defaultstate="collapsed" desc="Verbose resolution diagnostics support">
   147     enum VerboseResolutionMode {
   148         SUCCESS("success"),
   149         FAILURE("failure"),
   150         APPLICABLE("applicable"),
   151         INAPPLICABLE("inapplicable"),
   152         DEFERRED_INST("deferred-inference"),
   153         PREDEF("predef"),
   154         OBJECT_INIT("object-init"),
   155         INTERNAL("internal");
   157         String opt;
   159         private VerboseResolutionMode(String opt) {
   160             this.opt = opt;
   161         }
   163         static EnumSet<VerboseResolutionMode> getVerboseResolutionMode(Options opts) {
   164             String s = opts.get("verboseResolution");
   165             EnumSet<VerboseResolutionMode> res = EnumSet.noneOf(VerboseResolutionMode.class);
   166             if (s == null) return res;
   167             if (s.contains("all")) {
   168                 res = EnumSet.allOf(VerboseResolutionMode.class);
   169             }
   170             Collection<String> args = Arrays.asList(s.split(","));
   171             for (VerboseResolutionMode mode : values()) {
   172                 if (args.contains(mode.opt)) {
   173                     res.add(mode);
   174                 } else if (args.contains("-" + mode.opt)) {
   175                     res.remove(mode);
   176                 }
   177             }
   178             return res;
   179         }
   180     }
   182     void reportVerboseResolutionDiagnostic(DiagnosticPosition dpos, Name name, Type site,
   183             List<Type> argtypes, List<Type> typeargtypes, Symbol bestSoFar) {
   184         boolean success = bestSoFar.kind < ERRONEOUS;
   186         if (success && !verboseResolutionMode.contains(VerboseResolutionMode.SUCCESS)) {
   187             return;
   188         } else if (!success && !verboseResolutionMode.contains(VerboseResolutionMode.FAILURE)) {
   189             return;
   190         }
   192         if (bestSoFar.name == names.init &&
   193                 bestSoFar.owner == syms.objectType.tsym &&
   194                 !verboseResolutionMode.contains(VerboseResolutionMode.OBJECT_INIT)) {
   195             return; //skip diags for Object constructor resolution
   196         } else if (site == syms.predefClass.type &&
   197                 !verboseResolutionMode.contains(VerboseResolutionMode.PREDEF)) {
   198             return; //skip spurious diags for predef symbols (i.e. operators)
   199         } else if (currentResolutionContext.internalResolution &&
   200                 !verboseResolutionMode.contains(VerboseResolutionMode.INTERNAL)) {
   201             return;
   202         }
   204         int pos = 0;
   205         int mostSpecificPos = -1;
   206         ListBuffer<JCDiagnostic> subDiags = ListBuffer.lb();
   207         for (Candidate c : currentResolutionContext.candidates) {
   208             if (currentResolutionContext.step != c.step ||
   209                     (c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.APPLICABLE)) ||
   210                     (!c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.INAPPLICABLE))) {
   211                 continue;
   212             } else {
   213                 subDiags.append(c.isApplicable() ?
   214                         getVerboseApplicableCandidateDiag(pos, c.sym, c.mtype) :
   215                         getVerboseInapplicableCandidateDiag(pos, c.sym, c.details));
   216                 if (c.sym == bestSoFar)
   217                     mostSpecificPos = pos;
   218                 pos++;
   219             }
   220         }
   221         String key = success ? "verbose.resolve.multi" : "verbose.resolve.multi.1";
   222         JCDiagnostic main = diags.note(log.currentSource(), dpos, key, name,
   223                 site.tsym, mostSpecificPos, currentResolutionContext.step,
   224                 methodArguments(argtypes), methodArguments(typeargtypes));
   225         JCDiagnostic d = new JCDiagnostic.MultilineDiagnostic(main, subDiags.toList());
   226         log.report(d);
   227     }
   229     JCDiagnostic getVerboseApplicableCandidateDiag(int pos, Symbol sym, Type inst) {
   230         JCDiagnostic subDiag = null;
   231         if (sym.type.tag == FORALL) {
   232             subDiag = diags.fragment("partial.inst.sig", inst);
   233         }
   235         String key = subDiag == null ?
   236                 "applicable.method.found" :
   237                 "applicable.method.found.1";
   239         return diags.fragment(key, pos, sym, subDiag);
   240     }
   242     JCDiagnostic getVerboseInapplicableCandidateDiag(int pos, Symbol sym, JCDiagnostic subDiag) {
   243         return diags.fragment("not.applicable.method.found", pos, sym, subDiag);
   244     }
   245     // </editor-fold>
   247 /* ************************************************************************
   248  * Identifier resolution
   249  *************************************************************************/
   251     /** An environment is "static" if its static level is greater than
   252      *  the one of its outer environment
   253      */
   254     static boolean isStatic(Env<AttrContext> env) {
   255         return env.info.staticLevel > env.outer.info.staticLevel;
   256     }
   258     /** An environment is an "initializer" if it is a constructor or
   259      *  an instance initializer.
   260      */
   261     static boolean isInitializer(Env<AttrContext> env) {
   262         Symbol owner = env.info.scope.owner;
   263         return owner.isConstructor() ||
   264             owner.owner.kind == TYP &&
   265             (owner.kind == VAR ||
   266              owner.kind == MTH && (owner.flags() & BLOCK) != 0) &&
   267             (owner.flags() & STATIC) == 0;
   268     }
   270     /** Is class accessible in given evironment?
   271      *  @param env    The current environment.
   272      *  @param c      The class whose accessibility is checked.
   273      */
   274     public boolean isAccessible(Env<AttrContext> env, TypeSymbol c) {
   275         return isAccessible(env, c, false);
   276     }
   278     public boolean isAccessible(Env<AttrContext> env, TypeSymbol c, boolean checkInner) {
   279         boolean isAccessible = false;
   280         switch ((short)(c.flags() & AccessFlags)) {
   281             case PRIVATE:
   282                 isAccessible =
   283                     env.enclClass.sym.outermostClass() ==
   284                     c.owner.outermostClass();
   285                 break;
   286             case 0:
   287                 isAccessible =
   288                     env.toplevel.packge == c.owner // fast special case
   289                     ||
   290                     env.toplevel.packge == c.packge()
   291                     ||
   292                     // Hack: this case is added since synthesized default constructors
   293                     // of anonymous classes should be allowed to access
   294                     // classes which would be inaccessible otherwise.
   295                     env.enclMethod != null &&
   296                     (env.enclMethod.mods.flags & ANONCONSTR) != 0;
   297                 break;
   298             default: // error recovery
   299             case PUBLIC:
   300                 isAccessible = true;
   301                 break;
   302             case PROTECTED:
   303                 isAccessible =
   304                     env.toplevel.packge == c.owner // fast special case
   305                     ||
   306                     env.toplevel.packge == c.packge()
   307                     ||
   308                     isInnerSubClass(env.enclClass.sym, c.owner);
   309                 break;
   310         }
   311         return (checkInner == false || c.type.getEnclosingType() == Type.noType) ?
   312             isAccessible :
   313             isAccessible && isAccessible(env, c.type.getEnclosingType(), checkInner);
   314     }
   315     //where
   316         /** Is given class a subclass of given base class, or an inner class
   317          *  of a subclass?
   318          *  Return null if no such class exists.
   319          *  @param c     The class which is the subclass or is contained in it.
   320          *  @param base  The base class
   321          */
   322         private boolean isInnerSubClass(ClassSymbol c, Symbol base) {
   323             while (c != null && !c.isSubClass(base, types)) {
   324                 c = c.owner.enclClass();
   325             }
   326             return c != null;
   327         }
   329     boolean isAccessible(Env<AttrContext> env, Type t) {
   330         return isAccessible(env, t, false);
   331     }
   333     boolean isAccessible(Env<AttrContext> env, Type t, boolean checkInner) {
   334         return (t.tag == ARRAY)
   335             ? isAccessible(env, types.elemtype(t))
   336             : isAccessible(env, t.tsym, checkInner);
   337     }
   339     /** Is symbol accessible as a member of given type in given evironment?
   340      *  @param env    The current environment.
   341      *  @param site   The type of which the tested symbol is regarded
   342      *                as a member.
   343      *  @param sym    The symbol.
   344      */
   345     public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym) {
   346         return isAccessible(env, site, sym, false);
   347     }
   348     public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym, boolean checkInner) {
   349         if (sym.name == names.init && sym.owner != site.tsym) return false;
   350         switch ((short)(sym.flags() & AccessFlags)) {
   351         case PRIVATE:
   352             return
   353                 (env.enclClass.sym == sym.owner // fast special case
   354                  ||
   355                  env.enclClass.sym.outermostClass() ==
   356                  sym.owner.outermostClass())
   357                 &&
   358                 sym.isInheritedIn(site.tsym, types);
   359         case 0:
   360             return
   361                 (env.toplevel.packge == sym.owner.owner // fast special case
   362                  ||
   363                  env.toplevel.packge == sym.packge())
   364                 &&
   365                 isAccessible(env, site, checkInner)
   366                 &&
   367                 sym.isInheritedIn(site.tsym, types)
   368                 &&
   369                 notOverriddenIn(site, sym);
   370         case PROTECTED:
   371             return
   372                 (env.toplevel.packge == sym.owner.owner // fast special case
   373                  ||
   374                  env.toplevel.packge == sym.packge()
   375                  ||
   376                  isProtectedAccessible(sym, env.enclClass.sym, site)
   377                  ||
   378                  // OK to select instance method or field from 'super' or type name
   379                  // (but type names should be disallowed elsewhere!)
   380                  env.info.selectSuper && (sym.flags() & STATIC) == 0 && sym.kind != TYP)
   381                 &&
   382                 isAccessible(env, site, checkInner)
   383                 &&
   384                 notOverriddenIn(site, sym);
   385         default: // this case includes erroneous combinations as well
   386             return isAccessible(env, site, checkInner) && notOverriddenIn(site, sym);
   387         }
   388     }
   389     //where
   390     /* `sym' is accessible only if not overridden by
   391      * another symbol which is a member of `site'
   392      * (because, if it is overridden, `sym' is not strictly
   393      * speaking a member of `site'). A polymorphic signature method
   394      * cannot be overridden (e.g. MH.invokeExact(Object[])).
   395      */
   396     private boolean notOverriddenIn(Type site, Symbol sym) {
   397         if (sym.kind != MTH || sym.isConstructor() || sym.isStatic())
   398             return true;
   399         else {
   400             Symbol s2 = ((MethodSymbol)sym).implementation(site.tsym, types, true);
   401             return (s2 == null || s2 == sym || sym.owner == s2.owner ||
   402                     !types.isSubSignature(types.memberType(site, s2), types.memberType(site, sym)));
   403         }
   404     }
   405     //where
   406         /** Is given protected symbol accessible if it is selected from given site
   407          *  and the selection takes place in given class?
   408          *  @param sym     The symbol with protected access
   409          *  @param c       The class where the access takes place
   410          *  @site          The type of the qualifier
   411          */
   412         private
   413         boolean isProtectedAccessible(Symbol sym, ClassSymbol c, Type site) {
   414             while (c != null &&
   415                    !(c.isSubClass(sym.owner, types) &&
   416                      (c.flags() & INTERFACE) == 0 &&
   417                      // In JLS 2e 6.6.2.1, the subclass restriction applies
   418                      // only to instance fields and methods -- types are excluded
   419                      // regardless of whether they are declared 'static' or not.
   420                      ((sym.flags() & STATIC) != 0 || sym.kind == TYP || site.tsym.isSubClass(c, types))))
   421                 c = c.owner.enclClass();
   422             return c != null;
   423         }
   425     /** Try to instantiate the type of a method so that it fits
   426      *  given type arguments and argument types. If succesful, return
   427      *  the method's instantiated type, else return null.
   428      *  The instantiation will take into account an additional leading
   429      *  formal parameter if the method is an instance method seen as a member
   430      *  of un underdetermined site In this case, we treat site as an additional
   431      *  parameter and the parameters of the class containing the method as
   432      *  additional type variables that get instantiated.
   433      *
   434      *  @param env         The current environment
   435      *  @param site        The type of which the method is a member.
   436      *  @param m           The method symbol.
   437      *  @param argtypes    The invocation's given value arguments.
   438      *  @param typeargtypes    The invocation's given type arguments.
   439      *  @param allowBoxing Allow boxing conversions of arguments.
   440      *  @param useVarargs Box trailing arguments into an array for varargs.
   441      */
   442     Type rawInstantiate(Env<AttrContext> env,
   443                         Type site,
   444                         Symbol m,
   445                         ResultInfo resultInfo,
   446                         List<Type> argtypes,
   447                         List<Type> typeargtypes,
   448                         boolean allowBoxing,
   449                         boolean useVarargs,
   450                         Warner warn)
   451         throws Infer.InferenceException {
   452         if (useVarargs && (m.flags() & VARARGS) == 0)
   453             throw inapplicableMethodException.setMessage();
   454         Type mt = types.memberType(site, m);
   456         // tvars is the list of formal type variables for which type arguments
   457         // need to inferred.
   458         List<Type> tvars = List.nil();
   459         if (typeargtypes == null) typeargtypes = List.nil();
   460         if (mt.tag != FORALL && typeargtypes.nonEmpty()) {
   461             // This is not a polymorphic method, but typeargs are supplied
   462             // which is fine, see JLS 15.12.2.1
   463         } else if (mt.tag == FORALL && typeargtypes.nonEmpty()) {
   464             ForAll pmt = (ForAll) mt;
   465             if (typeargtypes.length() != pmt.tvars.length())
   466                 throw inapplicableMethodException.setMessage("arg.length.mismatch"); // not enough args
   467             // Check type arguments are within bounds
   468             List<Type> formals = pmt.tvars;
   469             List<Type> actuals = typeargtypes;
   470             while (formals.nonEmpty() && actuals.nonEmpty()) {
   471                 List<Type> bounds = types.subst(types.getBounds((TypeVar)formals.head),
   472                                                 pmt.tvars, typeargtypes);
   473                 for (; bounds.nonEmpty(); bounds = bounds.tail)
   474                     if (!types.isSubtypeUnchecked(actuals.head, bounds.head, warn))
   475                         throw inapplicableMethodException.setMessage("explicit.param.do.not.conform.to.bounds",actuals.head, bounds);
   476                 formals = formals.tail;
   477                 actuals = actuals.tail;
   478             }
   479             mt = types.subst(pmt.qtype, pmt.tvars, typeargtypes);
   480         } else if (mt.tag == FORALL) {
   481             ForAll pmt = (ForAll) mt;
   482             List<Type> tvars1 = types.newInstances(pmt.tvars);
   483             tvars = tvars.appendList(tvars1);
   484             mt = types.subst(pmt.qtype, pmt.tvars, tvars1);
   485         }
   487         // find out whether we need to go the slow route via infer
   488         boolean instNeeded = tvars.tail != null; /*inlined: tvars.nonEmpty()*/
   489         for (List<Type> l = argtypes;
   490              l.tail != null/*inlined: l.nonEmpty()*/ && !instNeeded;
   491              l = l.tail) {
   492             if (l.head.tag == FORALL) instNeeded = true;
   493         }
   495         if (instNeeded)
   496             return infer.instantiateMethod(env,
   497                                     tvars,
   498                                     (MethodType)mt,
   499                                     resultInfo,
   500                                     m,
   501                                     argtypes,
   502                                     allowBoxing,
   503                                     useVarargs,
   504                                     warn);
   506         checkRawArgumentsAcceptable(env, argtypes, mt.getParameterTypes(),
   507                                 allowBoxing, useVarargs, warn);
   508         return mt;
   509     }
   511     /** Same but returns null instead throwing a NoInstanceException
   512      */
   513     Type instantiate(Env<AttrContext> env,
   514                      Type site,
   515                      Symbol m,
   516                      ResultInfo resultInfo,
   517                      List<Type> argtypes,
   518                      List<Type> typeargtypes,
   519                      boolean allowBoxing,
   520                      boolean useVarargs,
   521                      Warner warn) {
   522         try {
   523             return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
   524                                   allowBoxing, useVarargs, warn);
   525         } catch (InapplicableMethodException ex) {
   526             return null;
   527         }
   528     }
   530     /** Check if a parameter list accepts a list of args.
   531      */
   532     boolean argumentsAcceptable(Env<AttrContext> env,
   533                                 List<Type> argtypes,
   534                                 List<Type> formals,
   535                                 boolean allowBoxing,
   536                                 boolean useVarargs,
   537                                 Warner warn) {
   538         try {
   539             checkRawArgumentsAcceptable(env, argtypes, formals, allowBoxing, useVarargs, warn);
   540             return true;
   541         } catch (InapplicableMethodException ex) {
   542             return false;
   543         }
   544     }
   545     /**
   546      * A check handler is used by the main method applicability routine in order
   547      * to handle specific method applicability failures. It is assumed that a class
   548      * implementing this interface should throw exceptions that are a subtype of
   549      * InapplicableMethodException (see below). Such exception will terminate the
   550      * method applicability check and propagate important info outwards (for the
   551      * purpose of generating better diagnostics).
   552      */
   553     interface MethodCheckHandler {
   554         /* The number of actuals and formals differ */
   555         InapplicableMethodException arityMismatch();
   556         /* An actual argument type does not conform to the corresponding formal type */
   557         InapplicableMethodException argumentMismatch(boolean varargs, JCDiagnostic details);
   558         /* The element type of a varargs is not accessible in the current context */
   559         InapplicableMethodException inaccessibleVarargs(Symbol location, Type expected);
   560     }
   562     /**
   563      * Basic method check handler used within Resolve - all methods end up
   564      * throwing InapplicableMethodException; a diagnostic fragment that describes
   565      * the cause as to why the method is not applicable is set on the exception
   566      * before it is thrown.
   567      */
   568     MethodCheckHandler resolveHandler = new MethodCheckHandler() {
   569             public InapplicableMethodException arityMismatch() {
   570                 return inapplicableMethodException.setMessage("arg.length.mismatch");
   571             }
   572             public InapplicableMethodException argumentMismatch(boolean varargs, JCDiagnostic details) {
   573                 String key = varargs ?
   574                         "varargs.argument.mismatch" :
   575                         "no.conforming.assignment.exists";
   576                 return inapplicableMethodException.setMessage(key,
   577                         details);
   578             }
   579             public InapplicableMethodException inaccessibleVarargs(Symbol location, Type expected) {
   580                 return inapplicableMethodException.setMessage("inaccessible.varargs.type",
   581                         expected, Kinds.kindName(location), location);
   582             }
   583     };
   585     void checkRawArgumentsAcceptable(Env<AttrContext> env,
   586                                 List<Type> argtypes,
   587                                 List<Type> formals,
   588                                 boolean allowBoxing,
   589                                 boolean useVarargs,
   590                                 Warner warn) {
   591         checkRawArgumentsAcceptable(env, infer.emptyContext, argtypes, formals,
   592                 allowBoxing, useVarargs, warn, resolveHandler);
   593     }
   595     /**
   596      * Main method applicability routine. Given a list of actual types A,
   597      * a list of formal types F, determines whether the types in A are
   598      * compatible (by method invocation conversion) with the types in F.
   599      *
   600      * Since this routine is shared between overload resolution and method
   601      * type-inference, it is crucial that actual types are converted to the
   602      * corresponding 'undet' form (i.e. where inference variables are replaced
   603      * with undetvars) so that constraints can be propagated and collected.
   604      *
   605      * Moreover, if one or more types in A is a poly type, this routine calls
   606      * Infer.instantiateArg in order to complete the poly type (this might involve
   607      * deferred attribution).
   608      *
   609      * A method check handler (see above) is used in order to report errors.
   610      */
   611     void checkRawArgumentsAcceptable(final Env<AttrContext> env,
   612                                 final Infer.InferenceContext inferenceContext,
   613                                 List<Type> argtypes,
   614                                 List<Type> formals,
   615                                 boolean allowBoxing,
   616                                 boolean useVarargs,
   617                                 Warner warn,
   618                                 MethodCheckHandler handler) {
   619         Type varargsFormal = useVarargs ? formals.last() : null;
   620         ListBuffer<Type> checkedArgs = ListBuffer.lb();
   622         if (varargsFormal == null &&
   623                 argtypes.size() != formals.size()) {
   624             throw handler.arityMismatch(); // not enough args
   625         }
   627         while (argtypes.nonEmpty() && formals.head != varargsFormal) {
   628             ResultInfo resultInfo = methodCheckResult(formals.head, allowBoxing, false, inferenceContext, handler, warn);
   629             checkedArgs.append(resultInfo.check(env.tree.pos(), argtypes.head));
   630             argtypes = argtypes.tail;
   631             formals = formals.tail;
   632         }
   634         if (formals.head != varargsFormal) {
   635             throw handler.arityMismatch(); // not enough args
   636         }
   638         if (useVarargs) {
   639             //note: if applicability check is triggered by most specific test,
   640             //the last argument of a varargs is _not_ an array type (see JLS 15.12.2.5)
   641             Type elt = types.elemtype(varargsFormal);
   642             while (argtypes.nonEmpty()) {
   643                 ResultInfo resultInfo = methodCheckResult(elt, allowBoxing, true, inferenceContext, handler, warn);
   644                 checkedArgs.append(resultInfo.check(env.tree.pos(), argtypes.head));
   645                 argtypes = argtypes.tail;
   646             }
   647             //check varargs element type accessibility
   648             varargsAccessible(env, elt, handler, inferenceContext);
   649         }
   650     }
   652     void varargsAccessible(final Env<AttrContext> env, final Type t, final Resolve.MethodCheckHandler handler, final InferenceContext inferenceContext) {
   653         if (inferenceContext.free(t)) {
   654             inferenceContext.addFreeTypeListener(List.of(t), new FreeTypeListener() {
   655                 @Override
   656                 public void typesInferred(InferenceContext inferenceContext) {
   657                     varargsAccessible(env, inferenceContext.asInstType(t, types), handler, inferenceContext);
   658                 }
   659             });
   660         } else {
   661             if (!isAccessible(env, t)) {
   662                 Symbol location = env.enclClass.sym;
   663                 throw handler.inaccessibleVarargs(location, t);
   664             }
   665         }
   666     }
   668     /**
   669      * Check context to be used during method applicability checks. A method check
   670      * context might contain inference variables.
   671      */
   672     abstract class MethodCheckContext implements CheckContext {
   674         MethodCheckHandler handler;
   675         boolean useVarargs;
   676         Infer.InferenceContext inferenceContext;
   677         Warner rsWarner;
   679         public MethodCheckContext(MethodCheckHandler handler, boolean useVarargs, Infer.InferenceContext inferenceContext, Warner rsWarner) {
   680             this.handler = handler;
   681             this.useVarargs = useVarargs;
   682             this.inferenceContext = inferenceContext;
   683             this.rsWarner = rsWarner;
   684         }
   686         public void report(DiagnosticPosition pos, JCDiagnostic details) {
   687             throw handler.argumentMismatch(useVarargs, details);
   688         }
   690         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
   691             return rsWarner;
   692         }
   694         public InferenceContext inferenceContext() {
   695             return inferenceContext;
   696         }
   697     }
   699     /**
   700      * Subclass of method check context class that implements strict method conversion.
   701      * Strict method conversion checks compatibility between types using subtyping tests.
   702      */
   703     class StrictMethodContext extends MethodCheckContext {
   705         public StrictMethodContext(MethodCheckHandler handler, boolean useVarargs, Infer.InferenceContext inferenceContext, Warner rsWarner) {
   706             super(handler, useVarargs, inferenceContext, rsWarner);
   707         }
   709         public boolean compatible(Type found, Type req, Warner warn) {
   710             return types.isSubtypeUnchecked(found, inferenceContext.asFree(req, types), warn);
   711         }
   712     }
   714     /**
   715      * Subclass of method check context class that implements loose method conversion.
   716      * Loose method conversion checks compatibility between types using method conversion tests.
   717      */
   718     class LooseMethodContext extends MethodCheckContext {
   720         public LooseMethodContext(MethodCheckHandler handler, boolean useVarargs, Infer.InferenceContext inferenceContext, Warner rsWarner) {
   721             super(handler, useVarargs, inferenceContext, rsWarner);
   722         }
   724         public boolean compatible(Type found, Type req, Warner warn) {
   725             return types.isConvertible(found, inferenceContext.asFree(req, types), warn);
   726         }
   727     }
   729     /**
   730      * Create a method check context to be used during method applicability check
   731      */
   732     ResultInfo methodCheckResult(Type to, boolean allowBoxing, boolean useVarargs,
   733             Infer.InferenceContext inferenceContext, MethodCheckHandler methodHandler, Warner rsWarner) {
   734         MethodCheckContext checkContext = allowBoxing ?
   735                 new LooseMethodContext(methodHandler, useVarargs, inferenceContext, rsWarner) :
   736                 new StrictMethodContext(methodHandler, useVarargs, inferenceContext, rsWarner);
   737         return attr.new ResultInfo(VAL, to, checkContext) {
   738             @Override
   739             protected Type check(DiagnosticPosition pos, Type found) {
   740                 return super.check(pos, chk.checkNonVoid(pos, types.capture(types.upperBound(found.baseType()))));
   741             }
   742         };
   743     }
   745     public static class InapplicableMethodException extends RuntimeException {
   746         private static final long serialVersionUID = 0;
   748         JCDiagnostic diagnostic;
   749         JCDiagnostic.Factory diags;
   751         InapplicableMethodException(JCDiagnostic.Factory diags) {
   752             this.diagnostic = null;
   753             this.diags = diags;
   754         }
   755         InapplicableMethodException setMessage() {
   756             return setMessage((JCDiagnostic)null);
   757         }
   758         InapplicableMethodException setMessage(String key) {
   759             return setMessage(key != null ? diags.fragment(key) : null);
   760         }
   761         InapplicableMethodException setMessage(String key, Object... args) {
   762             return setMessage(key != null ? diags.fragment(key, args) : null);
   763         }
   764         InapplicableMethodException setMessage(JCDiagnostic diag) {
   765             this.diagnostic = diag;
   766             return this;
   767         }
   769         public JCDiagnostic getDiagnostic() {
   770             return diagnostic;
   771         }
   772     }
   773     private final InapplicableMethodException inapplicableMethodException;
   775 /* ***************************************************************************
   776  *  Symbol lookup
   777  *  the following naming conventions for arguments are used
   778  *
   779  *       env      is the environment where the symbol was mentioned
   780  *       site     is the type of which the symbol is a member
   781  *       name     is the symbol's name
   782  *                if no arguments are given
   783  *       argtypes are the value arguments, if we search for a method
   784  *
   785  *  If no symbol was found, a ResolveError detailing the problem is returned.
   786  ****************************************************************************/
   788     /** Find field. Synthetic fields are always skipped.
   789      *  @param env     The current environment.
   790      *  @param site    The original type from where the selection takes place.
   791      *  @param name    The name of the field.
   792      *  @param c       The class to search for the field. This is always
   793      *                 a superclass or implemented interface of site's class.
   794      */
   795     Symbol findField(Env<AttrContext> env,
   796                      Type site,
   797                      Name name,
   798                      TypeSymbol c) {
   799         while (c.type.tag == TYPEVAR)
   800             c = c.type.getUpperBound().tsym;
   801         Symbol bestSoFar = varNotFound;
   802         Symbol sym;
   803         Scope.Entry e = c.members().lookup(name);
   804         while (e.scope != null) {
   805             if (e.sym.kind == VAR && (e.sym.flags_field & SYNTHETIC) == 0) {
   806                 return isAccessible(env, site, e.sym)
   807                     ? e.sym : new AccessError(env, site, e.sym);
   808             }
   809             e = e.next();
   810         }
   811         Type st = types.supertype(c.type);
   812         if (st != null && (st.tag == CLASS || st.tag == TYPEVAR)) {
   813             sym = findField(env, site, name, st.tsym);
   814             if (sym.kind < bestSoFar.kind) bestSoFar = sym;
   815         }
   816         for (List<Type> l = types.interfaces(c.type);
   817              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
   818              l = l.tail) {
   819             sym = findField(env, site, name, l.head.tsym);
   820             if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
   821                 sym.owner != bestSoFar.owner)
   822                 bestSoFar = new AmbiguityError(bestSoFar, sym);
   823             else if (sym.kind < bestSoFar.kind)
   824                 bestSoFar = sym;
   825         }
   826         return bestSoFar;
   827     }
   829     /** Resolve a field identifier, throw a fatal error if not found.
   830      *  @param pos       The position to use for error reporting.
   831      *  @param env       The environment current at the method invocation.
   832      *  @param site      The type of the qualifying expression, in which
   833      *                   identifier is searched.
   834      *  @param name      The identifier's name.
   835      */
   836     public VarSymbol resolveInternalField(DiagnosticPosition pos, Env<AttrContext> env,
   837                                           Type site, Name name) {
   838         Symbol sym = findField(env, site, name, site.tsym);
   839         if (sym.kind == VAR) return (VarSymbol)sym;
   840         else throw new FatalError(
   841                  diags.fragment("fatal.err.cant.locate.field",
   842                                 name));
   843     }
   845     /** Find unqualified variable or field with given name.
   846      *  Synthetic fields always skipped.
   847      *  @param env     The current environment.
   848      *  @param name    The name of the variable or field.
   849      */
   850     Symbol findVar(Env<AttrContext> env, Name name) {
   851         Symbol bestSoFar = varNotFound;
   852         Symbol sym;
   853         Env<AttrContext> env1 = env;
   854         boolean staticOnly = false;
   855         while (env1.outer != null) {
   856             if (isStatic(env1)) staticOnly = true;
   857             Scope.Entry e = env1.info.scope.lookup(name);
   858             while (e.scope != null &&
   859                    (e.sym.kind != VAR ||
   860                     (e.sym.flags_field & SYNTHETIC) != 0))
   861                 e = e.next();
   862             sym = (e.scope != null)
   863                 ? e.sym
   864                 : findField(
   865                     env1, env1.enclClass.sym.type, name, env1.enclClass.sym);
   866             if (sym.exists()) {
   867                 if (staticOnly &&
   868                     sym.kind == VAR &&
   869                     sym.owner.kind == TYP &&
   870                     (sym.flags() & STATIC) == 0)
   871                     return new StaticError(sym);
   872                 else
   873                     return sym;
   874             } else if (sym.kind < bestSoFar.kind) {
   875                 bestSoFar = sym;
   876             }
   878             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
   879             env1 = env1.outer;
   880         }
   882         sym = findField(env, syms.predefClass.type, name, syms.predefClass);
   883         if (sym.exists())
   884             return sym;
   885         if (bestSoFar.exists())
   886             return bestSoFar;
   888         Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
   889         for (; e.scope != null; e = e.next()) {
   890             sym = e.sym;
   891             Type origin = e.getOrigin().owner.type;
   892             if (sym.kind == VAR) {
   893                 if (e.sym.owner.type != origin)
   894                     sym = sym.clone(e.getOrigin().owner);
   895                 return isAccessible(env, origin, sym)
   896                     ? sym : new AccessError(env, origin, sym);
   897             }
   898         }
   900         Symbol origin = null;
   901         e = env.toplevel.starImportScope.lookup(name);
   902         for (; e.scope != null; e = e.next()) {
   903             sym = e.sym;
   904             if (sym.kind != VAR)
   905                 continue;
   906             // invariant: sym.kind == VAR
   907             if (bestSoFar.kind < AMBIGUOUS && sym.owner != bestSoFar.owner)
   908                 return new AmbiguityError(bestSoFar, sym);
   909             else if (bestSoFar.kind >= VAR) {
   910                 origin = e.getOrigin().owner;
   911                 bestSoFar = isAccessible(env, origin.type, sym)
   912                     ? sym : new AccessError(env, origin.type, sym);
   913             }
   914         }
   915         if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type)
   916             return bestSoFar.clone(origin);
   917         else
   918             return bestSoFar;
   919     }
   921     Warner noteWarner = new Warner();
   923     /** Select the best method for a call site among two choices.
   924      *  @param env              The current environment.
   925      *  @param site             The original type from where the
   926      *                          selection takes place.
   927      *  @param argtypes         The invocation's value arguments,
   928      *  @param typeargtypes     The invocation's type arguments,
   929      *  @param sym              Proposed new best match.
   930      *  @param bestSoFar        Previously found best match.
   931      *  @param allowBoxing Allow boxing conversions of arguments.
   932      *  @param useVarargs Box trailing arguments into an array for varargs.
   933      */
   934     @SuppressWarnings("fallthrough")
   935     Symbol selectBest(Env<AttrContext> env,
   936                       Type site,
   937                       List<Type> argtypes,
   938                       List<Type> typeargtypes,
   939                       Symbol sym,
   940                       Symbol bestSoFar,
   941                       boolean allowBoxing,
   942                       boolean useVarargs,
   943                       boolean operator) {
   944         if (sym.kind == ERR) return bestSoFar;
   945         if (!sym.isInheritedIn(site.tsym, types)) return bestSoFar;
   946         Assert.check(sym.kind < AMBIGUOUS);
   947         try {
   948             Type mt = rawInstantiate(env, site, sym, null, argtypes, typeargtypes,
   949                                allowBoxing, useVarargs, Warner.noWarnings);
   950             if (!operator)
   951                 currentResolutionContext.addApplicableCandidate(sym, mt);
   952         } catch (InapplicableMethodException ex) {
   953             if (!operator)
   954                 currentResolutionContext.addInapplicableCandidate(sym, ex.getDiagnostic());
   955             switch (bestSoFar.kind) {
   956             case ABSENT_MTH:
   957                 return wrongMethod;
   958             case WRONG_MTH:
   959                 if (operator) return bestSoFar;
   960             case WRONG_MTHS:
   961                 return wrongMethods;
   962             default:
   963                 return bestSoFar;
   964             }
   965         }
   966         if (!isAccessible(env, site, sym)) {
   967             return (bestSoFar.kind == ABSENT_MTH)
   968                 ? new AccessError(env, site, sym)
   969                 : bestSoFar;
   970         }
   971         return (bestSoFar.kind > AMBIGUOUS)
   972             ? sym
   973             : mostSpecific(sym, bestSoFar, env, site,
   974                            allowBoxing && operator, useVarargs);
   975     }
   977     /* Return the most specific of the two methods for a call,
   978      *  given that both are accessible and applicable.
   979      *  @param m1               A new candidate for most specific.
   980      *  @param m2               The previous most specific candidate.
   981      *  @param env              The current environment.
   982      *  @param site             The original type from where the selection
   983      *                          takes place.
   984      *  @param allowBoxing Allow boxing conversions of arguments.
   985      *  @param useVarargs Box trailing arguments into an array for varargs.
   986      */
   987     Symbol mostSpecific(Symbol m1,
   988                         Symbol m2,
   989                         Env<AttrContext> env,
   990                         final Type site,
   991                         boolean allowBoxing,
   992                         boolean useVarargs) {
   993         switch (m2.kind) {
   994         case MTH:
   995             if (m1 == m2) return m1;
   996             boolean m1SignatureMoreSpecific = signatureMoreSpecific(env, site, m1, m2, allowBoxing, useVarargs);
   997             boolean m2SignatureMoreSpecific = signatureMoreSpecific(env, site, m2, m1, allowBoxing, useVarargs);
   998             if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) {
   999                 Type mt1 = types.memberType(site, m1);
  1000                 Type mt2 = types.memberType(site, m2);
  1001                 if (!types.overrideEquivalent(mt1, mt2))
  1002                     return ambiguityError(m1, m2);
  1004                 // same signature; select (a) the non-bridge method, or
  1005                 // (b) the one that overrides the other, or (c) the concrete
  1006                 // one, or (d) merge both abstract signatures
  1007                 if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE))
  1008                     return ((m1.flags() & BRIDGE) != 0) ? m2 : m1;
  1010                 // if one overrides or hides the other, use it
  1011                 TypeSymbol m1Owner = (TypeSymbol)m1.owner;
  1012                 TypeSymbol m2Owner = (TypeSymbol)m2.owner;
  1013                 if (types.asSuper(m1Owner.type, m2Owner) != null &&
  1014                     ((m1.owner.flags_field & INTERFACE) == 0 ||
  1015                      (m2.owner.flags_field & INTERFACE) != 0) &&
  1016                     m1.overrides(m2, m1Owner, types, false))
  1017                     return m1;
  1018                 if (types.asSuper(m2Owner.type, m1Owner) != null &&
  1019                     ((m2.owner.flags_field & INTERFACE) == 0 ||
  1020                      (m1.owner.flags_field & INTERFACE) != 0) &&
  1021                     m2.overrides(m1, m2Owner, types, false))
  1022                     return m2;
  1023                 boolean m1Abstract = (m1.flags() & ABSTRACT) != 0;
  1024                 boolean m2Abstract = (m2.flags() & ABSTRACT) != 0;
  1025                 if (m1Abstract && !m2Abstract) return m2;
  1026                 if (m2Abstract && !m1Abstract) return m1;
  1027                 // both abstract or both concrete
  1028                 if (!m1Abstract && !m2Abstract)
  1029                     return ambiguityError(m1, m2);
  1030                 // check that both signatures have the same erasure
  1031                 if (!types.isSameTypes(m1.erasure(types).getParameterTypes(),
  1032                                        m2.erasure(types).getParameterTypes()))
  1033                     return ambiguityError(m1, m2);
  1034                 // both abstract, neither overridden; merge throws clause and result type
  1035                 Type mst = mostSpecificReturnType(mt1, mt2);
  1036                 if (mst == null) {
  1037                     // Theoretically, this can't happen, but it is possible
  1038                     // due to error recovery or mixing incompatible class files
  1039                     return ambiguityError(m1, m2);
  1041                 Symbol mostSpecific = mst == mt1 ? m1 : m2;
  1042                 List<Type> allThrown = chk.intersect(mt1.getThrownTypes(), mt2.getThrownTypes());
  1043                 Type newSig = types.createMethodTypeWithThrown(mostSpecific.type, allThrown);
  1044                 MethodSymbol result = new MethodSymbol(
  1045                         mostSpecific.flags(),
  1046                         mostSpecific.name,
  1047                         newSig,
  1048                         mostSpecific.owner) {
  1049                     @Override
  1050                     public MethodSymbol implementation(TypeSymbol origin, Types types, boolean checkResult) {
  1051                         if (origin == site.tsym)
  1052                             return this;
  1053                         else
  1054                             return super.implementation(origin, types, checkResult);
  1056                     };
  1057                 return result;
  1059             if (m1SignatureMoreSpecific) return m1;
  1060             if (m2SignatureMoreSpecific) return m2;
  1061             return ambiguityError(m1, m2);
  1062         case AMBIGUOUS:
  1063             AmbiguityError e = (AmbiguityError)m2;
  1064             Symbol err1 = mostSpecific(m1, e.sym, env, site, allowBoxing, useVarargs);
  1065             Symbol err2 = mostSpecific(m1, e.sym2, env, site, allowBoxing, useVarargs);
  1066             if (err1 == err2) return err1;
  1067             if (err1 == e.sym && err2 == e.sym2) return m2;
  1068             if (err1 instanceof AmbiguityError &&
  1069                 err2 instanceof AmbiguityError &&
  1070                 ((AmbiguityError)err1).sym == ((AmbiguityError)err2).sym)
  1071                 return ambiguityError(m1, m2);
  1072             else
  1073                 return ambiguityError(err1, err2);
  1074         default:
  1075             throw new AssertionError();
  1078     //where
  1079     private boolean signatureMoreSpecific(Env<AttrContext> env, Type site, Symbol m1, Symbol m2, boolean allowBoxing, boolean useVarargs) {
  1080         noteWarner.clear();
  1081         Type mtype1 = types.memberType(site, adjustVarargs(m1, m2, useVarargs));
  1082         Type mtype2 = instantiate(env, site, adjustVarargs(m2, m1, useVarargs), null,
  1083                 types.lowerBoundArgtypes(mtype1), null,
  1084                 allowBoxing, false, noteWarner);
  1085         return mtype2 != null &&
  1086                 !noteWarner.hasLint(Lint.LintCategory.UNCHECKED);
  1088     //where
  1089     private Symbol adjustVarargs(Symbol to, Symbol from, boolean useVarargs) {
  1090         List<Type> fromArgs = from.type.getParameterTypes();
  1091         List<Type> toArgs = to.type.getParameterTypes();
  1092         if (useVarargs &&
  1093                 (from.flags() & VARARGS) != 0 &&
  1094                 (to.flags() & VARARGS) != 0) {
  1095             Type varargsTypeFrom = fromArgs.last();
  1096             Type varargsTypeTo = toArgs.last();
  1097             ListBuffer<Type> args = ListBuffer.lb();
  1098             if (toArgs.length() < fromArgs.length()) {
  1099                 //if we are checking a varargs method 'from' against another varargs
  1100                 //method 'to' (where arity of 'to' < arity of 'from') then expand signature
  1101                 //of 'to' to 'fit' arity of 'from' (this means adding fake formals to 'to'
  1102                 //until 'to' signature has the same arity as 'from')
  1103                 while (fromArgs.head != varargsTypeFrom) {
  1104                     args.append(toArgs.head == varargsTypeTo ? types.elemtype(varargsTypeTo) : toArgs.head);
  1105                     fromArgs = fromArgs.tail;
  1106                     toArgs = toArgs.head == varargsTypeTo ?
  1107                         toArgs :
  1108                         toArgs.tail;
  1110             } else {
  1111                 //formal argument list is same as original list where last
  1112                 //argument (array type) is removed
  1113                 args.appendList(toArgs.reverse().tail.reverse());
  1115             //append varargs element type as last synthetic formal
  1116             args.append(types.elemtype(varargsTypeTo));
  1117             Type mtype = types.createMethodTypeWithParameters(to.type, args.toList());
  1118             return new MethodSymbol(to.flags_field & ~VARARGS, to.name, mtype, to.owner);
  1119         } else {
  1120             return to;
  1123     //where
  1124     Type mostSpecificReturnType(Type mt1, Type mt2) {
  1125         Type rt1 = mt1.getReturnType();
  1126         Type rt2 = mt2.getReturnType();
  1128         if (mt1.tag == FORALL && mt2.tag == FORALL) {
  1129             //if both are generic methods, adjust return type ahead of subtyping check
  1130             rt1 = types.subst(rt1, mt1.getTypeArguments(), mt2.getTypeArguments());
  1132         //first use subtyping, then return type substitutability
  1133         if (types.isSubtype(rt1, rt2)) {
  1134             return mt1;
  1135         } else if (types.isSubtype(rt2, rt1)) {
  1136             return mt2;
  1137         } else if (types.returnTypeSubstitutable(mt1, mt2)) {
  1138             return mt1;
  1139         } else if (types.returnTypeSubstitutable(mt2, mt1)) {
  1140             return mt2;
  1141         } else {
  1142             return null;
  1145     //where
  1146     Symbol ambiguityError(Symbol m1, Symbol m2) {
  1147         if (((m1.flags() | m2.flags()) & CLASH) != 0) {
  1148             return (m1.flags() & CLASH) == 0 ? m1 : m2;
  1149         } else {
  1150             return new AmbiguityError(m1, m2);
  1154     /** Find best qualified method matching given name, type and value
  1155      *  arguments.
  1156      *  @param env       The current environment.
  1157      *  @param site      The original type from where the selection
  1158      *                   takes place.
  1159      *  @param name      The method's name.
  1160      *  @param argtypes  The method's value arguments.
  1161      *  @param typeargtypes The method's type arguments
  1162      *  @param allowBoxing Allow boxing conversions of arguments.
  1163      *  @param useVarargs Box trailing arguments into an array for varargs.
  1164      */
  1165     Symbol findMethod(Env<AttrContext> env,
  1166                       Type site,
  1167                       Name name,
  1168                       List<Type> argtypes,
  1169                       List<Type> typeargtypes,
  1170                       boolean allowBoxing,
  1171                       boolean useVarargs,
  1172                       boolean operator) {
  1173         Symbol bestSoFar = methodNotFound;
  1174         bestSoFar = findMethod(env,
  1175                           site,
  1176                           name,
  1177                           argtypes,
  1178                           typeargtypes,
  1179                           site.tsym.type,
  1180                           bestSoFar,
  1181                           allowBoxing,
  1182                           useVarargs,
  1183                           operator);
  1184         reportVerboseResolutionDiagnostic(env.tree.pos(), name, site, argtypes, typeargtypes, bestSoFar);
  1185         return bestSoFar;
  1187     // where
  1188     private Symbol findMethod(Env<AttrContext> env,
  1189                               Type site,
  1190                               Name name,
  1191                               List<Type> argtypes,
  1192                               List<Type> typeargtypes,
  1193                               Type intype,
  1194                               Symbol bestSoFar,
  1195                               boolean allowBoxing,
  1196                               boolean useVarargs,
  1197                               boolean operator) {
  1198         boolean abstractOk = true;
  1199         List<Type> itypes = List.nil();
  1200         for (TypeSymbol s : superclasses(intype)) {
  1201             bestSoFar = lookupMethod(env, site, name, argtypes, typeargtypes,
  1202                     s.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
  1203             abstractOk &= excludeAbstractsFilter.accepts(s);
  1204             if (abstractOk) {
  1205                 for (Type itype : types.interfaces(s.type)) {
  1206                     itypes = types.union(types.closure(itype), itypes);
  1209             if (name == names.init) break;
  1212         Symbol concrete = bestSoFar.kind < ERR &&
  1213                 (bestSoFar.flags() & ABSTRACT) == 0 ?
  1214                 bestSoFar : methodNotFound;
  1216         if (name != names.init) {
  1217             //keep searching for abstract methods
  1218             for (Type itype : itypes) {
  1219                 if (!itype.isInterface()) continue; //skip j.l.Object (included by Types.closure())
  1220                 bestSoFar = lookupMethod(env, site, name, argtypes, typeargtypes,
  1221                     itype.tsym.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
  1222                     if (concrete != bestSoFar &&
  1223                             concrete.kind < ERR  && bestSoFar.kind < ERR &&
  1224                             types.isSubSignature(concrete.type, bestSoFar.type)) {
  1225                         //this is an hack - as javac does not do full membership checks
  1226                         //most specific ends up comparing abstract methods that might have
  1227                         //been implemented by some concrete method in a subclass and,
  1228                         //because of raw override, it is possible for an abstract method
  1229                         //to be more specific than the concrete method - so we need
  1230                         //to explicitly call that out (see CR 6178365)
  1231                         bestSoFar = concrete;
  1235         return bestSoFar;
  1238     /**
  1239      * Return an Iterable object to scan the superclasses of a given type.
  1240      * It's crucial that the scan is done lazily, as we don't want to accidentally
  1241      * access more supertypes than strictly needed (as this could trigger completion
  1242      * errors if some of the not-needed supertypes are missing/ill-formed).
  1243      */
  1244     Iterable<TypeSymbol> superclasses(final Type intype) {
  1245         return new Iterable<TypeSymbol>() {
  1246             public Iterator<TypeSymbol> iterator() {
  1247                 return new Iterator<TypeSymbol>() {
  1249                     List<TypeSymbol> seen = List.nil();
  1250                     TypeSymbol currentSym = getSymbol(intype);
  1252                     public boolean hasNext() {
  1253                         return currentSym != null;
  1256                     public TypeSymbol next() {
  1257                         TypeSymbol prevSym = currentSym;
  1258                         currentSym = getSymbol(types.supertype(currentSym.type));
  1259                         return prevSym;
  1262                     public void remove() {
  1263                         throw new UnsupportedOperationException("Not supported yet.");
  1266                     TypeSymbol getSymbol(Type intype) {
  1267                         if (intype.tag != CLASS &&
  1268                                 intype.tag != TYPEVAR) {
  1269                             return null;
  1271                         while (intype.tag == TYPEVAR)
  1272                             intype = intype.getUpperBound();
  1273                         if (seen.contains(intype.tsym)) {
  1274                             //degenerate case in which we have a circular
  1275                             //class hierarchy - because of ill-formed classfiles
  1276                             return null;
  1278                         seen = seen.prepend(intype.tsym);
  1279                         return intype.tsym;
  1281                 };
  1283         };
  1286     /**
  1287      * We should not look for abstract methods if receiver is a concrete class
  1288      * (as concrete classes are expected to implement all abstracts coming
  1289      * from superinterfaces)
  1290      */
  1291     Filter<Symbol> excludeAbstractsFilter = new Filter<Symbol>() {
  1292         public boolean accepts(Symbol s) {
  1293             return (s.flags() & (ABSTRACT | INTERFACE | ENUM)) != 0;
  1295     };
  1297     /**
  1298      * Lookup a method with given name and argument types in a given scope
  1299      */
  1300     Symbol lookupMethod(Env<AttrContext> env,
  1301             Type site,
  1302             Name name,
  1303             List<Type> argtypes,
  1304             List<Type> typeargtypes,
  1305             Scope sc,
  1306             Symbol bestSoFar,
  1307             boolean allowBoxing,
  1308             boolean useVarargs,
  1309             boolean operator,
  1310             boolean abstractok) {
  1311         for (Symbol s : sc.getElementsByName(name, lookupFilter)) {
  1312             bestSoFar = selectBest(env, site, argtypes, typeargtypes, s,
  1313                     bestSoFar, allowBoxing, useVarargs, operator);
  1315         return bestSoFar;
  1317     //where
  1318         Filter<Symbol> lookupFilter = new Filter<Symbol>() {
  1319             public boolean accepts(Symbol s) {
  1320                 return s.kind == MTH &&
  1321                         (s.flags() & SYNTHETIC) == 0;
  1323         };
  1325     /** Find unqualified method matching given name, type and value arguments.
  1326      *  @param env       The current environment.
  1327      *  @param name      The method's name.
  1328      *  @param argtypes  The method's value arguments.
  1329      *  @param typeargtypes  The method's type arguments.
  1330      *  @param allowBoxing Allow boxing conversions of arguments.
  1331      *  @param useVarargs Box trailing arguments into an array for varargs.
  1332      */
  1333     Symbol findFun(Env<AttrContext> env, Name name,
  1334                    List<Type> argtypes, List<Type> typeargtypes,
  1335                    boolean allowBoxing, boolean useVarargs) {
  1336         Symbol bestSoFar = methodNotFound;
  1337         Symbol sym;
  1338         Env<AttrContext> env1 = env;
  1339         boolean staticOnly = false;
  1340         while (env1.outer != null) {
  1341             if (isStatic(env1)) staticOnly = true;
  1342             sym = findMethod(
  1343                 env1, env1.enclClass.sym.type, name, argtypes, typeargtypes,
  1344                 allowBoxing, useVarargs, false);
  1345             if (sym.exists()) {
  1346                 if (staticOnly &&
  1347                     sym.kind == MTH &&
  1348                     sym.owner.kind == TYP &&
  1349                     (sym.flags() & STATIC) == 0) return new StaticError(sym);
  1350                 else return sym;
  1351             } else if (sym.kind < bestSoFar.kind) {
  1352                 bestSoFar = sym;
  1354             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  1355             env1 = env1.outer;
  1358         sym = findMethod(env, syms.predefClass.type, name, argtypes,
  1359                          typeargtypes, allowBoxing, useVarargs, false);
  1360         if (sym.exists())
  1361             return sym;
  1363         Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
  1364         for (; e.scope != null; e = e.next()) {
  1365             sym = e.sym;
  1366             Type origin = e.getOrigin().owner.type;
  1367             if (sym.kind == MTH) {
  1368                 if (e.sym.owner.type != origin)
  1369                     sym = sym.clone(e.getOrigin().owner);
  1370                 if (!isAccessible(env, origin, sym))
  1371                     sym = new AccessError(env, origin, sym);
  1372                 bestSoFar = selectBest(env, origin,
  1373                                        argtypes, typeargtypes,
  1374                                        sym, bestSoFar,
  1375                                        allowBoxing, useVarargs, false);
  1378         if (bestSoFar.exists())
  1379             return bestSoFar;
  1381         e = env.toplevel.starImportScope.lookup(name);
  1382         for (; e.scope != null; e = e.next()) {
  1383             sym = e.sym;
  1384             Type origin = e.getOrigin().owner.type;
  1385             if (sym.kind == MTH) {
  1386                 if (e.sym.owner.type != origin)
  1387                     sym = sym.clone(e.getOrigin().owner);
  1388                 if (!isAccessible(env, origin, sym))
  1389                     sym = new AccessError(env, origin, sym);
  1390                 bestSoFar = selectBest(env, origin,
  1391                                        argtypes, typeargtypes,
  1392                                        sym, bestSoFar,
  1393                                        allowBoxing, useVarargs, false);
  1396         return bestSoFar;
  1399     /** Load toplevel or member class with given fully qualified name and
  1400      *  verify that it is accessible.
  1401      *  @param env       The current environment.
  1402      *  @param name      The fully qualified name of the class to be loaded.
  1403      */
  1404     Symbol loadClass(Env<AttrContext> env, Name name) {
  1405         try {
  1406             ClassSymbol c = reader.loadClass(name);
  1407             return isAccessible(env, c) ? c : new AccessError(c);
  1408         } catch (ClassReader.BadClassFile err) {
  1409             throw err;
  1410         } catch (CompletionFailure ex) {
  1411             return typeNotFound;
  1415     /** Find qualified member type.
  1416      *  @param env       The current environment.
  1417      *  @param site      The original type from where the selection takes
  1418      *                   place.
  1419      *  @param name      The type's name.
  1420      *  @param c         The class to search for the member type. This is
  1421      *                   always a superclass or implemented interface of
  1422      *                   site's class.
  1423      */
  1424     Symbol findMemberType(Env<AttrContext> env,
  1425                           Type site,
  1426                           Name name,
  1427                           TypeSymbol c) {
  1428         Symbol bestSoFar = typeNotFound;
  1429         Symbol sym;
  1430         Scope.Entry e = c.members().lookup(name);
  1431         while (e.scope != null) {
  1432             if (e.sym.kind == TYP) {
  1433                 return isAccessible(env, site, e.sym)
  1434                     ? e.sym
  1435                     : new AccessError(env, site, e.sym);
  1437             e = e.next();
  1439         Type st = types.supertype(c.type);
  1440         if (st != null && st.tag == CLASS) {
  1441             sym = findMemberType(env, site, name, st.tsym);
  1442             if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1444         for (List<Type> l = types.interfaces(c.type);
  1445              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
  1446              l = l.tail) {
  1447             sym = findMemberType(env, site, name, l.head.tsym);
  1448             if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
  1449                 sym.owner != bestSoFar.owner)
  1450                 bestSoFar = new AmbiguityError(bestSoFar, sym);
  1451             else if (sym.kind < bestSoFar.kind)
  1452                 bestSoFar = sym;
  1454         return bestSoFar;
  1457     /** Find a global type in given scope and load corresponding class.
  1458      *  @param env       The current environment.
  1459      *  @param scope     The scope in which to look for the type.
  1460      *  @param name      The type's name.
  1461      */
  1462     Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name) {
  1463         Symbol bestSoFar = typeNotFound;
  1464         for (Scope.Entry e = scope.lookup(name); e.scope != null; e = e.next()) {
  1465             Symbol sym = loadClass(env, e.sym.flatName());
  1466             if (bestSoFar.kind == TYP && sym.kind == TYP &&
  1467                 bestSoFar != sym)
  1468                 return new AmbiguityError(bestSoFar, sym);
  1469             else if (sym.kind < bestSoFar.kind)
  1470                 bestSoFar = sym;
  1472         return bestSoFar;
  1475     /** Find an unqualified type symbol.
  1476      *  @param env       The current environment.
  1477      *  @param name      The type's name.
  1478      */
  1479     Symbol findType(Env<AttrContext> env, Name name) {
  1480         Symbol bestSoFar = typeNotFound;
  1481         Symbol sym;
  1482         boolean staticOnly = false;
  1483         for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
  1484             if (isStatic(env1)) staticOnly = true;
  1485             for (Scope.Entry e = env1.info.scope.lookup(name);
  1486                  e.scope != null;
  1487                  e = e.next()) {
  1488                 if (e.sym.kind == TYP) {
  1489                     if (staticOnly &&
  1490                         e.sym.type.tag == TYPEVAR &&
  1491                         e.sym.owner.kind == TYP) return new StaticError(e.sym);
  1492                     return e.sym;
  1496             sym = findMemberType(env1, env1.enclClass.sym.type, name,
  1497                                  env1.enclClass.sym);
  1498             if (staticOnly && sym.kind == TYP &&
  1499                 sym.type.tag == CLASS &&
  1500                 sym.type.getEnclosingType().tag == CLASS &&
  1501                 env1.enclClass.sym.type.isParameterized() &&
  1502                 sym.type.getEnclosingType().isParameterized())
  1503                 return new StaticError(sym);
  1504             else if (sym.exists()) return sym;
  1505             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1507             JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass;
  1508             if ((encl.sym.flags() & STATIC) != 0)
  1509                 staticOnly = true;
  1512         if (!env.tree.hasTag(IMPORT)) {
  1513             sym = findGlobalType(env, env.toplevel.namedImportScope, name);
  1514             if (sym.exists()) return sym;
  1515             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1517             sym = findGlobalType(env, env.toplevel.packge.members(), name);
  1518             if (sym.exists()) return sym;
  1519             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1521             sym = findGlobalType(env, env.toplevel.starImportScope, name);
  1522             if (sym.exists()) return sym;
  1523             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1526         return bestSoFar;
  1529     /** Find an unqualified identifier which matches a specified kind set.
  1530      *  @param env       The current environment.
  1531      *  @param name      The indentifier's name.
  1532      *  @param kind      Indicates the possible symbol kinds
  1533      *                   (a subset of VAL, TYP, PCK).
  1534      */
  1535     Symbol findIdent(Env<AttrContext> env, Name name, int kind) {
  1536         Symbol bestSoFar = typeNotFound;
  1537         Symbol sym;
  1539         if ((kind & VAR) != 0) {
  1540             sym = findVar(env, name);
  1541             if (sym.exists()) return sym;
  1542             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1545         if ((kind & TYP) != 0) {
  1546             sym = findType(env, name);
  1547             if (sym.exists()) return sym;
  1548             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1551         if ((kind & PCK) != 0) return reader.enterPackage(name);
  1552         else return bestSoFar;
  1555     /** Find an identifier in a package which matches a specified kind set.
  1556      *  @param env       The current environment.
  1557      *  @param name      The identifier's name.
  1558      *  @param kind      Indicates the possible symbol kinds
  1559      *                   (a nonempty subset of TYP, PCK).
  1560      */
  1561     Symbol findIdentInPackage(Env<AttrContext> env, TypeSymbol pck,
  1562                               Name name, int kind) {
  1563         Name fullname = TypeSymbol.formFullName(name, pck);
  1564         Symbol bestSoFar = typeNotFound;
  1565         PackageSymbol pack = null;
  1566         if ((kind & PCK) != 0) {
  1567             pack = reader.enterPackage(fullname);
  1568             if (pack.exists()) return pack;
  1570         if ((kind & TYP) != 0) {
  1571             Symbol sym = loadClass(env, fullname);
  1572             if (sym.exists()) {
  1573                 // don't allow programs to use flatnames
  1574                 if (name == sym.name) return sym;
  1576             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1578         return (pack != null) ? pack : bestSoFar;
  1581     /** Find an identifier among the members of a given type `site'.
  1582      *  @param env       The current environment.
  1583      *  @param site      The type containing the symbol to be found.
  1584      *  @param name      The identifier's name.
  1585      *  @param kind      Indicates the possible symbol kinds
  1586      *                   (a subset of VAL, TYP).
  1587      */
  1588     Symbol findIdentInType(Env<AttrContext> env, Type site,
  1589                            Name name, int kind) {
  1590         Symbol bestSoFar = typeNotFound;
  1591         Symbol sym;
  1592         if ((kind & VAR) != 0) {
  1593             sym = findField(env, site, name, site.tsym);
  1594             if (sym.exists()) return sym;
  1595             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1598         if ((kind & TYP) != 0) {
  1599             sym = findMemberType(env, site, name, site.tsym);
  1600             if (sym.exists()) return sym;
  1601             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1603         return bestSoFar;
  1606 /* ***************************************************************************
  1607  *  Access checking
  1608  *  The following methods convert ResolveErrors to ErrorSymbols, issuing
  1609  *  an error message in the process
  1610  ****************************************************************************/
  1612     /** If `sym' is a bad symbol: report error and return errSymbol
  1613      *  else pass through unchanged,
  1614      *  additional arguments duplicate what has been used in trying to find the
  1615      *  symbol {@literal (--> flyweight pattern)}. This improves performance since we
  1616      *  expect misses to happen frequently.
  1618      *  @param sym       The symbol that was found, or a ResolveError.
  1619      *  @param pos       The position to use for error reporting.
  1620      *  @param site      The original type from where the selection took place.
  1621      *  @param name      The symbol's name.
  1622      *  @param argtypes  The invocation's value arguments,
  1623      *                   if we looked for a method.
  1624      *  @param typeargtypes  The invocation's type arguments,
  1625      *                   if we looked for a method.
  1626      */
  1627     Symbol access(Symbol sym,
  1628                   DiagnosticPosition pos,
  1629                   Symbol location,
  1630                   Type site,
  1631                   Name name,
  1632                   boolean qualified,
  1633                   List<Type> argtypes,
  1634                   List<Type> typeargtypes) {
  1635         if (sym.kind >= AMBIGUOUS) {
  1636             ResolveError errSym = (ResolveError)sym;
  1637             if (!site.isErroneous() &&
  1638                 !Type.isErroneous(argtypes) &&
  1639                 (typeargtypes==null || !Type.isErroneous(typeargtypes)))
  1640                 logResolveError(errSym, pos, location, site, name, argtypes, typeargtypes);
  1641             sym = errSym.access(name, qualified ? site.tsym : syms.noSymbol);
  1643         return sym;
  1646     /** Same as original access(), but without location.
  1647      */
  1648     Symbol access(Symbol sym,
  1649                   DiagnosticPosition pos,
  1650                   Type site,
  1651                   Name name,
  1652                   boolean qualified,
  1653                   List<Type> argtypes,
  1654                   List<Type> typeargtypes) {
  1655         return access(sym, pos, site.tsym, site, name, qualified, argtypes, typeargtypes);
  1658     /** Same as original access(), but without type arguments and arguments.
  1659      */
  1660     Symbol access(Symbol sym,
  1661                   DiagnosticPosition pos,
  1662                   Symbol location,
  1663                   Type site,
  1664                   Name name,
  1665                   boolean qualified) {
  1666         if (sym.kind >= AMBIGUOUS)
  1667             return access(sym, pos, location, site, name, qualified, List.<Type>nil(), null);
  1668         else
  1669             return sym;
  1672     /** Same as original access(), but without location, type arguments and arguments.
  1673      */
  1674     Symbol access(Symbol sym,
  1675                   DiagnosticPosition pos,
  1676                   Type site,
  1677                   Name name,
  1678                   boolean qualified) {
  1679         return access(sym, pos, site.tsym, site, name, qualified);
  1682     /** Check that sym is not an abstract method.
  1683      */
  1684     void checkNonAbstract(DiagnosticPosition pos, Symbol sym) {
  1685         if ((sym.flags() & ABSTRACT) != 0)
  1686             log.error(pos, "abstract.cant.be.accessed.directly",
  1687                       kindName(sym), sym, sym.location());
  1690 /* ***************************************************************************
  1691  *  Debugging
  1692  ****************************************************************************/
  1694     /** print all scopes starting with scope s and proceeding outwards.
  1695      *  used for debugging.
  1696      */
  1697     public void printscopes(Scope s) {
  1698         while (s != null) {
  1699             if (s.owner != null)
  1700                 System.err.print(s.owner + ": ");
  1701             for (Scope.Entry e = s.elems; e != null; e = e.sibling) {
  1702                 if ((e.sym.flags() & ABSTRACT) != 0)
  1703                     System.err.print("abstract ");
  1704                 System.err.print(e.sym + " ");
  1706             System.err.println();
  1707             s = s.next;
  1711     void printscopes(Env<AttrContext> env) {
  1712         while (env.outer != null) {
  1713             System.err.println("------------------------------");
  1714             printscopes(env.info.scope);
  1715             env = env.outer;
  1719     public void printscopes(Type t) {
  1720         while (t.tag == CLASS) {
  1721             printscopes(t.tsym.members());
  1722             t = types.supertype(t);
  1726 /* ***************************************************************************
  1727  *  Name resolution
  1728  *  Naming conventions are as for symbol lookup
  1729  *  Unlike the find... methods these methods will report access errors
  1730  ****************************************************************************/
  1732     /** Resolve an unqualified (non-method) identifier.
  1733      *  @param pos       The position to use for error reporting.
  1734      *  @param env       The environment current at the identifier use.
  1735      *  @param name      The identifier's name.
  1736      *  @param kind      The set of admissible symbol kinds for the identifier.
  1737      */
  1738     Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env,
  1739                         Name name, int kind) {
  1740         return access(
  1741             findIdent(env, name, kind),
  1742             pos, env.enclClass.sym.type, name, false);
  1745     /** Resolve an unqualified method identifier.
  1746      *  @param pos       The position to use for error reporting.
  1747      *  @param env       The environment current at the method invocation.
  1748      *  @param name      The identifier's name.
  1749      *  @param argtypes  The types of the invocation's value arguments.
  1750      *  @param typeargtypes  The types of the invocation's type arguments.
  1751      */
  1752     Symbol resolveMethod(DiagnosticPosition pos,
  1753                          Env<AttrContext> env,
  1754                          Name name,
  1755                          List<Type> argtypes,
  1756                          List<Type> typeargtypes) {
  1757         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  1758         try {
  1759             currentResolutionContext = new MethodResolutionContext();
  1760             Symbol sym = methodNotFound;
  1761             List<MethodResolutionPhase> steps = methodResolutionSteps;
  1762             while (steps.nonEmpty() &&
  1763                    steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  1764                    sym.kind >= ERRONEOUS) {
  1765                 currentResolutionContext.step = steps.head;
  1766                 sym = findFun(env, name, argtypes, typeargtypes,
  1767                         steps.head.isBoxingRequired,
  1768                         env.info.varArgs = steps.head.isVarargsRequired);
  1769                 currentResolutionContext.resolutionCache.put(steps.head, sym);
  1770                 steps = steps.tail;
  1772             if (sym.kind >= AMBIGUOUS) {//if nothing is found return the 'first' error
  1773                 MethodResolutionPhase errPhase =
  1774                         currentResolutionContext.firstErroneousResolutionPhase();
  1775                 sym = access(currentResolutionContext.resolutionCache.get(errPhase),
  1776                         pos, env.enclClass.sym.type, name, false, argtypes, typeargtypes);
  1777                 env.info.varArgs = errPhase.isVarargsRequired;
  1779             return sym;
  1781         finally {
  1782             currentResolutionContext = prevResolutionContext;
  1786     /** Resolve a qualified method identifier
  1787      *  @param pos       The position to use for error reporting.
  1788      *  @param env       The environment current at the method invocation.
  1789      *  @param site      The type of the qualifying expression, in which
  1790      *                   identifier is searched.
  1791      *  @param name      The identifier's name.
  1792      *  @param argtypes  The types of the invocation's value arguments.
  1793      *  @param typeargtypes  The types of the invocation's type arguments.
  1794      */
  1795     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
  1796                                   Type site, Name name, List<Type> argtypes,
  1797                                   List<Type> typeargtypes) {
  1798         return resolveQualifiedMethod(pos, env, site.tsym, site, name, argtypes, typeargtypes);
  1800     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
  1801                                   Symbol location, Type site, Name name, List<Type> argtypes,
  1802                                   List<Type> typeargtypes) {
  1803         return resolveQualifiedMethod(new MethodResolutionContext(), pos, env, location, site, name, argtypes, typeargtypes);
  1805     private Symbol resolveQualifiedMethod(MethodResolutionContext resolveContext,
  1806                                   DiagnosticPosition pos, Env<AttrContext> env,
  1807                                   Symbol location, Type site, Name name, List<Type> argtypes,
  1808                                   List<Type> typeargtypes) {
  1809         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  1810         try {
  1811             currentResolutionContext = resolveContext;
  1812             Symbol sym = methodNotFound;
  1813             List<MethodResolutionPhase> steps = methodResolutionSteps;
  1814             while (steps.nonEmpty() &&
  1815                    steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  1816                    sym.kind >= ERRONEOUS) {
  1817                 currentResolutionContext.step = steps.head;
  1818                 sym = findMethod(env, site, name, argtypes, typeargtypes,
  1819                         steps.head.isBoxingRequired(),
  1820                         env.info.varArgs = steps.head.isVarargsRequired(), false);
  1821                 currentResolutionContext.resolutionCache.put(steps.head, sym);
  1822                 steps = steps.tail;
  1824             if (sym.kind >= AMBIGUOUS) {
  1825                 //if nothing is found return the 'first' error
  1826                 MethodResolutionPhase errPhase =
  1827                         currentResolutionContext.firstErroneousResolutionPhase();
  1828                 sym = access(currentResolutionContext.resolutionCache.get(errPhase),
  1829                         pos, location, site, name, true, argtypes, typeargtypes);
  1830                 env.info.varArgs = errPhase.isVarargsRequired;
  1831             } else if (allowMethodHandles) {
  1832                 MethodSymbol msym = (MethodSymbol)sym;
  1833                 if (msym.isSignaturePolymorphic(types)) {
  1834                     env.info.varArgs = false;
  1835                     return findPolymorphicSignatureInstance(env, sym, argtypes);
  1838             return sym;
  1840         finally {
  1841             currentResolutionContext = prevResolutionContext;
  1845     /** Find or create an implicit method of exactly the given type (after erasure).
  1846      *  Searches in a side table, not the main scope of the site.
  1847      *  This emulates the lookup process required by JSR 292 in JVM.
  1848      *  @param env       Attribution environment
  1849      *  @param spMethod  signature polymorphic method - i.e. MH.invokeExact
  1850      *  @param argtypes  The required argument types
  1851      */
  1852     Symbol findPolymorphicSignatureInstance(Env<AttrContext> env,
  1853                                             Symbol spMethod,
  1854                                             List<Type> argtypes) {
  1855         Type mtype = infer.instantiatePolymorphicSignatureInstance(env,
  1856                 (MethodSymbol)spMethod, argtypes);
  1857         for (Symbol sym : polymorphicSignatureScope.getElementsByName(spMethod.name)) {
  1858             if (types.isSameType(mtype, sym.type)) {
  1859                return sym;
  1863         // create the desired method
  1864         long flags = ABSTRACT | HYPOTHETICAL | spMethod.flags() & Flags.AccessFlags;
  1865         Symbol msym = new MethodSymbol(flags, spMethod.name, mtype, spMethod.owner);
  1866         polymorphicSignatureScope.enter(msym);
  1867         return msym;
  1870     /** Resolve a qualified method identifier, throw a fatal error if not
  1871      *  found.
  1872      *  @param pos       The position to use for error reporting.
  1873      *  @param env       The environment current at the method invocation.
  1874      *  @param site      The type of the qualifying expression, in which
  1875      *                   identifier is searched.
  1876      *  @param name      The identifier's name.
  1877      *  @param argtypes  The types of the invocation's value arguments.
  1878      *  @param typeargtypes  The types of the invocation's type arguments.
  1879      */
  1880     public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env,
  1881                                         Type site, Name name,
  1882                                         List<Type> argtypes,
  1883                                         List<Type> typeargtypes) {
  1884         MethodResolutionContext resolveContext = new MethodResolutionContext();
  1885         resolveContext.internalResolution = true;
  1886         Symbol sym = resolveQualifiedMethod(resolveContext, pos, env, site.tsym,
  1887                 site, name, argtypes, typeargtypes);
  1888         if (sym.kind == MTH) return (MethodSymbol)sym;
  1889         else throw new FatalError(
  1890                  diags.fragment("fatal.err.cant.locate.meth",
  1891                                 name));
  1894     /** Resolve constructor.
  1895      *  @param pos       The position to use for error reporting.
  1896      *  @param env       The environment current at the constructor invocation.
  1897      *  @param site      The type of class for which a constructor is searched.
  1898      *  @param argtypes  The types of the constructor invocation's value
  1899      *                   arguments.
  1900      *  @param typeargtypes  The types of the constructor invocation's type
  1901      *                   arguments.
  1902      */
  1903     Symbol resolveConstructor(DiagnosticPosition pos,
  1904                               Env<AttrContext> env,
  1905                               Type site,
  1906                               List<Type> argtypes,
  1907                               List<Type> typeargtypes) {
  1908         return resolveConstructor(new MethodResolutionContext(), pos, env, site, argtypes, typeargtypes);
  1910     private Symbol resolveConstructor(MethodResolutionContext resolveContext,
  1911                               DiagnosticPosition pos,
  1912                               Env<AttrContext> env,
  1913                               Type site,
  1914                               List<Type> argtypes,
  1915                               List<Type> typeargtypes) {
  1916         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  1917         try {
  1918             currentResolutionContext = resolveContext;
  1919             Symbol sym = methodNotFound;
  1920             List<MethodResolutionPhase> steps = methodResolutionSteps;
  1921             while (steps.nonEmpty() &&
  1922                    steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  1923                    sym.kind >= ERRONEOUS) {
  1924                 currentResolutionContext.step = steps.head;
  1925                 sym = findConstructor(pos, env, site, argtypes, typeargtypes,
  1926                         steps.head.isBoxingRequired(),
  1927                         env.info.varArgs = steps.head.isVarargsRequired());
  1928                 currentResolutionContext.resolutionCache.put(steps.head, sym);
  1929                 steps = steps.tail;
  1931             if (sym.kind >= AMBIGUOUS) {//if nothing is found return the 'first' error
  1932                 MethodResolutionPhase errPhase = currentResolutionContext.firstErroneousResolutionPhase();
  1933                 sym = access(currentResolutionContext.resolutionCache.get(errPhase),
  1934                         pos, site, names.init, true, argtypes, typeargtypes);
  1935                 env.info.varArgs = errPhase.isVarargsRequired();
  1937             return sym;
  1939         finally {
  1940             currentResolutionContext = prevResolutionContext;
  1944     /** Resolve constructor using diamond inference.
  1945      *  @param pos       The position to use for error reporting.
  1946      *  @param env       The environment current at the constructor invocation.
  1947      *  @param site      The type of class for which a constructor is searched.
  1948      *                   The scope of this class has been touched in attribution.
  1949      *  @param argtypes  The types of the constructor invocation's value
  1950      *                   arguments.
  1951      *  @param typeargtypes  The types of the constructor invocation's type
  1952      *                   arguments.
  1953      */
  1954     Symbol resolveDiamond(DiagnosticPosition pos,
  1955                               Env<AttrContext> env,
  1956                               Type site,
  1957                               List<Type> argtypes,
  1958                               List<Type> typeargtypes) {
  1959         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  1960         try {
  1961             currentResolutionContext = new MethodResolutionContext();
  1962             Symbol sym = methodNotFound;
  1963             List<MethodResolutionPhase> steps = methodResolutionSteps;
  1964             while (steps.nonEmpty() &&
  1965                    steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  1966                    sym.kind >= ERRONEOUS) {
  1967                 currentResolutionContext.step = steps.head;
  1968                 sym = findDiamond(env, site, argtypes, typeargtypes,
  1969                         steps.head.isBoxingRequired(),
  1970                         env.info.varArgs = steps.head.isVarargsRequired());
  1971                 currentResolutionContext.resolutionCache.put(steps.head, sym);
  1972                 steps = steps.tail;
  1974             if (sym.kind >= AMBIGUOUS) {
  1975                 Symbol errSym =
  1976                         currentResolutionContext.resolutionCache.get(currentResolutionContext.firstErroneousResolutionPhase());
  1977                 final JCDiagnostic details = errSym.kind == WRONG_MTH ?
  1978                                 ((InapplicableSymbolError)errSym).errCandidate().details :
  1979                                 null;
  1980                 errSym = new InapplicableSymbolError(errSym.kind, "diamondError") {
  1981                     @Override
  1982                     JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos,
  1983                             Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
  1984                         String key = details == null ?
  1985                             "cant.apply.diamond" :
  1986                             "cant.apply.diamond.1";
  1987                         return diags.create(dkind, log.currentSource(), pos, key,
  1988                                 diags.fragment("diamond", site.tsym), details);
  1990                 };
  1991                 MethodResolutionPhase errPhase = currentResolutionContext.firstErroneousResolutionPhase();
  1992                 sym = access(errSym, pos, site, names.init, true, argtypes, typeargtypes);
  1993                 env.info.varArgs = errPhase.isVarargsRequired();
  1995             return sym;
  1997         finally {
  1998             currentResolutionContext = prevResolutionContext;
  2002     /** This method scans all the constructor symbol in a given class scope -
  2003      *  assuming that the original scope contains a constructor of the kind:
  2004      *  {@code Foo(X x, Y y)}, where X,Y are class type-variables declared in Foo,
  2005      *  a method check is executed against the modified constructor type:
  2006      *  {@code <X,Y>Foo<X,Y>(X x, Y y)}. This is crucial in order to enable diamond
  2007      *  inference. The inferred return type of the synthetic constructor IS
  2008      *  the inferred type for the diamond operator.
  2009      */
  2010     private Symbol findDiamond(Env<AttrContext> env,
  2011                               Type site,
  2012                               List<Type> argtypes,
  2013                               List<Type> typeargtypes,
  2014                               boolean allowBoxing,
  2015                               boolean useVarargs) {
  2016         Symbol bestSoFar = methodNotFound;
  2017         for (Scope.Entry e = site.tsym.members().lookup(names.init);
  2018              e.scope != null;
  2019              e = e.next()) {
  2020             final Symbol sym = e.sym;
  2021             //- System.out.println(" e " + e.sym);
  2022             if (sym.kind == MTH &&
  2023                 (sym.flags_field & SYNTHETIC) == 0) {
  2024                     List<Type> oldParams = e.sym.type.tag == FORALL ?
  2025                             ((ForAll)sym.type).tvars :
  2026                             List.<Type>nil();
  2027                     Type constrType = new ForAll(site.tsym.type.getTypeArguments().appendList(oldParams),
  2028                             types.createMethodTypeWithReturn(sym.type.asMethodType(), site));
  2029                     MethodSymbol newConstr = new MethodSymbol(sym.flags(), names.init, constrType, site.tsym) {
  2030                         @Override
  2031                         public Symbol baseSymbol() {
  2032                             return sym;
  2034                     };
  2035                     bestSoFar = selectBest(env, site, argtypes, typeargtypes,
  2036                             newConstr,
  2037                             bestSoFar,
  2038                             allowBoxing,
  2039                             useVarargs,
  2040                             false);
  2043         return bestSoFar;
  2046     /** Resolve constructor.
  2047      *  @param pos       The position to use for error reporting.
  2048      *  @param env       The environment current at the constructor invocation.
  2049      *  @param site      The type of class for which a constructor is searched.
  2050      *  @param argtypes  The types of the constructor invocation's value
  2051      *                   arguments.
  2052      *  @param typeargtypes  The types of the constructor invocation's type
  2053      *                   arguments.
  2054      *  @param allowBoxing Allow boxing and varargs conversions.
  2055      *  @param useVarargs Box trailing arguments into an array for varargs.
  2056      */
  2057     Symbol resolveConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  2058                               Type site, List<Type> argtypes,
  2059                               List<Type> typeargtypes,
  2060                               boolean allowBoxing,
  2061                               boolean useVarargs) {
  2062         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  2063         try {
  2064             currentResolutionContext = new MethodResolutionContext();
  2065             return findConstructor(pos, env, site, argtypes, typeargtypes, allowBoxing, useVarargs);
  2067         finally {
  2068             currentResolutionContext = prevResolutionContext;
  2072     Symbol findConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  2073                               Type site, List<Type> argtypes,
  2074                               List<Type> typeargtypes,
  2075                               boolean allowBoxing,
  2076                               boolean useVarargs) {
  2077         Symbol sym = findMethod(env, site,
  2078                                     names.init, argtypes,
  2079                                     typeargtypes, allowBoxing,
  2080                                     useVarargs, false);
  2081         chk.checkDeprecated(pos, env.info.scope.owner, sym);
  2082         return sym;
  2085     /** Resolve a constructor, throw a fatal error if not found.
  2086      *  @param pos       The position to use for error reporting.
  2087      *  @param env       The environment current at the method invocation.
  2088      *  @param site      The type to be constructed.
  2089      *  @param argtypes  The types of the invocation's value arguments.
  2090      *  @param typeargtypes  The types of the invocation's type arguments.
  2091      */
  2092     public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  2093                                         Type site,
  2094                                         List<Type> argtypes,
  2095                                         List<Type> typeargtypes) {
  2096         MethodResolutionContext resolveContext = new MethodResolutionContext();
  2097         resolveContext.internalResolution = true;
  2098         Symbol sym = resolveConstructor(resolveContext, pos, env, site, argtypes, typeargtypes);
  2099         if (sym.kind == MTH) return (MethodSymbol)sym;
  2100         else throw new FatalError(
  2101                  diags.fragment("fatal.err.cant.locate.ctor", site));
  2104     /** Resolve operator.
  2105      *  @param pos       The position to use for error reporting.
  2106      *  @param optag     The tag of the operation tree.
  2107      *  @param env       The environment current at the operation.
  2108      *  @param argtypes  The types of the operands.
  2109      */
  2110     Symbol resolveOperator(DiagnosticPosition pos, JCTree.Tag optag,
  2111                            Env<AttrContext> env, List<Type> argtypes) {
  2112         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  2113         try {
  2114             currentResolutionContext = new MethodResolutionContext();
  2115             Name name = treeinfo.operatorName(optag);
  2116             Symbol sym = findMethod(env, syms.predefClass.type, name, argtypes,
  2117                                     null, false, false, true);
  2118             if (boxingEnabled && sym.kind >= WRONG_MTHS)
  2119                 sym = findMethod(env, syms.predefClass.type, name, argtypes,
  2120                                  null, true, false, true);
  2121             return access(sym, pos, env.enclClass.sym.type, name,
  2122                           false, argtypes, null);
  2124         finally {
  2125             currentResolutionContext = prevResolutionContext;
  2129     /** Resolve operator.
  2130      *  @param pos       The position to use for error reporting.
  2131      *  @param optag     The tag of the operation tree.
  2132      *  @param env       The environment current at the operation.
  2133      *  @param arg       The type of the operand.
  2134      */
  2135     Symbol resolveUnaryOperator(DiagnosticPosition pos, JCTree.Tag optag, Env<AttrContext> env, Type arg) {
  2136         return resolveOperator(pos, optag, env, List.of(arg));
  2139     /** Resolve binary operator.
  2140      *  @param pos       The position to use for error reporting.
  2141      *  @param optag     The tag of the operation tree.
  2142      *  @param env       The environment current at the operation.
  2143      *  @param left      The types of the left operand.
  2144      *  @param right     The types of the right operand.
  2145      */
  2146     Symbol resolveBinaryOperator(DiagnosticPosition pos,
  2147                                  JCTree.Tag optag,
  2148                                  Env<AttrContext> env,
  2149                                  Type left,
  2150                                  Type right) {
  2151         return resolveOperator(pos, optag, env, List.of(left, right));
  2154     /**
  2155      * Resolve `c.name' where name == this or name == super.
  2156      * @param pos           The position to use for error reporting.
  2157      * @param env           The environment current at the expression.
  2158      * @param c             The qualifier.
  2159      * @param name          The identifier's name.
  2160      */
  2161     Symbol resolveSelf(DiagnosticPosition pos,
  2162                        Env<AttrContext> env,
  2163                        TypeSymbol c,
  2164                        Name name) {
  2165         Env<AttrContext> env1 = env;
  2166         boolean staticOnly = false;
  2167         while (env1.outer != null) {
  2168             if (isStatic(env1)) staticOnly = true;
  2169             if (env1.enclClass.sym == c) {
  2170                 Symbol sym = env1.info.scope.lookup(name).sym;
  2171                 if (sym != null) {
  2172                     if (staticOnly) sym = new StaticError(sym);
  2173                     return access(sym, pos, env.enclClass.sym.type,
  2174                                   name, true);
  2177             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  2178             env1 = env1.outer;
  2180         log.error(pos, "not.encl.class", c);
  2181         return syms.errSymbol;
  2184     /**
  2185      * Resolve `c.this' for an enclosing class c that contains the
  2186      * named member.
  2187      * @param pos           The position to use for error reporting.
  2188      * @param env           The environment current at the expression.
  2189      * @param member        The member that must be contained in the result.
  2190      */
  2191     Symbol resolveSelfContaining(DiagnosticPosition pos,
  2192                                  Env<AttrContext> env,
  2193                                  Symbol member,
  2194                                  boolean isSuperCall) {
  2195         Name name = names._this;
  2196         Env<AttrContext> env1 = isSuperCall ? env.outer : env;
  2197         boolean staticOnly = false;
  2198         if (env1 != null) {
  2199             while (env1 != null && env1.outer != null) {
  2200                 if (isStatic(env1)) staticOnly = true;
  2201                 if (env1.enclClass.sym.isSubClass(member.owner, types)) {
  2202                     Symbol sym = env1.info.scope.lookup(name).sym;
  2203                     if (sym != null) {
  2204                         if (staticOnly) sym = new StaticError(sym);
  2205                         return access(sym, pos, env.enclClass.sym.type,
  2206                                       name, true);
  2209                 if ((env1.enclClass.sym.flags() & STATIC) != 0)
  2210                     staticOnly = true;
  2211                 env1 = env1.outer;
  2214         log.error(pos, "encl.class.required", member);
  2215         return syms.errSymbol;
  2218     /**
  2219      * Resolve an appropriate implicit this instance for t's container.
  2220      * JLS 8.8.5.1 and 15.9.2
  2221      */
  2222     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
  2223         return resolveImplicitThis(pos, env, t, false);
  2226     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t, boolean isSuperCall) {
  2227         Type thisType = (((t.tsym.owner.kind & (MTH|VAR)) != 0)
  2228                          ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
  2229                          : resolveSelfContaining(pos, env, t.tsym, isSuperCall)).type;
  2230         if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
  2231             log.error(pos, "cant.ref.before.ctor.called", "this");
  2232         return thisType;
  2235 /* ***************************************************************************
  2236  *  ResolveError classes, indicating error situations when accessing symbols
  2237  ****************************************************************************/
  2239     //used by TransTypes when checking target type of synthetic cast
  2240     public void logAccessErrorInternal(Env<AttrContext> env, JCTree tree, Type type) {
  2241         AccessError error = new AccessError(env, env.enclClass.type, type.tsym);
  2242         logResolveError(error, tree.pos(), env.enclClass.sym, env.enclClass.type, null, null, null);
  2244     //where
  2245     private void logResolveError(ResolveError error,
  2246             DiagnosticPosition pos,
  2247             Symbol location,
  2248             Type site,
  2249             Name name,
  2250             List<Type> argtypes,
  2251             List<Type> typeargtypes) {
  2252         JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
  2253                 pos, location, site, name, argtypes, typeargtypes);
  2254         if (d != null) {
  2255             d.setFlag(DiagnosticFlag.RESOLVE_ERROR);
  2256             log.report(d);
  2260     private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
  2262     public Object methodArguments(List<Type> argtypes) {
  2263         return argtypes == null || argtypes.isEmpty() ? noArgs : argtypes;
  2266     /**
  2267      * Root class for resolution errors. Subclass of ResolveError
  2268      * represent a different kinds of resolution error - as such they must
  2269      * specify how they map into concrete compiler diagnostics.
  2270      */
  2271     private abstract class ResolveError extends Symbol {
  2273         /** The name of the kind of error, for debugging only. */
  2274         final String debugName;
  2276         ResolveError(int kind, String debugName) {
  2277             super(kind, 0, null, null, null);
  2278             this.debugName = debugName;
  2281         @Override
  2282         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
  2283             throw new AssertionError();
  2286         @Override
  2287         public String toString() {
  2288             return debugName;
  2291         @Override
  2292         public boolean exists() {
  2293             return false;
  2296         /**
  2297          * Create an external representation for this erroneous symbol to be
  2298          * used during attribution - by default this returns the symbol of a
  2299          * brand new error type which stores the original type found
  2300          * during resolution.
  2302          * @param name     the name used during resolution
  2303          * @param location the location from which the symbol is accessed
  2304          */
  2305         protected Symbol access(Name name, TypeSymbol location) {
  2306             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  2309         /**
  2310          * Create a diagnostic representing this resolution error.
  2312          * @param dkind     The kind of the diagnostic to be created (e.g error).
  2313          * @param pos       The position to be used for error reporting.
  2314          * @param site      The original type from where the selection took place.
  2315          * @param name      The name of the symbol to be resolved.
  2316          * @param argtypes  The invocation's value arguments,
  2317          *                  if we looked for a method.
  2318          * @param typeargtypes  The invocation's type arguments,
  2319          *                      if we looked for a method.
  2320          */
  2321         abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2322                 DiagnosticPosition pos,
  2323                 Symbol location,
  2324                 Type site,
  2325                 Name name,
  2326                 List<Type> argtypes,
  2327                 List<Type> typeargtypes);
  2329         /**
  2330          * A name designates an operator if it consists
  2331          * of a non-empty sequence of operator symbols {@literal +-~!/*%&|^<>= }
  2332          */
  2333         boolean isOperator(Name name) {
  2334             int i = 0;
  2335             while (i < name.getByteLength() &&
  2336                    "+-~!*/%&|^<>=".indexOf(name.getByteAt(i)) >= 0) i++;
  2337             return i > 0 && i == name.getByteLength();
  2341     /**
  2342      * This class is the root class of all resolution errors caused by
  2343      * an invalid symbol being found during resolution.
  2344      */
  2345     abstract class InvalidSymbolError extends ResolveError {
  2347         /** The invalid symbol found during resolution */
  2348         Symbol sym;
  2350         InvalidSymbolError(int kind, Symbol sym, String debugName) {
  2351             super(kind, debugName);
  2352             this.sym = sym;
  2355         @Override
  2356         public boolean exists() {
  2357             return true;
  2360         @Override
  2361         public String toString() {
  2362              return super.toString() + " wrongSym=" + sym;
  2365         @Override
  2366         public Symbol access(Name name, TypeSymbol location) {
  2367             if (sym.kind >= AMBIGUOUS)
  2368                 return ((ResolveError)sym).access(name, location);
  2369             else if ((sym.kind & ERRONEOUS) == 0 && (sym.kind & TYP) != 0)
  2370                 return types.createErrorType(name, location, sym.type).tsym;
  2371             else
  2372                 return sym;
  2376     /**
  2377      * InvalidSymbolError error class indicating that a symbol matching a
  2378      * given name does not exists in a given site.
  2379      */
  2380     class SymbolNotFoundError extends ResolveError {
  2382         SymbolNotFoundError(int kind) {
  2383             super(kind, "symbol not found error");
  2386         @Override
  2387         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2388                 DiagnosticPosition pos,
  2389                 Symbol location,
  2390                 Type site,
  2391                 Name name,
  2392                 List<Type> argtypes,
  2393                 List<Type> typeargtypes) {
  2394             argtypes = argtypes == null ? List.<Type>nil() : argtypes;
  2395             typeargtypes = typeargtypes == null ? List.<Type>nil() : typeargtypes;
  2396             if (name == names.error)
  2397                 return null;
  2399             if (isOperator(name)) {
  2400                 boolean isUnaryOp = argtypes.size() == 1;
  2401                 String key = argtypes.size() == 1 ?
  2402                     "operator.cant.be.applied" :
  2403                     "operator.cant.be.applied.1";
  2404                 Type first = argtypes.head;
  2405                 Type second = !isUnaryOp ? argtypes.tail.head : null;
  2406                 return diags.create(dkind, log.currentSource(), pos,
  2407                         key, name, first, second);
  2409             boolean hasLocation = false;
  2410             if (location == null) {
  2411                 location = site.tsym;
  2413             if (!location.name.isEmpty()) {
  2414                 if (location.kind == PCK && !site.tsym.exists()) {
  2415                     return diags.create(dkind, log.currentSource(), pos,
  2416                         "doesnt.exist", location);
  2418                 hasLocation = !location.name.equals(names._this) &&
  2419                         !location.name.equals(names._super);
  2421             boolean isConstructor = kind == ABSENT_MTH &&
  2422                     name == names.table.names.init;
  2423             KindName kindname = isConstructor ? KindName.CONSTRUCTOR : absentKind(kind);
  2424             Name idname = isConstructor ? site.tsym.name : name;
  2425             String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation);
  2426             if (hasLocation) {
  2427                 return diags.create(dkind, log.currentSource(), pos,
  2428                         errKey, kindname, idname, //symbol kindname, name
  2429                         typeargtypes, argtypes, //type parameters and arguments (if any)
  2430                         getLocationDiag(location, site)); //location kindname, type
  2432             else {
  2433                 return diags.create(dkind, log.currentSource(), pos,
  2434                         errKey, kindname, idname, //symbol kindname, name
  2435                         typeargtypes, argtypes); //type parameters and arguments (if any)
  2438         //where
  2439         private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) {
  2440             String key = "cant.resolve";
  2441             String suffix = hasLocation ? ".location" : "";
  2442             switch (kindname) {
  2443                 case METHOD:
  2444                 case CONSTRUCTOR: {
  2445                     suffix += ".args";
  2446                     suffix += hasTypeArgs ? ".params" : "";
  2449             return key + suffix;
  2451         private JCDiagnostic getLocationDiag(Symbol location, Type site) {
  2452             if (location.kind == VAR) {
  2453                 return diags.fragment("location.1",
  2454                     kindName(location),
  2455                     location,
  2456                     location.type);
  2457             } else {
  2458                 return diags.fragment("location",
  2459                     typeKindName(site),
  2460                     site,
  2461                     null);
  2466     /**
  2467      * InvalidSymbolError error class indicating that a given symbol
  2468      * (either a method, a constructor or an operand) is not applicable
  2469      * given an actual arguments/type argument list.
  2470      */
  2471     class InapplicableSymbolError extends ResolveError {
  2473         InapplicableSymbolError() {
  2474             super(WRONG_MTH, "inapplicable symbol error");
  2477         protected InapplicableSymbolError(int kind, String debugName) {
  2478             super(kind, debugName);
  2481         @Override
  2482         public String toString() {
  2483             return super.toString();
  2486         @Override
  2487         public boolean exists() {
  2488             return true;
  2491         @Override
  2492         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2493                 DiagnosticPosition pos,
  2494                 Symbol location,
  2495                 Type site,
  2496                 Name name,
  2497                 List<Type> argtypes,
  2498                 List<Type> typeargtypes) {
  2499             if (name == names.error)
  2500                 return null;
  2502             if (isOperator(name)) {
  2503                 boolean isUnaryOp = argtypes.size() == 1;
  2504                 String key = argtypes.size() == 1 ?
  2505                     "operator.cant.be.applied" :
  2506                     "operator.cant.be.applied.1";
  2507                 Type first = argtypes.head;
  2508                 Type second = !isUnaryOp ? argtypes.tail.head : null;
  2509                 return diags.create(dkind, log.currentSource(), pos,
  2510                         key, name, first, second);
  2512             else {
  2513                 Candidate c = errCandidate();
  2514                 Symbol ws = c.sym.asMemberOf(site, types);
  2515                 return diags.create(dkind, log.currentSource(), pos,
  2516                           "cant.apply.symbol" + (c.details != null ? ".1" : ""),
  2517                           kindName(ws),
  2518                           ws.name == names.init ? ws.owner.name : ws.name,
  2519                           methodArguments(ws.type.getParameterTypes()),
  2520                           methodArguments(argtypes),
  2521                           kindName(ws.owner),
  2522                           ws.owner.type,
  2523                           c.details);
  2527         @Override
  2528         public Symbol access(Name name, TypeSymbol location) {
  2529             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  2532         protected boolean shouldReport(Candidate c) {
  2533             return !c.isApplicable() &&
  2534                     (((c.sym.flags() & VARARGS) != 0 && c.step == VARARITY) ||
  2535                       (c.sym.flags() & VARARGS) == 0 && c.step == (boxingEnabled ? BOX : BASIC));
  2538         private Candidate errCandidate() {
  2539             for (Candidate c : currentResolutionContext.candidates) {
  2540                 if (shouldReport(c)) {
  2541                     return c;
  2544             Assert.error();
  2545             return null;
  2549     /**
  2550      * ResolveError error class indicating that a set of symbols
  2551      * (either methods, constructors or operands) is not applicable
  2552      * given an actual arguments/type argument list.
  2553      */
  2554     class InapplicableSymbolsError extends InapplicableSymbolError {
  2556         InapplicableSymbolsError() {
  2557             super(WRONG_MTHS, "inapplicable symbols");
  2560         @Override
  2561         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2562                 DiagnosticPosition pos,
  2563                 Symbol location,
  2564                 Type site,
  2565                 Name name,
  2566                 List<Type> argtypes,
  2567                 List<Type> typeargtypes) {
  2568             if (currentResolutionContext.candidates.nonEmpty()) {
  2569                 JCDiagnostic err = diags.create(dkind,
  2570                         log.currentSource(),
  2571                         pos,
  2572                         "cant.apply.symbols",
  2573                         name == names.init ? KindName.CONSTRUCTOR : absentKind(kind),
  2574                         getName(),
  2575                         argtypes);
  2576                 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(site));
  2577             } else {
  2578                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
  2579                     location, site, name, argtypes, typeargtypes);
  2583         //where
  2584         List<JCDiagnostic> candidateDetails(Type site) {
  2585             List<JCDiagnostic> details = List.nil();
  2586             for (Candidate c : currentResolutionContext.candidates) {
  2587                 if (!shouldReport(c)) continue;
  2588                 JCDiagnostic detailDiag = diags.fragment("inapplicable.method",
  2589                         Kinds.kindName(c.sym),
  2590                         c.sym.location(site, types),
  2591                         c.sym.asMemberOf(site, types),
  2592                         c.details);
  2593                 details = details.prepend(detailDiag);
  2595             return details.reverse();
  2598         private Name getName() {
  2599             Symbol sym = currentResolutionContext.candidates.head.sym;
  2600             return sym.name == names.init ?
  2601                 sym.owner.name :
  2602                 sym.name;
  2606     /**
  2607      * An InvalidSymbolError error class indicating that a symbol is not
  2608      * accessible from a given site
  2609      */
  2610     class AccessError extends InvalidSymbolError {
  2612         private Env<AttrContext> env;
  2613         private Type site;
  2615         AccessError(Symbol sym) {
  2616             this(null, null, sym);
  2619         AccessError(Env<AttrContext> env, Type site, Symbol sym) {
  2620             super(HIDDEN, sym, "access error");
  2621             this.env = env;
  2622             this.site = site;
  2623             if (debugResolve)
  2624                 log.error("proc.messager", sym + " @ " + site + " is inaccessible.");
  2627         @Override
  2628         public boolean exists() {
  2629             return false;
  2632         @Override
  2633         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2634                 DiagnosticPosition pos,
  2635                 Symbol location,
  2636                 Type site,
  2637                 Name name,
  2638                 List<Type> argtypes,
  2639                 List<Type> typeargtypes) {
  2640             if (sym.owner.type.tag == ERROR)
  2641                 return null;
  2643             if (sym.name == names.init && sym.owner != site.tsym) {
  2644                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
  2645                         pos, location, site, name, argtypes, typeargtypes);
  2647             else if ((sym.flags() & PUBLIC) != 0
  2648                 || (env != null && this.site != null
  2649                     && !isAccessible(env, this.site))) {
  2650                 return diags.create(dkind, log.currentSource(),
  2651                         pos, "not.def.access.class.intf.cant.access",
  2652                     sym, sym.location());
  2654             else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) {
  2655                 return diags.create(dkind, log.currentSource(),
  2656                         pos, "report.access", sym,
  2657                         asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
  2658                         sym.location());
  2660             else {
  2661                 return diags.create(dkind, log.currentSource(),
  2662                         pos, "not.def.public.cant.access", sym, sym.location());
  2667     /**
  2668      * InvalidSymbolError error class indicating that an instance member
  2669      * has erroneously been accessed from a static context.
  2670      */
  2671     class StaticError extends InvalidSymbolError {
  2673         StaticError(Symbol sym) {
  2674             super(STATICERR, sym, "static error");
  2677         @Override
  2678         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2679                 DiagnosticPosition pos,
  2680                 Symbol location,
  2681                 Type site,
  2682                 Name name,
  2683                 List<Type> argtypes,
  2684                 List<Type> typeargtypes) {
  2685             Symbol errSym = ((sym.kind == TYP && sym.type.tag == CLASS)
  2686                 ? types.erasure(sym.type).tsym
  2687                 : sym);
  2688             return diags.create(dkind, log.currentSource(), pos,
  2689                     "non-static.cant.be.ref", kindName(sym), errSym);
  2693     /**
  2694      * InvalidSymbolError error class indicating that a pair of symbols
  2695      * (either methods, constructors or operands) are ambiguous
  2696      * given an actual arguments/type argument list.
  2697      */
  2698     class AmbiguityError extends InvalidSymbolError {
  2700         /** The other maximally specific symbol */
  2701         Symbol sym2;
  2703         AmbiguityError(Symbol sym1, Symbol sym2) {
  2704             super(AMBIGUOUS, sym1, "ambiguity error");
  2705             this.sym2 = sym2;
  2708         @Override
  2709         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2710                 DiagnosticPosition pos,
  2711                 Symbol location,
  2712                 Type site,
  2713                 Name name,
  2714                 List<Type> argtypes,
  2715                 List<Type> typeargtypes) {
  2716             AmbiguityError pair = this;
  2717             while (true) {
  2718                 if (pair.sym.kind == AMBIGUOUS)
  2719                     pair = (AmbiguityError)pair.sym;
  2720                 else if (pair.sym2.kind == AMBIGUOUS)
  2721                     pair = (AmbiguityError)pair.sym2;
  2722                 else break;
  2724             Name sname = pair.sym.name;
  2725             if (sname == names.init) sname = pair.sym.owner.name;
  2726             return diags.create(dkind, log.currentSource(),
  2727                       pos, "ref.ambiguous", sname,
  2728                       kindName(pair.sym),
  2729                       pair.sym,
  2730                       pair.sym.location(site, types),
  2731                       kindName(pair.sym2),
  2732                       pair.sym2,
  2733                       pair.sym2.location(site, types));
  2737     enum MethodResolutionPhase {
  2738         BASIC(false, false),
  2739         BOX(true, false),
  2740         VARARITY(true, true);
  2742         boolean isBoxingRequired;
  2743         boolean isVarargsRequired;
  2745         MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) {
  2746            this.isBoxingRequired = isBoxingRequired;
  2747            this.isVarargsRequired = isVarargsRequired;
  2750         public boolean isBoxingRequired() {
  2751             return isBoxingRequired;
  2754         public boolean isVarargsRequired() {
  2755             return isVarargsRequired;
  2758         public boolean isApplicable(boolean boxingEnabled, boolean varargsEnabled) {
  2759             return (varargsEnabled || !isVarargsRequired) &&
  2760                    (boxingEnabled || !isBoxingRequired);
  2764     final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
  2766     /**
  2767      * A resolution context is used to keep track of intermediate results of
  2768      * overload resolution, such as list of method that are not applicable
  2769      * (used to generate more precise diagnostics) and so on. Resolution contexts
  2770      * can be nested - this means that when each overload resolution routine should
  2771      * work within the resolution context it created.
  2772      */
  2773     class MethodResolutionContext {
  2775         private List<Candidate> candidates = List.nil();
  2777         private Map<MethodResolutionPhase, Symbol> resolutionCache =
  2778             new EnumMap<MethodResolutionPhase, Symbol>(MethodResolutionPhase.class);
  2780         private MethodResolutionPhase step = null;
  2782         private boolean internalResolution = false;
  2784         private MethodResolutionPhase firstErroneousResolutionPhase() {
  2785             MethodResolutionPhase bestSoFar = BASIC;
  2786             Symbol sym = methodNotFound;
  2787             List<MethodResolutionPhase> steps = methodResolutionSteps;
  2788             while (steps.nonEmpty() &&
  2789                    steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  2790                    sym.kind >= WRONG_MTHS) {
  2791                 sym = resolutionCache.get(steps.head);
  2792                 bestSoFar = steps.head;
  2793                 steps = steps.tail;
  2795             return bestSoFar;
  2798         void addInapplicableCandidate(Symbol sym, JCDiagnostic details) {
  2799             Candidate c = new Candidate(currentResolutionContext.step, sym, details, null);
  2800             if (!candidates.contains(c))
  2801                 candidates = candidates.append(c);
  2804         void addApplicableCandidate(Symbol sym, Type mtype) {
  2805             Candidate c = new Candidate(currentResolutionContext.step, sym, null, mtype);
  2806             candidates = candidates.append(c);
  2809         /**
  2810          * This class represents an overload resolution candidate. There are two
  2811          * kinds of candidates: applicable methods and inapplicable methods;
  2812          * applicable methods have a pointer to the instantiated method type,
  2813          * while inapplicable candidates contain further details about the
  2814          * reason why the method has been considered inapplicable.
  2815          */
  2816         class Candidate {
  2818             final MethodResolutionPhase step;
  2819             final Symbol sym;
  2820             final JCDiagnostic details;
  2821             final Type mtype;
  2823             private Candidate(MethodResolutionPhase step, Symbol sym, JCDiagnostic details, Type mtype) {
  2824                 this.step = step;
  2825                 this.sym = sym;
  2826                 this.details = details;
  2827                 this.mtype = mtype;
  2830             @Override
  2831             public boolean equals(Object o) {
  2832                 if (o instanceof Candidate) {
  2833                     Symbol s1 = this.sym;
  2834                     Symbol s2 = ((Candidate)o).sym;
  2835                     if  ((s1 != s2 &&
  2836                         (s1.overrides(s2, s1.owner.type.tsym, types, false) ||
  2837                         (s2.overrides(s1, s2.owner.type.tsym, types, false)))) ||
  2838                         ((s1.isConstructor() || s2.isConstructor()) && s1.owner != s2.owner))
  2839                         return true;
  2841                 return false;
  2844             boolean isApplicable() {
  2845                 return mtype != null;
  2850     MethodResolutionContext currentResolutionContext = null;

mercurial