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

Sat, 29 Sep 2012 09:00:58 -0700

author
ksrini
date
Sat, 29 Sep 2012 09:00:58 -0700
changeset 1346
20e4a54b1629
parent 1342
1a65d6565b45
child 1347
1408af4cd8b0
permissions
-rw-r--r--

7198582: (java) Minor refactor of JavacParser
Reviewed-by: jjg, ksrini
Contributed-by: jan.lahoda@oracle.com

     1 /*
     2  * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.comp;
    28 import com.sun.tools.javac.api.Formattable.LocalizedString;
    29 import com.sun.tools.javac.code.*;
    30 import com.sun.tools.javac.code.Symbol.*;
    31 import com.sun.tools.javac.code.Type.*;
    32 import com.sun.tools.javac.comp.Attr.ResultInfo;
    33 import com.sun.tools.javac.comp.Check.CheckContext;
    34 import com.sun.tools.javac.comp.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.Iterator;
    52 import java.util.Map;
    53 import java.util.Set;
    55 import javax.lang.model.element.ElementVisitor;
    57 import static com.sun.tools.javac.code.Flags.*;
    58 import static com.sun.tools.javac.code.Flags.BLOCK;
    59 import static com.sun.tools.javac.code.Kinds.*;
    60 import static com.sun.tools.javac.code.Kinds.ERRONEOUS;
    61 import static com.sun.tools.javac.code.TypeTags.*;
    62 import static com.sun.tools.javac.comp.Resolve.MethodResolutionPhase.*;
    63 import static com.sun.tools.javac.tree.JCTree.Tag.*;
    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     protected static boolean isStatic(Env<AttrContext> env) {
   255         return env.info.staticLevel > env.outer.info.staticLevel;
   256     }
   258     /** An environment is an "initializer" if it is a constructor or
   259      *  an instance initializer.
   260      */
   261     static boolean isInitializer(Env<AttrContext> env) {
   262         Symbol owner = env.info.scope.owner;
   263         return owner.isConstructor() ||
   264             owner.owner.kind == TYP &&
   265             (owner.kind == VAR ||
   266              owner.kind == MTH && (owner.flags() & BLOCK) != 0) &&
   267             (owner.flags() & STATIC) == 0;
   268     }
   270     /** Is class accessible in given evironment?
   271      *  @param env    The current environment.
   272      *  @param c      The class whose accessibility is checked.
   273      */
   274     public boolean isAccessible(Env<AttrContext> env, TypeSymbol c) {
   275         return isAccessible(env, c, false);
   276     }
   278     public boolean isAccessible(Env<AttrContext> env, TypeSymbol c, boolean checkInner) {
   279         boolean isAccessible = false;
   280         switch ((short)(c.flags() & AccessFlags)) {
   281             case PRIVATE:
   282                 isAccessible =
   283                     env.enclClass.sym.outermostClass() ==
   284                     c.owner.outermostClass();
   285                 break;
   286             case 0:
   287                 isAccessible =
   288                     env.toplevel.packge == c.owner // fast special case
   289                     ||
   290                     env.toplevel.packge == c.packge()
   291                     ||
   292                     // Hack: this case is added since synthesized default constructors
   293                     // of anonymous classes should be allowed to access
   294                     // classes which would be inaccessible otherwise.
   295                     env.enclMethod != null &&
   296                     (env.enclMethod.mods.flags & ANONCONSTR) != 0;
   297                 break;
   298             default: // error recovery
   299             case PUBLIC:
   300                 isAccessible = true;
   301                 break;
   302             case PROTECTED:
   303                 isAccessible =
   304                     env.toplevel.packge == c.owner // fast special case
   305                     ||
   306                     env.toplevel.packge == c.packge()
   307                     ||
   308                     isInnerSubClass(env.enclClass.sym, c.owner);
   309                 break;
   310         }
   311         return (checkInner == false || c.type.getEnclosingType() == Type.noType) ?
   312             isAccessible :
   313             isAccessible && isAccessible(env, c.type.getEnclosingType(), checkInner);
   314     }
   315     //where
   316         /** Is given class a subclass of given base class, or an inner class
   317          *  of a subclass?
   318          *  Return null if no such class exists.
   319          *  @param c     The class which is the subclass or is contained in it.
   320          *  @param base  The base class
   321          */
   322         private boolean isInnerSubClass(ClassSymbol c, Symbol base) {
   323             while (c != null && !c.isSubClass(base, types)) {
   324                 c = c.owner.enclClass();
   325             }
   326             return c != null;
   327         }
   329     boolean isAccessible(Env<AttrContext> env, Type t) {
   330         return isAccessible(env, t, false);
   331     }
   333     boolean isAccessible(Env<AttrContext> env, Type t, boolean checkInner) {
   334         return (t.tag == ARRAY)
   335             ? isAccessible(env, types.elemtype(t))
   336             : isAccessible(env, t.tsym, checkInner);
   337     }
   339     /** Is symbol accessible as a member of given type in given evironment?
   340      *  @param env    The current environment.
   341      *  @param site   The type of which the tested symbol is regarded
   342      *                as a member.
   343      *  @param sym    The symbol.
   344      */
   345     public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym) {
   346         return isAccessible(env, site, sym, false);
   347     }
   348     public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym, boolean checkInner) {
   349         if (sym.name == names.init && sym.owner != site.tsym) return false;
   350         switch ((short)(sym.flags() & AccessFlags)) {
   351         case PRIVATE:
   352             return
   353                 (env.enclClass.sym == sym.owner // fast special case
   354                  ||
   355                  env.enclClass.sym.outermostClass() ==
   356                  sym.owner.outermostClass())
   357                 &&
   358                 sym.isInheritedIn(site.tsym, types);
   359         case 0:
   360             return
   361                 (env.toplevel.packge == sym.owner.owner // fast special case
   362                  ||
   363                  env.toplevel.packge == sym.packge())
   364                 &&
   365                 isAccessible(env, site, checkInner)
   366                 &&
   367                 sym.isInheritedIn(site.tsym, types)
   368                 &&
   369                 notOverriddenIn(site, sym);
   370         case PROTECTED:
   371             return
   372                 (env.toplevel.packge == sym.owner.owner // fast special case
   373                  ||
   374                  env.toplevel.packge == sym.packge()
   375                  ||
   376                  isProtectedAccessible(sym, env.enclClass.sym, site)
   377                  ||
   378                  // OK to select instance method or field from 'super' or type name
   379                  // (but type names should be disallowed elsewhere!)
   380                  env.info.selectSuper && (sym.flags() & STATIC) == 0 && sym.kind != TYP)
   381                 &&
   382                 isAccessible(env, site, checkInner)
   383                 &&
   384                 notOverriddenIn(site, sym);
   385         default: // this case includes erroneous combinations as well
   386             return isAccessible(env, site, checkInner) && notOverriddenIn(site, sym);
   387         }
   388     }
   389     //where
   390     /* `sym' is accessible only if not overridden by
   391      * another symbol which is a member of `site'
   392      * (because, if it is overridden, `sym' is not strictly
   393      * speaking a member of `site'). A polymorphic signature method
   394      * cannot be overridden (e.g. MH.invokeExact(Object[])).
   395      */
   396     private boolean notOverriddenIn(Type site, Symbol sym) {
   397         if (sym.kind != MTH || sym.isConstructor() || sym.isStatic())
   398             return true;
   399         else {
   400             Symbol s2 = ((MethodSymbol)sym).implementation(site.tsym, types, true);
   401             return (s2 == null || s2 == sym || sym.owner == s2.owner ||
   402                     !types.isSubSignature(types.memberType(site, s2), types.memberType(site, sym)));
   403         }
   404     }
   405     //where
   406         /** Is given protected symbol accessible if it is selected from given site
   407          *  and the selection takes place in given class?
   408          *  @param sym     The symbol with protected access
   409          *  @param c       The class where the access takes place
   410          *  @site          The type of the qualifier
   411          */
   412         private
   413         boolean isProtectedAccessible(Symbol sym, ClassSymbol c, Type site) {
   414             while (c != null &&
   415                    !(c.isSubClass(sym.owner, types) &&
   416                      (c.flags() & INTERFACE) == 0 &&
   417                      // In JLS 2e 6.6.2.1, the subclass restriction applies
   418                      // only to instance fields and methods -- types are excluded
   419                      // regardless of whether they are declared 'static' or not.
   420                      ((sym.flags() & STATIC) != 0 || sym.kind == TYP || site.tsym.isSubClass(c, types))))
   421                 c = c.owner.enclClass();
   422             return c != null;
   423         }
   425     /** Try to instantiate the type of a method so that it fits
   426      *  given type arguments and argument types. If succesful, return
   427      *  the method's instantiated type, else return null.
   428      *  The instantiation will take into account an additional leading
   429      *  formal parameter if the method is an instance method seen as a member
   430      *  of un underdetermined site In this case, we treat site as an additional
   431      *  parameter and the parameters of the class containing the method as
   432      *  additional type variables that get instantiated.
   433      *
   434      *  @param env         The current environment
   435      *  @param site        The type of which the method is a member.
   436      *  @param m           The method symbol.
   437      *  @param argtypes    The invocation's given value arguments.
   438      *  @param typeargtypes    The invocation's given type arguments.
   439      *  @param allowBoxing Allow boxing conversions of arguments.
   440      *  @param useVarargs Box trailing arguments into an array for varargs.
   441      */
   442     Type rawInstantiate(Env<AttrContext> env,
   443                         Type site,
   444                         Symbol m,
   445                         ResultInfo resultInfo,
   446                         List<Type> argtypes,
   447                         List<Type> typeargtypes,
   448                         boolean allowBoxing,
   449                         boolean useVarargs,
   450                         Warner warn)
   451         throws Infer.InferenceException {
   452         if (useVarargs && (m.flags() & VARARGS) == 0)
   453             throw inapplicableMethodException.setMessage();
   454         Type mt = types.memberType(site, m);
   456         // tvars is the list of formal type variables for which type arguments
   457         // need to inferred.
   458         List<Type> tvars = List.nil();
   459         if (typeargtypes == null) typeargtypes = List.nil();
   460         if (mt.tag != FORALL && typeargtypes.nonEmpty()) {
   461             // This is not a polymorphic method, but typeargs are supplied
   462             // which is fine, see JLS 15.12.2.1
   463         } else if (mt.tag == FORALL && typeargtypes.nonEmpty()) {
   464             ForAll pmt = (ForAll) mt;
   465             if (typeargtypes.length() != pmt.tvars.length())
   466                 throw inapplicableMethodException.setMessage("arg.length.mismatch"); // not enough args
   467             // Check type arguments are within bounds
   468             List<Type> formals = pmt.tvars;
   469             List<Type> actuals = typeargtypes;
   470             while (formals.nonEmpty() && actuals.nonEmpty()) {
   471                 List<Type> bounds = types.subst(types.getBounds((TypeVar)formals.head),
   472                                                 pmt.tvars, typeargtypes);
   473                 for (; bounds.nonEmpty(); bounds = bounds.tail)
   474                     if (!types.isSubtypeUnchecked(actuals.head, bounds.head, warn))
   475                         throw inapplicableMethodException.setMessage("explicit.param.do.not.conform.to.bounds",actuals.head, bounds);
   476                 formals = formals.tail;
   477                 actuals = actuals.tail;
   478             }
   479             mt = types.subst(pmt.qtype, pmt.tvars, typeargtypes);
   480         } else if (mt.tag == FORALL) {
   481             ForAll pmt = (ForAll) mt;
   482             List<Type> tvars1 = types.newInstances(pmt.tvars);
   483             tvars = tvars.appendList(tvars1);
   484             mt = types.subst(pmt.qtype, pmt.tvars, tvars1);
   485         }
   487         // find out whether we need to go the slow route via infer
   488         boolean instNeeded = tvars.tail != null; /*inlined: tvars.nonEmpty()*/
   489         for (List<Type> l = argtypes;
   490              l.tail != null/*inlined: l.nonEmpty()*/ && !instNeeded;
   491              l = l.tail) {
   492             if (l.head.tag == FORALL) instNeeded = true;
   493         }
   495         if (instNeeded)
   496             return infer.instantiateMethod(env,
   497                                     tvars,
   498                                     (MethodType)mt,
   499                                     resultInfo,
   500                                     m,
   501                                     argtypes,
   502                                     allowBoxing,
   503                                     useVarargs,
   504                                     warn);
   506         checkRawArgumentsAcceptable(env, argtypes, mt.getParameterTypes(),
   507                                 allowBoxing, useVarargs, warn);
   508         return mt;
   509     }
   511     /** Same but returns null instead throwing a NoInstanceException
   512      */
   513     Type instantiate(Env<AttrContext> env,
   514                      Type site,
   515                      Symbol m,
   516                      ResultInfo resultInfo,
   517                      List<Type> argtypes,
   518                      List<Type> typeargtypes,
   519                      boolean allowBoxing,
   520                      boolean useVarargs,
   521                      Warner warn) {
   522         try {
   523             return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
   524                                   allowBoxing, useVarargs, warn);
   525         } catch (InapplicableMethodException ex) {
   526             return null;
   527         }
   528     }
   530     /** Check if a parameter list accepts a list of args.
   531      */
   532     boolean argumentsAcceptable(Env<AttrContext> env,
   533                                 List<Type> argtypes,
   534                                 List<Type> formals,
   535                                 boolean allowBoxing,
   536                                 boolean useVarargs,
   537                                 Warner warn) {
   538         try {
   539             checkRawArgumentsAcceptable(env, argtypes, formals, allowBoxing, useVarargs, warn);
   540             return true;
   541         } catch (InapplicableMethodException ex) {
   542             return false;
   543         }
   544     }
   545     /**
   546      * A check handler is used by the main method applicability routine in order
   547      * to handle specific method applicability failures. It is assumed that a class
   548      * implementing this interface should throw exceptions that are a subtype of
   549      * InapplicableMethodException (see below). Such exception will terminate the
   550      * method applicability check and propagate important info outwards (for the
   551      * purpose of generating better diagnostics).
   552      */
   553     interface MethodCheckHandler {
   554         /* The number of actuals and formals differ */
   555         InapplicableMethodException arityMismatch();
   556         /* An actual argument type does not conform to the corresponding formal type */
   557         InapplicableMethodException argumentMismatch(boolean varargs, JCDiagnostic details);
   558         /* The element type of a varargs is not accessible in the current context */
   559         InapplicableMethodException inaccessibleVarargs(Symbol location, Type expected);
   560     }
   562     /**
   563      * Basic method check handler used within Resolve - all methods end up
   564      * throwing InapplicableMethodException; a diagnostic fragment that describes
   565      * the cause as to why the method is not applicable is set on the exception
   566      * before it is thrown.
   567      */
   568     MethodCheckHandler resolveHandler = new MethodCheckHandler() {
   569             public InapplicableMethodException arityMismatch() {
   570                 return inapplicableMethodException.setMessage("arg.length.mismatch");
   571             }
   572             public InapplicableMethodException argumentMismatch(boolean varargs, JCDiagnostic details) {
   573                 String key = varargs ?
   574                         "varargs.argument.mismatch" :
   575                         "no.conforming.assignment.exists";
   576                 return inapplicableMethodException.setMessage(key,
   577                         details);
   578             }
   579             public InapplicableMethodException inaccessibleVarargs(Symbol location, Type expected) {
   580                 return inapplicableMethodException.setMessage("inaccessible.varargs.type",
   581                         expected, Kinds.kindName(location), location);
   582             }
   583     };
   585     void checkRawArgumentsAcceptable(Env<AttrContext> env,
   586                                 List<Type> argtypes,
   587                                 List<Type> formals,
   588                                 boolean allowBoxing,
   589                                 boolean useVarargs,
   590                                 Warner warn) {
   591         checkRawArgumentsAcceptable(env, infer.emptyContext, argtypes, formals,
   592                 allowBoxing, useVarargs, warn, resolveHandler);
   593     }
   595     /**
   596      * Main method applicability routine. Given a list of actual types A,
   597      * a list of formal types F, determines whether the types in A are
   598      * compatible (by method invocation conversion) with the types in F.
   599      *
   600      * Since this routine is shared between overload resolution and method
   601      * type-inference, it is crucial that actual types are converted to the
   602      * corresponding 'undet' form (i.e. where inference variables are replaced
   603      * with undetvars) so that constraints can be propagated and collected.
   604      *
   605      * Moreover, if one or more types in A is a poly type, this routine calls
   606      * Infer.instantiateArg in order to complete the poly type (this might involve
   607      * deferred attribution).
   608      *
   609      * A method check handler (see above) is used in order to report errors.
   610      */
   611     void checkRawArgumentsAcceptable(final Env<AttrContext> env,
   612                                 final Infer.InferenceContext inferenceContext,
   613                                 List<Type> argtypes,
   614                                 List<Type> formals,
   615                                 boolean allowBoxing,
   616                                 boolean useVarargs,
   617                                 Warner warn,
   618                                 MethodCheckHandler handler) {
   619         Type varargsFormal = useVarargs ? formals.last() : null;
   620         ListBuffer<Type> checkedArgs = ListBuffer.lb();
   622         if (varargsFormal == null &&
   623                 argtypes.size() != formals.size()) {
   624             throw handler.arityMismatch(); // not enough args
   625         }
   627         while (argtypes.nonEmpty() && formals.head != varargsFormal) {
   628             ResultInfo resultInfo = methodCheckResult(formals.head, allowBoxing, false, inferenceContext, handler, warn);
   629             checkedArgs.append(resultInfo.check(env.tree.pos(), argtypes.head));
   630             argtypes = argtypes.tail;
   631             formals = formals.tail;
   632         }
   634         if (formals.head != varargsFormal) {
   635             throw handler.arityMismatch(); // not enough args
   636         }
   638         if (useVarargs) {
   639             //note: if applicability check is triggered by most specific test,
   640             //the last argument of a varargs is _not_ an array type (see JLS 15.12.2.5)
   641             Type elt = types.elemtype(varargsFormal);
   642             while (argtypes.nonEmpty()) {
   643                 ResultInfo resultInfo = methodCheckResult(elt, allowBoxing, true, inferenceContext, handler, warn);
   644                 checkedArgs.append(resultInfo.check(env.tree.pos(), argtypes.head));
   645                 argtypes = argtypes.tail;
   646             }
   647             //check varargs element type accessibility
   648             varargsAccessible(env, elt, handler, inferenceContext);
   649         }
   650     }
   652     void varargsAccessible(final Env<AttrContext> env, final Type t, final Resolve.MethodCheckHandler handler, final InferenceContext inferenceContext) {
   653         if (inferenceContext.free(t)) {
   654             inferenceContext.addFreeTypeListener(List.of(t), new FreeTypeListener() {
   655                 @Override
   656                 public void typesInferred(InferenceContext inferenceContext) {
   657                     varargsAccessible(env, inferenceContext.asInstType(t, types), handler, inferenceContext);
   658                 }
   659             });
   660         } else {
   661             if (!isAccessible(env, t)) {
   662                 Symbol location = env.enclClass.sym;
   663                 throw handler.inaccessibleVarargs(location, t);
   664             }
   665         }
   666     }
   668     /**
   669      * Check context to be used during method applicability checks. A method check
   670      * context might contain inference variables.
   671      */
   672     abstract class MethodCheckContext implements CheckContext {
   674         MethodCheckHandler handler;
   675         boolean useVarargs;
   676         Infer.InferenceContext inferenceContext;
   677         Warner rsWarner;
   679         public MethodCheckContext(MethodCheckHandler handler, boolean useVarargs, Infer.InferenceContext inferenceContext, Warner rsWarner) {
   680             this.handler = handler;
   681             this.useVarargs = useVarargs;
   682             this.inferenceContext = inferenceContext;
   683             this.rsWarner = rsWarner;
   684         }
   686         public void report(DiagnosticPosition pos, JCDiagnostic details) {
   687             throw handler.argumentMismatch(useVarargs, details);
   688         }
   690         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
   691             return rsWarner;
   692         }
   694         public InferenceContext inferenceContext() {
   695             return inferenceContext;
   696         }
   697     }
   699     /**
   700      * Subclass of method check context class that implements strict method conversion.
   701      * Strict method conversion checks compatibility between types using subtyping tests.
   702      */
   703     class StrictMethodContext extends MethodCheckContext {
   705         public StrictMethodContext(MethodCheckHandler handler, boolean useVarargs, Infer.InferenceContext inferenceContext, Warner rsWarner) {
   706             super(handler, useVarargs, inferenceContext, rsWarner);
   707         }
   709         public boolean compatible(Type found, Type req, Warner warn) {
   710             return types.isSubtypeUnchecked(found, inferenceContext.asFree(req, types), warn);
   711         }
   712     }
   714     /**
   715      * Subclass of method check context class that implements loose method conversion.
   716      * Loose method conversion checks compatibility between types using method conversion tests.
   717      */
   718     class LooseMethodContext extends MethodCheckContext {
   720         public LooseMethodContext(MethodCheckHandler handler, boolean useVarargs, Infer.InferenceContext inferenceContext, Warner rsWarner) {
   721             super(handler, useVarargs, inferenceContext, rsWarner);
   722         }
   724         public boolean compatible(Type found, Type req, Warner warn) {
   725             return types.isConvertible(found, inferenceContext.asFree(req, types), warn);
   726         }
   727     }
   729     /**
   730      * Create a method check context to be used during method applicability check
   731      */
   732     ResultInfo methodCheckResult(Type to, boolean allowBoxing, boolean useVarargs,
   733             Infer.InferenceContext inferenceContext, MethodCheckHandler methodHandler, Warner rsWarner) {
   734         MethodCheckContext checkContext = allowBoxing ?
   735                 new LooseMethodContext(methodHandler, useVarargs, inferenceContext, rsWarner) :
   736                 new StrictMethodContext(methodHandler, useVarargs, inferenceContext, rsWarner);
   737         return attr.new ResultInfo(VAL, to, checkContext) {
   738             @Override
   739             protected Type check(DiagnosticPosition pos, Type found) {
   740                 return super.check(pos, chk.checkNonVoid(pos, types.capture(types.upperBound(found.baseType()))));
   741             }
   742         };
   743     }
   745     public static class InapplicableMethodException extends RuntimeException {
   746         private static final long serialVersionUID = 0;
   748         JCDiagnostic diagnostic;
   749         JCDiagnostic.Factory diags;
   751         InapplicableMethodException(JCDiagnostic.Factory diags) {
   752             this.diagnostic = null;
   753             this.diags = diags;
   754         }
   755         InapplicableMethodException setMessage() {
   756             return setMessage((JCDiagnostic)null);
   757         }
   758         InapplicableMethodException setMessage(String key) {
   759             return setMessage(key != null ? diags.fragment(key) : null);
   760         }
   761         InapplicableMethodException setMessage(String key, Object... args) {
   762             return setMessage(key != null ? diags.fragment(key, args) : null);
   763         }
   764         InapplicableMethodException setMessage(JCDiagnostic diag) {
   765             this.diagnostic = diag;
   766             return this;
   767         }
   769         public JCDiagnostic getDiagnostic() {
   770             return diagnostic;
   771         }
   772     }
   773     private final InapplicableMethodException inapplicableMethodException;
   775 /* ***************************************************************************
   776  *  Symbol lookup
   777  *  the following naming conventions for arguments are used
   778  *
   779  *       env      is the environment where the symbol was mentioned
   780  *       site     is the type of which the symbol is a member
   781  *       name     is the symbol's name
   782  *                if no arguments are given
   783  *       argtypes are the value arguments, if we search for a method
   784  *
   785  *  If no symbol was found, a ResolveError detailing the problem is returned.
   786  ****************************************************************************/
   788     /** Find field. Synthetic fields are always skipped.
   789      *  @param env     The current environment.
   790      *  @param site    The original type from where the selection takes place.
   791      *  @param name    The name of the field.
   792      *  @param c       The class to search for the field. This is always
   793      *                 a superclass or implemented interface of site's class.
   794      */
   795     Symbol findField(Env<AttrContext> env,
   796                      Type site,
   797                      Name name,
   798                      TypeSymbol c) {
   799         while (c.type.tag == TYPEVAR)
   800             c = c.type.getUpperBound().tsym;
   801         Symbol bestSoFar = varNotFound;
   802         Symbol sym;
   803         Scope.Entry e = c.members().lookup(name);
   804         while (e.scope != null) {
   805             if (e.sym.kind == VAR && (e.sym.flags_field & SYNTHETIC) == 0) {
   806                 return isAccessible(env, site, e.sym)
   807                     ? e.sym : new AccessError(env, site, e.sym);
   808             }
   809             e = e.next();
   810         }
   811         Type st = types.supertype(c.type);
   812         if (st != null && (st.tag == CLASS || st.tag == TYPEVAR)) {
   813             sym = findField(env, site, name, st.tsym);
   814             if (sym.kind < bestSoFar.kind) bestSoFar = sym;
   815         }
   816         for (List<Type> l = types.interfaces(c.type);
   817              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
   818              l = l.tail) {
   819             sym = findField(env, site, name, l.head.tsym);
   820             if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
   821                 sym.owner != bestSoFar.owner)
   822                 bestSoFar = new AmbiguityError(bestSoFar, sym);
   823             else if (sym.kind < bestSoFar.kind)
   824                 bestSoFar = sym;
   825         }
   826         return bestSoFar;
   827     }
   829     /** Resolve a field identifier, throw a fatal error if not found.
   830      *  @param pos       The position to use for error reporting.
   831      *  @param env       The environment current at the method invocation.
   832      *  @param site      The type of the qualifying expression, in which
   833      *                   identifier is searched.
   834      *  @param name      The identifier's name.
   835      */
   836     public VarSymbol resolveInternalField(DiagnosticPosition pos, Env<AttrContext> env,
   837                                           Type site, Name name) {
   838         Symbol sym = findField(env, site, name, site.tsym);
   839         if (sym.kind == VAR) return (VarSymbol)sym;
   840         else throw new FatalError(
   841                  diags.fragment("fatal.err.cant.locate.field",
   842                                 name));
   843     }
   845     /** Find unqualified variable or field with given name.
   846      *  Synthetic fields always skipped.
   847      *  @param env     The current environment.
   848      *  @param name    The name of the variable or field.
   849      */
   850     Symbol findVar(Env<AttrContext> env, Name name) {
   851         Symbol bestSoFar = varNotFound;
   852         Symbol sym;
   853         Env<AttrContext> env1 = env;
   854         boolean staticOnly = false;
   855         while (env1.outer != null) {
   856             if (isStatic(env1)) staticOnly = true;
   857             Scope.Entry e = env1.info.scope.lookup(name);
   858             while (e.scope != null &&
   859                    (e.sym.kind != VAR ||
   860                     (e.sym.flags_field & SYNTHETIC) != 0))
   861                 e = e.next();
   862             sym = (e.scope != null)
   863                 ? e.sym
   864                 : findField(
   865                     env1, env1.enclClass.sym.type, name, env1.enclClass.sym);
   866             if (sym.exists()) {
   867                 if (staticOnly &&
   868                     sym.kind == VAR &&
   869                     sym.owner.kind == TYP &&
   870                     (sym.flags() & STATIC) == 0)
   871                     return new StaticError(sym);
   872                 else
   873                     return sym;
   874             } else if (sym.kind < bestSoFar.kind) {
   875                 bestSoFar = sym;
   876             }
   878             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
   879             env1 = env1.outer;
   880         }
   882         sym = findField(env, syms.predefClass.type, name, syms.predefClass);
   883         if (sym.exists())
   884             return sym;
   885         if (bestSoFar.exists())
   886             return bestSoFar;
   888         Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
   889         for (; e.scope != null; e = e.next()) {
   890             sym = e.sym;
   891             Type origin = e.getOrigin().owner.type;
   892             if (sym.kind == VAR) {
   893                 if (e.sym.owner.type != origin)
   894                     sym = sym.clone(e.getOrigin().owner);
   895                 return isAccessible(env, origin, sym)
   896                     ? sym : new AccessError(env, origin, sym);
   897             }
   898         }
   900         Symbol origin = null;
   901         e = env.toplevel.starImportScope.lookup(name);
   902         for (; e.scope != null; e = e.next()) {
   903             sym = e.sym;
   904             if (sym.kind != VAR)
   905                 continue;
   906             // invariant: sym.kind == VAR
   907             if (bestSoFar.kind < AMBIGUOUS && sym.owner != bestSoFar.owner)
   908                 return new AmbiguityError(bestSoFar, sym);
   909             else if (bestSoFar.kind >= VAR) {
   910                 origin = e.getOrigin().owner;
   911                 bestSoFar = isAccessible(env, origin.type, sym)
   912                     ? sym : new AccessError(env, origin.type, sym);
   913             }
   914         }
   915         if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type)
   916             return bestSoFar.clone(origin);
   917         else
   918             return bestSoFar;
   919     }
   921     Warner noteWarner = new Warner();
   923     /** Select the best method for a call site among two choices.
   924      *  @param env              The current environment.
   925      *  @param site             The original type from where the
   926      *                          selection takes place.
   927      *  @param argtypes         The invocation's value arguments,
   928      *  @param typeargtypes     The invocation's type arguments,
   929      *  @param sym              Proposed new best match.
   930      *  @param bestSoFar        Previously found best match.
   931      *  @param allowBoxing Allow boxing conversions of arguments.
   932      *  @param useVarargs Box trailing arguments into an array for varargs.
   933      */
   934     @SuppressWarnings("fallthrough")
   935     Symbol selectBest(Env<AttrContext> env,
   936                       Type site,
   937                       List<Type> argtypes,
   938                       List<Type> typeargtypes,
   939                       Symbol sym,
   940                       Symbol bestSoFar,
   941                       boolean allowBoxing,
   942                       boolean useVarargs,
   943                       boolean operator) {
   944         if (sym.kind == ERR) return bestSoFar;
   945         if (!sym.isInheritedIn(site.tsym, types)) return bestSoFar;
   946         Assert.check(sym.kind < AMBIGUOUS);
   947         try {
   948             Type mt = rawInstantiate(env, site, sym, null, argtypes, typeargtypes,
   949                                allowBoxing, useVarargs, Warner.noWarnings);
   950             if (!operator)
   951                 currentResolutionContext.addApplicableCandidate(sym, mt);
   952         } catch (InapplicableMethodException ex) {
   953             if (!operator)
   954                 currentResolutionContext.addInapplicableCandidate(sym, ex.getDiagnostic());
   955             switch (bestSoFar.kind) {
   956             case ABSENT_MTH:
   957                 return wrongMethod;
   958             case WRONG_MTH:
   959                 if (operator) return bestSoFar;
   960             case WRONG_MTHS:
   961                 return wrongMethods;
   962             default:
   963                 return bestSoFar;
   964             }
   965         }
   966         if (!isAccessible(env, site, sym)) {
   967             return (bestSoFar.kind == ABSENT_MTH)
   968                 ? new AccessError(env, site, sym)
   969                 : bestSoFar;
   970         }
   971         return (bestSoFar.kind > AMBIGUOUS)
   972             ? sym
   973             : mostSpecific(sym, bestSoFar, env, site,
   974                            allowBoxing && operator, useVarargs);
   975     }
   977     /* Return the most specific of the two methods for a call,
   978      *  given that both are accessible and applicable.
   979      *  @param m1               A new candidate for most specific.
   980      *  @param m2               The previous most specific candidate.
   981      *  @param env              The current environment.
   982      *  @param site             The original type from where the selection
   983      *                          takes place.
   984      *  @param allowBoxing Allow boxing conversions of arguments.
   985      *  @param useVarargs Box trailing arguments into an array for varargs.
   986      */
   987     Symbol mostSpecific(Symbol m1,
   988                         Symbol m2,
   989                         Env<AttrContext> env,
   990                         final Type site,
   991                         boolean allowBoxing,
   992                         boolean useVarargs) {
   993         switch (m2.kind) {
   994         case MTH:
   995             if (m1 == m2) return m1;
   996             boolean m1SignatureMoreSpecific = signatureMoreSpecific(env, site, m1, m2, allowBoxing, useVarargs);
   997             boolean m2SignatureMoreSpecific = signatureMoreSpecific(env, site, m2, m1, allowBoxing, useVarargs);
   998             if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) {
   999                 Type mt1 = types.memberType(site, m1);
  1000                 Type mt2 = types.memberType(site, m2);
  1001                 if (!types.overrideEquivalent(mt1, mt2))
  1002                     return ambiguityError(m1, m2);
  1004                 // same signature; select (a) the non-bridge method, or
  1005                 // (b) the one that overrides the other, or (c) the concrete
  1006                 // one, or (d) merge both abstract signatures
  1007                 if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE))
  1008                     return ((m1.flags() & BRIDGE) != 0) ? m2 : m1;
  1010                 // if one overrides or hides the other, use it
  1011                 TypeSymbol m1Owner = (TypeSymbol)m1.owner;
  1012                 TypeSymbol m2Owner = (TypeSymbol)m2.owner;
  1013                 if (types.asSuper(m1Owner.type, m2Owner) != null &&
  1014                     ((m1.owner.flags_field & INTERFACE) == 0 ||
  1015                      (m2.owner.flags_field & INTERFACE) != 0) &&
  1016                     m1.overrides(m2, m1Owner, types, false))
  1017                     return m1;
  1018                 if (types.asSuper(m2Owner.type, m1Owner) != null &&
  1019                     ((m2.owner.flags_field & INTERFACE) == 0 ||
  1020                      (m1.owner.flags_field & INTERFACE) != 0) &&
  1021                     m2.overrides(m1, m2Owner, types, false))
  1022                     return m2;
  1023                 boolean m1Abstract = (m1.flags() & ABSTRACT) != 0;
  1024                 boolean m2Abstract = (m2.flags() & ABSTRACT) != 0;
  1025                 if (m1Abstract && !m2Abstract) return m2;
  1026                 if (m2Abstract && !m1Abstract) return m1;
  1027                 // both abstract or both concrete
  1028                 if (!m1Abstract && !m2Abstract)
  1029                     return ambiguityError(m1, m2);
  1030                 // check that both signatures have the same erasure
  1031                 if (!types.isSameTypes(m1.erasure(types).getParameterTypes(),
  1032                                        m2.erasure(types).getParameterTypes()))
  1033                     return ambiguityError(m1, m2);
  1034                 // both abstract, neither overridden; merge throws clause and result type
  1035                 Type mst = mostSpecificReturnType(mt1, mt2);
  1036                 if (mst == null) {
  1037                     // Theoretically, this can't happen, but it is possible
  1038                     // due to error recovery or mixing incompatible class files
  1039                     return ambiguityError(m1, m2);
  1041                 Symbol mostSpecific = mst == mt1 ? m1 : m2;
  1042                 List<Type> allThrown = chk.intersect(mt1.getThrownTypes(), mt2.getThrownTypes());
  1043                 Type newSig = types.createMethodTypeWithThrown(mostSpecific.type, allThrown);
  1044                 MethodSymbol result = new MethodSymbol(
  1045                         mostSpecific.flags(),
  1046                         mostSpecific.name,
  1047                         newSig,
  1048                         mostSpecific.owner) {
  1049                     @Override
  1050                     public MethodSymbol implementation(TypeSymbol origin, Types types, boolean checkResult) {
  1051                         if (origin == site.tsym)
  1052                             return this;
  1053                         else
  1054                             return super.implementation(origin, types, checkResult);
  1056                     };
  1057                 return result;
  1059             if (m1SignatureMoreSpecific) return m1;
  1060             if (m2SignatureMoreSpecific) return m2;
  1061             return ambiguityError(m1, m2);
  1062         case AMBIGUOUS:
  1063             AmbiguityError e = (AmbiguityError)m2;
  1064             Symbol err1 = mostSpecific(m1, e.sym, env, site, allowBoxing, useVarargs);
  1065             Symbol err2 = mostSpecific(m1, e.sym2, env, site, allowBoxing, useVarargs);
  1066             if (err1 == err2) return err1;
  1067             if (err1 == e.sym && err2 == e.sym2) return m2;
  1068             if (err1 instanceof AmbiguityError &&
  1069                 err2 instanceof AmbiguityError &&
  1070                 ((AmbiguityError)err1).sym == ((AmbiguityError)err2).sym)
  1071                 return ambiguityError(m1, m2);
  1072             else
  1073                 return ambiguityError(err1, err2);
  1074         default:
  1075             throw new AssertionError();
  1078     //where
  1079     private boolean signatureMoreSpecific(Env<AttrContext> env, Type site, Symbol m1, Symbol m2, boolean allowBoxing, boolean useVarargs) {
  1080         noteWarner.clear();
  1081         Type mtype1 = types.memberType(site, adjustVarargs(m1, m2, useVarargs));
  1082         Type mtype2 = instantiate(env, site, adjustVarargs(m2, m1, useVarargs), null,
  1083                 types.lowerBoundArgtypes(mtype1), null,
  1084                 allowBoxing, false, noteWarner);
  1085         return mtype2 != null &&
  1086                 !noteWarner.hasLint(Lint.LintCategory.UNCHECKED);
  1088     //where
  1089     private Symbol adjustVarargs(Symbol to, Symbol from, boolean useVarargs) {
  1090         List<Type> fromArgs = from.type.getParameterTypes();
  1091         List<Type> toArgs = to.type.getParameterTypes();
  1092         if (useVarargs &&
  1093                 (from.flags() & VARARGS) != 0 &&
  1094                 (to.flags() & VARARGS) != 0) {
  1095             Type varargsTypeFrom = fromArgs.last();
  1096             Type varargsTypeTo = toArgs.last();
  1097             ListBuffer<Type> args = ListBuffer.lb();
  1098             if (toArgs.length() < fromArgs.length()) {
  1099                 //if we are checking a varargs method 'from' against another varargs
  1100                 //method 'to' (where arity of 'to' < arity of 'from') then expand signature
  1101                 //of 'to' to 'fit' arity of 'from' (this means adding fake formals to 'to'
  1102                 //until 'to' signature has the same arity as 'from')
  1103                 while (fromArgs.head != varargsTypeFrom) {
  1104                     args.append(toArgs.head == varargsTypeTo ? types.elemtype(varargsTypeTo) : toArgs.head);
  1105                     fromArgs = fromArgs.tail;
  1106                     toArgs = toArgs.head == varargsTypeTo ?
  1107                         toArgs :
  1108                         toArgs.tail;
  1110             } else {
  1111                 //formal argument list is same as original list where last
  1112                 //argument (array type) is removed
  1113                 args.appendList(toArgs.reverse().tail.reverse());
  1115             //append varargs element type as last synthetic formal
  1116             args.append(types.elemtype(varargsTypeTo));
  1117             Type mtype = types.createMethodTypeWithParameters(to.type, args.toList());
  1118             return new MethodSymbol(to.flags_field & ~VARARGS, to.name, mtype, to.owner);
  1119         } else {
  1120             return to;
  1123     //where
  1124     Type mostSpecificReturnType(Type mt1, Type mt2) {
  1125         Type rt1 = mt1.getReturnType();
  1126         Type rt2 = mt2.getReturnType();
  1128         if (mt1.tag == FORALL && mt2.tag == FORALL) {
  1129             //if both are generic methods, adjust return type ahead of subtyping check
  1130             rt1 = types.subst(rt1, mt1.getTypeArguments(), mt2.getTypeArguments());
  1132         //first use subtyping, then return type substitutability
  1133         if (types.isSubtype(rt1, rt2)) {
  1134             return mt1;
  1135         } else if (types.isSubtype(rt2, rt1)) {
  1136             return mt2;
  1137         } else if (types.returnTypeSubstitutable(mt1, mt2)) {
  1138             return mt1;
  1139         } else if (types.returnTypeSubstitutable(mt2, mt1)) {
  1140             return mt2;
  1141         } else {
  1142             return null;
  1145     //where
  1146     Symbol ambiguityError(Symbol m1, Symbol m2) {
  1147         if (((m1.flags() | m2.flags()) & CLASH) != 0) {
  1148             return (m1.flags() & CLASH) == 0 ? m1 : m2;
  1149         } else {
  1150             return new AmbiguityError(m1, m2);
  1154     /** Find best qualified method matching given name, type and value
  1155      *  arguments.
  1156      *  @param env       The current environment.
  1157      *  @param site      The original type from where the selection
  1158      *                   takes place.
  1159      *  @param name      The method's name.
  1160      *  @param argtypes  The method's value arguments.
  1161      *  @param typeargtypes The method's type arguments
  1162      *  @param allowBoxing Allow boxing conversions of arguments.
  1163      *  @param useVarargs Box trailing arguments into an array for varargs.
  1164      */
  1165     Symbol findMethod(Env<AttrContext> env,
  1166                       Type site,
  1167                       Name name,
  1168                       List<Type> argtypes,
  1169                       List<Type> typeargtypes,
  1170                       boolean allowBoxing,
  1171                       boolean useVarargs,
  1172                       boolean operator) {
  1173         Symbol bestSoFar = methodNotFound;
  1174         bestSoFar = findMethod(env,
  1175                           site,
  1176                           name,
  1177                           argtypes,
  1178                           typeargtypes,
  1179                           site.tsym.type,
  1180                           bestSoFar,
  1181                           allowBoxing,
  1182                           useVarargs,
  1183                           operator);
  1184         reportVerboseResolutionDiagnostic(env.tree.pos(), name, site, argtypes, typeargtypes, bestSoFar);
  1185         return bestSoFar;
  1187     // where
  1188     private Symbol findMethod(Env<AttrContext> env,
  1189                               Type site,
  1190                               Name name,
  1191                               List<Type> argtypes,
  1192                               List<Type> typeargtypes,
  1193                               Type intype,
  1194                               Symbol bestSoFar,
  1195                               boolean allowBoxing,
  1196                               boolean useVarargs,
  1197                               boolean operator) {
  1198         boolean abstractOk = true;
  1199         List<Type> itypes = List.nil();
  1200         for (TypeSymbol s : superclasses(intype)) {
  1201             bestSoFar = lookupMethod(env, site, name, argtypes, typeargtypes,
  1202                     s.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
  1203             //We should not look for abstract methods if receiver is a concrete class
  1204             //(as concrete classes are expected to implement all abstracts coming
  1205             //from superinterfaces)
  1206             abstractOk &= (s.flags() & (ABSTRACT | INTERFACE | ENUM)) != 0;
  1207             if (abstractOk) {
  1208                 for (Type itype : types.interfaces(s.type)) {
  1209                     itypes = types.union(types.closure(itype), itypes);
  1212             if (name == names.init) break;
  1215         Symbol concrete = bestSoFar.kind < ERR &&
  1216                 (bestSoFar.flags() & ABSTRACT) == 0 ?
  1217                 bestSoFar : methodNotFound;
  1219         if (name != names.init) {
  1220             //keep searching for abstract methods
  1221             for (Type itype : itypes) {
  1222                 if (!itype.isInterface()) continue; //skip j.l.Object (included by Types.closure())
  1223                 bestSoFar = lookupMethod(env, site, name, argtypes, typeargtypes,
  1224                     itype.tsym.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
  1225                     if (concrete != bestSoFar &&
  1226                             concrete.kind < ERR  && bestSoFar.kind < ERR &&
  1227                             types.isSubSignature(concrete.type, bestSoFar.type)) {
  1228                         //this is an hack - as javac does not do full membership checks
  1229                         //most specific ends up comparing abstract methods that might have
  1230                         //been implemented by some concrete method in a subclass and,
  1231                         //because of raw override, it is possible for an abstract method
  1232                         //to be more specific than the concrete method - so we need
  1233                         //to explicitly call that out (see CR 6178365)
  1234                         bestSoFar = concrete;
  1238         return bestSoFar;
  1241     /**
  1242      * Return an Iterable object to scan the superclasses of a given type.
  1243      * It's crucial that the scan is done lazily, as we don't want to accidentally
  1244      * access more supertypes than strictly needed (as this could trigger completion
  1245      * errors if some of the not-needed supertypes are missing/ill-formed).
  1246      */
  1247     Iterable<TypeSymbol> superclasses(final Type intype) {
  1248         return new Iterable<TypeSymbol>() {
  1249             public Iterator<TypeSymbol> iterator() {
  1250                 return new Iterator<TypeSymbol>() {
  1252                     List<TypeSymbol> seen = List.nil();
  1253                     TypeSymbol currentSym = symbolFor(intype);
  1254                     TypeSymbol prevSym = null;
  1256                     public boolean hasNext() {
  1257                         if (currentSym == syms.noSymbol) {
  1258                             currentSym = symbolFor(types.supertype(prevSym.type));
  1260                         return currentSym != null;
  1263                     public TypeSymbol next() {
  1264                         prevSym = currentSym;
  1265                         currentSym = syms.noSymbol;
  1266                         Assert.check(prevSym != null || prevSym != syms.noSymbol);
  1267                         return prevSym;
  1270                     public void remove() {
  1271                         throw new UnsupportedOperationException();
  1274                     TypeSymbol symbolFor(Type t) {
  1275                         if (t.tag != CLASS &&
  1276                                 t.tag != TYPEVAR) {
  1277                             return null;
  1279                         while (t.tag == TYPEVAR)
  1280                             t = t.getUpperBound();
  1281                         if (seen.contains(t.tsym)) {
  1282                             //degenerate case in which we have a circular
  1283                             //class hierarchy - because of ill-formed classfiles
  1284                             return null;
  1286                         seen = seen.prepend(t.tsym);
  1287                         return t.tsym;
  1289                 };
  1291         };
  1294     /**
  1295      * Lookup a method with given name and argument types in a given scope
  1296      */
  1297     Symbol lookupMethod(Env<AttrContext> env,
  1298             Type site,
  1299             Name name,
  1300             List<Type> argtypes,
  1301             List<Type> typeargtypes,
  1302             Scope sc,
  1303             Symbol bestSoFar,
  1304             boolean allowBoxing,
  1305             boolean useVarargs,
  1306             boolean operator,
  1307             boolean abstractok) {
  1308         for (Symbol s : sc.getElementsByName(name, lookupFilter)) {
  1309             bestSoFar = selectBest(env, site, argtypes, typeargtypes, s,
  1310                     bestSoFar, allowBoxing, useVarargs, operator);
  1312         return bestSoFar;
  1314     //where
  1315         Filter<Symbol> lookupFilter = new Filter<Symbol>() {
  1316             public boolean accepts(Symbol s) {
  1317                 return s.kind == MTH &&
  1318                         (s.flags() & SYNTHETIC) == 0;
  1320         };
  1322     /** Find unqualified method matching given name, type and value arguments.
  1323      *  @param env       The current environment.
  1324      *  @param name      The method's name.
  1325      *  @param argtypes  The method's value arguments.
  1326      *  @param typeargtypes  The method's type arguments.
  1327      *  @param allowBoxing Allow boxing conversions of arguments.
  1328      *  @param useVarargs Box trailing arguments into an array for varargs.
  1329      */
  1330     Symbol findFun(Env<AttrContext> env, Name name,
  1331                    List<Type> argtypes, List<Type> typeargtypes,
  1332                    boolean allowBoxing, boolean useVarargs) {
  1333         Symbol bestSoFar = methodNotFound;
  1334         Symbol sym;
  1335         Env<AttrContext> env1 = env;
  1336         boolean staticOnly = false;
  1337         while (env1.outer != null) {
  1338             if (isStatic(env1)) staticOnly = true;
  1339             sym = findMethod(
  1340                 env1, env1.enclClass.sym.type, name, argtypes, typeargtypes,
  1341                 allowBoxing, useVarargs, false);
  1342             if (sym.exists()) {
  1343                 if (staticOnly &&
  1344                     sym.kind == MTH &&
  1345                     sym.owner.kind == TYP &&
  1346                     (sym.flags() & STATIC) == 0) return new StaticError(sym);
  1347                 else return sym;
  1348             } else if (sym.kind < bestSoFar.kind) {
  1349                 bestSoFar = sym;
  1351             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  1352             env1 = env1.outer;
  1355         sym = findMethod(env, syms.predefClass.type, name, argtypes,
  1356                          typeargtypes, allowBoxing, useVarargs, false);
  1357         if (sym.exists())
  1358             return sym;
  1360         Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
  1361         for (; e.scope != null; e = e.next()) {
  1362             sym = e.sym;
  1363             Type origin = e.getOrigin().owner.type;
  1364             if (sym.kind == MTH) {
  1365                 if (e.sym.owner.type != origin)
  1366                     sym = sym.clone(e.getOrigin().owner);
  1367                 if (!isAccessible(env, origin, sym))
  1368                     sym = new AccessError(env, origin, sym);
  1369                 bestSoFar = selectBest(env, origin,
  1370                                        argtypes, typeargtypes,
  1371                                        sym, bestSoFar,
  1372                                        allowBoxing, useVarargs, false);
  1375         if (bestSoFar.exists())
  1376             return bestSoFar;
  1378         e = env.toplevel.starImportScope.lookup(name);
  1379         for (; e.scope != null; e = e.next()) {
  1380             sym = e.sym;
  1381             Type origin = e.getOrigin().owner.type;
  1382             if (sym.kind == MTH) {
  1383                 if (e.sym.owner.type != origin)
  1384                     sym = sym.clone(e.getOrigin().owner);
  1385                 if (!isAccessible(env, origin, sym))
  1386                     sym = new AccessError(env, origin, sym);
  1387                 bestSoFar = selectBest(env, origin,
  1388                                        argtypes, typeargtypes,
  1389                                        sym, bestSoFar,
  1390                                        allowBoxing, useVarargs, false);
  1393         return bestSoFar;
  1396     /** Load toplevel or member class with given fully qualified name and
  1397      *  verify that it is accessible.
  1398      *  @param env       The current environment.
  1399      *  @param name      The fully qualified name of the class to be loaded.
  1400      */
  1401     Symbol loadClass(Env<AttrContext> env, Name name) {
  1402         try {
  1403             ClassSymbol c = reader.loadClass(name);
  1404             return isAccessible(env, c) ? c : new AccessError(c);
  1405         } catch (ClassReader.BadClassFile err) {
  1406             throw err;
  1407         } catch (CompletionFailure ex) {
  1408             return typeNotFound;
  1412     /** Find qualified member type.
  1413      *  @param env       The current environment.
  1414      *  @param site      The original type from where the selection takes
  1415      *                   place.
  1416      *  @param name      The type's name.
  1417      *  @param c         The class to search for the member type. This is
  1418      *                   always a superclass or implemented interface of
  1419      *                   site's class.
  1420      */
  1421     Symbol findMemberType(Env<AttrContext> env,
  1422                           Type site,
  1423                           Name name,
  1424                           TypeSymbol c) {
  1425         Symbol bestSoFar = typeNotFound;
  1426         Symbol sym;
  1427         Scope.Entry e = c.members().lookup(name);
  1428         while (e.scope != null) {
  1429             if (e.sym.kind == TYP) {
  1430                 return isAccessible(env, site, e.sym)
  1431                     ? e.sym
  1432                     : new AccessError(env, site, e.sym);
  1434             e = e.next();
  1436         Type st = types.supertype(c.type);
  1437         if (st != null && st.tag == CLASS) {
  1438             sym = findMemberType(env, site, name, st.tsym);
  1439             if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1441         for (List<Type> l = types.interfaces(c.type);
  1442              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
  1443              l = l.tail) {
  1444             sym = findMemberType(env, site, name, l.head.tsym);
  1445             if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
  1446                 sym.owner != bestSoFar.owner)
  1447                 bestSoFar = new AmbiguityError(bestSoFar, sym);
  1448             else if (sym.kind < bestSoFar.kind)
  1449                 bestSoFar = sym;
  1451         return bestSoFar;
  1454     /** Find a global type in given scope and load corresponding class.
  1455      *  @param env       The current environment.
  1456      *  @param scope     The scope in which to look for the type.
  1457      *  @param name      The type's name.
  1458      */
  1459     Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name) {
  1460         Symbol bestSoFar = typeNotFound;
  1461         for (Scope.Entry e = scope.lookup(name); e.scope != null; e = e.next()) {
  1462             Symbol sym = loadClass(env, e.sym.flatName());
  1463             if (bestSoFar.kind == TYP && sym.kind == TYP &&
  1464                 bestSoFar != sym)
  1465                 return new AmbiguityError(bestSoFar, sym);
  1466             else if (sym.kind < bestSoFar.kind)
  1467                 bestSoFar = sym;
  1469         return bestSoFar;
  1472     /** Find an unqualified type symbol.
  1473      *  @param env       The current environment.
  1474      *  @param name      The type's name.
  1475      */
  1476     Symbol findType(Env<AttrContext> env, Name name) {
  1477         Symbol bestSoFar = typeNotFound;
  1478         Symbol sym;
  1479         boolean staticOnly = false;
  1480         for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
  1481             if (isStatic(env1)) staticOnly = true;
  1482             for (Scope.Entry e = env1.info.scope.lookup(name);
  1483                  e.scope != null;
  1484                  e = e.next()) {
  1485                 if (e.sym.kind == TYP) {
  1486                     if (staticOnly &&
  1487                         e.sym.type.tag == TYPEVAR &&
  1488                         e.sym.owner.kind == TYP) return new StaticError(e.sym);
  1489                     return e.sym;
  1493             sym = findMemberType(env1, env1.enclClass.sym.type, name,
  1494                                  env1.enclClass.sym);
  1495             if (staticOnly && sym.kind == TYP &&
  1496                 sym.type.tag == CLASS &&
  1497                 sym.type.getEnclosingType().tag == CLASS &&
  1498                 env1.enclClass.sym.type.isParameterized() &&
  1499                 sym.type.getEnclosingType().isParameterized())
  1500                 return new StaticError(sym);
  1501             else if (sym.exists()) return sym;
  1502             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1504             JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass;
  1505             if ((encl.sym.flags() & STATIC) != 0)
  1506                 staticOnly = true;
  1509         if (!env.tree.hasTag(IMPORT)) {
  1510             sym = findGlobalType(env, env.toplevel.namedImportScope, name);
  1511             if (sym.exists()) return sym;
  1512             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1514             sym = findGlobalType(env, env.toplevel.packge.members(), name);
  1515             if (sym.exists()) return sym;
  1516             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1518             sym = findGlobalType(env, env.toplevel.starImportScope, name);
  1519             if (sym.exists()) return sym;
  1520             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1523         return bestSoFar;
  1526     /** Find an unqualified identifier which matches a specified kind set.
  1527      *  @param env       The current environment.
  1528      *  @param name      The indentifier's name.
  1529      *  @param kind      Indicates the possible symbol kinds
  1530      *                   (a subset of VAL, TYP, PCK).
  1531      */
  1532     Symbol findIdent(Env<AttrContext> env, Name name, int kind) {
  1533         Symbol bestSoFar = typeNotFound;
  1534         Symbol sym;
  1536         if ((kind & VAR) != 0) {
  1537             sym = findVar(env, name);
  1538             if (sym.exists()) return sym;
  1539             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1542         if ((kind & TYP) != 0) {
  1543             sym = findType(env, name);
  1544             if (sym.exists()) return sym;
  1545             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1548         if ((kind & PCK) != 0) return reader.enterPackage(name);
  1549         else return bestSoFar;
  1552     /** Find an identifier in a package which matches a specified kind set.
  1553      *  @param env       The current environment.
  1554      *  @param name      The identifier's name.
  1555      *  @param kind      Indicates the possible symbol kinds
  1556      *                   (a nonempty subset of TYP, PCK).
  1557      */
  1558     Symbol findIdentInPackage(Env<AttrContext> env, TypeSymbol pck,
  1559                               Name name, int kind) {
  1560         Name fullname = TypeSymbol.formFullName(name, pck);
  1561         Symbol bestSoFar = typeNotFound;
  1562         PackageSymbol pack = null;
  1563         if ((kind & PCK) != 0) {
  1564             pack = reader.enterPackage(fullname);
  1565             if (pack.exists()) return pack;
  1567         if ((kind & TYP) != 0) {
  1568             Symbol sym = loadClass(env, fullname);
  1569             if (sym.exists()) {
  1570                 // don't allow programs to use flatnames
  1571                 if (name == sym.name) return sym;
  1573             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1575         return (pack != null) ? pack : bestSoFar;
  1578     /** Find an identifier among the members of a given type `site'.
  1579      *  @param env       The current environment.
  1580      *  @param site      The type containing the symbol to be found.
  1581      *  @param name      The identifier's name.
  1582      *  @param kind      Indicates the possible symbol kinds
  1583      *                   (a subset of VAL, TYP).
  1584      */
  1585     Symbol findIdentInType(Env<AttrContext> env, Type site,
  1586                            Name name, int kind) {
  1587         Symbol bestSoFar = typeNotFound;
  1588         Symbol sym;
  1589         if ((kind & VAR) != 0) {
  1590             sym = findField(env, site, name, site.tsym);
  1591             if (sym.exists()) return sym;
  1592             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1595         if ((kind & TYP) != 0) {
  1596             sym = findMemberType(env, site, name, site.tsym);
  1597             if (sym.exists()) return sym;
  1598             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1600         return bestSoFar;
  1603 /* ***************************************************************************
  1604  *  Access checking
  1605  *  The following methods convert ResolveErrors to ErrorSymbols, issuing
  1606  *  an error message in the process
  1607  ****************************************************************************/
  1609     /** If `sym' is a bad symbol: report error and return errSymbol
  1610      *  else pass through unchanged,
  1611      *  additional arguments duplicate what has been used in trying to find the
  1612      *  symbol {@literal (--> flyweight pattern)}. This improves performance since we
  1613      *  expect misses to happen frequently.
  1615      *  @param sym       The symbol that was found, or a ResolveError.
  1616      *  @param pos       The position to use for error reporting.
  1617      *  @param site      The original type from where the selection took place.
  1618      *  @param name      The symbol's name.
  1619      *  @param argtypes  The invocation's value arguments,
  1620      *                   if we looked for a method.
  1621      *  @param typeargtypes  The invocation's type arguments,
  1622      *                   if we looked for a method.
  1623      */
  1624     Symbol access(Symbol sym,
  1625                   DiagnosticPosition pos,
  1626                   Symbol location,
  1627                   Type site,
  1628                   Name name,
  1629                   boolean qualified,
  1630                   List<Type> argtypes,
  1631                   List<Type> typeargtypes) {
  1632         if (sym.kind >= AMBIGUOUS) {
  1633             ResolveError errSym = (ResolveError)sym;
  1634             if (!site.isErroneous() &&
  1635                 !Type.isErroneous(argtypes) &&
  1636                 (typeargtypes==null || !Type.isErroneous(typeargtypes)))
  1637                 logResolveError(errSym, pos, location, site, name, argtypes, typeargtypes);
  1638             sym = errSym.access(name, qualified ? site.tsym : syms.noSymbol);
  1640         return sym;
  1643     /** Same as original access(), but without location.
  1644      */
  1645     Symbol access(Symbol sym,
  1646                   DiagnosticPosition pos,
  1647                   Type site,
  1648                   Name name,
  1649                   boolean qualified,
  1650                   List<Type> argtypes,
  1651                   List<Type> typeargtypes) {
  1652         return access(sym, pos, site.tsym, site, name, qualified, argtypes, typeargtypes);
  1655     /** Same as original access(), but without type arguments and arguments.
  1656      */
  1657     Symbol access(Symbol sym,
  1658                   DiagnosticPosition pos,
  1659                   Symbol location,
  1660                   Type site,
  1661                   Name name,
  1662                   boolean qualified) {
  1663         if (sym.kind >= AMBIGUOUS)
  1664             return access(sym, pos, location, site, name, qualified, List.<Type>nil(), null);
  1665         else
  1666             return sym;
  1669     /** Same as original access(), but without location, type arguments and arguments.
  1670      */
  1671     Symbol access(Symbol sym,
  1672                   DiagnosticPosition pos,
  1673                   Type site,
  1674                   Name name,
  1675                   boolean qualified) {
  1676         return access(sym, pos, site.tsym, site, name, qualified);
  1679     /** Check that sym is not an abstract method.
  1680      */
  1681     void checkNonAbstract(DiagnosticPosition pos, Symbol sym) {
  1682         if ((sym.flags() & ABSTRACT) != 0)
  1683             log.error(pos, "abstract.cant.be.accessed.directly",
  1684                       kindName(sym), sym, sym.location());
  1687 /* ***************************************************************************
  1688  *  Debugging
  1689  ****************************************************************************/
  1691     /** print all scopes starting with scope s and proceeding outwards.
  1692      *  used for debugging.
  1693      */
  1694     public void printscopes(Scope s) {
  1695         while (s != null) {
  1696             if (s.owner != null)
  1697                 System.err.print(s.owner + ": ");
  1698             for (Scope.Entry e = s.elems; e != null; e = e.sibling) {
  1699                 if ((e.sym.flags() & ABSTRACT) != 0)
  1700                     System.err.print("abstract ");
  1701                 System.err.print(e.sym + " ");
  1703             System.err.println();
  1704             s = s.next;
  1708     void printscopes(Env<AttrContext> env) {
  1709         while (env.outer != null) {
  1710             System.err.println("------------------------------");
  1711             printscopes(env.info.scope);
  1712             env = env.outer;
  1716     public void printscopes(Type t) {
  1717         while (t.tag == CLASS) {
  1718             printscopes(t.tsym.members());
  1719             t = types.supertype(t);
  1723 /* ***************************************************************************
  1724  *  Name resolution
  1725  *  Naming conventions are as for symbol lookup
  1726  *  Unlike the find... methods these methods will report access errors
  1727  ****************************************************************************/
  1729     /** Resolve an unqualified (non-method) identifier.
  1730      *  @param pos       The position to use for error reporting.
  1731      *  @param env       The environment current at the identifier use.
  1732      *  @param name      The identifier's name.
  1733      *  @param kind      The set of admissible symbol kinds for the identifier.
  1734      */
  1735     Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env,
  1736                         Name name, int kind) {
  1737         return access(
  1738             findIdent(env, name, kind),
  1739             pos, env.enclClass.sym.type, name, false);
  1742     /** Resolve an unqualified method identifier.
  1743      *  @param pos       The position to use for error reporting.
  1744      *  @param env       The environment current at the method invocation.
  1745      *  @param name      The identifier's name.
  1746      *  @param argtypes  The types of the invocation's value arguments.
  1747      *  @param typeargtypes  The types of the invocation's type arguments.
  1748      */
  1749     Symbol resolveMethod(DiagnosticPosition pos,
  1750                          Env<AttrContext> env,
  1751                          Name name,
  1752                          List<Type> argtypes,
  1753                          List<Type> typeargtypes) {
  1754         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  1755         try {
  1756             currentResolutionContext = new MethodResolutionContext();
  1757             Symbol sym = methodNotFound;
  1758             List<MethodResolutionPhase> steps = methodResolutionSteps;
  1759             while (steps.nonEmpty() &&
  1760                    steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  1761                    sym.kind >= ERRONEOUS) {
  1762                 currentResolutionContext.step = steps.head;
  1763                 sym = findFun(env, name, argtypes, typeargtypes,
  1764                         steps.head.isBoxingRequired,
  1765                         env.info.varArgs = steps.head.isVarargsRequired);
  1766                 currentResolutionContext.resolutionCache.put(steps.head, sym);
  1767                 steps = steps.tail;
  1769             if (sym.kind >= AMBIGUOUS) {//if nothing is found return the 'first' error
  1770                 MethodResolutionPhase errPhase =
  1771                         currentResolutionContext.firstErroneousResolutionPhase();
  1772                 sym = access(currentResolutionContext.resolutionCache.get(errPhase),
  1773                         pos, env.enclClass.sym.type, name, false, argtypes, typeargtypes);
  1774                 env.info.varArgs = errPhase.isVarargsRequired;
  1776             return sym;
  1778         finally {
  1779             currentResolutionContext = prevResolutionContext;
  1783     /** Resolve a qualified method identifier
  1784      *  @param pos       The position to use for error reporting.
  1785      *  @param env       The environment current at the method invocation.
  1786      *  @param site      The type of the qualifying expression, in which
  1787      *                   identifier is searched.
  1788      *  @param name      The identifier's name.
  1789      *  @param argtypes  The types of the invocation's value arguments.
  1790      *  @param typeargtypes  The types of the invocation's type arguments.
  1791      */
  1792     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
  1793                                   Type site, Name name, List<Type> argtypes,
  1794                                   List<Type> typeargtypes) {
  1795         return resolveQualifiedMethod(pos, env, site.tsym, site, name, argtypes, typeargtypes);
  1797     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
  1798                                   Symbol location, Type site, Name name, List<Type> argtypes,
  1799                                   List<Type> typeargtypes) {
  1800         return resolveQualifiedMethod(new MethodResolutionContext(), pos, env, location, site, name, argtypes, typeargtypes);
  1802     private Symbol resolveQualifiedMethod(MethodResolutionContext resolveContext,
  1803                                   DiagnosticPosition pos, Env<AttrContext> env,
  1804                                   Symbol location, Type site, Name name, List<Type> argtypes,
  1805                                   List<Type> typeargtypes) {
  1806         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  1807         try {
  1808             currentResolutionContext = resolveContext;
  1809             Symbol sym = methodNotFound;
  1810             List<MethodResolutionPhase> steps = methodResolutionSteps;
  1811             while (steps.nonEmpty() &&
  1812                    steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  1813                    sym.kind >= ERRONEOUS) {
  1814                 currentResolutionContext.step = steps.head;
  1815                 sym = findMethod(env, site, name, argtypes, typeargtypes,
  1816                         steps.head.isBoxingRequired(),
  1817                         env.info.varArgs = steps.head.isVarargsRequired(), false);
  1818                 currentResolutionContext.resolutionCache.put(steps.head, sym);
  1819                 steps = steps.tail;
  1821             if (sym.kind >= AMBIGUOUS) {
  1822                 //if nothing is found return the 'first' error
  1823                 MethodResolutionPhase errPhase =
  1824                         currentResolutionContext.firstErroneousResolutionPhase();
  1825                 sym = access(currentResolutionContext.resolutionCache.get(errPhase),
  1826                         pos, location, site, name, true, argtypes, typeargtypes);
  1827                 env.info.varArgs = errPhase.isVarargsRequired;
  1828             } else if (allowMethodHandles) {
  1829                 MethodSymbol msym = (MethodSymbol)sym;
  1830                 if (msym.isSignaturePolymorphic(types)) {
  1831                     env.info.varArgs = false;
  1832                     return findPolymorphicSignatureInstance(env, sym, argtypes);
  1835             return sym;
  1837         finally {
  1838             currentResolutionContext = prevResolutionContext;
  1842     /** Find or create an implicit method of exactly the given type (after erasure).
  1843      *  Searches in a side table, not the main scope of the site.
  1844      *  This emulates the lookup process required by JSR 292 in JVM.
  1845      *  @param env       Attribution environment
  1846      *  @param spMethod  signature polymorphic method - i.e. MH.invokeExact
  1847      *  @param argtypes  The required argument types
  1848      */
  1849     Symbol findPolymorphicSignatureInstance(Env<AttrContext> env,
  1850                                             Symbol spMethod,
  1851                                             List<Type> argtypes) {
  1852         Type mtype = infer.instantiatePolymorphicSignatureInstance(env,
  1853                 (MethodSymbol)spMethod, argtypes);
  1854         for (Symbol sym : polymorphicSignatureScope.getElementsByName(spMethod.name)) {
  1855             if (types.isSameType(mtype, sym.type)) {
  1856                return sym;
  1860         // create the desired method
  1861         long flags = ABSTRACT | HYPOTHETICAL | spMethod.flags() & Flags.AccessFlags;
  1862         Symbol msym = new MethodSymbol(flags, spMethod.name, mtype, spMethod.owner);
  1863         polymorphicSignatureScope.enter(msym);
  1864         return msym;
  1867     /** Resolve a qualified method identifier, throw a fatal error if not
  1868      *  found.
  1869      *  @param pos       The position to use for error reporting.
  1870      *  @param env       The environment current at the method invocation.
  1871      *  @param site      The type of the qualifying expression, in which
  1872      *                   identifier is searched.
  1873      *  @param name      The identifier's name.
  1874      *  @param argtypes  The types of the invocation's value arguments.
  1875      *  @param typeargtypes  The types of the invocation's type arguments.
  1876      */
  1877     public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env,
  1878                                         Type site, Name name,
  1879                                         List<Type> argtypes,
  1880                                         List<Type> typeargtypes) {
  1881         MethodResolutionContext resolveContext = new MethodResolutionContext();
  1882         resolveContext.internalResolution = true;
  1883         Symbol sym = resolveQualifiedMethod(resolveContext, pos, env, site.tsym,
  1884                 site, name, argtypes, typeargtypes);
  1885         if (sym.kind == MTH) return (MethodSymbol)sym;
  1886         else throw new FatalError(
  1887                  diags.fragment("fatal.err.cant.locate.meth",
  1888                                 name));
  1891     /** Resolve constructor.
  1892      *  @param pos       The position to use for error reporting.
  1893      *  @param env       The environment current at the constructor invocation.
  1894      *  @param site      The type of class for which a constructor is searched.
  1895      *  @param argtypes  The types of the constructor invocation's value
  1896      *                   arguments.
  1897      *  @param typeargtypes  The types of the constructor invocation's type
  1898      *                   arguments.
  1899      */
  1900     Symbol resolveConstructor(DiagnosticPosition pos,
  1901                               Env<AttrContext> env,
  1902                               Type site,
  1903                               List<Type> argtypes,
  1904                               List<Type> typeargtypes) {
  1905         return resolveConstructor(new MethodResolutionContext(), pos, env, site, argtypes, typeargtypes);
  1907     private Symbol resolveConstructor(MethodResolutionContext resolveContext,
  1908                               DiagnosticPosition pos,
  1909                               Env<AttrContext> env,
  1910                               Type site,
  1911                               List<Type> argtypes,
  1912                               List<Type> typeargtypes) {
  1913         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  1914         try {
  1915             currentResolutionContext = resolveContext;
  1916             Symbol sym = methodNotFound;
  1917             List<MethodResolutionPhase> steps = methodResolutionSteps;
  1918             while (steps.nonEmpty() &&
  1919                    steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  1920                    sym.kind >= ERRONEOUS) {
  1921                 currentResolutionContext.step = steps.head;
  1922                 sym = findConstructor(pos, env, site, argtypes, typeargtypes,
  1923                         steps.head.isBoxingRequired(),
  1924                         env.info.varArgs = steps.head.isVarargsRequired());
  1925                 currentResolutionContext.resolutionCache.put(steps.head, sym);
  1926                 steps = steps.tail;
  1928             if (sym.kind >= AMBIGUOUS) {//if nothing is found return the 'first' error
  1929                 MethodResolutionPhase errPhase = currentResolutionContext.firstErroneousResolutionPhase();
  1930                 sym = access(currentResolutionContext.resolutionCache.get(errPhase),
  1931                         pos, site, names.init, true, argtypes, typeargtypes);
  1932                 env.info.varArgs = errPhase.isVarargsRequired();
  1934             return sym;
  1936         finally {
  1937             currentResolutionContext = prevResolutionContext;
  1941     /** Resolve constructor using diamond inference.
  1942      *  @param pos       The position to use for error reporting.
  1943      *  @param env       The environment current at the constructor invocation.
  1944      *  @param site      The type of class for which a constructor is searched.
  1945      *                   The scope of this class has been touched in attribution.
  1946      *  @param argtypes  The types of the constructor invocation's value
  1947      *                   arguments.
  1948      *  @param typeargtypes  The types of the constructor invocation's type
  1949      *                   arguments.
  1950      */
  1951     Symbol resolveDiamond(DiagnosticPosition pos,
  1952                               Env<AttrContext> env,
  1953                               Type site,
  1954                               List<Type> argtypes,
  1955                               List<Type> typeargtypes) {
  1956         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  1957         try {
  1958             currentResolutionContext = new MethodResolutionContext();
  1959             Symbol sym = methodNotFound;
  1960             List<MethodResolutionPhase> steps = methodResolutionSteps;
  1961             while (steps.nonEmpty() &&
  1962                    steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  1963                    sym.kind >= ERRONEOUS) {
  1964                 currentResolutionContext.step = steps.head;
  1965                 sym = findDiamond(env, site, argtypes, typeargtypes,
  1966                         steps.head.isBoxingRequired(),
  1967                         env.info.varArgs = steps.head.isVarargsRequired());
  1968                 currentResolutionContext.resolutionCache.put(steps.head, sym);
  1969                 steps = steps.tail;
  1971             if (sym.kind >= AMBIGUOUS) {
  1972                 Symbol errSym =
  1973                         currentResolutionContext.resolutionCache.get(currentResolutionContext.firstErroneousResolutionPhase());
  1974                 final JCDiagnostic details = errSym.kind == WRONG_MTH ?
  1975                                 ((InapplicableSymbolError)errSym).errCandidate().details :
  1976                                 null;
  1977                 errSym = new InapplicableSymbolError(errSym.kind, "diamondError") {
  1978                     @Override
  1979                     JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos,
  1980                             Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
  1981                         String key = details == null ?
  1982                             "cant.apply.diamond" :
  1983                             "cant.apply.diamond.1";
  1984                         return diags.create(dkind, log.currentSource(), pos, key,
  1985                                 diags.fragment("diamond", site.tsym), details);
  1987                 };
  1988                 MethodResolutionPhase errPhase = currentResolutionContext.firstErroneousResolutionPhase();
  1989                 sym = access(errSym, pos, site, names.init, true, argtypes, typeargtypes);
  1990                 env.info.varArgs = errPhase.isVarargsRequired();
  1992             return sym;
  1994         finally {
  1995             currentResolutionContext = prevResolutionContext;
  1999     /** This method scans all the constructor symbol in a given class scope -
  2000      *  assuming that the original scope contains a constructor of the kind:
  2001      *  {@code Foo(X x, Y y)}, where X,Y are class type-variables declared in Foo,
  2002      *  a method check is executed against the modified constructor type:
  2003      *  {@code <X,Y>Foo<X,Y>(X x, Y y)}. This is crucial in order to enable diamond
  2004      *  inference. The inferred return type of the synthetic constructor IS
  2005      *  the inferred type for the diamond operator.
  2006      */
  2007     private Symbol findDiamond(Env<AttrContext> env,
  2008                               Type site,
  2009                               List<Type> argtypes,
  2010                               List<Type> typeargtypes,
  2011                               boolean allowBoxing,
  2012                               boolean useVarargs) {
  2013         Symbol bestSoFar = methodNotFound;
  2014         for (Scope.Entry e = site.tsym.members().lookup(names.init);
  2015              e.scope != null;
  2016              e = e.next()) {
  2017             final Symbol sym = e.sym;
  2018             //- System.out.println(" e " + e.sym);
  2019             if (sym.kind == MTH &&
  2020                 (sym.flags_field & SYNTHETIC) == 0) {
  2021                     List<Type> oldParams = e.sym.type.tag == FORALL ?
  2022                             ((ForAll)sym.type).tvars :
  2023                             List.<Type>nil();
  2024                     Type constrType = new ForAll(site.tsym.type.getTypeArguments().appendList(oldParams),
  2025                             types.createMethodTypeWithReturn(sym.type.asMethodType(), site));
  2026                     MethodSymbol newConstr = new MethodSymbol(sym.flags(), names.init, constrType, site.tsym) {
  2027                         @Override
  2028                         public Symbol baseSymbol() {
  2029                             return sym;
  2031                     };
  2032                     bestSoFar = selectBest(env, site, argtypes, typeargtypes,
  2033                             newConstr,
  2034                             bestSoFar,
  2035                             allowBoxing,
  2036                             useVarargs,
  2037                             false);
  2040         return bestSoFar;
  2043     /** Resolve constructor.
  2044      *  @param pos       The position to use for error reporting.
  2045      *  @param env       The environment current at the constructor invocation.
  2046      *  @param site      The type of class for which a constructor is searched.
  2047      *  @param argtypes  The types of the constructor invocation's value
  2048      *                   arguments.
  2049      *  @param typeargtypes  The types of the constructor invocation's type
  2050      *                   arguments.
  2051      *  @param allowBoxing Allow boxing and varargs conversions.
  2052      *  @param useVarargs Box trailing arguments into an array for varargs.
  2053      */
  2054     Symbol resolveConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  2055                               Type site, List<Type> argtypes,
  2056                               List<Type> typeargtypes,
  2057                               boolean allowBoxing,
  2058                               boolean useVarargs) {
  2059         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  2060         try {
  2061             currentResolutionContext = new MethodResolutionContext();
  2062             return findConstructor(pos, env, site, argtypes, typeargtypes, allowBoxing, useVarargs);
  2064         finally {
  2065             currentResolutionContext = prevResolutionContext;
  2069     Symbol findConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  2070                               Type site, List<Type> argtypes,
  2071                               List<Type> typeargtypes,
  2072                               boolean allowBoxing,
  2073                               boolean useVarargs) {
  2074         Symbol sym = findMethod(env, site,
  2075                                     names.init, argtypes,
  2076                                     typeargtypes, allowBoxing,
  2077                                     useVarargs, false);
  2078         chk.checkDeprecated(pos, env.info.scope.owner, sym);
  2079         return sym;
  2082     /** Resolve a constructor, throw a fatal error if not found.
  2083      *  @param pos       The position to use for error reporting.
  2084      *  @param env       The environment current at the method invocation.
  2085      *  @param site      The type to be constructed.
  2086      *  @param argtypes  The types of the invocation's value arguments.
  2087      *  @param typeargtypes  The types of the invocation's type arguments.
  2088      */
  2089     public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  2090                                         Type site,
  2091                                         List<Type> argtypes,
  2092                                         List<Type> typeargtypes) {
  2093         MethodResolutionContext resolveContext = new MethodResolutionContext();
  2094         resolveContext.internalResolution = true;
  2095         Symbol sym = resolveConstructor(resolveContext, pos, env, site, argtypes, typeargtypes);
  2096         if (sym.kind == MTH) return (MethodSymbol)sym;
  2097         else throw new FatalError(
  2098                  diags.fragment("fatal.err.cant.locate.ctor", site));
  2101     /** Resolve operator.
  2102      *  @param pos       The position to use for error reporting.
  2103      *  @param optag     The tag of the operation tree.
  2104      *  @param env       The environment current at the operation.
  2105      *  @param argtypes  The types of the operands.
  2106      */
  2107     Symbol resolveOperator(DiagnosticPosition pos, JCTree.Tag optag,
  2108                            Env<AttrContext> env, List<Type> argtypes) {
  2109         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  2110         try {
  2111             currentResolutionContext = new MethodResolutionContext();
  2112             Name name = treeinfo.operatorName(optag);
  2113             Symbol sym = findMethod(env, syms.predefClass.type, name, argtypes,
  2114                                     null, false, false, true);
  2115             if (boxingEnabled && sym.kind >= WRONG_MTHS)
  2116                 sym = findMethod(env, syms.predefClass.type, name, argtypes,
  2117                                  null, true, false, true);
  2118             return access(sym, pos, env.enclClass.sym.type, name,
  2119                           false, argtypes, null);
  2121         finally {
  2122             currentResolutionContext = prevResolutionContext;
  2126     /** Resolve operator.
  2127      *  @param pos       The position to use for error reporting.
  2128      *  @param optag     The tag of the operation tree.
  2129      *  @param env       The environment current at the operation.
  2130      *  @param arg       The type of the operand.
  2131      */
  2132     Symbol resolveUnaryOperator(DiagnosticPosition pos, JCTree.Tag optag, Env<AttrContext> env, Type arg) {
  2133         return resolveOperator(pos, optag, env, List.of(arg));
  2136     /** Resolve binary operator.
  2137      *  @param pos       The position to use for error reporting.
  2138      *  @param optag     The tag of the operation tree.
  2139      *  @param env       The environment current at the operation.
  2140      *  @param left      The types of the left operand.
  2141      *  @param right     The types of the right operand.
  2142      */
  2143     Symbol resolveBinaryOperator(DiagnosticPosition pos,
  2144                                  JCTree.Tag optag,
  2145                                  Env<AttrContext> env,
  2146                                  Type left,
  2147                                  Type right) {
  2148         return resolveOperator(pos, optag, env, List.of(left, right));
  2151     /**
  2152      * Resolve `c.name' where name == this or name == super.
  2153      * @param pos           The position to use for error reporting.
  2154      * @param env           The environment current at the expression.
  2155      * @param c             The qualifier.
  2156      * @param name          The identifier's name.
  2157      */
  2158     Symbol resolveSelf(DiagnosticPosition pos,
  2159                        Env<AttrContext> env,
  2160                        TypeSymbol c,
  2161                        Name name) {
  2162         Env<AttrContext> env1 = env;
  2163         boolean staticOnly = false;
  2164         while (env1.outer != null) {
  2165             if (isStatic(env1)) staticOnly = true;
  2166             if (env1.enclClass.sym == c) {
  2167                 Symbol sym = env1.info.scope.lookup(name).sym;
  2168                 if (sym != null) {
  2169                     if (staticOnly) sym = new StaticError(sym);
  2170                     return access(sym, pos, env.enclClass.sym.type,
  2171                                   name, true);
  2174             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  2175             env1 = env1.outer;
  2177         log.error(pos, "not.encl.class", c);
  2178         return syms.errSymbol;
  2181     /**
  2182      * Resolve `c.this' for an enclosing class c that contains the
  2183      * named member.
  2184      * @param pos           The position to use for error reporting.
  2185      * @param env           The environment current at the expression.
  2186      * @param member        The member that must be contained in the result.
  2187      */
  2188     Symbol resolveSelfContaining(DiagnosticPosition pos,
  2189                                  Env<AttrContext> env,
  2190                                  Symbol member,
  2191                                  boolean isSuperCall) {
  2192         Name name = names._this;
  2193         Env<AttrContext> env1 = isSuperCall ? env.outer : env;
  2194         boolean staticOnly = false;
  2195         if (env1 != null) {
  2196             while (env1 != null && env1.outer != null) {
  2197                 if (isStatic(env1)) staticOnly = true;
  2198                 if (env1.enclClass.sym.isSubClass(member.owner, types)) {
  2199                     Symbol sym = env1.info.scope.lookup(name).sym;
  2200                     if (sym != null) {
  2201                         if (staticOnly) sym = new StaticError(sym);
  2202                         return access(sym, pos, env.enclClass.sym.type,
  2203                                       name, true);
  2206                 if ((env1.enclClass.sym.flags() & STATIC) != 0)
  2207                     staticOnly = true;
  2208                 env1 = env1.outer;
  2211         log.error(pos, "encl.class.required", member);
  2212         return syms.errSymbol;
  2215     /**
  2216      * Resolve an appropriate implicit this instance for t's container.
  2217      * JLS 8.8.5.1 and 15.9.2
  2218      */
  2219     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
  2220         return resolveImplicitThis(pos, env, t, false);
  2223     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t, boolean isSuperCall) {
  2224         Type thisType = (((t.tsym.owner.kind & (MTH|VAR)) != 0)
  2225                          ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
  2226                          : resolveSelfContaining(pos, env, t.tsym, isSuperCall)).type;
  2227         if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
  2228             log.error(pos, "cant.ref.before.ctor.called", "this");
  2229         return thisType;
  2232 /* ***************************************************************************
  2233  *  ResolveError classes, indicating error situations when accessing symbols
  2234  ****************************************************************************/
  2236     //used by TransTypes when checking target type of synthetic cast
  2237     public void logAccessErrorInternal(Env<AttrContext> env, JCTree tree, Type type) {
  2238         AccessError error = new AccessError(env, env.enclClass.type, type.tsym);
  2239         logResolveError(error, tree.pos(), env.enclClass.sym, env.enclClass.type, null, null, null);
  2241     //where
  2242     private void logResolveError(ResolveError error,
  2243             DiagnosticPosition pos,
  2244             Symbol location,
  2245             Type site,
  2246             Name name,
  2247             List<Type> argtypes,
  2248             List<Type> typeargtypes) {
  2249         JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
  2250                 pos, location, site, name, argtypes, typeargtypes);
  2251         if (d != null) {
  2252             d.setFlag(DiagnosticFlag.RESOLVE_ERROR);
  2253             log.report(d);
  2257     private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
  2259     public Object methodArguments(List<Type> argtypes) {
  2260         return argtypes == null || argtypes.isEmpty() ? noArgs : argtypes;
  2263     /**
  2264      * Root class for resolution errors. Subclass of ResolveError
  2265      * represent a different kinds of resolution error - as such they must
  2266      * specify how they map into concrete compiler diagnostics.
  2267      */
  2268     private abstract class ResolveError extends Symbol {
  2270         /** The name of the kind of error, for debugging only. */
  2271         final String debugName;
  2273         ResolveError(int kind, String debugName) {
  2274             super(kind, 0, null, null, null);
  2275             this.debugName = debugName;
  2278         @Override
  2279         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
  2280             throw new AssertionError();
  2283         @Override
  2284         public String toString() {
  2285             return debugName;
  2288         @Override
  2289         public boolean exists() {
  2290             return false;
  2293         /**
  2294          * Create an external representation for this erroneous symbol to be
  2295          * used during attribution - by default this returns the symbol of a
  2296          * brand new error type which stores the original type found
  2297          * during resolution.
  2299          * @param name     the name used during resolution
  2300          * @param location the location from which the symbol is accessed
  2301          */
  2302         protected Symbol access(Name name, TypeSymbol location) {
  2303             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  2306         /**
  2307          * Create a diagnostic representing this resolution error.
  2309          * @param dkind     The kind of the diagnostic to be created (e.g error).
  2310          * @param pos       The position to be used for error reporting.
  2311          * @param site      The original type from where the selection took place.
  2312          * @param name      The name of the symbol to be resolved.
  2313          * @param argtypes  The invocation's value arguments,
  2314          *                  if we looked for a method.
  2315          * @param typeargtypes  The invocation's type arguments,
  2316          *                      if we looked for a method.
  2317          */
  2318         abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2319                 DiagnosticPosition pos,
  2320                 Symbol location,
  2321                 Type site,
  2322                 Name name,
  2323                 List<Type> argtypes,
  2324                 List<Type> typeargtypes);
  2326         /**
  2327          * A name designates an operator if it consists
  2328          * of a non-empty sequence of operator symbols {@literal +-~!/*%&|^<>= }
  2329          */
  2330         boolean isOperator(Name name) {
  2331             int i = 0;
  2332             while (i < name.getByteLength() &&
  2333                    "+-~!*/%&|^<>=".indexOf(name.getByteAt(i)) >= 0) i++;
  2334             return i > 0 && i == name.getByteLength();
  2338     /**
  2339      * This class is the root class of all resolution errors caused by
  2340      * an invalid symbol being found during resolution.
  2341      */
  2342     abstract class InvalidSymbolError extends ResolveError {
  2344         /** The invalid symbol found during resolution */
  2345         Symbol sym;
  2347         InvalidSymbolError(int kind, Symbol sym, String debugName) {
  2348             super(kind, debugName);
  2349             this.sym = sym;
  2352         @Override
  2353         public boolean exists() {
  2354             return true;
  2357         @Override
  2358         public String toString() {
  2359              return super.toString() + " wrongSym=" + sym;
  2362         @Override
  2363         public Symbol access(Name name, TypeSymbol location) {
  2364             if (sym.kind >= AMBIGUOUS)
  2365                 return ((ResolveError)sym).access(name, location);
  2366             else if ((sym.kind & ERRONEOUS) == 0 && (sym.kind & TYP) != 0)
  2367                 return types.createErrorType(name, location, sym.type).tsym;
  2368             else
  2369                 return sym;
  2373     /**
  2374      * InvalidSymbolError error class indicating that a symbol matching a
  2375      * given name does not exists in a given site.
  2376      */
  2377     class SymbolNotFoundError extends ResolveError {
  2379         SymbolNotFoundError(int kind) {
  2380             super(kind, "symbol not found error");
  2383         @Override
  2384         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2385                 DiagnosticPosition pos,
  2386                 Symbol location,
  2387                 Type site,
  2388                 Name name,
  2389                 List<Type> argtypes,
  2390                 List<Type> typeargtypes) {
  2391             argtypes = argtypes == null ? List.<Type>nil() : argtypes;
  2392             typeargtypes = typeargtypes == null ? List.<Type>nil() : typeargtypes;
  2393             if (name == names.error)
  2394                 return null;
  2396             if (isOperator(name)) {
  2397                 boolean isUnaryOp = argtypes.size() == 1;
  2398                 String key = argtypes.size() == 1 ?
  2399                     "operator.cant.be.applied" :
  2400                     "operator.cant.be.applied.1";
  2401                 Type first = argtypes.head;
  2402                 Type second = !isUnaryOp ? argtypes.tail.head : null;
  2403                 return diags.create(dkind, log.currentSource(), pos,
  2404                         key, name, first, second);
  2406             boolean hasLocation = false;
  2407             if (location == null) {
  2408                 location = site.tsym;
  2410             if (!location.name.isEmpty()) {
  2411                 if (location.kind == PCK && !site.tsym.exists()) {
  2412                     return diags.create(dkind, log.currentSource(), pos,
  2413                         "doesnt.exist", location);
  2415                 hasLocation = !location.name.equals(names._this) &&
  2416                         !location.name.equals(names._super);
  2418             boolean isConstructor = kind == ABSENT_MTH &&
  2419                     name == names.table.names.init;
  2420             KindName kindname = isConstructor ? KindName.CONSTRUCTOR : absentKind(kind);
  2421             Name idname = isConstructor ? site.tsym.name : name;
  2422             String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation);
  2423             if (hasLocation) {
  2424                 return diags.create(dkind, log.currentSource(), pos,
  2425                         errKey, kindname, idname, //symbol kindname, name
  2426                         typeargtypes, argtypes, //type parameters and arguments (if any)
  2427                         getLocationDiag(location, site)); //location kindname, type
  2429             else {
  2430                 return diags.create(dkind, log.currentSource(), pos,
  2431                         errKey, kindname, idname, //symbol kindname, name
  2432                         typeargtypes, argtypes); //type parameters and arguments (if any)
  2435         //where
  2436         private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) {
  2437             String key = "cant.resolve";
  2438             String suffix = hasLocation ? ".location" : "";
  2439             switch (kindname) {
  2440                 case METHOD:
  2441                 case CONSTRUCTOR: {
  2442                     suffix += ".args";
  2443                     suffix += hasTypeArgs ? ".params" : "";
  2446             return key + suffix;
  2448         private JCDiagnostic getLocationDiag(Symbol location, Type site) {
  2449             if (location.kind == VAR) {
  2450                 return diags.fragment("location.1",
  2451                     kindName(location),
  2452                     location,
  2453                     location.type);
  2454             } else {
  2455                 return diags.fragment("location",
  2456                     typeKindName(site),
  2457                     site,
  2458                     null);
  2463     /**
  2464      * InvalidSymbolError error class indicating that a given symbol
  2465      * (either a method, a constructor or an operand) is not applicable
  2466      * given an actual arguments/type argument list.
  2467      */
  2468     class InapplicableSymbolError extends ResolveError {
  2470         InapplicableSymbolError() {
  2471             super(WRONG_MTH, "inapplicable symbol error");
  2474         protected InapplicableSymbolError(int kind, String debugName) {
  2475             super(kind, debugName);
  2478         @Override
  2479         public String toString() {
  2480             return super.toString();
  2483         @Override
  2484         public boolean exists() {
  2485             return true;
  2488         @Override
  2489         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2490                 DiagnosticPosition pos,
  2491                 Symbol location,
  2492                 Type site,
  2493                 Name name,
  2494                 List<Type> argtypes,
  2495                 List<Type> typeargtypes) {
  2496             if (name == names.error)
  2497                 return null;
  2499             if (isOperator(name)) {
  2500                 boolean isUnaryOp = argtypes.size() == 1;
  2501                 String key = argtypes.size() == 1 ?
  2502                     "operator.cant.be.applied" :
  2503                     "operator.cant.be.applied.1";
  2504                 Type first = argtypes.head;
  2505                 Type second = !isUnaryOp ? argtypes.tail.head : null;
  2506                 return diags.create(dkind, log.currentSource(), pos,
  2507                         key, name, first, second);
  2509             else {
  2510                 Candidate c = errCandidate();
  2511                 Symbol ws = c.sym.asMemberOf(site, types);
  2512                 return diags.create(dkind, log.currentSource(), pos,
  2513                           "cant.apply.symbol" + (c.details != null ? ".1" : ""),
  2514                           kindName(ws),
  2515                           ws.name == names.init ? ws.owner.name : ws.name,
  2516                           methodArguments(ws.type.getParameterTypes()),
  2517                           methodArguments(argtypes),
  2518                           kindName(ws.owner),
  2519                           ws.owner.type,
  2520                           c.details);
  2524         @Override
  2525         public Symbol access(Name name, TypeSymbol location) {
  2526             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  2529         protected boolean shouldReport(Candidate c) {
  2530             return !c.isApplicable() &&
  2531                     (((c.sym.flags() & VARARGS) != 0 && c.step == VARARITY) ||
  2532                       (c.sym.flags() & VARARGS) == 0 && c.step == (boxingEnabled ? BOX : BASIC));
  2535         private Candidate errCandidate() {
  2536             for (Candidate c : currentResolutionContext.candidates) {
  2537                 if (shouldReport(c)) {
  2538                     return c;
  2541             Assert.error();
  2542             return null;
  2546     /**
  2547      * ResolveError error class indicating that a set of symbols
  2548      * (either methods, constructors or operands) is not applicable
  2549      * given an actual arguments/type argument list.
  2550      */
  2551     class InapplicableSymbolsError extends InapplicableSymbolError {
  2553         InapplicableSymbolsError() {
  2554             super(WRONG_MTHS, "inapplicable symbols");
  2557         @Override
  2558         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2559                 DiagnosticPosition pos,
  2560                 Symbol location,
  2561                 Type site,
  2562                 Name name,
  2563                 List<Type> argtypes,
  2564                 List<Type> typeargtypes) {
  2565             if (currentResolutionContext.candidates.nonEmpty()) {
  2566                 JCDiagnostic err = diags.create(dkind,
  2567                         log.currentSource(),
  2568                         pos,
  2569                         "cant.apply.symbols",
  2570                         name == names.init ? KindName.CONSTRUCTOR : absentKind(kind),
  2571                         getName(),
  2572                         argtypes);
  2573                 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(site));
  2574             } else {
  2575                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
  2576                     location, site, name, argtypes, typeargtypes);
  2580         //where
  2581         List<JCDiagnostic> candidateDetails(Type site) {
  2582             List<JCDiagnostic> details = List.nil();
  2583             for (Candidate c : currentResolutionContext.candidates) {
  2584                 if (!shouldReport(c)) continue;
  2585                 JCDiagnostic detailDiag = diags.fragment("inapplicable.method",
  2586                         Kinds.kindName(c.sym),
  2587                         c.sym.location(site, types),
  2588                         c.sym.asMemberOf(site, types),
  2589                         c.details);
  2590                 details = details.prepend(detailDiag);
  2592             return details.reverse();
  2595         private Name getName() {
  2596             Symbol sym = currentResolutionContext.candidates.head.sym;
  2597             return sym.name == names.init ?
  2598                 sym.owner.name :
  2599                 sym.name;
  2603     /**
  2604      * An InvalidSymbolError error class indicating that a symbol is not
  2605      * accessible from a given site
  2606      */
  2607     class AccessError extends InvalidSymbolError {
  2609         private Env<AttrContext> env;
  2610         private Type site;
  2612         AccessError(Symbol sym) {
  2613             this(null, null, sym);
  2616         AccessError(Env<AttrContext> env, Type site, Symbol sym) {
  2617             super(HIDDEN, sym, "access error");
  2618             this.env = env;
  2619             this.site = site;
  2620             if (debugResolve)
  2621                 log.error("proc.messager", sym + " @ " + site + " is inaccessible.");
  2624         @Override
  2625         public boolean exists() {
  2626             return false;
  2629         @Override
  2630         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2631                 DiagnosticPosition pos,
  2632                 Symbol location,
  2633                 Type site,
  2634                 Name name,
  2635                 List<Type> argtypes,
  2636                 List<Type> typeargtypes) {
  2637             if (sym.owner.type.tag == ERROR)
  2638                 return null;
  2640             if (sym.name == names.init && sym.owner != site.tsym) {
  2641                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
  2642                         pos, location, site, name, argtypes, typeargtypes);
  2644             else if ((sym.flags() & PUBLIC) != 0
  2645                 || (env != null && this.site != null
  2646                     && !isAccessible(env, this.site))) {
  2647                 return diags.create(dkind, log.currentSource(),
  2648                         pos, "not.def.access.class.intf.cant.access",
  2649                     sym, sym.location());
  2651             else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) {
  2652                 return diags.create(dkind, log.currentSource(),
  2653                         pos, "report.access", sym,
  2654                         asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
  2655                         sym.location());
  2657             else {
  2658                 return diags.create(dkind, log.currentSource(),
  2659                         pos, "not.def.public.cant.access", sym, sym.location());
  2664     /**
  2665      * InvalidSymbolError error class indicating that an instance member
  2666      * has erroneously been accessed from a static context.
  2667      */
  2668     class StaticError extends InvalidSymbolError {
  2670         StaticError(Symbol sym) {
  2671             super(STATICERR, sym, "static error");
  2674         @Override
  2675         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2676                 DiagnosticPosition pos,
  2677                 Symbol location,
  2678                 Type site,
  2679                 Name name,
  2680                 List<Type> argtypes,
  2681                 List<Type> typeargtypes) {
  2682             Symbol errSym = ((sym.kind == TYP && sym.type.tag == CLASS)
  2683                 ? types.erasure(sym.type).tsym
  2684                 : sym);
  2685             return diags.create(dkind, log.currentSource(), pos,
  2686                     "non-static.cant.be.ref", kindName(sym), errSym);
  2690     /**
  2691      * InvalidSymbolError error class indicating that a pair of symbols
  2692      * (either methods, constructors or operands) are ambiguous
  2693      * given an actual arguments/type argument list.
  2694      */
  2695     class AmbiguityError extends InvalidSymbolError {
  2697         /** The other maximally specific symbol */
  2698         Symbol sym2;
  2700         AmbiguityError(Symbol sym1, Symbol sym2) {
  2701             super(AMBIGUOUS, sym1, "ambiguity error");
  2702             this.sym2 = sym2;
  2705         @Override
  2706         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2707                 DiagnosticPosition pos,
  2708                 Symbol location,
  2709                 Type site,
  2710                 Name name,
  2711                 List<Type> argtypes,
  2712                 List<Type> typeargtypes) {
  2713             AmbiguityError pair = this;
  2714             while (true) {
  2715                 if (pair.sym.kind == AMBIGUOUS)
  2716                     pair = (AmbiguityError)pair.sym;
  2717                 else if (pair.sym2.kind == AMBIGUOUS)
  2718                     pair = (AmbiguityError)pair.sym2;
  2719                 else break;
  2721             Name sname = pair.sym.name;
  2722             if (sname == names.init) sname = pair.sym.owner.name;
  2723             return diags.create(dkind, log.currentSource(),
  2724                       pos, "ref.ambiguous", sname,
  2725                       kindName(pair.sym),
  2726                       pair.sym,
  2727                       pair.sym.location(site, types),
  2728                       kindName(pair.sym2),
  2729                       pair.sym2,
  2730                       pair.sym2.location(site, types));
  2734     enum MethodResolutionPhase {
  2735         BASIC(false, false),
  2736         BOX(true, false),
  2737         VARARITY(true, true);
  2739         boolean isBoxingRequired;
  2740         boolean isVarargsRequired;
  2742         MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) {
  2743            this.isBoxingRequired = isBoxingRequired;
  2744            this.isVarargsRequired = isVarargsRequired;
  2747         public boolean isBoxingRequired() {
  2748             return isBoxingRequired;
  2751         public boolean isVarargsRequired() {
  2752             return isVarargsRequired;
  2755         public boolean isApplicable(boolean boxingEnabled, boolean varargsEnabled) {
  2756             return (varargsEnabled || !isVarargsRequired) &&
  2757                    (boxingEnabled || !isBoxingRequired);
  2761     final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
  2763     /**
  2764      * A resolution context is used to keep track of intermediate results of
  2765      * overload resolution, such as list of method that are not applicable
  2766      * (used to generate more precise diagnostics) and so on. Resolution contexts
  2767      * can be nested - this means that when each overload resolution routine should
  2768      * work within the resolution context it created.
  2769      */
  2770     class MethodResolutionContext {
  2772         private List<Candidate> candidates = List.nil();
  2774         private Map<MethodResolutionPhase, Symbol> resolutionCache =
  2775             new EnumMap<MethodResolutionPhase, Symbol>(MethodResolutionPhase.class);
  2777         private MethodResolutionPhase step = null;
  2779         private boolean internalResolution = false;
  2781         private MethodResolutionPhase firstErroneousResolutionPhase() {
  2782             MethodResolutionPhase bestSoFar = BASIC;
  2783             Symbol sym = methodNotFound;
  2784             List<MethodResolutionPhase> steps = methodResolutionSteps;
  2785             while (steps.nonEmpty() &&
  2786                    steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  2787                    sym.kind >= WRONG_MTHS) {
  2788                 sym = resolutionCache.get(steps.head);
  2789                 bestSoFar = steps.head;
  2790                 steps = steps.tail;
  2792             return bestSoFar;
  2795         void addInapplicableCandidate(Symbol sym, JCDiagnostic details) {
  2796             Candidate c = new Candidate(currentResolutionContext.step, sym, details, null);
  2797             if (!candidates.contains(c))
  2798                 candidates = candidates.append(c);
  2801         void addApplicableCandidate(Symbol sym, Type mtype) {
  2802             Candidate c = new Candidate(currentResolutionContext.step, sym, null, mtype);
  2803             candidates = candidates.append(c);
  2806         /**
  2807          * This class represents an overload resolution candidate. There are two
  2808          * kinds of candidates: applicable methods and inapplicable methods;
  2809          * applicable methods have a pointer to the instantiated method type,
  2810          * while inapplicable candidates contain further details about the
  2811          * reason why the method has been considered inapplicable.
  2812          */
  2813         class Candidate {
  2815             final MethodResolutionPhase step;
  2816             final Symbol sym;
  2817             final JCDiagnostic details;
  2818             final Type mtype;
  2820             private Candidate(MethodResolutionPhase step, Symbol sym, JCDiagnostic details, Type mtype) {
  2821                 this.step = step;
  2822                 this.sym = sym;
  2823                 this.details = details;
  2824                 this.mtype = mtype;
  2827             @Override
  2828             public boolean equals(Object o) {
  2829                 if (o instanceof Candidate) {
  2830                     Symbol s1 = this.sym;
  2831                     Symbol s2 = ((Candidate)o).sym;
  2832                     if  ((s1 != s2 &&
  2833                         (s1.overrides(s2, s1.owner.type.tsym, types, false) ||
  2834                         (s2.overrides(s1, s2.owner.type.tsym, types, false)))) ||
  2835                         ((s1.isConstructor() || s2.isConstructor()) && s1.owner != s2.owner))
  2836                         return true;
  2838                 return false;
  2841             boolean isApplicable() {
  2842                 return mtype != null;
  2847     MethodResolutionContext currentResolutionContext = null;

mercurial