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

Sat, 18 Sep 2010 09:56:23 -0700

author
mcimadamore
date
Sat, 18 Sep 2010 09:56:23 -0700
changeset 689
77cc34d5e548
parent 674
584365f256a7
child 700
7b413ac1a720
permissions
-rw-r--r--

5088624: cannot find symbol message should be more intelligent
Summary: Resolve.java should keep track of all candidates found during a method resolution sweep to generate more meaningful diagnostics
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 1999, 2008, 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.util.*;
    29 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    30 import com.sun.tools.javac.code.*;
    31 import com.sun.tools.javac.jvm.*;
    32 import com.sun.tools.javac.tree.*;
    33 import com.sun.tools.javac.api.Formattable.LocalizedString;
    34 import static com.sun.tools.javac.comp.Resolve.MethodResolutionPhase.*;
    36 import com.sun.tools.javac.code.Type.*;
    37 import com.sun.tools.javac.code.Symbol.*;
    38 import com.sun.tools.javac.tree.JCTree.*;
    40 import static com.sun.tools.javac.code.Flags.*;
    41 import static com.sun.tools.javac.code.Kinds.*;
    42 import static com.sun.tools.javac.code.TypeTags.*;
    43 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
    44 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType;
    45 import javax.lang.model.element.ElementVisitor;
    47 import java.util.Map;
    48 import java.util.HashMap;
    50 /** Helper class for name resolution, used mostly by the attribution phase.
    51  *
    52  *  <p><b>This is NOT part of any supported API.
    53  *  If you write code that depends on this, you do so at your own risk.
    54  *  This code and its internal interfaces are subject to change or
    55  *  deletion without notice.</b>
    56  */
    57 public class Resolve {
    58     protected static final Context.Key<Resolve> resolveKey =
    59         new Context.Key<Resolve>();
    61     Names names;
    62     Log log;
    63     Symtab syms;
    64     Check chk;
    65     Infer infer;
    66     ClassReader reader;
    67     TreeInfo treeinfo;
    68     Types types;
    69     JCDiagnostic.Factory diags;
    70     public final boolean boxingEnabled; // = source.allowBoxing();
    71     public final boolean varargsEnabled; // = source.allowVarargs();
    72     public final boolean allowMethodHandles;
    73     public final boolean allowInvokeDynamic;
    74     public final boolean allowTransitionalJSR292;
    75     private final boolean debugResolve;
    77     Scope polymorphicSignatureScope;
    79     public static Resolve instance(Context context) {
    80         Resolve instance = context.get(resolveKey);
    81         if (instance == null)
    82             instance = new Resolve(context);
    83         return instance;
    84     }
    86     protected Resolve(Context context) {
    87         context.put(resolveKey, this);
    88         syms = Symtab.instance(context);
    90         varNotFound = new
    91             SymbolNotFoundError(ABSENT_VAR);
    92         wrongMethod = new
    93             InapplicableSymbolError(syms.errSymbol);
    94         wrongMethods = new
    95             InapplicableSymbolsError(syms.errSymbol);
    96         methodNotFound = new
    97             SymbolNotFoundError(ABSENT_MTH);
    98         typeNotFound = new
    99             SymbolNotFoundError(ABSENT_TYP);
   101         names = Names.instance(context);
   102         log = Log.instance(context);
   103         chk = Check.instance(context);
   104         infer = Infer.instance(context);
   105         reader = ClassReader.instance(context);
   106         treeinfo = TreeInfo.instance(context);
   107         types = Types.instance(context);
   108         diags = JCDiagnostic.Factory.instance(context);
   109         Source source = Source.instance(context);
   110         boxingEnabled = source.allowBoxing();
   111         varargsEnabled = source.allowVarargs();
   112         Options options = Options.instance(context);
   113         debugResolve = options.get("debugresolve") != null;
   114         allowTransitionalJSR292 = options.get("allowTransitionalJSR292") != null;
   115         Target target = Target.instance(context);
   116         allowMethodHandles = allowTransitionalJSR292 ||
   117                 target.hasMethodHandles();
   118         allowInvokeDynamic = (allowTransitionalJSR292 ||
   119                 target.hasInvokedynamic()) &&
   120                 options.get("invokedynamic") != null;
   121         polymorphicSignatureScope = new Scope(syms.noSymbol);
   123         inapplicableMethodException = new InapplicableMethodException(diags);
   124     }
   126     /** error symbols, which are returned when resolution fails
   127      */
   128     final SymbolNotFoundError varNotFound;
   129     final InapplicableSymbolError wrongMethod;
   130     final InapplicableSymbolsError wrongMethods;
   131     final SymbolNotFoundError methodNotFound;
   132     final SymbolNotFoundError typeNotFound;
   134 /* ************************************************************************
   135  * Identifier resolution
   136  *************************************************************************/
   138     /** An environment is "static" if its static level is greater than
   139      *  the one of its outer environment
   140      */
   141     static boolean isStatic(Env<AttrContext> env) {
   142         return env.info.staticLevel > env.outer.info.staticLevel;
   143     }
   145     /** An environment is an "initializer" if it is a constructor or
   146      *  an instance initializer.
   147      */
   148     static boolean isInitializer(Env<AttrContext> env) {
   149         Symbol owner = env.info.scope.owner;
   150         return owner.isConstructor() ||
   151             owner.owner.kind == TYP &&
   152             (owner.kind == VAR ||
   153              owner.kind == MTH && (owner.flags() & BLOCK) != 0) &&
   154             (owner.flags() & STATIC) == 0;
   155     }
   157     /** Is class accessible in given evironment?
   158      *  @param env    The current environment.
   159      *  @param c      The class whose accessibility is checked.
   160      */
   161     public boolean isAccessible(Env<AttrContext> env, TypeSymbol c) {
   162         switch ((short)(c.flags() & AccessFlags)) {
   163         case PRIVATE:
   164             return
   165                 env.enclClass.sym.outermostClass() ==
   166                 c.owner.outermostClass();
   167         case 0:
   168             return
   169                 env.toplevel.packge == c.owner // fast special case
   170                 ||
   171                 env.toplevel.packge == c.packge()
   172                 ||
   173                 // Hack: this case is added since synthesized default constructors
   174                 // of anonymous classes should be allowed to access
   175                 // classes which would be inaccessible otherwise.
   176                 env.enclMethod != null &&
   177                 (env.enclMethod.mods.flags & ANONCONSTR) != 0;
   178         default: // error recovery
   179         case PUBLIC:
   180             return true;
   181         case PROTECTED:
   182             return
   183                 env.toplevel.packge == c.owner // fast special case
   184                 ||
   185                 env.toplevel.packge == c.packge()
   186                 ||
   187                 isInnerSubClass(env.enclClass.sym, c.owner);
   188         }
   189     }
   190     //where
   191         /** Is given class a subclass of given base class, or an inner class
   192          *  of a subclass?
   193          *  Return null if no such class exists.
   194          *  @param c     The class which is the subclass or is contained in it.
   195          *  @param base  The base class
   196          */
   197         private boolean isInnerSubClass(ClassSymbol c, Symbol base) {
   198             while (c != null && !c.isSubClass(base, types)) {
   199                 c = c.owner.enclClass();
   200             }
   201             return c != null;
   202         }
   204     boolean isAccessible(Env<AttrContext> env, Type t) {
   205         return (t.tag == ARRAY)
   206             ? isAccessible(env, types.elemtype(t))
   207             : isAccessible(env, t.tsym);
   208     }
   210     /** Is symbol accessible as a member of given type in given evironment?
   211      *  @param env    The current environment.
   212      *  @param site   The type of which the tested symbol is regarded
   213      *                as a member.
   214      *  @param sym    The symbol.
   215      */
   216     public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym) {
   217         if (sym.name == names.init && sym.owner != site.tsym) return false;
   218         ClassSymbol sub;
   219         switch ((short)(sym.flags() & AccessFlags)) {
   220         case PRIVATE:
   221             return
   222                 (env.enclClass.sym == sym.owner // fast special case
   223                  ||
   224                  env.enclClass.sym.outermostClass() ==
   225                  sym.owner.outermostClass())
   226                 &&
   227                 sym.isInheritedIn(site.tsym, types);
   228         case 0:
   229             return
   230                 (env.toplevel.packge == sym.owner.owner // fast special case
   231                  ||
   232                  env.toplevel.packge == sym.packge())
   233                 &&
   234                 isAccessible(env, site)
   235                 &&
   236                 sym.isInheritedIn(site.tsym, types)
   237                 &&
   238                 notOverriddenIn(site, sym);
   239         case PROTECTED:
   240             return
   241                 (env.toplevel.packge == sym.owner.owner // fast special case
   242                  ||
   243                  env.toplevel.packge == sym.packge()
   244                  ||
   245                  isProtectedAccessible(sym, env.enclClass.sym, site)
   246                  ||
   247                  // OK to select instance method or field from 'super' or type name
   248                  // (but type names should be disallowed elsewhere!)
   249                  env.info.selectSuper && (sym.flags() & STATIC) == 0 && sym.kind != TYP)
   250                 &&
   251                 isAccessible(env, site)
   252                 &&
   253                 notOverriddenIn(site, sym);
   254         default: // this case includes erroneous combinations as well
   255             return isAccessible(env, site) && notOverriddenIn(site, sym);
   256         }
   257     }
   258     //where
   259     /* `sym' is accessible only if not overridden by
   260      * another symbol which is a member of `site'
   261      * (because, if it is overridden, `sym' is not strictly
   262      * speaking a member of `site'). A polymorphic signature method
   263      * cannot be overridden (e.g. MH.invokeExact(Object[])).
   264      */
   265     private boolean notOverriddenIn(Type site, Symbol sym) {
   266         if (sym.kind != MTH || sym.isConstructor() || sym.isStatic())
   267             return true;
   268         else {
   269             Symbol s2 = ((MethodSymbol)sym).implementation(site.tsym, types, true);
   270             return (s2 == null || s2 == sym ||
   271                     s2.isPolymorphicSignatureGeneric() ||
   272                     !types.isSubSignature(types.memberType(site, s2), types.memberType(site, sym)));
   273         }
   274     }
   275     //where
   276         /** Is given protected symbol accessible if it is selected from given site
   277          *  and the selection takes place in given class?
   278          *  @param sym     The symbol with protected access
   279          *  @param c       The class where the access takes place
   280          *  @site          The type of the qualifier
   281          */
   282         private
   283         boolean isProtectedAccessible(Symbol sym, ClassSymbol c, Type site) {
   284             while (c != null &&
   285                    !(c.isSubClass(sym.owner, types) &&
   286                      (c.flags() & INTERFACE) == 0 &&
   287                      // In JLS 2e 6.6.2.1, the subclass restriction applies
   288                      // only to instance fields and methods -- types are excluded
   289                      // regardless of whether they are declared 'static' or not.
   290                      ((sym.flags() & STATIC) != 0 || sym.kind == TYP || site.tsym.isSubClass(c, types))))
   291                 c = c.owner.enclClass();
   292             return c != null;
   293         }
   295     /** Try to instantiate the type of a method so that it fits
   296      *  given type arguments and argument types. If succesful, return
   297      *  the method's instantiated type, else return null.
   298      *  The instantiation will take into account an additional leading
   299      *  formal parameter if the method is an instance method seen as a member
   300      *  of un underdetermined site In this case, we treat site as an additional
   301      *  parameter and the parameters of the class containing the method as
   302      *  additional type variables that get instantiated.
   303      *
   304      *  @param env         The current environment
   305      *  @param site        The type of which the method is a member.
   306      *  @param m           The method symbol.
   307      *  @param argtypes    The invocation's given value arguments.
   308      *  @param typeargtypes    The invocation's given type arguments.
   309      *  @param allowBoxing Allow boxing conversions of arguments.
   310      *  @param useVarargs Box trailing arguments into an array for varargs.
   311      */
   312     Type rawInstantiate(Env<AttrContext> env,
   313                         Type site,
   314                         Symbol m,
   315                         List<Type> argtypes,
   316                         List<Type> typeargtypes,
   317                         boolean allowBoxing,
   318                         boolean useVarargs,
   319                         Warner warn)
   320         throws Infer.InferenceException {
   321         boolean polymorphicSignature = (m.isPolymorphicSignatureGeneric() && allowMethodHandles) ||
   322                                         isTransitionalDynamicCallSite(site, m);
   323         if (useVarargs && (m.flags() & VARARGS) == 0)
   324             throw inapplicableMethodException.setMessage(null);
   325         Type mt = types.memberType(site, m);
   327         // tvars is the list of formal type variables for which type arguments
   328         // need to inferred.
   329         List<Type> tvars = env.info.tvars;
   330         if (typeargtypes == null) typeargtypes = List.nil();
   331         if (allowTransitionalJSR292 && polymorphicSignature && typeargtypes.nonEmpty()) {
   332             //transitional 292 call sites might have wrong number of targs
   333         }
   334         else if (mt.tag != FORALL && typeargtypes.nonEmpty()) {
   335             // This is not a polymorphic method, but typeargs are supplied
   336             // which is fine, see JLS3 15.12.2.1
   337         } else if (mt.tag == FORALL && typeargtypes.nonEmpty()) {
   338             ForAll pmt = (ForAll) mt;
   339             if (typeargtypes.length() != pmt.tvars.length())
   340                 throw inapplicableMethodException.setMessage("arg.length.mismatch"); // not enough args
   341             // Check type arguments are within bounds
   342             List<Type> formals = pmt.tvars;
   343             List<Type> actuals = typeargtypes;
   344             while (formals.nonEmpty() && actuals.nonEmpty()) {
   345                 List<Type> bounds = types.subst(types.getBounds((TypeVar)formals.head),
   346                                                 pmt.tvars, typeargtypes);
   347                 for (; bounds.nonEmpty(); bounds = bounds.tail)
   348                     if (!types.isSubtypeUnchecked(actuals.head, bounds.head, warn))
   349                         throw inapplicableMethodException.setMessage("explicit.param.do.not.conform.to.bounds",actuals.head, bounds);
   350                 formals = formals.tail;
   351                 actuals = actuals.tail;
   352             }
   353             mt = types.subst(pmt.qtype, pmt.tvars, typeargtypes);
   354         } else if (mt.tag == FORALL) {
   355             ForAll pmt = (ForAll) mt;
   356             List<Type> tvars1 = types.newInstances(pmt.tvars);
   357             tvars = tvars.appendList(tvars1);
   358             mt = types.subst(pmt.qtype, pmt.tvars, tvars1);
   359         }
   361         // find out whether we need to go the slow route via infer
   362         boolean instNeeded = tvars.tail != null || /*inlined: tvars.nonEmpty()*/
   363                 polymorphicSignature;
   364         for (List<Type> l = argtypes;
   365              l.tail != null/*inlined: l.nonEmpty()*/ && !instNeeded;
   366              l = l.tail) {
   367             if (l.head.tag == FORALL) instNeeded = true;
   368         }
   370         if (instNeeded)
   371             return polymorphicSignature ?
   372                 infer.instantiatePolymorphicSignatureInstance(env, site, m.name, (MethodSymbol)m, argtypes, typeargtypes) :
   373                 infer.instantiateMethod(env,
   374                                     tvars,
   375                                     (MethodType)mt,
   376                                     m,
   377                                     argtypes,
   378                                     allowBoxing,
   379                                     useVarargs,
   380                                     warn);
   382         checkRawArgumentsAcceptable(argtypes, mt.getParameterTypes(),
   383                                 allowBoxing, useVarargs, warn);
   384         return mt;
   385     }
   387     boolean isTransitionalDynamicCallSite(Type site, Symbol sym) {
   388         return allowTransitionalJSR292 &&  // old logic that doesn't use annotations
   389                 !sym.isPolymorphicSignatureInstance() &&
   390                 ((allowMethodHandles && site == syms.methodHandleType && // invokeExact, invokeGeneric, invoke
   391                     (sym.name == names.invoke && sym.isPolymorphicSignatureGeneric())) ||
   392                 (site == syms.invokeDynamicType && allowInvokeDynamic)); // InvokeDynamic.XYZ
   393     }
   395     /** Same but returns null instead throwing a NoInstanceException
   396      */
   397     Type instantiate(Env<AttrContext> env,
   398                      Type site,
   399                      Symbol m,
   400                      List<Type> argtypes,
   401                      List<Type> typeargtypes,
   402                      boolean allowBoxing,
   403                      boolean useVarargs,
   404                      Warner warn) {
   405         try {
   406             return rawInstantiate(env, site, m, argtypes, typeargtypes,
   407                                   allowBoxing, useVarargs, warn);
   408         } catch (InapplicableMethodException ex) {
   409             return null;
   410         }
   411     }
   413     /** Check if a parameter list accepts a list of args.
   414      */
   415     boolean argumentsAcceptable(List<Type> argtypes,
   416                                 List<Type> formals,
   417                                 boolean allowBoxing,
   418                                 boolean useVarargs,
   419                                 Warner warn) {
   420         try {
   421             checkRawArgumentsAcceptable(argtypes, formals, allowBoxing, useVarargs, warn);
   422             return true;
   423         } catch (InapplicableMethodException ex) {
   424             return false;
   425         }
   426     }
   427     void checkRawArgumentsAcceptable(List<Type> argtypes,
   428                                 List<Type> formals,
   429                                 boolean allowBoxing,
   430                                 boolean useVarargs,
   431                                 Warner warn) {
   432         Type varargsFormal = useVarargs ? formals.last() : null;
   433         if (varargsFormal == null &&
   434                 argtypes.size() != formals.size()) {
   435             throw inapplicableMethodException.setMessage("arg.length.mismatch"); // not enough args
   436         }
   438         while (argtypes.nonEmpty() && formals.head != varargsFormal) {
   439             boolean works = allowBoxing
   440                 ? types.isConvertible(argtypes.head, formals.head, warn)
   441                 : types.isSubtypeUnchecked(argtypes.head, formals.head, warn);
   442             if (!works)
   443                 throw inapplicableMethodException.setMessage("no.conforming.assignment.exists",
   444                         argtypes.head,
   445                         formals.head);
   446             argtypes = argtypes.tail;
   447             formals = formals.tail;
   448         }
   450         if (formals.head != varargsFormal)
   451             throw inapplicableMethodException.setMessage("arg.length.mismatch"); // not enough args
   453         if (useVarargs) {
   454             Type elt = types.elemtype(varargsFormal);
   455             while (argtypes.nonEmpty()) {
   456                 if (!types.isConvertible(argtypes.head, elt, warn))
   457                     throw inapplicableMethodException.setMessage("varargs.argument.mismatch",
   458                             argtypes.head,
   459                             elt);
   460                 argtypes = argtypes.tail;
   461             }
   462         }
   463         return;
   464     }
   465     // where
   466         public static class InapplicableMethodException extends RuntimeException {
   467             private static final long serialVersionUID = 0;
   469             JCDiagnostic diagnostic;
   470             JCDiagnostic.Factory diags;
   472             InapplicableMethodException(JCDiagnostic.Factory diags) {
   473                 this.diagnostic = null;
   474                 this.diags = diags;
   475             }
   476             InapplicableMethodException setMessage(String key) {
   477                 this.diagnostic = key != null ? diags.fragment(key) : null;
   478                 return this;
   479             }
   480             InapplicableMethodException setMessage(String key, Object... args) {
   481                 this.diagnostic = key != null ? diags.fragment(key, args) : null;
   482                 return this;
   483             }
   485             public JCDiagnostic getDiagnostic() {
   486                 return diagnostic;
   487             }
   488         }
   489         private final InapplicableMethodException inapplicableMethodException;
   491 /* ***************************************************************************
   492  *  Symbol lookup
   493  *  the following naming conventions for arguments are used
   494  *
   495  *       env      is the environment where the symbol was mentioned
   496  *       site     is the type of which the symbol is a member
   497  *       name     is the symbol's name
   498  *                if no arguments are given
   499  *       argtypes are the value arguments, if we search for a method
   500  *
   501  *  If no symbol was found, a ResolveError detailing the problem is returned.
   502  ****************************************************************************/
   504     /** Find field. Synthetic fields are always skipped.
   505      *  @param env     The current environment.
   506      *  @param site    The original type from where the selection takes place.
   507      *  @param name    The name of the field.
   508      *  @param c       The class to search for the field. This is always
   509      *                 a superclass or implemented interface of site's class.
   510      */
   511     Symbol findField(Env<AttrContext> env,
   512                      Type site,
   513                      Name name,
   514                      TypeSymbol c) {
   515         while (c.type.tag == TYPEVAR)
   516             c = c.type.getUpperBound().tsym;
   517         Symbol bestSoFar = varNotFound;
   518         Symbol sym;
   519         Scope.Entry e = c.members().lookup(name);
   520         while (e.scope != null) {
   521             if (e.sym.kind == VAR && (e.sym.flags_field & SYNTHETIC) == 0) {
   522                 return isAccessible(env, site, e.sym)
   523                     ? e.sym : new AccessError(env, site, e.sym);
   524             }
   525             e = e.next();
   526         }
   527         Type st = types.supertype(c.type);
   528         if (st != null && (st.tag == CLASS || st.tag == TYPEVAR)) {
   529             sym = findField(env, site, name, st.tsym);
   530             if (sym.kind < bestSoFar.kind) bestSoFar = sym;
   531         }
   532         for (List<Type> l = types.interfaces(c.type);
   533              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
   534              l = l.tail) {
   535             sym = findField(env, site, name, l.head.tsym);
   536             if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
   537                 sym.owner != bestSoFar.owner)
   538                 bestSoFar = new AmbiguityError(bestSoFar, sym);
   539             else if (sym.kind < bestSoFar.kind)
   540                 bestSoFar = sym;
   541         }
   542         return bestSoFar;
   543     }
   545     /** Resolve a field identifier, throw a fatal error if not found.
   546      *  @param pos       The position to use for error reporting.
   547      *  @param env       The environment current at the method invocation.
   548      *  @param site      The type of the qualifying expression, in which
   549      *                   identifier is searched.
   550      *  @param name      The identifier's name.
   551      */
   552     public VarSymbol resolveInternalField(DiagnosticPosition pos, Env<AttrContext> env,
   553                                           Type site, Name name) {
   554         Symbol sym = findField(env, site, name, site.tsym);
   555         if (sym.kind == VAR) return (VarSymbol)sym;
   556         else throw new FatalError(
   557                  diags.fragment("fatal.err.cant.locate.field",
   558                                 name));
   559     }
   561     /** Find unqualified variable or field with given name.
   562      *  Synthetic fields always skipped.
   563      *  @param env     The current environment.
   564      *  @param name    The name of the variable or field.
   565      */
   566     Symbol findVar(Env<AttrContext> env, Name name) {
   567         Symbol bestSoFar = varNotFound;
   568         Symbol sym;
   569         Env<AttrContext> env1 = env;
   570         boolean staticOnly = false;
   571         while (env1.outer != null) {
   572             if (isStatic(env1)) staticOnly = true;
   573             Scope.Entry e = env1.info.scope.lookup(name);
   574             while (e.scope != null &&
   575                    (e.sym.kind != VAR ||
   576                     (e.sym.flags_field & SYNTHETIC) != 0))
   577                 e = e.next();
   578             sym = (e.scope != null)
   579                 ? e.sym
   580                 : findField(
   581                     env1, env1.enclClass.sym.type, name, env1.enclClass.sym);
   582             if (sym.exists()) {
   583                 if (staticOnly &&
   584                     sym.kind == VAR &&
   585                     sym.owner.kind == TYP &&
   586                     (sym.flags() & STATIC) == 0)
   587                     return new StaticError(sym);
   588                 else
   589                     return sym;
   590             } else if (sym.kind < bestSoFar.kind) {
   591                 bestSoFar = sym;
   592             }
   594             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
   595             env1 = env1.outer;
   596         }
   598         sym = findField(env, syms.predefClass.type, name, syms.predefClass);
   599         if (sym.exists())
   600             return sym;
   601         if (bestSoFar.exists())
   602             return bestSoFar;
   604         Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
   605         for (; e.scope != null; e = e.next()) {
   606             sym = e.sym;
   607             Type origin = e.getOrigin().owner.type;
   608             if (sym.kind == VAR) {
   609                 if (e.sym.owner.type != origin)
   610                     sym = sym.clone(e.getOrigin().owner);
   611                 return isAccessible(env, origin, sym)
   612                     ? sym : new AccessError(env, origin, sym);
   613             }
   614         }
   616         Symbol origin = null;
   617         e = env.toplevel.starImportScope.lookup(name);
   618         for (; e.scope != null; e = e.next()) {
   619             sym = e.sym;
   620             if (sym.kind != VAR)
   621                 continue;
   622             // invariant: sym.kind == VAR
   623             if (bestSoFar.kind < AMBIGUOUS && sym.owner != bestSoFar.owner)
   624                 return new AmbiguityError(bestSoFar, sym);
   625             else if (bestSoFar.kind >= VAR) {
   626                 origin = e.getOrigin().owner;
   627                 bestSoFar = isAccessible(env, origin.type, sym)
   628                     ? sym : new AccessError(env, origin.type, sym);
   629             }
   630         }
   631         if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type)
   632             return bestSoFar.clone(origin);
   633         else
   634             return bestSoFar;
   635     }
   637     Warner noteWarner = new Warner();
   639     /** Select the best method for a call site among two choices.
   640      *  @param env              The current environment.
   641      *  @param site             The original type from where the
   642      *                          selection takes place.
   643      *  @param argtypes         The invocation's value arguments,
   644      *  @param typeargtypes     The invocation's type arguments,
   645      *  @param sym              Proposed new best match.
   646      *  @param bestSoFar        Previously found best match.
   647      *  @param allowBoxing Allow boxing conversions of arguments.
   648      *  @param useVarargs Box trailing arguments into an array for varargs.
   649      */
   650     @SuppressWarnings("fallthrough")
   651     Symbol selectBest(Env<AttrContext> env,
   652                       Type site,
   653                       List<Type> argtypes,
   654                       List<Type> typeargtypes,
   655                       Symbol sym,
   656                       Symbol bestSoFar,
   657                       boolean allowBoxing,
   658                       boolean useVarargs,
   659                       boolean operator) {
   660         if (sym.kind == ERR) return bestSoFar;
   661         if (!sym.isInheritedIn(site.tsym, types)) return bestSoFar;
   662         assert sym.kind < AMBIGUOUS;
   663         try {
   664             rawInstantiate(env, site, sym, argtypes, typeargtypes,
   665                                allowBoxing, useVarargs, Warner.noWarnings);
   666         } catch (InapplicableMethodException ex) {
   667             switch (bestSoFar.kind) {
   668             case ABSENT_MTH:
   669                 return wrongMethod.setWrongSym(sym, ex.getDiagnostic());
   670             case WRONG_MTH:
   671                 wrongMethods.addCandidate(currentStep, wrongMethod.sym, wrongMethod.explanation);
   672             case WRONG_MTHS:
   673                 return wrongMethods.addCandidate(currentStep, sym, ex.getDiagnostic());
   674             default:
   675                 return bestSoFar;
   676             }
   677         }
   678         if (!isAccessible(env, site, sym)) {
   679             return (bestSoFar.kind == ABSENT_MTH)
   680                 ? new AccessError(env, site, sym)
   681                 : bestSoFar;
   682             }
   683         return (bestSoFar.kind > AMBIGUOUS)
   684             ? sym
   685             : mostSpecific(sym, bestSoFar, env, site,
   686                            allowBoxing && operator, useVarargs);
   687     }
   689     /* Return the most specific of the two methods for a call,
   690      *  given that both are accessible and applicable.
   691      *  @param m1               A new candidate for most specific.
   692      *  @param m2               The previous most specific candidate.
   693      *  @param env              The current environment.
   694      *  @param site             The original type from where the selection
   695      *                          takes place.
   696      *  @param allowBoxing Allow boxing conversions of arguments.
   697      *  @param useVarargs Box trailing arguments into an array for varargs.
   698      */
   699     Symbol mostSpecific(Symbol m1,
   700                         Symbol m2,
   701                         Env<AttrContext> env,
   702                         final Type site,
   703                         boolean allowBoxing,
   704                         boolean useVarargs) {
   705         switch (m2.kind) {
   706         case MTH:
   707             if (m1 == m2) return m1;
   708             Type mt1 = types.memberType(site, m1);
   709             noteWarner.unchecked = false;
   710             boolean m1SignatureMoreSpecific =
   711                 (instantiate(env, site, m2, types.lowerBoundArgtypes(mt1), null,
   712                              allowBoxing, false, noteWarner) != null ||
   713                  useVarargs && instantiate(env, site, m2, types.lowerBoundArgtypes(mt1), null,
   714                                            allowBoxing, true, noteWarner) != null) &&
   715                 !noteWarner.unchecked;
   716             Type mt2 = types.memberType(site, m2);
   717             noteWarner.unchecked = false;
   718             boolean m2SignatureMoreSpecific =
   719                 (instantiate(env, site, m1, types.lowerBoundArgtypes(mt2), null,
   720                              allowBoxing, false, noteWarner) != null ||
   721                  useVarargs && instantiate(env, site, m1, types.lowerBoundArgtypes(mt2), null,
   722                                            allowBoxing, true, noteWarner) != null) &&
   723                 !noteWarner.unchecked;
   724             if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) {
   725                 if (!types.overrideEquivalent(mt1, mt2))
   726                     return new AmbiguityError(m1, m2);
   727                 // same signature; select (a) the non-bridge method, or
   728                 // (b) the one that overrides the other, or (c) the concrete
   729                 // one, or (d) merge both abstract signatures
   730                 if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE)) {
   731                     return ((m1.flags() & BRIDGE) != 0) ? m2 : m1;
   732                 }
   733                 // if one overrides or hides the other, use it
   734                 TypeSymbol m1Owner = (TypeSymbol)m1.owner;
   735                 TypeSymbol m2Owner = (TypeSymbol)m2.owner;
   736                 if (types.asSuper(m1Owner.type, m2Owner) != null &&
   737                     ((m1.owner.flags_field & INTERFACE) == 0 ||
   738                      (m2.owner.flags_field & INTERFACE) != 0) &&
   739                     m1.overrides(m2, m1Owner, types, false))
   740                     return m1;
   741                 if (types.asSuper(m2Owner.type, m1Owner) != null &&
   742                     ((m2.owner.flags_field & INTERFACE) == 0 ||
   743                      (m1.owner.flags_field & INTERFACE) != 0) &&
   744                     m2.overrides(m1, m2Owner, types, false))
   745                     return m2;
   746                 boolean m1Abstract = (m1.flags() & ABSTRACT) != 0;
   747                 boolean m2Abstract = (m2.flags() & ABSTRACT) != 0;
   748                 if (m1Abstract && !m2Abstract) return m2;
   749                 if (m2Abstract && !m1Abstract) return m1;
   750                 // both abstract or both concrete
   751                 if (!m1Abstract && !m2Abstract)
   752                     return new AmbiguityError(m1, m2);
   753                 // check that both signatures have the same erasure
   754                 if (!types.isSameTypes(m1.erasure(types).getParameterTypes(),
   755                                        m2.erasure(types).getParameterTypes()))
   756                     return new AmbiguityError(m1, m2);
   757                 // both abstract, neither overridden; merge throws clause and result type
   758                 Symbol mostSpecific;
   759                 Type result2 = mt2.getReturnType();
   760                 if (mt2.tag == FORALL)
   761                     result2 = types.subst(result2, ((ForAll)mt2).tvars, ((ForAll)mt1).tvars);
   762                 if (types.isSubtype(mt1.getReturnType(), result2)) {
   763                     mostSpecific = m1;
   764                 } else if (types.isSubtype(result2, mt1.getReturnType())) {
   765                     mostSpecific = m2;
   766                 } else {
   767                     // Theoretically, this can't happen, but it is possible
   768                     // due to error recovery or mixing incompatible class files
   769                     return new AmbiguityError(m1, m2);
   770                 }
   771                 MethodSymbol result = new MethodSymbol(
   772                         mostSpecific.flags(),
   773                         mostSpecific.name,
   774                         null,
   775                         mostSpecific.owner) {
   776                     @Override
   777                     public MethodSymbol implementation(TypeSymbol origin, Types types, boolean checkResult) {
   778                         if (origin == site.tsym)
   779                             return this;
   780                         else
   781                             return super.implementation(origin, types, checkResult);
   782                     }
   783                 };
   784                 result.type = (Type)mostSpecific.type.clone();
   785                 result.type.setThrown(chk.intersect(mt1.getThrownTypes(),
   786                                                     mt2.getThrownTypes()));
   787                 return result;
   788             }
   789             if (m1SignatureMoreSpecific) return m1;
   790             if (m2SignatureMoreSpecific) return m2;
   791             return new AmbiguityError(m1, m2);
   792         case AMBIGUOUS:
   793             AmbiguityError e = (AmbiguityError)m2;
   794             Symbol err1 = mostSpecific(m1, e.sym, env, site, allowBoxing, useVarargs);
   795             Symbol err2 = mostSpecific(m1, e.sym2, env, site, allowBoxing, useVarargs);
   796             if (err1 == err2) return err1;
   797             if (err1 == e.sym && err2 == e.sym2) return m2;
   798             if (err1 instanceof AmbiguityError &&
   799                 err2 instanceof AmbiguityError &&
   800                 ((AmbiguityError)err1).sym == ((AmbiguityError)err2).sym)
   801                 return new AmbiguityError(m1, m2);
   802             else
   803                 return new AmbiguityError(err1, err2);
   804         default:
   805             throw new AssertionError();
   806         }
   807     }
   809     /** Find best qualified method matching given name, type and value
   810      *  arguments.
   811      *  @param env       The current environment.
   812      *  @param site      The original type from where the selection
   813      *                   takes place.
   814      *  @param name      The method's name.
   815      *  @param argtypes  The method's value arguments.
   816      *  @param typeargtypes The method's type arguments
   817      *  @param allowBoxing Allow boxing conversions of arguments.
   818      *  @param useVarargs Box trailing arguments into an array for varargs.
   819      */
   820     Symbol findMethod(Env<AttrContext> env,
   821                       Type site,
   822                       Name name,
   823                       List<Type> argtypes,
   824                       List<Type> typeargtypes,
   825                       boolean allowBoxing,
   826                       boolean useVarargs,
   827                       boolean operator) {
   828         Symbol bestSoFar = methodNotFound;
   829         return findMethod(env,
   830                           site,
   831                           name,
   832                           argtypes,
   833                           typeargtypes,
   834                           site.tsym.type,
   835                           true,
   836                           bestSoFar,
   837                           allowBoxing,
   838                           useVarargs,
   839                           operator);
   840     }
   841     // where
   842     private Symbol findMethod(Env<AttrContext> env,
   843                               Type site,
   844                               Name name,
   845                               List<Type> argtypes,
   846                               List<Type> typeargtypes,
   847                               Type intype,
   848                               boolean abstractok,
   849                               Symbol bestSoFar,
   850                               boolean allowBoxing,
   851                               boolean useVarargs,
   852                               boolean operator) {
   853         for (Type ct = intype; ct.tag == CLASS || ct.tag == TYPEVAR; ct = types.supertype(ct)) {
   854             while (ct.tag == TYPEVAR)
   855                 ct = ct.getUpperBound();
   856             ClassSymbol c = (ClassSymbol)ct.tsym;
   857             if ((c.flags() & (ABSTRACT | INTERFACE | ENUM)) == 0)
   858                 abstractok = false;
   859             for (Scope.Entry e = c.members().lookup(name);
   860                  e.scope != null;
   861                  e = e.next()) {
   862                 //- System.out.println(" e " + e.sym);
   863                 if (e.sym.kind == MTH &&
   864                     (e.sym.flags_field & SYNTHETIC) == 0) {
   865                     bestSoFar = selectBest(env, site, argtypes, typeargtypes,
   866                                            e.sym, bestSoFar,
   867                                            allowBoxing,
   868                                            useVarargs,
   869                                            operator);
   870                 }
   871             }
   872             if (name == names.init)
   873                 break;
   874             //- System.out.println(" - " + bestSoFar);
   875             if (abstractok) {
   876                 Symbol concrete = methodNotFound;
   877                 if ((bestSoFar.flags() & ABSTRACT) == 0)
   878                     concrete = bestSoFar;
   879                 for (List<Type> l = types.interfaces(c.type);
   880                      l.nonEmpty();
   881                      l = l.tail) {
   882                     bestSoFar = findMethod(env, site, name, argtypes,
   883                                            typeargtypes,
   884                                            l.head, abstractok, bestSoFar,
   885                                            allowBoxing, useVarargs, operator);
   886                 }
   887                 if (concrete != bestSoFar &&
   888                     concrete.kind < ERR  && bestSoFar.kind < ERR &&
   889                     types.isSubSignature(concrete.type, bestSoFar.type))
   890                     bestSoFar = concrete;
   891             }
   892         }
   893         return bestSoFar;
   894     }
   896     /** Find unqualified method matching given name, type and value arguments.
   897      *  @param env       The current environment.
   898      *  @param name      The method's name.
   899      *  @param argtypes  The method's value arguments.
   900      *  @param typeargtypes  The method's type arguments.
   901      *  @param allowBoxing Allow boxing conversions of arguments.
   902      *  @param useVarargs Box trailing arguments into an array for varargs.
   903      */
   904     Symbol findFun(Env<AttrContext> env, Name name,
   905                    List<Type> argtypes, List<Type> typeargtypes,
   906                    boolean allowBoxing, boolean useVarargs) {
   907         Symbol bestSoFar = methodNotFound;
   908         Symbol sym;
   909         Env<AttrContext> env1 = env;
   910         boolean staticOnly = false;
   911         while (env1.outer != null) {
   912             if (isStatic(env1)) staticOnly = true;
   913             sym = findMethod(
   914                 env1, env1.enclClass.sym.type, name, argtypes, typeargtypes,
   915                 allowBoxing, useVarargs, false);
   916             if (sym.exists()) {
   917                 if (staticOnly &&
   918                     sym.kind == MTH &&
   919                     sym.owner.kind == TYP &&
   920                     (sym.flags() & STATIC) == 0) return new StaticError(sym);
   921                 else return sym;
   922             } else if (sym.kind < bestSoFar.kind) {
   923                 bestSoFar = sym;
   924             }
   925             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
   926             env1 = env1.outer;
   927         }
   929         sym = findMethod(env, syms.predefClass.type, name, argtypes,
   930                          typeargtypes, allowBoxing, useVarargs, false);
   931         if (sym.exists())
   932             return sym;
   934         Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
   935         for (; e.scope != null; e = e.next()) {
   936             sym = e.sym;
   937             Type origin = e.getOrigin().owner.type;
   938             if (sym.kind == MTH) {
   939                 if (e.sym.owner.type != origin)
   940                     sym = sym.clone(e.getOrigin().owner);
   941                 if (!isAccessible(env, origin, sym))
   942                     sym = new AccessError(env, origin, sym);
   943                 bestSoFar = selectBest(env, origin,
   944                                        argtypes, typeargtypes,
   945                                        sym, bestSoFar,
   946                                        allowBoxing, useVarargs, false);
   947             }
   948         }
   949         if (bestSoFar.exists())
   950             return bestSoFar;
   952         e = env.toplevel.starImportScope.lookup(name);
   953         for (; e.scope != null; e = e.next()) {
   954             sym = e.sym;
   955             Type origin = e.getOrigin().owner.type;
   956             if (sym.kind == MTH) {
   957                 if (e.sym.owner.type != origin)
   958                     sym = sym.clone(e.getOrigin().owner);
   959                 if (!isAccessible(env, origin, sym))
   960                     sym = new AccessError(env, origin, sym);
   961                 bestSoFar = selectBest(env, origin,
   962                                        argtypes, typeargtypes,
   963                                        sym, bestSoFar,
   964                                        allowBoxing, useVarargs, false);
   965             }
   966         }
   967         return bestSoFar;
   968     }
   970     /** Load toplevel or member class with given fully qualified name and
   971      *  verify that it is accessible.
   972      *  @param env       The current environment.
   973      *  @param name      The fully qualified name of the class to be loaded.
   974      */
   975     Symbol loadClass(Env<AttrContext> env, Name name) {
   976         try {
   977             ClassSymbol c = reader.loadClass(name);
   978             return isAccessible(env, c) ? c : new AccessError(c);
   979         } catch (ClassReader.BadClassFile err) {
   980             throw err;
   981         } catch (CompletionFailure ex) {
   982             return typeNotFound;
   983         }
   984     }
   986     /** Find qualified member type.
   987      *  @param env       The current environment.
   988      *  @param site      The original type from where the selection takes
   989      *                   place.
   990      *  @param name      The type's name.
   991      *  @param c         The class to search for the member type. This is
   992      *                   always a superclass or implemented interface of
   993      *                   site's class.
   994      */
   995     Symbol findMemberType(Env<AttrContext> env,
   996                           Type site,
   997                           Name name,
   998                           TypeSymbol c) {
   999         Symbol bestSoFar = typeNotFound;
  1000         Symbol sym;
  1001         Scope.Entry e = c.members().lookup(name);
  1002         while (e.scope != null) {
  1003             if (e.sym.kind == TYP) {
  1004                 return isAccessible(env, site, e.sym)
  1005                     ? e.sym
  1006                     : new AccessError(env, site, e.sym);
  1008             e = e.next();
  1010         Type st = types.supertype(c.type);
  1011         if (st != null && st.tag == CLASS) {
  1012             sym = findMemberType(env, site, name, st.tsym);
  1013             if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1015         for (List<Type> l = types.interfaces(c.type);
  1016              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
  1017              l = l.tail) {
  1018             sym = findMemberType(env, site, name, l.head.tsym);
  1019             if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
  1020                 sym.owner != bestSoFar.owner)
  1021                 bestSoFar = new AmbiguityError(bestSoFar, sym);
  1022             else if (sym.kind < bestSoFar.kind)
  1023                 bestSoFar = sym;
  1025         return bestSoFar;
  1028     /** Find a global type in given scope and load corresponding class.
  1029      *  @param env       The current environment.
  1030      *  @param scope     The scope in which to look for the type.
  1031      *  @param name      The type's name.
  1032      */
  1033     Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name) {
  1034         Symbol bestSoFar = typeNotFound;
  1035         for (Scope.Entry e = scope.lookup(name); e.scope != null; e = e.next()) {
  1036             Symbol sym = loadClass(env, e.sym.flatName());
  1037             if (bestSoFar.kind == TYP && sym.kind == TYP &&
  1038                 bestSoFar != sym)
  1039                 return new AmbiguityError(bestSoFar, sym);
  1040             else if (sym.kind < bestSoFar.kind)
  1041                 bestSoFar = sym;
  1043         return bestSoFar;
  1046     /** Find an unqualified type symbol.
  1047      *  @param env       The current environment.
  1048      *  @param name      The type's name.
  1049      */
  1050     Symbol findType(Env<AttrContext> env, Name name) {
  1051         Symbol bestSoFar = typeNotFound;
  1052         Symbol sym;
  1053         boolean staticOnly = false;
  1054         for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
  1055             if (isStatic(env1)) staticOnly = true;
  1056             for (Scope.Entry e = env1.info.scope.lookup(name);
  1057                  e.scope != null;
  1058                  e = e.next()) {
  1059                 if (e.sym.kind == TYP) {
  1060                     if (staticOnly &&
  1061                         e.sym.type.tag == TYPEVAR &&
  1062                         e.sym.owner.kind == TYP) return new StaticError(e.sym);
  1063                     return e.sym;
  1067             sym = findMemberType(env1, env1.enclClass.sym.type, name,
  1068                                  env1.enclClass.sym);
  1069             if (staticOnly && sym.kind == TYP &&
  1070                 sym.type.tag == CLASS &&
  1071                 sym.type.getEnclosingType().tag == CLASS &&
  1072                 env1.enclClass.sym.type.isParameterized() &&
  1073                 sym.type.getEnclosingType().isParameterized())
  1074                 return new StaticError(sym);
  1075             else if (sym.exists()) return sym;
  1076             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1078             JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass;
  1079             if ((encl.sym.flags() & STATIC) != 0)
  1080                 staticOnly = true;
  1083         if (env.tree.getTag() != JCTree.IMPORT) {
  1084             sym = findGlobalType(env, env.toplevel.namedImportScope, name);
  1085             if (sym.exists()) return sym;
  1086             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1088             sym = findGlobalType(env, env.toplevel.packge.members(), name);
  1089             if (sym.exists()) return sym;
  1090             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1092             sym = findGlobalType(env, env.toplevel.starImportScope, name);
  1093             if (sym.exists()) return sym;
  1094             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1097         return bestSoFar;
  1100     /** Find an unqualified identifier which matches a specified kind set.
  1101      *  @param env       The current environment.
  1102      *  @param name      The indentifier's name.
  1103      *  @param kind      Indicates the possible symbol kinds
  1104      *                   (a subset of VAL, TYP, PCK).
  1105      */
  1106     Symbol findIdent(Env<AttrContext> env, Name name, int kind) {
  1107         Symbol bestSoFar = typeNotFound;
  1108         Symbol sym;
  1110         if ((kind & VAR) != 0) {
  1111             sym = findVar(env, name);
  1112             if (sym.exists()) return sym;
  1113             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1116         if ((kind & TYP) != 0) {
  1117             sym = findType(env, name);
  1118             if (sym.exists()) return sym;
  1119             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1122         if ((kind & PCK) != 0) return reader.enterPackage(name);
  1123         else return bestSoFar;
  1126     /** Find an identifier in a package which matches a specified kind set.
  1127      *  @param env       The current environment.
  1128      *  @param name      The identifier's name.
  1129      *  @param kind      Indicates the possible symbol kinds
  1130      *                   (a nonempty subset of TYP, PCK).
  1131      */
  1132     Symbol findIdentInPackage(Env<AttrContext> env, TypeSymbol pck,
  1133                               Name name, int kind) {
  1134         Name fullname = TypeSymbol.formFullName(name, pck);
  1135         Symbol bestSoFar = typeNotFound;
  1136         PackageSymbol pack = null;
  1137         if ((kind & PCK) != 0) {
  1138             pack = reader.enterPackage(fullname);
  1139             if (pack.exists()) return pack;
  1141         if ((kind & TYP) != 0) {
  1142             Symbol sym = loadClass(env, fullname);
  1143             if (sym.exists()) {
  1144                 // don't allow programs to use flatnames
  1145                 if (name == sym.name) return sym;
  1147             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1149         return (pack != null) ? pack : bestSoFar;
  1152     /** Find an identifier among the members of a given type `site'.
  1153      *  @param env       The current environment.
  1154      *  @param site      The type containing the symbol to be found.
  1155      *  @param name      The identifier's name.
  1156      *  @param kind      Indicates the possible symbol kinds
  1157      *                   (a subset of VAL, TYP).
  1158      */
  1159     Symbol findIdentInType(Env<AttrContext> env, Type site,
  1160                            Name name, int kind) {
  1161         Symbol bestSoFar = typeNotFound;
  1162         Symbol sym;
  1163         if ((kind & VAR) != 0) {
  1164             sym = findField(env, site, name, site.tsym);
  1165             if (sym.exists()) return sym;
  1166             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1169         if ((kind & TYP) != 0) {
  1170             sym = findMemberType(env, site, name, site.tsym);
  1171             if (sym.exists()) return sym;
  1172             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1174         return bestSoFar;
  1177 /* ***************************************************************************
  1178  *  Access checking
  1179  *  The following methods convert ResolveErrors to ErrorSymbols, issuing
  1180  *  an error message in the process
  1181  ****************************************************************************/
  1183     /** If `sym' is a bad symbol: report error and return errSymbol
  1184      *  else pass through unchanged,
  1185      *  additional arguments duplicate what has been used in trying to find the
  1186      *  symbol (--> flyweight pattern). This improves performance since we
  1187      *  expect misses to happen frequently.
  1189      *  @param sym       The symbol that was found, or a ResolveError.
  1190      *  @param pos       The position to use for error reporting.
  1191      *  @param site      The original type from where the selection took place.
  1192      *  @param name      The symbol's name.
  1193      *  @param argtypes  The invocation's value arguments,
  1194      *                   if we looked for a method.
  1195      *  @param typeargtypes  The invocation's type arguments,
  1196      *                   if we looked for a method.
  1197      */
  1198     Symbol access(Symbol sym,
  1199                   DiagnosticPosition pos,
  1200                   Type site,
  1201                   Name name,
  1202                   boolean qualified,
  1203                   List<Type> argtypes,
  1204                   List<Type> typeargtypes) {
  1205         if (sym.kind >= AMBIGUOUS) {
  1206             ResolveError errSym = (ResolveError)sym;
  1207             if (!site.isErroneous() &&
  1208                 !Type.isErroneous(argtypes) &&
  1209                 (typeargtypes==null || !Type.isErroneous(typeargtypes)))
  1210                 logResolveError(errSym, pos, site, name, argtypes, typeargtypes);
  1211             sym = errSym.access(name, qualified ? site.tsym : syms.noSymbol);
  1213         return sym;
  1216     /** Same as above, but without type arguments and arguments.
  1217      */
  1218     Symbol access(Symbol sym,
  1219                   DiagnosticPosition pos,
  1220                   Type site,
  1221                   Name name,
  1222                   boolean qualified) {
  1223         if (sym.kind >= AMBIGUOUS)
  1224             return access(sym, pos, site, name, qualified, List.<Type>nil(), null);
  1225         else
  1226             return sym;
  1229     /** Check that sym is not an abstract method.
  1230      */
  1231     void checkNonAbstract(DiagnosticPosition pos, Symbol sym) {
  1232         if ((sym.flags() & ABSTRACT) != 0)
  1233             log.error(pos, "abstract.cant.be.accessed.directly",
  1234                       kindName(sym), sym, sym.location());
  1237 /* ***************************************************************************
  1238  *  Debugging
  1239  ****************************************************************************/
  1241     /** print all scopes starting with scope s and proceeding outwards.
  1242      *  used for debugging.
  1243      */
  1244     public void printscopes(Scope s) {
  1245         while (s != null) {
  1246             if (s.owner != null)
  1247                 System.err.print(s.owner + ": ");
  1248             for (Scope.Entry e = s.elems; e != null; e = e.sibling) {
  1249                 if ((e.sym.flags() & ABSTRACT) != 0)
  1250                     System.err.print("abstract ");
  1251                 System.err.print(e.sym + " ");
  1253             System.err.println();
  1254             s = s.next;
  1258     void printscopes(Env<AttrContext> env) {
  1259         while (env.outer != null) {
  1260             System.err.println("------------------------------");
  1261             printscopes(env.info.scope);
  1262             env = env.outer;
  1266     public void printscopes(Type t) {
  1267         while (t.tag == CLASS) {
  1268             printscopes(t.tsym.members());
  1269             t = types.supertype(t);
  1273 /* ***************************************************************************
  1274  *  Name resolution
  1275  *  Naming conventions are as for symbol lookup
  1276  *  Unlike the find... methods these methods will report access errors
  1277  ****************************************************************************/
  1279     /** Resolve an unqualified (non-method) identifier.
  1280      *  @param pos       The position to use for error reporting.
  1281      *  @param env       The environment current at the identifier use.
  1282      *  @param name      The identifier's name.
  1283      *  @param kind      The set of admissible symbol kinds for the identifier.
  1284      */
  1285     Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env,
  1286                         Name name, int kind) {
  1287         return access(
  1288             findIdent(env, name, kind),
  1289             pos, env.enclClass.sym.type, name, false);
  1292     /** Resolve an unqualified method identifier.
  1293      *  @param pos       The position to use for error reporting.
  1294      *  @param env       The environment current at the method invocation.
  1295      *  @param name      The identifier's name.
  1296      *  @param argtypes  The types of the invocation's value arguments.
  1297      *  @param typeargtypes  The types of the invocation's type arguments.
  1298      */
  1299     Symbol resolveMethod(DiagnosticPosition pos,
  1300                          Env<AttrContext> env,
  1301                          Name name,
  1302                          List<Type> argtypes,
  1303                          List<Type> typeargtypes) {
  1304         Symbol sym = startResolution();
  1305         List<MethodResolutionPhase> steps = methodResolutionSteps;
  1306         while (steps.nonEmpty() &&
  1307                steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  1308                sym.kind >= ERRONEOUS) {
  1309             currentStep = steps.head;
  1310             sym = findFun(env, name, argtypes, typeargtypes,
  1311                     steps.head.isBoxingRequired,
  1312                     env.info.varArgs = steps.head.isVarargsRequired);
  1313             methodResolutionCache.put(steps.head, sym);
  1314             steps = steps.tail;
  1316         if (sym.kind >= AMBIGUOUS) {//if nothing is found return the 'first' error
  1317             MethodResolutionPhase errPhase =
  1318                     firstErroneousResolutionPhase();
  1319             sym = access(methodResolutionCache.get(errPhase),
  1320                     pos, env.enclClass.sym.type, name, false, argtypes, typeargtypes);
  1321             env.info.varArgs = errPhase.isVarargsRequired;
  1323         return sym;
  1326     private Symbol startResolution() {
  1327         wrongMethod.clear();
  1328         wrongMethods.clear();
  1329         return methodNotFound;
  1332     /** Resolve a qualified method identifier
  1333      *  @param pos       The position to use for error reporting.
  1334      *  @param env       The environment current at the method invocation.
  1335      *  @param site      The type of the qualifying expression, in which
  1336      *                   identifier is searched.
  1337      *  @param name      The identifier's name.
  1338      *  @param argtypes  The types of the invocation's value arguments.
  1339      *  @param typeargtypes  The types of the invocation's type arguments.
  1340      */
  1341     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
  1342                                   Type site, Name name, List<Type> argtypes,
  1343                                   List<Type> typeargtypes) {
  1344         Symbol sym = startResolution();
  1345         List<MethodResolutionPhase> steps = methodResolutionSteps;
  1346         while (steps.nonEmpty() &&
  1347                steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  1348                sym.kind >= ERRONEOUS) {
  1349             currentStep = steps.head;
  1350             sym = findMethod(env, site, name, argtypes, typeargtypes,
  1351                     steps.head.isBoxingRequired(),
  1352                     env.info.varArgs = steps.head.isVarargsRequired(), false);
  1353             methodResolutionCache.put(steps.head, sym);
  1354             steps = steps.tail;
  1356         if (sym.kind >= AMBIGUOUS) {
  1357             if (site.tsym.isPolymorphicSignatureGeneric() ||
  1358                     isTransitionalDynamicCallSite(site, sym)) {
  1359                 //polymorphic receiver - synthesize new method symbol
  1360                 env.info.varArgs = false;
  1361                 sym = findPolymorphicSignatureInstance(env,
  1362                         site, name, null, argtypes, typeargtypes);
  1364             else {
  1365                 //if nothing is found return the 'first' error
  1366                 MethodResolutionPhase errPhase =
  1367                         firstErroneousResolutionPhase();
  1368                 sym = access(methodResolutionCache.get(errPhase),
  1369                         pos, site, name, true, argtypes, typeargtypes);
  1370                 env.info.varArgs = errPhase.isVarargsRequired;
  1372         } else if (allowMethodHandles && sym.isPolymorphicSignatureGeneric()) {
  1373             //non-instantiated polymorphic signature - synthesize new method symbol
  1374             env.info.varArgs = false;
  1375             sym = findPolymorphicSignatureInstance(env,
  1376                     site, name, (MethodSymbol)sym, argtypes, typeargtypes);
  1378         return sym;
  1381     /** Find or create an implicit method of exactly the given type (after erasure).
  1382      *  Searches in a side table, not the main scope of the site.
  1383      *  This emulates the lookup process required by JSR 292 in JVM.
  1384      *  @param env       Attribution environment
  1385      *  @param site      The original type from where the selection takes place.
  1386      *  @param name      The method's name.
  1387      *  @param spMethod  A template for the implicit method, or null.
  1388      *  @param argtypes  The required argument types.
  1389      *  @param typeargtypes  The required type arguments.
  1390      */
  1391     Symbol findPolymorphicSignatureInstance(Env<AttrContext> env, Type site,
  1392                                             Name name,
  1393                                             MethodSymbol spMethod,  // sig. poly. method or null if none
  1394                                             List<Type> argtypes,
  1395                                             List<Type> typeargtypes) {
  1396         if (typeargtypes.nonEmpty() && (site.tsym.isPolymorphicSignatureGeneric() ||
  1397                 (spMethod != null && spMethod.isPolymorphicSignatureGeneric()))) {
  1398             log.warning(env.tree.pos(), "type.parameter.on.polymorphic.signature");
  1401         Type mtype = infer.instantiatePolymorphicSignatureInstance(env,
  1402                 site, name, spMethod, argtypes, typeargtypes);
  1403         long flags = ABSTRACT | HYPOTHETICAL | POLYMORPHIC_SIGNATURE |
  1404                     (spMethod != null ?
  1405                         spMethod.flags() & Flags.AccessFlags :
  1406                         Flags.PUBLIC | Flags.STATIC);
  1407         Symbol m = null;
  1408         for (Scope.Entry e = polymorphicSignatureScope.lookup(name);
  1409              e.scope != null;
  1410              e = e.next()) {
  1411             Symbol sym = e.sym;
  1412             if (types.isSameType(mtype, sym.type) &&
  1413                 (sym.flags() & Flags.STATIC) == (flags & Flags.STATIC) &&
  1414                 types.isSameType(sym.owner.type, site)) {
  1415                m = sym;
  1416                break;
  1419         if (m == null) {
  1420             // create the desired method
  1421             m = new MethodSymbol(flags, name, mtype, site.tsym);
  1422             polymorphicSignatureScope.enter(m);
  1424         return m;
  1427     /** Resolve a qualified method identifier, throw a fatal error if not
  1428      *  found.
  1429      *  @param pos       The position to use for error reporting.
  1430      *  @param env       The environment current at the method invocation.
  1431      *  @param site      The type of the qualifying expression, in which
  1432      *                   identifier is searched.
  1433      *  @param name      The identifier's name.
  1434      *  @param argtypes  The types of the invocation's value arguments.
  1435      *  @param typeargtypes  The types of the invocation's type arguments.
  1436      */
  1437     public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env,
  1438                                         Type site, Name name,
  1439                                         List<Type> argtypes,
  1440                                         List<Type> typeargtypes) {
  1441         Symbol sym = resolveQualifiedMethod(
  1442             pos, env, site, name, argtypes, typeargtypes);
  1443         if (sym.kind == MTH) return (MethodSymbol)sym;
  1444         else throw new FatalError(
  1445                  diags.fragment("fatal.err.cant.locate.meth",
  1446                                 name));
  1449     /** Resolve constructor.
  1450      *  @param pos       The position to use for error reporting.
  1451      *  @param env       The environment current at the constructor invocation.
  1452      *  @param site      The type of class for which a constructor is searched.
  1453      *  @param argtypes  The types of the constructor invocation's value
  1454      *                   arguments.
  1455      *  @param typeargtypes  The types of the constructor invocation's type
  1456      *                   arguments.
  1457      */
  1458     Symbol resolveConstructor(DiagnosticPosition pos,
  1459                               Env<AttrContext> env,
  1460                               Type site,
  1461                               List<Type> argtypes,
  1462                               List<Type> typeargtypes) {
  1463         Symbol sym = startResolution();
  1464         List<MethodResolutionPhase> steps = methodResolutionSteps;
  1465         while (steps.nonEmpty() &&
  1466                steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  1467                sym.kind >= ERRONEOUS) {
  1468             currentStep = steps.head;
  1469             sym = resolveConstructor(pos, env, site, argtypes, typeargtypes,
  1470                     steps.head.isBoxingRequired(),
  1471                     env.info.varArgs = steps.head.isVarargsRequired());
  1472             methodResolutionCache.put(steps.head, sym);
  1473             steps = steps.tail;
  1475         if (sym.kind >= AMBIGUOUS) {//if nothing is found return the 'first' error
  1476             MethodResolutionPhase errPhase = firstErroneousResolutionPhase();
  1477             sym = access(methodResolutionCache.get(errPhase),
  1478                     pos, site, names.init, true, argtypes, typeargtypes);
  1479             env.info.varArgs = errPhase.isVarargsRequired();
  1481         return sym;
  1484     /** Resolve constructor using diamond inference.
  1485      *  @param pos       The position to use for error reporting.
  1486      *  @param env       The environment current at the constructor invocation.
  1487      *  @param site      The type of class for which a constructor is searched.
  1488      *                   The scope of this class has been touched in attribution.
  1489      *  @param argtypes  The types of the constructor invocation's value
  1490      *                   arguments.
  1491      *  @param typeargtypes  The types of the constructor invocation's type
  1492      *                   arguments.
  1493      */
  1494     Symbol resolveDiamond(DiagnosticPosition pos,
  1495                               Env<AttrContext> env,
  1496                               Type site,
  1497                               List<Type> argtypes,
  1498                               List<Type> typeargtypes) {
  1499         Symbol sym = startResolution();
  1500         List<MethodResolutionPhase> steps = methodResolutionSteps;
  1501         while (steps.nonEmpty() &&
  1502                steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  1503                sym.kind >= ERRONEOUS) {
  1504             currentStep = steps.head;
  1505             sym = resolveConstructor(pos, env, site, argtypes, typeargtypes,
  1506                     steps.head.isBoxingRequired(),
  1507                     env.info.varArgs = steps.head.isVarargsRequired());
  1508             methodResolutionCache.put(steps.head, sym);
  1509             steps = steps.tail;
  1511         if (sym.kind >= AMBIGUOUS) {
  1512             final JCDiagnostic details = sym.kind == WRONG_MTH ?
  1513                 ((InapplicableSymbolError)sym).explanation :
  1514                 null;
  1515             Symbol errSym = new ResolveError(WRONG_MTH, "diamond error") {
  1516                 @Override
  1517                 JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
  1518                     String key = details == null ?
  1519                         "cant.apply.diamond" :
  1520                         "cant.apply.diamond.1";
  1521                     return diags.create(dkind, log.currentSource(), pos, key, diags.fragment("diamond", site.tsym), details);
  1523             };
  1524             MethodResolutionPhase errPhase = firstErroneousResolutionPhase();
  1525             sym = access(errSym, pos, site, names.init, true, argtypes, typeargtypes);
  1526             env.info.varArgs = errPhase.isVarargsRequired();
  1528         return sym;
  1531     /** Resolve constructor.
  1532      *  @param pos       The position to use for error reporting.
  1533      *  @param env       The environment current at the constructor invocation.
  1534      *  @param site      The type of class for which a constructor is searched.
  1535      *  @param argtypes  The types of the constructor invocation's value
  1536      *                   arguments.
  1537      *  @param typeargtypes  The types of the constructor invocation's type
  1538      *                   arguments.
  1539      *  @param allowBoxing Allow boxing and varargs conversions.
  1540      *  @param useVarargs Box trailing arguments into an array for varargs.
  1541      */
  1542     Symbol resolveConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  1543                               Type site, List<Type> argtypes,
  1544                               List<Type> typeargtypes,
  1545                               boolean allowBoxing,
  1546                               boolean useVarargs) {
  1547         Symbol sym = findMethod(env, site,
  1548                                 names.init, argtypes,
  1549                                 typeargtypes, allowBoxing,
  1550                                 useVarargs, false);
  1551         if ((sym.flags() & DEPRECATED) != 0 &&
  1552             (env.info.scope.owner.flags() & DEPRECATED) == 0 &&
  1553             env.info.scope.owner.outermostClass() != sym.outermostClass())
  1554             chk.warnDeprecated(pos, sym);
  1555         return sym;
  1558     /** Resolve a constructor, throw a fatal error if not found.
  1559      *  @param pos       The position to use for error reporting.
  1560      *  @param env       The environment current at the method invocation.
  1561      *  @param site      The type to be constructed.
  1562      *  @param argtypes  The types of the invocation's value arguments.
  1563      *  @param typeargtypes  The types of the invocation's type arguments.
  1564      */
  1565     public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  1566                                         Type site,
  1567                                         List<Type> argtypes,
  1568                                         List<Type> typeargtypes) {
  1569         Symbol sym = resolveConstructor(
  1570             pos, env, site, argtypes, typeargtypes);
  1571         if (sym.kind == MTH) return (MethodSymbol)sym;
  1572         else throw new FatalError(
  1573                  diags.fragment("fatal.err.cant.locate.ctor", site));
  1576     /** Resolve operator.
  1577      *  @param pos       The position to use for error reporting.
  1578      *  @param optag     The tag of the operation tree.
  1579      *  @param env       The environment current at the operation.
  1580      *  @param argtypes  The types of the operands.
  1581      */
  1582     Symbol resolveOperator(DiagnosticPosition pos, int optag,
  1583                            Env<AttrContext> env, List<Type> argtypes) {
  1584         Name name = treeinfo.operatorName(optag);
  1585         Symbol sym = findMethod(env, syms.predefClass.type, name, argtypes,
  1586                                 null, false, false, true);
  1587         if (boxingEnabled && sym.kind >= WRONG_MTHS)
  1588             sym = findMethod(env, syms.predefClass.type, name, argtypes,
  1589                              null, true, false, true);
  1590         return access(sym, pos, env.enclClass.sym.type, name,
  1591                       false, argtypes, null);
  1594     /** Resolve operator.
  1595      *  @param pos       The position to use for error reporting.
  1596      *  @param optag     The tag of the operation tree.
  1597      *  @param env       The environment current at the operation.
  1598      *  @param arg       The type of the operand.
  1599      */
  1600     Symbol resolveUnaryOperator(DiagnosticPosition pos, int optag, Env<AttrContext> env, Type arg) {
  1601         return resolveOperator(pos, optag, env, List.of(arg));
  1604     /** Resolve binary operator.
  1605      *  @param pos       The position to use for error reporting.
  1606      *  @param optag     The tag of the operation tree.
  1607      *  @param env       The environment current at the operation.
  1608      *  @param left      The types of the left operand.
  1609      *  @param right     The types of the right operand.
  1610      */
  1611     Symbol resolveBinaryOperator(DiagnosticPosition pos,
  1612                                  int optag,
  1613                                  Env<AttrContext> env,
  1614                                  Type left,
  1615                                  Type right) {
  1616         return resolveOperator(pos, optag, env, List.of(left, right));
  1619     /**
  1620      * Resolve `c.name' where name == this or name == super.
  1621      * @param pos           The position to use for error reporting.
  1622      * @param env           The environment current at the expression.
  1623      * @param c             The qualifier.
  1624      * @param name          The identifier's name.
  1625      */
  1626     Symbol resolveSelf(DiagnosticPosition pos,
  1627                        Env<AttrContext> env,
  1628                        TypeSymbol c,
  1629                        Name name) {
  1630         Env<AttrContext> env1 = env;
  1631         boolean staticOnly = false;
  1632         while (env1.outer != null) {
  1633             if (isStatic(env1)) staticOnly = true;
  1634             if (env1.enclClass.sym == c) {
  1635                 Symbol sym = env1.info.scope.lookup(name).sym;
  1636                 if (sym != null) {
  1637                     if (staticOnly) sym = new StaticError(sym);
  1638                     return access(sym, pos, env.enclClass.sym.type,
  1639                                   name, true);
  1642             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  1643             env1 = env1.outer;
  1645         log.error(pos, "not.encl.class", c);
  1646         return syms.errSymbol;
  1649     /**
  1650      * Resolve `c.this' for an enclosing class c that contains the
  1651      * named member.
  1652      * @param pos           The position to use for error reporting.
  1653      * @param env           The environment current at the expression.
  1654      * @param member        The member that must be contained in the result.
  1655      */
  1656     Symbol resolveSelfContaining(DiagnosticPosition pos,
  1657                                  Env<AttrContext> env,
  1658                                  Symbol member) {
  1659         Name name = names._this;
  1660         Env<AttrContext> env1 = env;
  1661         boolean staticOnly = false;
  1662         while (env1.outer != null) {
  1663             if (isStatic(env1)) staticOnly = true;
  1664             if (env1.enclClass.sym.isSubClass(member.owner, types) &&
  1665                 isAccessible(env, env1.enclClass.sym.type, member)) {
  1666                 Symbol sym = env1.info.scope.lookup(name).sym;
  1667                 if (sym != null) {
  1668                     if (staticOnly) sym = new StaticError(sym);
  1669                     return access(sym, pos, env.enclClass.sym.type,
  1670                                   name, true);
  1673             if ((env1.enclClass.sym.flags() & STATIC) != 0)
  1674                 staticOnly = true;
  1675             env1 = env1.outer;
  1677         log.error(pos, "encl.class.required", member);
  1678         return syms.errSymbol;
  1681     /**
  1682      * Resolve an appropriate implicit this instance for t's container.
  1683      * JLS2 8.8.5.1 and 15.9.2
  1684      */
  1685     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
  1686         Type thisType = (((t.tsym.owner.kind & (MTH|VAR)) != 0)
  1687                          ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
  1688                          : resolveSelfContaining(pos, env, t.tsym)).type;
  1689         if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
  1690             log.error(pos, "cant.ref.before.ctor.called", "this");
  1691         return thisType;
  1694 /* ***************************************************************************
  1695  *  ResolveError classes, indicating error situations when accessing symbols
  1696  ****************************************************************************/
  1698     public void logAccessError(Env<AttrContext> env, JCTree tree, Type type) {
  1699         AccessError error = new AccessError(env, type.getEnclosingType(), type.tsym);
  1700         logResolveError(error, tree.pos(), type.getEnclosingType(), null, null, null);
  1702     //where
  1703     private void logResolveError(ResolveError error,
  1704             DiagnosticPosition pos,
  1705             Type site,
  1706             Name name,
  1707             List<Type> argtypes,
  1708             List<Type> typeargtypes) {
  1709         JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
  1710                 pos, site, name, argtypes, typeargtypes);
  1711         if (d != null) {
  1712             d.setFlag(DiagnosticFlag.RESOLVE_ERROR);
  1713             log.report(d);
  1717     private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
  1719     public Object methodArguments(List<Type> argtypes) {
  1720         return argtypes.isEmpty() ? noArgs : argtypes;
  1723     /**
  1724      * Root class for resolution errors. Subclass of ResolveError
  1725      * represent a different kinds of resolution error - as such they must
  1726      * specify how they map into concrete compiler diagnostics.
  1727      */
  1728     private abstract class ResolveError extends Symbol {
  1730         /** The name of the kind of error, for debugging only. */
  1731         final String debugName;
  1733         ResolveError(int kind, String debugName) {
  1734             super(kind, 0, null, null, null);
  1735             this.debugName = debugName;
  1738         @Override
  1739         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
  1740             throw new AssertionError();
  1743         @Override
  1744         public String toString() {
  1745             return debugName;
  1748         @Override
  1749         public boolean exists() {
  1750             return false;
  1753         /**
  1754          * Create an external representation for this erroneous symbol to be
  1755          * used during attribution - by default this returns the symbol of a
  1756          * brand new error type which stores the original type found
  1757          * during resolution.
  1759          * @param name     the name used during resolution
  1760          * @param location the location from which the symbol is accessed
  1761          */
  1762         protected Symbol access(Name name, TypeSymbol location) {
  1763             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  1766         /**
  1767          * Create a diagnostic representing this resolution error.
  1769          * @param dkind     The kind of the diagnostic to be created (e.g error).
  1770          * @param pos       The position to be used for error reporting.
  1771          * @param site      The original type from where the selection took place.
  1772          * @param name      The name of the symbol to be resolved.
  1773          * @param argtypes  The invocation's value arguments,
  1774          *                  if we looked for a method.
  1775          * @param typeargtypes  The invocation's type arguments,
  1776          *                      if we looked for a method.
  1777          */
  1778         abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  1779                 DiagnosticPosition pos,
  1780                 Type site,
  1781                 Name name,
  1782                 List<Type> argtypes,
  1783                 List<Type> typeargtypes);
  1785         /**
  1786          * A name designates an operator if it consists
  1787          * of a non-empty sequence of operator symbols +-~!/*%&|^<>=
  1788          */
  1789         boolean isOperator(Name name) {
  1790             int i = 0;
  1791             while (i < name.getByteLength() &&
  1792                    "+-~!*/%&|^<>=".indexOf(name.getByteAt(i)) >= 0) i++;
  1793             return i > 0 && i == name.getByteLength();
  1797     /**
  1798      * This class is the root class of all resolution errors caused by
  1799      * an invalid symbol being found during resolution.
  1800      */
  1801     abstract class InvalidSymbolError extends ResolveError {
  1803         /** The invalid symbol found during resolution */
  1804         Symbol sym;
  1806         InvalidSymbolError(int kind, Symbol sym, String debugName) {
  1807             super(kind, debugName);
  1808             this.sym = sym;
  1811         @Override
  1812         public boolean exists() {
  1813             return true;
  1816         @Override
  1817         public String toString() {
  1818              return super.toString() + " wrongSym=" + sym;
  1821         @Override
  1822         public Symbol access(Name name, TypeSymbol location) {
  1823             if (sym.kind >= AMBIGUOUS)
  1824                 return ((ResolveError)sym).access(name, location);
  1825             else if ((sym.kind & ERRONEOUS) == 0 && (sym.kind & TYP) != 0)
  1826                 return types.createErrorType(name, location, sym.type).tsym;
  1827             else
  1828                 return sym;
  1832     /**
  1833      * InvalidSymbolError error class indicating that a symbol matching a
  1834      * given name does not exists in a given site.
  1835      */
  1836     class SymbolNotFoundError extends ResolveError {
  1838         SymbolNotFoundError(int kind) {
  1839             super(kind, "symbol not found error");
  1842         @Override
  1843         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  1844                 DiagnosticPosition pos,
  1845                 Type site,
  1846                 Name name,
  1847                 List<Type> argtypes,
  1848                 List<Type> typeargtypes) {
  1849             argtypes = argtypes == null ? List.<Type>nil() : argtypes;
  1850             typeargtypes = typeargtypes == null ? List.<Type>nil() : typeargtypes;
  1851             if (name == names.error)
  1852                 return null;
  1854             if (isOperator(name)) {
  1855                 return diags.create(dkind, log.currentSource(), pos,
  1856                         "operator.cant.be.applied", name, argtypes);
  1858             boolean hasLocation = false;
  1859             if (!site.tsym.name.isEmpty()) {
  1860                 if (site.tsym.kind == PCK && !site.tsym.exists()) {
  1861                     return diags.create(dkind, log.currentSource(), pos,
  1862                         "doesnt.exist", site.tsym);
  1864                 hasLocation = true;
  1866             boolean isConstructor = kind == ABSENT_MTH &&
  1867                     name == names.table.names.init;
  1868             KindName kindname = isConstructor ? KindName.CONSTRUCTOR : absentKind(kind);
  1869             Name idname = isConstructor ? site.tsym.name : name;
  1870             String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation);
  1871             if (hasLocation) {
  1872                 return diags.create(dkind, log.currentSource(), pos,
  1873                         errKey, kindname, idname, //symbol kindname, name
  1874                         typeargtypes, argtypes, //type parameters and arguments (if any)
  1875                         typeKindName(site), site); //location kindname, type
  1877             else {
  1878                 return diags.create(dkind, log.currentSource(), pos,
  1879                         errKey, kindname, idname, //symbol kindname, name
  1880                         typeargtypes, argtypes); //type parameters and arguments (if any)
  1883         //where
  1884         private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) {
  1885             String key = "cant.resolve";
  1886             String suffix = hasLocation ? ".location" : "";
  1887             switch (kindname) {
  1888                 case METHOD:
  1889                 case CONSTRUCTOR: {
  1890                     suffix += ".args";
  1891                     suffix += hasTypeArgs ? ".params" : "";
  1894             return key + suffix;
  1898     /**
  1899      * InvalidSymbolError error class indicating that a given symbol
  1900      * (either a method, a constructor or an operand) is not applicable
  1901      * given an actual arguments/type argument list.
  1902      */
  1903     class InapplicableSymbolError extends InvalidSymbolError {
  1905         /** An auxiliary explanation set in case of instantiation errors. */
  1906         JCDiagnostic explanation;
  1908         InapplicableSymbolError(Symbol sym) {
  1909             super(WRONG_MTH, sym, "inapplicable symbol error");
  1912         /** Update sym and explanation and return this.
  1913          */
  1914         InapplicableSymbolError setWrongSym(Symbol sym, JCDiagnostic explanation) {
  1915             this.sym = sym;
  1916             if (this.sym == sym && explanation != null)
  1917                 this.explanation = explanation; //update the details
  1918             return this;
  1921         /** Update sym and return this.
  1922          */
  1923         InapplicableSymbolError setWrongSym(Symbol sym) {
  1924             this.sym = sym;
  1925             return this;
  1928         @Override
  1929         public String toString() {
  1930             return super.toString() + " explanation=" + explanation;
  1933         @Override
  1934         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  1935                 DiagnosticPosition pos,
  1936                 Type site,
  1937                 Name name,
  1938                 List<Type> argtypes,
  1939                 List<Type> typeargtypes) {
  1940             if (name == names.error)
  1941                 return null;
  1943             if (isOperator(name)) {
  1944                 return diags.create(dkind, log.currentSource(),
  1945                         pos, "operator.cant.be.applied", name, argtypes);
  1947             else {
  1948                 Symbol ws = sym.asMemberOf(site, types);
  1949                 return diags.create(dkind, log.currentSource(), pos,
  1950                           "cant.apply.symbol" + (explanation != null ? ".1" : ""),
  1951                           kindName(ws),
  1952                           ws.name == names.init ? ws.owner.name : ws.name,
  1953                           methodArguments(ws.type.getParameterTypes()),
  1954                           methodArguments(argtypes),
  1955                           kindName(ws.owner),
  1956                           ws.owner.type,
  1957                           explanation);
  1961         void clear() {
  1962             explanation = null;
  1965         @Override
  1966         public Symbol access(Name name, TypeSymbol location) {
  1967             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  1971     /**
  1972      * ResolveError error class indicating that a set of symbols
  1973      * (either methods, constructors or operands) is not applicable
  1974      * given an actual arguments/type argument list.
  1975      */
  1976     class InapplicableSymbolsError extends ResolveError {
  1978         private List<Candidate> candidates = List.nil();
  1980         InapplicableSymbolsError(Symbol sym) {
  1981             super(WRONG_MTHS, "inapplicable symbols");
  1984         @Override
  1985         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  1986                 DiagnosticPosition pos,
  1987                 Type site,
  1988                 Name name,
  1989                 List<Type> argtypes,
  1990                 List<Type> typeargtypes) {
  1991             if (candidates.nonEmpty()) {
  1992                 JCDiagnostic err = diags.create(dkind,
  1993                         log.currentSource(),
  1994                         pos,
  1995                         "cant.apply.symbols",
  1996                         name == names.init ? KindName.CONSTRUCTOR : absentKind(kind),
  1997                         getName(),
  1998                         argtypes);
  1999                 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(site));
  2000             } else {
  2001                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
  2002                     site, name, argtypes, typeargtypes);
  2006         //where
  2007         List<JCDiagnostic> candidateDetails(Type site) {
  2008             List<JCDiagnostic> details = List.nil();
  2009             for (Candidate c : candidates)
  2010                 details = details.prepend(c.getDiagnostic(site));
  2011             return details.reverse();
  2014         Symbol addCandidate(MethodResolutionPhase currentStep, Symbol sym, JCDiagnostic details) {
  2015             Candidate c = new Candidate(currentStep, sym, details);
  2016             if (c.isValid() && !candidates.contains(c))
  2017                 candidates = candidates.append(c);
  2018             return this;
  2021         void clear() {
  2022             candidates = List.nil();
  2025         private Name getName() {
  2026             Symbol sym = candidates.head.sym;
  2027             return sym.name == names.init ?
  2028                 sym.owner.name :
  2029                 sym.name;
  2032         private class Candidate {
  2034             final MethodResolutionPhase step;
  2035             final Symbol sym;
  2036             final JCDiagnostic details;
  2038             private Candidate(MethodResolutionPhase step, Symbol sym, JCDiagnostic details) {
  2039                 this.step = step;
  2040                 this.sym = sym;
  2041                 this.details = details;
  2044             JCDiagnostic getDiagnostic(Type site) {
  2045                 return diags.fragment("inapplicable.method",
  2046                         Kinds.kindName(sym),
  2047                         sym.location(site, types),
  2048                         sym.asMemberOf(site, types),
  2049                         details);
  2052             @Override
  2053             public boolean equals(Object o) {
  2054                 if (o instanceof Candidate) {
  2055                     Symbol s1 = this.sym;
  2056                     Symbol s2 = ((Candidate)o).sym;
  2057                     if  ((s1 != s2 &&
  2058                         (s1.overrides(s2, s1.owner.type.tsym, types, false) ||
  2059                         (s2.overrides(s1, s2.owner.type.tsym, types, false)))) ||
  2060                         ((s1.isConstructor() || s2.isConstructor()) && s1.owner != s2.owner))
  2061                         return true;
  2063                 return false;
  2066             boolean isValid() {
  2067                 return  (((sym.flags() & VARARGS) != 0 && step == VARARITY) ||
  2068                           (sym.flags() & VARARGS) == 0 && step == (boxingEnabled ? BOX : BASIC));
  2073     /**
  2074      * An InvalidSymbolError error class indicating that a symbol is not
  2075      * accessible from a given site
  2076      */
  2077     class AccessError extends InvalidSymbolError {
  2079         private Env<AttrContext> env;
  2080         private Type site;
  2082         AccessError(Symbol sym) {
  2083             this(null, null, sym);
  2086         AccessError(Env<AttrContext> env, Type site, Symbol sym) {
  2087             super(HIDDEN, sym, "access error");
  2088             this.env = env;
  2089             this.site = site;
  2090             if (debugResolve)
  2091                 log.error("proc.messager", sym + " @ " + site + " is inaccessible.");
  2094         @Override
  2095         public boolean exists() {
  2096             return false;
  2099         @Override
  2100         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2101                 DiagnosticPosition pos,
  2102                 Type site,
  2103                 Name name,
  2104                 List<Type> argtypes,
  2105                 List<Type> typeargtypes) {
  2106             if (sym.owner.type.tag == ERROR)
  2107                 return null;
  2109             if (sym.name == names.init && sym.owner != site.tsym) {
  2110                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
  2111                         pos, site, name, argtypes, typeargtypes);
  2113             else if ((sym.flags() & PUBLIC) != 0
  2114                 || (env != null && this.site != null
  2115                     && !isAccessible(env, this.site))) {
  2116                 return diags.create(dkind, log.currentSource(),
  2117                         pos, "not.def.access.class.intf.cant.access",
  2118                     sym, sym.location());
  2120             else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) {
  2121                 return diags.create(dkind, log.currentSource(),
  2122                         pos, "report.access", sym,
  2123                         asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
  2124                         sym.location());
  2126             else {
  2127                 return diags.create(dkind, log.currentSource(),
  2128                         pos, "not.def.public.cant.access", sym, sym.location());
  2133     /**
  2134      * InvalidSymbolError error class indicating that an instance member
  2135      * has erroneously been accessed from a static context.
  2136      */
  2137     class StaticError extends InvalidSymbolError {
  2139         StaticError(Symbol sym) {
  2140             super(STATICERR, sym, "static error");
  2143         @Override
  2144         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2145                 DiagnosticPosition pos,
  2146                 Type site,
  2147                 Name name,
  2148                 List<Type> argtypes,
  2149                 List<Type> typeargtypes) {
  2150             Symbol errSym = ((sym.kind == TYP && sym.type.tag == CLASS)
  2151                 ? types.erasure(sym.type).tsym
  2152                 : sym);
  2153             return diags.create(dkind, log.currentSource(), pos,
  2154                     "non-static.cant.be.ref", kindName(sym), errSym);
  2158     /**
  2159      * InvalidSymbolError error class indicating that a pair of symbols
  2160      * (either methods, constructors or operands) are ambiguous
  2161      * given an actual arguments/type argument list.
  2162      */
  2163     class AmbiguityError extends InvalidSymbolError {
  2165         /** The other maximally specific symbol */
  2166         Symbol sym2;
  2168         AmbiguityError(Symbol sym1, Symbol sym2) {
  2169             super(AMBIGUOUS, sym1, "ambiguity error");
  2170             this.sym2 = sym2;
  2173         @Override
  2174         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2175                 DiagnosticPosition pos,
  2176                 Type site,
  2177                 Name name,
  2178                 List<Type> argtypes,
  2179                 List<Type> typeargtypes) {
  2180             AmbiguityError pair = this;
  2181             while (true) {
  2182                 if (pair.sym.kind == AMBIGUOUS)
  2183                     pair = (AmbiguityError)pair.sym;
  2184                 else if (pair.sym2.kind == AMBIGUOUS)
  2185                     pair = (AmbiguityError)pair.sym2;
  2186                 else break;
  2188             Name sname = pair.sym.name;
  2189             if (sname == names.init) sname = pair.sym.owner.name;
  2190             return diags.create(dkind, log.currentSource(),
  2191                       pos, "ref.ambiguous", sname,
  2192                       kindName(pair.sym),
  2193                       pair.sym,
  2194                       pair.sym.location(site, types),
  2195                       kindName(pair.sym2),
  2196                       pair.sym2,
  2197                       pair.sym2.location(site, types));
  2201     enum MethodResolutionPhase {
  2202         BASIC(false, false),
  2203         BOX(true, false),
  2204         VARARITY(true, true);
  2206         boolean isBoxingRequired;
  2207         boolean isVarargsRequired;
  2209         MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) {
  2210            this.isBoxingRequired = isBoxingRequired;
  2211            this.isVarargsRequired = isVarargsRequired;
  2214         public boolean isBoxingRequired() {
  2215             return isBoxingRequired;
  2218         public boolean isVarargsRequired() {
  2219             return isVarargsRequired;
  2222         public boolean isApplicable(boolean boxingEnabled, boolean varargsEnabled) {
  2223             return (varargsEnabled || !isVarargsRequired) &&
  2224                    (boxingEnabled || !isBoxingRequired);
  2228     private Map<MethodResolutionPhase, Symbol> methodResolutionCache =
  2229         new HashMap<MethodResolutionPhase, Symbol>(MethodResolutionPhase.values().length);
  2231     final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
  2233     private MethodResolutionPhase currentStep = null;
  2235     private MethodResolutionPhase firstErroneousResolutionPhase() {
  2236         MethodResolutionPhase bestSoFar = BASIC;
  2237         Symbol sym = methodNotFound;
  2238         List<MethodResolutionPhase> steps = methodResolutionSteps;
  2239         while (steps.nonEmpty() &&
  2240                steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  2241                sym.kind >= WRONG_MTHS) {
  2242             sym = methodResolutionCache.get(steps.head);
  2243             bestSoFar = steps.head;
  2244             steps = steps.tail;
  2246         return bestSoFar;

mercurial