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

Tue, 25 Sep 2012 11:55:34 +0100

author
mcimadamore
date
Tue, 25 Sep 2012 11:55:34 +0100
changeset 1337
2eca84194807
parent 1335
99983a4a593b
child 1338
ad2ca2a4ab5e
permissions
-rw-r--r--

7175433: Inference cleanup: add helper class to handle inference variables
Summary: Add class to handle inference variables instantiation and associated info
Reviewed-by: jjg, dlsmith

     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))));
   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                 final JCDiagnostic details = sym.kind == WRONG_MTH ?
  1976                                 currentResolutionContext.candidates.head.details :
  1977                                 null;
  1978                 Symbol errSym = new ResolveError(WRONG_MTH, "diamond error") {
  1979                     @Override
  1980                     JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos,
  1981                             Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
  1982                         String key = details == null ?
  1983                             "cant.apply.diamond" :
  1984                             "cant.apply.diamond.1";
  1985                         return diags.create(dkind, log.currentSource(), pos, key,
  1986                                 diags.fragment("diamond", site.tsym), details);
  1988                 };
  1989                 MethodResolutionPhase errPhase = currentResolutionContext.firstErroneousResolutionPhase();
  1990                 sym = access(errSym, pos, site, names.init, true, argtypes, typeargtypes);
  1991                 env.info.varArgs = errPhase.isVarargsRequired();
  1993             return sym;
  1995         finally {
  1996             currentResolutionContext = prevResolutionContext;
  2000     /** This method scans all the constructor symbol in a given class scope -
  2001      *  assuming that the original scope contains a constructor of the kind:
  2002      *  {@code Foo(X x, Y y)}, where X,Y are class type-variables declared in Foo,
  2003      *  a method check is executed against the modified constructor type:
  2004      *  {@code <X,Y>Foo<X,Y>(X x, Y y)}. This is crucial in order to enable diamond
  2005      *  inference. The inferred return type of the synthetic constructor IS
  2006      *  the inferred type for the diamond operator.
  2007      */
  2008     private Symbol findDiamond(Env<AttrContext> env,
  2009                               Type site,
  2010                               List<Type> argtypes,
  2011                               List<Type> typeargtypes,
  2012                               boolean allowBoxing,
  2013                               boolean useVarargs) {
  2014         Symbol bestSoFar = methodNotFound;
  2015         for (Scope.Entry e = site.tsym.members().lookup(names.init);
  2016              e.scope != null;
  2017              e = e.next()) {
  2018             //- System.out.println(" e " + e.sym);
  2019             if (e.sym.kind == MTH &&
  2020                 (e.sym.flags_field & SYNTHETIC) == 0) {
  2021                     List<Type> oldParams = e.sym.type.tag == FORALL ?
  2022                             ((ForAll)e.sym.type).tvars :
  2023                             List.<Type>nil();
  2024                     Type constrType = new ForAll(site.tsym.type.getTypeArguments().appendList(oldParams),
  2025                             types.createMethodTypeWithReturn(e.sym.type.asMethodType(), site));
  2026                     bestSoFar = selectBest(env, site, argtypes, typeargtypes,
  2027                             new MethodSymbol(e.sym.flags(), names.init, constrType, site.tsym),
  2028                             bestSoFar,
  2029                             allowBoxing,
  2030                             useVarargs,
  2031                             false);
  2034         return bestSoFar;
  2037     /** Resolve constructor.
  2038      *  @param pos       The position to use for error reporting.
  2039      *  @param env       The environment current at the constructor invocation.
  2040      *  @param site      The type of class for which a constructor is searched.
  2041      *  @param argtypes  The types of the constructor invocation's value
  2042      *                   arguments.
  2043      *  @param typeargtypes  The types of the constructor invocation's type
  2044      *                   arguments.
  2045      *  @param allowBoxing Allow boxing and varargs conversions.
  2046      *  @param useVarargs Box trailing arguments into an array for varargs.
  2047      */
  2048     Symbol resolveConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  2049                               Type site, List<Type> argtypes,
  2050                               List<Type> typeargtypes,
  2051                               boolean allowBoxing,
  2052                               boolean useVarargs) {
  2053         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  2054         try {
  2055             currentResolutionContext = new MethodResolutionContext();
  2056             return findConstructor(pos, env, site, argtypes, typeargtypes, allowBoxing, useVarargs);
  2058         finally {
  2059             currentResolutionContext = prevResolutionContext;
  2063     Symbol findConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  2064                               Type site, List<Type> argtypes,
  2065                               List<Type> typeargtypes,
  2066                               boolean allowBoxing,
  2067                               boolean useVarargs) {
  2068         Symbol sym = findMethod(env, site,
  2069                                     names.init, argtypes,
  2070                                     typeargtypes, allowBoxing,
  2071                                     useVarargs, false);
  2072         chk.checkDeprecated(pos, env.info.scope.owner, sym);
  2073         return sym;
  2076     /** Resolve a constructor, throw a fatal error if not found.
  2077      *  @param pos       The position to use for error reporting.
  2078      *  @param env       The environment current at the method invocation.
  2079      *  @param site      The type to be constructed.
  2080      *  @param argtypes  The types of the invocation's value arguments.
  2081      *  @param typeargtypes  The types of the invocation's type arguments.
  2082      */
  2083     public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  2084                                         Type site,
  2085                                         List<Type> argtypes,
  2086                                         List<Type> typeargtypes) {
  2087         MethodResolutionContext resolveContext = new MethodResolutionContext();
  2088         resolveContext.internalResolution = true;
  2089         Symbol sym = resolveConstructor(resolveContext, pos, env, site, argtypes, typeargtypes);
  2090         if (sym.kind == MTH) return (MethodSymbol)sym;
  2091         else throw new FatalError(
  2092                  diags.fragment("fatal.err.cant.locate.ctor", site));
  2095     /** Resolve operator.
  2096      *  @param pos       The position to use for error reporting.
  2097      *  @param optag     The tag of the operation tree.
  2098      *  @param env       The environment current at the operation.
  2099      *  @param argtypes  The types of the operands.
  2100      */
  2101     Symbol resolveOperator(DiagnosticPosition pos, JCTree.Tag optag,
  2102                            Env<AttrContext> env, List<Type> argtypes) {
  2103         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  2104         try {
  2105             currentResolutionContext = new MethodResolutionContext();
  2106             Name name = treeinfo.operatorName(optag);
  2107             Symbol sym = findMethod(env, syms.predefClass.type, name, argtypes,
  2108                                     null, false, false, true);
  2109             if (boxingEnabled && sym.kind >= WRONG_MTHS)
  2110                 sym = findMethod(env, syms.predefClass.type, name, argtypes,
  2111                                  null, true, false, true);
  2112             return access(sym, pos, env.enclClass.sym.type, name,
  2113                           false, argtypes, null);
  2115         finally {
  2116             currentResolutionContext = prevResolutionContext;
  2120     /** Resolve operator.
  2121      *  @param pos       The position to use for error reporting.
  2122      *  @param optag     The tag of the operation tree.
  2123      *  @param env       The environment current at the operation.
  2124      *  @param arg       The type of the operand.
  2125      */
  2126     Symbol resolveUnaryOperator(DiagnosticPosition pos, JCTree.Tag optag, Env<AttrContext> env, Type arg) {
  2127         return resolveOperator(pos, optag, env, List.of(arg));
  2130     /** Resolve binary operator.
  2131      *  @param pos       The position to use for error reporting.
  2132      *  @param optag     The tag of the operation tree.
  2133      *  @param env       The environment current at the operation.
  2134      *  @param left      The types of the left operand.
  2135      *  @param right     The types of the right operand.
  2136      */
  2137     Symbol resolveBinaryOperator(DiagnosticPosition pos,
  2138                                  JCTree.Tag optag,
  2139                                  Env<AttrContext> env,
  2140                                  Type left,
  2141                                  Type right) {
  2142         return resolveOperator(pos, optag, env, List.of(left, right));
  2145     /**
  2146      * Resolve `c.name' where name == this or name == super.
  2147      * @param pos           The position to use for error reporting.
  2148      * @param env           The environment current at the expression.
  2149      * @param c             The qualifier.
  2150      * @param name          The identifier's name.
  2151      */
  2152     Symbol resolveSelf(DiagnosticPosition pos,
  2153                        Env<AttrContext> env,
  2154                        TypeSymbol c,
  2155                        Name name) {
  2156         Env<AttrContext> env1 = env;
  2157         boolean staticOnly = false;
  2158         while (env1.outer != null) {
  2159             if (isStatic(env1)) staticOnly = true;
  2160             if (env1.enclClass.sym == c) {
  2161                 Symbol sym = env1.info.scope.lookup(name).sym;
  2162                 if (sym != null) {
  2163                     if (staticOnly) sym = new StaticError(sym);
  2164                     return access(sym, pos, env.enclClass.sym.type,
  2165                                   name, true);
  2168             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  2169             env1 = env1.outer;
  2171         log.error(pos, "not.encl.class", c);
  2172         return syms.errSymbol;
  2175     /**
  2176      * Resolve `c.this' for an enclosing class c that contains the
  2177      * named member.
  2178      * @param pos           The position to use for error reporting.
  2179      * @param env           The environment current at the expression.
  2180      * @param member        The member that must be contained in the result.
  2181      */
  2182     Symbol resolveSelfContaining(DiagnosticPosition pos,
  2183                                  Env<AttrContext> env,
  2184                                  Symbol member,
  2185                                  boolean isSuperCall) {
  2186         Name name = names._this;
  2187         Env<AttrContext> env1 = isSuperCall ? env.outer : env;
  2188         boolean staticOnly = false;
  2189         if (env1 != null) {
  2190             while (env1 != null && env1.outer != null) {
  2191                 if (isStatic(env1)) staticOnly = true;
  2192                 if (env1.enclClass.sym.isSubClass(member.owner, types)) {
  2193                     Symbol sym = env1.info.scope.lookup(name).sym;
  2194                     if (sym != null) {
  2195                         if (staticOnly) sym = new StaticError(sym);
  2196                         return access(sym, pos, env.enclClass.sym.type,
  2197                                       name, true);
  2200                 if ((env1.enclClass.sym.flags() & STATIC) != 0)
  2201                     staticOnly = true;
  2202                 env1 = env1.outer;
  2205         log.error(pos, "encl.class.required", member);
  2206         return syms.errSymbol;
  2209     /**
  2210      * Resolve an appropriate implicit this instance for t's container.
  2211      * JLS 8.8.5.1 and 15.9.2
  2212      */
  2213     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
  2214         return resolveImplicitThis(pos, env, t, false);
  2217     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t, boolean isSuperCall) {
  2218         Type thisType = (((t.tsym.owner.kind & (MTH|VAR)) != 0)
  2219                          ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
  2220                          : resolveSelfContaining(pos, env, t.tsym, isSuperCall)).type;
  2221         if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
  2222             log.error(pos, "cant.ref.before.ctor.called", "this");
  2223         return thisType;
  2226 /* ***************************************************************************
  2227  *  ResolveError classes, indicating error situations when accessing symbols
  2228  ****************************************************************************/
  2230     //used by TransTypes when checking target type of synthetic cast
  2231     public void logAccessErrorInternal(Env<AttrContext> env, JCTree tree, Type type) {
  2232         AccessError error = new AccessError(env, env.enclClass.type, type.tsym);
  2233         logResolveError(error, tree.pos(), env.enclClass.sym, env.enclClass.type, null, null, null);
  2235     //where
  2236     private void logResolveError(ResolveError error,
  2237             DiagnosticPosition pos,
  2238             Symbol location,
  2239             Type site,
  2240             Name name,
  2241             List<Type> argtypes,
  2242             List<Type> typeargtypes) {
  2243         JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
  2244                 pos, location, site, name, argtypes, typeargtypes);
  2245         if (d != null) {
  2246             d.setFlag(DiagnosticFlag.RESOLVE_ERROR);
  2247             log.report(d);
  2251     private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
  2253     public Object methodArguments(List<Type> argtypes) {
  2254         return argtypes == null || argtypes.isEmpty() ? noArgs : argtypes;
  2257     /**
  2258      * Root class for resolution errors. Subclass of ResolveError
  2259      * represent a different kinds of resolution error - as such they must
  2260      * specify how they map into concrete compiler diagnostics.
  2261      */
  2262     private abstract class ResolveError extends Symbol {
  2264         /** The name of the kind of error, for debugging only. */
  2265         final String debugName;
  2267         ResolveError(int kind, String debugName) {
  2268             super(kind, 0, null, null, null);
  2269             this.debugName = debugName;
  2272         @Override
  2273         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
  2274             throw new AssertionError();
  2277         @Override
  2278         public String toString() {
  2279             return debugName;
  2282         @Override
  2283         public boolean exists() {
  2284             return false;
  2287         /**
  2288          * Create an external representation for this erroneous symbol to be
  2289          * used during attribution - by default this returns the symbol of a
  2290          * brand new error type which stores the original type found
  2291          * during resolution.
  2293          * @param name     the name used during resolution
  2294          * @param location the location from which the symbol is accessed
  2295          */
  2296         protected Symbol access(Name name, TypeSymbol location) {
  2297             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  2300         /**
  2301          * Create a diagnostic representing this resolution error.
  2303          * @param dkind     The kind of the diagnostic to be created (e.g error).
  2304          * @param pos       The position to be used for error reporting.
  2305          * @param site      The original type from where the selection took place.
  2306          * @param name      The name of the symbol to be resolved.
  2307          * @param argtypes  The invocation's value arguments,
  2308          *                  if we looked for a method.
  2309          * @param typeargtypes  The invocation's type arguments,
  2310          *                      if we looked for a method.
  2311          */
  2312         abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2313                 DiagnosticPosition pos,
  2314                 Symbol location,
  2315                 Type site,
  2316                 Name name,
  2317                 List<Type> argtypes,
  2318                 List<Type> typeargtypes);
  2320         /**
  2321          * A name designates an operator if it consists
  2322          * of a non-empty sequence of operator symbols {@literal +-~!/*%&|^<>= }
  2323          */
  2324         boolean isOperator(Name name) {
  2325             int i = 0;
  2326             while (i < name.getByteLength() &&
  2327                    "+-~!*/%&|^<>=".indexOf(name.getByteAt(i)) >= 0) i++;
  2328             return i > 0 && i == name.getByteLength();
  2332     /**
  2333      * This class is the root class of all resolution errors caused by
  2334      * an invalid symbol being found during resolution.
  2335      */
  2336     abstract class InvalidSymbolError extends ResolveError {
  2338         /** The invalid symbol found during resolution */
  2339         Symbol sym;
  2341         InvalidSymbolError(int kind, Symbol sym, String debugName) {
  2342             super(kind, debugName);
  2343             this.sym = sym;
  2346         @Override
  2347         public boolean exists() {
  2348             return true;
  2351         @Override
  2352         public String toString() {
  2353              return super.toString() + " wrongSym=" + sym;
  2356         @Override
  2357         public Symbol access(Name name, TypeSymbol location) {
  2358             if (sym.kind >= AMBIGUOUS)
  2359                 return ((ResolveError)sym).access(name, location);
  2360             else if ((sym.kind & ERRONEOUS) == 0 && (sym.kind & TYP) != 0)
  2361                 return types.createErrorType(name, location, sym.type).tsym;
  2362             else
  2363                 return sym;
  2367     /**
  2368      * InvalidSymbolError error class indicating that a symbol matching a
  2369      * given name does not exists in a given site.
  2370      */
  2371     class SymbolNotFoundError extends ResolveError {
  2373         SymbolNotFoundError(int kind) {
  2374             super(kind, "symbol not found error");
  2377         @Override
  2378         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2379                 DiagnosticPosition pos,
  2380                 Symbol location,
  2381                 Type site,
  2382                 Name name,
  2383                 List<Type> argtypes,
  2384                 List<Type> typeargtypes) {
  2385             argtypes = argtypes == null ? List.<Type>nil() : argtypes;
  2386             typeargtypes = typeargtypes == null ? List.<Type>nil() : typeargtypes;
  2387             if (name == names.error)
  2388                 return null;
  2390             if (isOperator(name)) {
  2391                 boolean isUnaryOp = argtypes.size() == 1;
  2392                 String key = argtypes.size() == 1 ?
  2393                     "operator.cant.be.applied" :
  2394                     "operator.cant.be.applied.1";
  2395                 Type first = argtypes.head;
  2396                 Type second = !isUnaryOp ? argtypes.tail.head : null;
  2397                 return diags.create(dkind, log.currentSource(), pos,
  2398                         key, name, first, second);
  2400             boolean hasLocation = false;
  2401             if (location == null) {
  2402                 location = site.tsym;
  2404             if (!location.name.isEmpty()) {
  2405                 if (location.kind == PCK && !site.tsym.exists()) {
  2406                     return diags.create(dkind, log.currentSource(), pos,
  2407                         "doesnt.exist", location);
  2409                 hasLocation = !location.name.equals(names._this) &&
  2410                         !location.name.equals(names._super);
  2412             boolean isConstructor = kind == ABSENT_MTH &&
  2413                     name == names.table.names.init;
  2414             KindName kindname = isConstructor ? KindName.CONSTRUCTOR : absentKind(kind);
  2415             Name idname = isConstructor ? site.tsym.name : name;
  2416             String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation);
  2417             if (hasLocation) {
  2418                 return diags.create(dkind, log.currentSource(), pos,
  2419                         errKey, kindname, idname, //symbol kindname, name
  2420                         typeargtypes, argtypes, //type parameters and arguments (if any)
  2421                         getLocationDiag(location, site)); //location kindname, type
  2423             else {
  2424                 return diags.create(dkind, log.currentSource(), pos,
  2425                         errKey, kindname, idname, //symbol kindname, name
  2426                         typeargtypes, argtypes); //type parameters and arguments (if any)
  2429         //where
  2430         private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) {
  2431             String key = "cant.resolve";
  2432             String suffix = hasLocation ? ".location" : "";
  2433             switch (kindname) {
  2434                 case METHOD:
  2435                 case CONSTRUCTOR: {
  2436                     suffix += ".args";
  2437                     suffix += hasTypeArgs ? ".params" : "";
  2440             return key + suffix;
  2442         private JCDiagnostic getLocationDiag(Symbol location, Type site) {
  2443             if (location.kind == VAR) {
  2444                 return diags.fragment("location.1",
  2445                     kindName(location),
  2446                     location,
  2447                     location.type);
  2448             } else {
  2449                 return diags.fragment("location",
  2450                     typeKindName(site),
  2451                     site,
  2452                     null);
  2457     /**
  2458      * InvalidSymbolError error class indicating that a given symbol
  2459      * (either a method, a constructor or an operand) is not applicable
  2460      * given an actual arguments/type argument list.
  2461      */
  2462     class InapplicableSymbolError extends ResolveError {
  2464         InapplicableSymbolError() {
  2465             super(WRONG_MTH, "inapplicable symbol error");
  2468         protected InapplicableSymbolError(int kind, String debugName) {
  2469             super(kind, debugName);
  2472         @Override
  2473         public String toString() {
  2474             return super.toString();
  2477         @Override
  2478         public boolean exists() {
  2479             return true;
  2482         @Override
  2483         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2484                 DiagnosticPosition pos,
  2485                 Symbol location,
  2486                 Type site,
  2487                 Name name,
  2488                 List<Type> argtypes,
  2489                 List<Type> typeargtypes) {
  2490             if (name == names.error)
  2491                 return null;
  2493             if (isOperator(name)) {
  2494                 boolean isUnaryOp = argtypes.size() == 1;
  2495                 String key = argtypes.size() == 1 ?
  2496                     "operator.cant.be.applied" :
  2497                     "operator.cant.be.applied.1";
  2498                 Type first = argtypes.head;
  2499                 Type second = !isUnaryOp ? argtypes.tail.head : null;
  2500                 return diags.create(dkind, log.currentSource(), pos,
  2501                         key, name, first, second);
  2503             else {
  2504                 Candidate c = errCandidate();
  2505                 Symbol ws = c.sym.asMemberOf(site, types);
  2506                 return diags.create(dkind, log.currentSource(), pos,
  2507                           "cant.apply.symbol" + (c.details != null ? ".1" : ""),
  2508                           kindName(ws),
  2509                           ws.name == names.init ? ws.owner.name : ws.name,
  2510                           methodArguments(ws.type.getParameterTypes()),
  2511                           methodArguments(argtypes),
  2512                           kindName(ws.owner),
  2513                           ws.owner.type,
  2514                           c.details);
  2518         @Override
  2519         public Symbol access(Name name, TypeSymbol location) {
  2520             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  2523         protected boolean shouldReport(Candidate c) {
  2524             return !c.isApplicable() &&
  2525                     (((c.sym.flags() & VARARGS) != 0 && c.step == VARARITY) ||
  2526                       (c.sym.flags() & VARARGS) == 0 && c.step == (boxingEnabled ? BOX : BASIC));
  2529         private Candidate errCandidate() {
  2530             for (Candidate c : currentResolutionContext.candidates) {
  2531                 if (shouldReport(c)) {
  2532                     return c;
  2535             Assert.error();
  2536             return null;
  2540     /**
  2541      * ResolveError error class indicating that a set of symbols
  2542      * (either methods, constructors or operands) is not applicable
  2543      * given an actual arguments/type argument list.
  2544      */
  2545     class InapplicableSymbolsError extends InapplicableSymbolError {
  2547         InapplicableSymbolsError() {
  2548             super(WRONG_MTHS, "inapplicable symbols");
  2551         @Override
  2552         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2553                 DiagnosticPosition pos,
  2554                 Symbol location,
  2555                 Type site,
  2556                 Name name,
  2557                 List<Type> argtypes,
  2558                 List<Type> typeargtypes) {
  2559             if (currentResolutionContext.candidates.nonEmpty()) {
  2560                 JCDiagnostic err = diags.create(dkind,
  2561                         log.currentSource(),
  2562                         pos,
  2563                         "cant.apply.symbols",
  2564                         name == names.init ? KindName.CONSTRUCTOR : absentKind(kind),
  2565                         getName(),
  2566                         argtypes);
  2567                 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(site));
  2568             } else {
  2569                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
  2570                     location, site, name, argtypes, typeargtypes);
  2574         //where
  2575         List<JCDiagnostic> candidateDetails(Type site) {
  2576             List<JCDiagnostic> details = List.nil();
  2577             for (Candidate c : currentResolutionContext.candidates) {
  2578                 if (!shouldReport(c)) continue;
  2579                 JCDiagnostic detailDiag = diags.fragment("inapplicable.method",
  2580                         Kinds.kindName(c.sym),
  2581                         c.sym.location(site, types),
  2582                         c.sym.asMemberOf(site, types),
  2583                         c.details);
  2584                 details = details.prepend(detailDiag);
  2586             return details.reverse();
  2589         private Name getName() {
  2590             Symbol sym = currentResolutionContext.candidates.head.sym;
  2591             return sym.name == names.init ?
  2592                 sym.owner.name :
  2593                 sym.name;
  2597     /**
  2598      * An InvalidSymbolError error class indicating that a symbol is not
  2599      * accessible from a given site
  2600      */
  2601     class AccessError extends InvalidSymbolError {
  2603         private Env<AttrContext> env;
  2604         private Type site;
  2606         AccessError(Symbol sym) {
  2607             this(null, null, sym);
  2610         AccessError(Env<AttrContext> env, Type site, Symbol sym) {
  2611             super(HIDDEN, sym, "access error");
  2612             this.env = env;
  2613             this.site = site;
  2614             if (debugResolve)
  2615                 log.error("proc.messager", sym + " @ " + site + " is inaccessible.");
  2618         @Override
  2619         public boolean exists() {
  2620             return false;
  2623         @Override
  2624         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2625                 DiagnosticPosition pos,
  2626                 Symbol location,
  2627                 Type site,
  2628                 Name name,
  2629                 List<Type> argtypes,
  2630                 List<Type> typeargtypes) {
  2631             if (sym.owner.type.tag == ERROR)
  2632                 return null;
  2634             if (sym.name == names.init && sym.owner != site.tsym) {
  2635                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
  2636                         pos, location, site, name, argtypes, typeargtypes);
  2638             else if ((sym.flags() & PUBLIC) != 0
  2639                 || (env != null && this.site != null
  2640                     && !isAccessible(env, this.site))) {
  2641                 return diags.create(dkind, log.currentSource(),
  2642                         pos, "not.def.access.class.intf.cant.access",
  2643                     sym, sym.location());
  2645             else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) {
  2646                 return diags.create(dkind, log.currentSource(),
  2647                         pos, "report.access", sym,
  2648                         asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
  2649                         sym.location());
  2651             else {
  2652                 return diags.create(dkind, log.currentSource(),
  2653                         pos, "not.def.public.cant.access", sym, sym.location());
  2658     /**
  2659      * InvalidSymbolError error class indicating that an instance member
  2660      * has erroneously been accessed from a static context.
  2661      */
  2662     class StaticError extends InvalidSymbolError {
  2664         StaticError(Symbol sym) {
  2665             super(STATICERR, sym, "static error");
  2668         @Override
  2669         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2670                 DiagnosticPosition pos,
  2671                 Symbol location,
  2672                 Type site,
  2673                 Name name,
  2674                 List<Type> argtypes,
  2675                 List<Type> typeargtypes) {
  2676             Symbol errSym = ((sym.kind == TYP && sym.type.tag == CLASS)
  2677                 ? types.erasure(sym.type).tsym
  2678                 : sym);
  2679             return diags.create(dkind, log.currentSource(), pos,
  2680                     "non-static.cant.be.ref", kindName(sym), errSym);
  2684     /**
  2685      * InvalidSymbolError error class indicating that a pair of symbols
  2686      * (either methods, constructors or operands) are ambiguous
  2687      * given an actual arguments/type argument list.
  2688      */
  2689     class AmbiguityError extends InvalidSymbolError {
  2691         /** The other maximally specific symbol */
  2692         Symbol sym2;
  2694         AmbiguityError(Symbol sym1, Symbol sym2) {
  2695             super(AMBIGUOUS, sym1, "ambiguity error");
  2696             this.sym2 = sym2;
  2699         @Override
  2700         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2701                 DiagnosticPosition pos,
  2702                 Symbol location,
  2703                 Type site,
  2704                 Name name,
  2705                 List<Type> argtypes,
  2706                 List<Type> typeargtypes) {
  2707             AmbiguityError pair = this;
  2708             while (true) {
  2709                 if (pair.sym.kind == AMBIGUOUS)
  2710                     pair = (AmbiguityError)pair.sym;
  2711                 else if (pair.sym2.kind == AMBIGUOUS)
  2712                     pair = (AmbiguityError)pair.sym2;
  2713                 else break;
  2715             Name sname = pair.sym.name;
  2716             if (sname == names.init) sname = pair.sym.owner.name;
  2717             return diags.create(dkind, log.currentSource(),
  2718                       pos, "ref.ambiguous", sname,
  2719                       kindName(pair.sym),
  2720                       pair.sym,
  2721                       pair.sym.location(site, types),
  2722                       kindName(pair.sym2),
  2723                       pair.sym2,
  2724                       pair.sym2.location(site, types));
  2728     enum MethodResolutionPhase {
  2729         BASIC(false, false),
  2730         BOX(true, false),
  2731         VARARITY(true, true);
  2733         boolean isBoxingRequired;
  2734         boolean isVarargsRequired;
  2736         MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) {
  2737            this.isBoxingRequired = isBoxingRequired;
  2738            this.isVarargsRequired = isVarargsRequired;
  2741         public boolean isBoxingRequired() {
  2742             return isBoxingRequired;
  2745         public boolean isVarargsRequired() {
  2746             return isVarargsRequired;
  2749         public boolean isApplicable(boolean boxingEnabled, boolean varargsEnabled) {
  2750             return (varargsEnabled || !isVarargsRequired) &&
  2751                    (boxingEnabled || !isBoxingRequired);
  2755     final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
  2757     /**
  2758      * A resolution context is used to keep track of intermediate results of
  2759      * overload resolution, such as list of method that are not applicable
  2760      * (used to generate more precise diagnostics) and so on. Resolution contexts
  2761      * can be nested - this means that when each overload resolution routine should
  2762      * work within the resolution context it created.
  2763      */
  2764     class MethodResolutionContext {
  2766         private List<Candidate> candidates = List.nil();
  2768         private Map<MethodResolutionPhase, Symbol> resolutionCache =
  2769             new EnumMap<MethodResolutionPhase, Symbol>(MethodResolutionPhase.class);
  2771         private MethodResolutionPhase step = null;
  2773         private boolean internalResolution = false;
  2775         private MethodResolutionPhase firstErroneousResolutionPhase() {
  2776             MethodResolutionPhase bestSoFar = BASIC;
  2777             Symbol sym = methodNotFound;
  2778             List<MethodResolutionPhase> steps = methodResolutionSteps;
  2779             while (steps.nonEmpty() &&
  2780                    steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  2781                    sym.kind >= WRONG_MTHS) {
  2782                 sym = resolutionCache.get(steps.head);
  2783                 bestSoFar = steps.head;
  2784                 steps = steps.tail;
  2786             return bestSoFar;
  2789         void addInapplicableCandidate(Symbol sym, JCDiagnostic details) {
  2790             Candidate c = new Candidate(currentResolutionContext.step, sym, details, null);
  2791             if (!candidates.contains(c))
  2792                 candidates = candidates.append(c);
  2795         void addApplicableCandidate(Symbol sym, Type mtype) {
  2796             Candidate c = new Candidate(currentResolutionContext.step, sym, null, mtype);
  2797             candidates = candidates.append(c);
  2800         /**
  2801          * This class represents an overload resolution candidate. There are two
  2802          * kinds of candidates: applicable methods and inapplicable methods;
  2803          * applicable methods have a pointer to the instantiated method type,
  2804          * while inapplicable candidates contain further details about the
  2805          * reason why the method has been considered inapplicable.
  2806          */
  2807         class Candidate {
  2809             final MethodResolutionPhase step;
  2810             final Symbol sym;
  2811             final JCDiagnostic details;
  2812             final Type mtype;
  2814             private Candidate(MethodResolutionPhase step, Symbol sym, JCDiagnostic details, Type mtype) {
  2815                 this.step = step;
  2816                 this.sym = sym;
  2817                 this.details = details;
  2818                 this.mtype = mtype;
  2821             @Override
  2822             public boolean equals(Object o) {
  2823                 if (o instanceof Candidate) {
  2824                     Symbol s1 = this.sym;
  2825                     Symbol s2 = ((Candidate)o).sym;
  2826                     if  ((s1 != s2 &&
  2827                         (s1.overrides(s2, s1.owner.type.tsym, types, false) ||
  2828                         (s2.overrides(s1, s2.owner.type.tsym, types, false)))) ||
  2829                         ((s1.isConstructor() || s2.isConstructor()) && s1.owner != s2.owner))
  2830                         return true;
  2832                 return false;
  2835             boolean isApplicable() {
  2836                 return mtype != null;
  2841     MethodResolutionContext currentResolutionContext = null;

mercurial