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

Wed, 14 Apr 2010 12:31:55 +0100

author
mcimadamore
date
Wed, 14 Apr 2010 12:31:55 +0100
changeset 537
9d9d08922405
parent 325
ad07b7ea9685
child 547
04cf82179fa7
child 571
f0e3ec1f9d9f
permissions
-rw-r--r--

6939620: Switch to 'complex' diamond inference scheme
Summary: Implement new inference scheme for diamond operator that takes into account type of actual arguments supplied to constructor
Reviewed-by: jjg, darcy

     1 /*
     2  * Copyright 1999-2008 Sun Microsystems, Inc.  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.  Sun designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    22  * CA 95054 USA or visit www.sun.com if you need additional information or
    23  * have any 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 javax.lang.model.element.ElementVisitor;
    45 import java.util.Map;
    46 import java.util.HashMap;
    48 /** Helper class for name resolution, used mostly by the attribution phase.
    49  *
    50  *  <p><b>This is NOT part of any API supported by Sun Microsystems.  If
    51  *  you write code that depends on this, you do so at your own risk.
    52  *  This code and its internal interfaces are subject to change or
    53  *  deletion without notice.</b>
    54  */
    55 public class Resolve {
    56     protected static final Context.Key<Resolve> resolveKey =
    57         new Context.Key<Resolve>();
    59     Names names;
    60     Log log;
    61     Symtab syms;
    62     Check chk;
    63     Infer infer;
    64     ClassReader reader;
    65     TreeInfo treeinfo;
    66     Types types;
    67     JCDiagnostic.Factory diags;
    68     public final boolean boxingEnabled; // = source.allowBoxing();
    69     public final boolean varargsEnabled; // = source.allowVarargs();
    70     public final boolean allowInvokedynamic; // = options.get("invokedynamic");
    71     private final boolean debugResolve;
    73     public static Resolve instance(Context context) {
    74         Resolve instance = context.get(resolveKey);
    75         if (instance == null)
    76             instance = new Resolve(context);
    77         return instance;
    78     }
    80     protected Resolve(Context context) {
    81         context.put(resolveKey, this);
    82         syms = Symtab.instance(context);
    84         varNotFound = new
    85             SymbolNotFoundError(ABSENT_VAR);
    86         wrongMethod = new
    87             InapplicableSymbolError(syms.errSymbol);
    88         wrongMethods = new
    89             InapplicableSymbolsError(syms.errSymbol);
    90         methodNotFound = new
    91             SymbolNotFoundError(ABSENT_MTH);
    92         typeNotFound = new
    93             SymbolNotFoundError(ABSENT_TYP);
    95         names = Names.instance(context);
    96         log = Log.instance(context);
    97         chk = Check.instance(context);
    98         infer = Infer.instance(context);
    99         reader = ClassReader.instance(context);
   100         treeinfo = TreeInfo.instance(context);
   101         types = Types.instance(context);
   102         diags = JCDiagnostic.Factory.instance(context);
   103         Source source = Source.instance(context);
   104         boxingEnabled = source.allowBoxing();
   105         varargsEnabled = source.allowVarargs();
   106         Options options = Options.instance(context);
   107         debugResolve = options.get("debugresolve") != null;
   108         allowInvokedynamic = options.get("invokedynamic") != null;
   109     }
   111     /** error symbols, which are returned when resolution fails
   112      */
   113     final SymbolNotFoundError varNotFound;
   114     final InapplicableSymbolError wrongMethod;
   115     final InapplicableSymbolsError wrongMethods;
   116     final SymbolNotFoundError methodNotFound;
   117     final SymbolNotFoundError typeNotFound;
   119 /* ************************************************************************
   120  * Identifier resolution
   121  *************************************************************************/
   123     /** An environment is "static" if its static level is greater than
   124      *  the one of its outer environment
   125      */
   126     static boolean isStatic(Env<AttrContext> env) {
   127         return env.info.staticLevel > env.outer.info.staticLevel;
   128     }
   130     /** An environment is an "initializer" if it is a constructor or
   131      *  an instance initializer.
   132      */
   133     static boolean isInitializer(Env<AttrContext> env) {
   134         Symbol owner = env.info.scope.owner;
   135         return owner.isConstructor() ||
   136             owner.owner.kind == TYP &&
   137             (owner.kind == VAR ||
   138              owner.kind == MTH && (owner.flags() & BLOCK) != 0) &&
   139             (owner.flags() & STATIC) == 0;
   140     }
   142     /** Is class accessible in given evironment?
   143      *  @param env    The current environment.
   144      *  @param c      The class whose accessibility is checked.
   145      */
   146     public boolean isAccessible(Env<AttrContext> env, TypeSymbol c) {
   147         switch ((short)(c.flags() & AccessFlags)) {
   148         case PRIVATE:
   149             return
   150                 env.enclClass.sym.outermostClass() ==
   151                 c.owner.outermostClass();
   152         case 0:
   153             return
   154                 env.toplevel.packge == c.owner // fast special case
   155                 ||
   156                 env.toplevel.packge == c.packge()
   157                 ||
   158                 // Hack: this case is added since synthesized default constructors
   159                 // of anonymous classes should be allowed to access
   160                 // classes which would be inaccessible otherwise.
   161                 env.enclMethod != null &&
   162                 (env.enclMethod.mods.flags & ANONCONSTR) != 0;
   163         default: // error recovery
   164         case PUBLIC:
   165             return true;
   166         case PROTECTED:
   167             return
   168                 env.toplevel.packge == c.owner // fast special case
   169                 ||
   170                 env.toplevel.packge == c.packge()
   171                 ||
   172                 isInnerSubClass(env.enclClass.sym, c.owner);
   173         }
   174     }
   175     //where
   176         /** Is given class a subclass of given base class, or an inner class
   177          *  of a subclass?
   178          *  Return null if no such class exists.
   179          *  @param c     The class which is the subclass or is contained in it.
   180          *  @param base  The base class
   181          */
   182         private boolean isInnerSubClass(ClassSymbol c, Symbol base) {
   183             while (c != null && !c.isSubClass(base, types)) {
   184                 c = c.owner.enclClass();
   185             }
   186             return c != null;
   187         }
   189     boolean isAccessible(Env<AttrContext> env, Type t) {
   190         return (t.tag == ARRAY)
   191             ? isAccessible(env, types.elemtype(t))
   192             : isAccessible(env, t.tsym);
   193     }
   195     /** Is symbol accessible as a member of given type in given evironment?
   196      *  @param env    The current environment.
   197      *  @param site   The type of which the tested symbol is regarded
   198      *                as a member.
   199      *  @param sym    The symbol.
   200      */
   201     public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym) {
   202         if (sym.name == names.init && sym.owner != site.tsym) return false;
   203         ClassSymbol sub;
   204         switch ((short)(sym.flags() & AccessFlags)) {
   205         case PRIVATE:
   206             return
   207                 (env.enclClass.sym == sym.owner // fast special case
   208                  ||
   209                  env.enclClass.sym.outermostClass() ==
   210                  sym.owner.outermostClass())
   211                 &&
   212                 sym.isInheritedIn(site.tsym, types);
   213         case 0:
   214             return
   215                 (env.toplevel.packge == sym.owner.owner // fast special case
   216                  ||
   217                  env.toplevel.packge == sym.packge())
   218                 &&
   219                 isAccessible(env, site)
   220                 &&
   221                 sym.isInheritedIn(site.tsym, types)
   222                 &&
   223                 notOverriddenIn(site, sym);
   224         case PROTECTED:
   225             return
   226                 (env.toplevel.packge == sym.owner.owner // fast special case
   227                  ||
   228                  env.toplevel.packge == sym.packge()
   229                  ||
   230                  isProtectedAccessible(sym, env.enclClass.sym, site)
   231                  ||
   232                  // OK to select instance method or field from 'super' or type name
   233                  // (but type names should be disallowed elsewhere!)
   234                  env.info.selectSuper && (sym.flags() & STATIC) == 0 && sym.kind != TYP)
   235                 &&
   236                 isAccessible(env, site)
   237                 &&
   238                 notOverriddenIn(site, sym);
   239         default: // this case includes erroneous combinations as well
   240             return isAccessible(env, site) && notOverriddenIn(site, sym);
   241         }
   242     }
   243     //where
   244     /* `sym' is accessible only if not overridden by
   245      * another symbol which is a member of `site'
   246      * (because, if it is overridden, `sym' is not strictly
   247      * speaking a member of `site'.)
   248      */
   249     private boolean notOverriddenIn(Type site, Symbol sym) {
   250         if (sym.kind != MTH || sym.isConstructor() || sym.isStatic())
   251             return true;
   252         else {
   253             Symbol s2 = ((MethodSymbol)sym).implementation(site.tsym, types, true);
   254             return (s2 == null || s2 == sym ||
   255                     !types.isSubSignature(types.memberType(site, s2), types.memberType(site, sym)));
   256         }
   257     }
   258     //where
   259         /** Is given protected symbol accessible if it is selected from given site
   260          *  and the selection takes place in given class?
   261          *  @param sym     The symbol with protected access
   262          *  @param c       The class where the access takes place
   263          *  @site          The type of the qualifier
   264          */
   265         private
   266         boolean isProtectedAccessible(Symbol sym, ClassSymbol c, Type site) {
   267             while (c != null &&
   268                    !(c.isSubClass(sym.owner, types) &&
   269                      (c.flags() & INTERFACE) == 0 &&
   270                      // In JLS 2e 6.6.2.1, the subclass restriction applies
   271                      // only to instance fields and methods -- types are excluded
   272                      // regardless of whether they are declared 'static' or not.
   273                      ((sym.flags() & STATIC) != 0 || sym.kind == TYP || site.tsym.isSubClass(c, types))))
   274                 c = c.owner.enclClass();
   275             return c != null;
   276         }
   278     /** Try to instantiate the type of a method so that it fits
   279      *  given type arguments and argument types. If succesful, return
   280      *  the method's instantiated type, else return null.
   281      *  The instantiation will take into account an additional leading
   282      *  formal parameter if the method is an instance method seen as a member
   283      *  of un underdetermined site In this case, we treat site as an additional
   284      *  parameter and the parameters of the class containing the method as
   285      *  additional type variables that get instantiated.
   286      *
   287      *  @param env         The current environment
   288      *  @param site        The type of which the method is a member.
   289      *  @param m           The method symbol.
   290      *  @param argtypes    The invocation's given value arguments.
   291      *  @param typeargtypes    The invocation's given type arguments.
   292      *  @param allowBoxing Allow boxing conversions of arguments.
   293      *  @param useVarargs Box trailing arguments into an array for varargs.
   294      */
   295     Type rawInstantiate(Env<AttrContext> env,
   296                         Type site,
   297                         Symbol m,
   298                         List<Type> argtypes,
   299                         List<Type> typeargtypes,
   300                         boolean allowBoxing,
   301                         boolean useVarargs,
   302                         Warner warn)
   303         throws Infer.InferenceException {
   304         if (useVarargs && (m.flags() & VARARGS) == 0) return null;
   305         Type mt = types.memberType(site, m);
   307         // tvars is the list of formal type variables for which type arguments
   308         // need to inferred.
   309         List<Type> tvars = env.info.tvars;
   310         if (typeargtypes == null) typeargtypes = List.nil();
   311         if (mt.tag != FORALL && typeargtypes.nonEmpty()) {
   312             // This is not a polymorphic method, but typeargs are supplied
   313             // which is fine, see JLS3 15.12.2.1
   314         } else if (mt.tag == FORALL && typeargtypes.nonEmpty()) {
   315             ForAll pmt = (ForAll) mt;
   316             if (typeargtypes.length() != pmt.tvars.length())
   317                 return null;
   318             // Check type arguments are within bounds
   319             List<Type> formals = pmt.tvars;
   320             List<Type> actuals = typeargtypes;
   321             while (formals.nonEmpty() && actuals.nonEmpty()) {
   322                 List<Type> bounds = types.subst(types.getBounds((TypeVar)formals.head),
   323                                                 pmt.tvars, typeargtypes);
   324                 for (; bounds.nonEmpty(); bounds = bounds.tail)
   325                     if (!types.isSubtypeUnchecked(actuals.head, bounds.head, warn))
   326                         return null;
   327                 formals = formals.tail;
   328                 actuals = actuals.tail;
   329             }
   330             mt = types.subst(pmt.qtype, pmt.tvars, typeargtypes);
   331         } else if (mt.tag == FORALL) {
   332             ForAll pmt = (ForAll) mt;
   333             List<Type> tvars1 = types.newInstances(pmt.tvars);
   334             tvars = tvars.appendList(tvars1);
   335             mt = types.subst(pmt.qtype, pmt.tvars, tvars1);
   336         }
   338         // find out whether we need to go the slow route via infer
   339         boolean instNeeded = tvars.tail != null/*inlined: tvars.nonEmpty()*/;
   340         for (List<Type> l = argtypes;
   341              l.tail != null/*inlined: l.nonEmpty()*/ && !instNeeded;
   342              l = l.tail) {
   343             if (l.head.tag == FORALL) instNeeded = true;
   344         }
   346         if (instNeeded)
   347             return
   348             infer.instantiateMethod(tvars,
   349                                     (MethodType)mt,
   350                                     argtypes,
   351                                     allowBoxing,
   352                                     useVarargs,
   353                                     warn);
   354         return
   355             argumentsAcceptable(argtypes, mt.getParameterTypes(),
   356                                 allowBoxing, useVarargs, warn)
   357             ? mt
   358             : null;
   359     }
   361     /** Same but returns null instead throwing a NoInstanceException
   362      */
   363     Type instantiate(Env<AttrContext> env,
   364                      Type site,
   365                      Symbol m,
   366                      List<Type> argtypes,
   367                      List<Type> typeargtypes,
   368                      boolean allowBoxing,
   369                      boolean useVarargs,
   370                      Warner warn) {
   371         try {
   372             return rawInstantiate(env, site, m, argtypes, typeargtypes,
   373                                   allowBoxing, useVarargs, warn);
   374         } catch (Infer.InferenceException ex) {
   375             return null;
   376         }
   377     }
   379     /** Check if a parameter list accepts a list of args.
   380      */
   381     boolean argumentsAcceptable(List<Type> argtypes,
   382                                 List<Type> formals,
   383                                 boolean allowBoxing,
   384                                 boolean useVarargs,
   385                                 Warner warn) {
   386         Type varargsFormal = useVarargs ? formals.last() : null;
   387         while (argtypes.nonEmpty() && formals.head != varargsFormal) {
   388             boolean works = allowBoxing
   389                 ? types.isConvertible(argtypes.head, formals.head, warn)
   390                 : types.isSubtypeUnchecked(argtypes.head, formals.head, warn);
   391             if (!works) return false;
   392             argtypes = argtypes.tail;
   393             formals = formals.tail;
   394         }
   395         if (formals.head != varargsFormal) return false; // not enough args
   396         if (!useVarargs)
   397             return argtypes.isEmpty();
   398         Type elt = types.elemtype(varargsFormal);
   399         while (argtypes.nonEmpty()) {
   400             if (!types.isConvertible(argtypes.head, elt, warn))
   401                 return false;
   402             argtypes = argtypes.tail;
   403         }
   404         return true;
   405     }
   407 /* ***************************************************************************
   408  *  Symbol lookup
   409  *  the following naming conventions for arguments are used
   410  *
   411  *       env      is the environment where the symbol was mentioned
   412  *       site     is the type of which the symbol is a member
   413  *       name     is the symbol's name
   414  *                if no arguments are given
   415  *       argtypes are the value arguments, if we search for a method
   416  *
   417  *  If no symbol was found, a ResolveError detailing the problem is returned.
   418  ****************************************************************************/
   420     /** Find field. Synthetic fields are always skipped.
   421      *  @param env     The current environment.
   422      *  @param site    The original type from where the selection takes place.
   423      *  @param name    The name of the field.
   424      *  @param c       The class to search for the field. This is always
   425      *                 a superclass or implemented interface of site's class.
   426      */
   427     Symbol findField(Env<AttrContext> env,
   428                      Type site,
   429                      Name name,
   430                      TypeSymbol c) {
   431         while (c.type.tag == TYPEVAR)
   432             c = c.type.getUpperBound().tsym;
   433         Symbol bestSoFar = varNotFound;
   434         Symbol sym;
   435         Scope.Entry e = c.members().lookup(name);
   436         while (e.scope != null) {
   437             if (e.sym.kind == VAR && (e.sym.flags_field & SYNTHETIC) == 0) {
   438                 return isAccessible(env, site, e.sym)
   439                     ? e.sym : new AccessError(env, site, e.sym);
   440             }
   441             e = e.next();
   442         }
   443         Type st = types.supertype(c.type);
   444         if (st != null && (st.tag == CLASS || st.tag == TYPEVAR)) {
   445             sym = findField(env, site, name, st.tsym);
   446             if (sym.kind < bestSoFar.kind) bestSoFar = sym;
   447         }
   448         for (List<Type> l = types.interfaces(c.type);
   449              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
   450              l = l.tail) {
   451             sym = findField(env, site, name, l.head.tsym);
   452             if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
   453                 sym.owner != bestSoFar.owner)
   454                 bestSoFar = new AmbiguityError(bestSoFar, sym);
   455             else if (sym.kind < bestSoFar.kind)
   456                 bestSoFar = sym;
   457         }
   458         return bestSoFar;
   459     }
   461     /** Resolve a field identifier, throw a fatal error if not found.
   462      *  @param pos       The position to use for error reporting.
   463      *  @param env       The environment current at the method invocation.
   464      *  @param site      The type of the qualifying expression, in which
   465      *                   identifier is searched.
   466      *  @param name      The identifier's name.
   467      */
   468     public VarSymbol resolveInternalField(DiagnosticPosition pos, Env<AttrContext> env,
   469                                           Type site, Name name) {
   470         Symbol sym = findField(env, site, name, site.tsym);
   471         if (sym.kind == VAR) return (VarSymbol)sym;
   472         else throw new FatalError(
   473                  diags.fragment("fatal.err.cant.locate.field",
   474                                 name));
   475     }
   477     /** Find unqualified variable or field with given name.
   478      *  Synthetic fields always skipped.
   479      *  @param env     The current environment.
   480      *  @param name    The name of the variable or field.
   481      */
   482     Symbol findVar(Env<AttrContext> env, Name name) {
   483         Symbol bestSoFar = varNotFound;
   484         Symbol sym;
   485         Env<AttrContext> env1 = env;
   486         boolean staticOnly = false;
   487         while (env1.outer != null) {
   488             if (isStatic(env1)) staticOnly = true;
   489             Scope.Entry e = env1.info.scope.lookup(name);
   490             while (e.scope != null &&
   491                    (e.sym.kind != VAR ||
   492                     (e.sym.flags_field & SYNTHETIC) != 0))
   493                 e = e.next();
   494             sym = (e.scope != null)
   495                 ? e.sym
   496                 : findField(
   497                     env1, env1.enclClass.sym.type, name, env1.enclClass.sym);
   498             if (sym.exists()) {
   499                 if (staticOnly &&
   500                     sym.kind == VAR &&
   501                     sym.owner.kind == TYP &&
   502                     (sym.flags() & STATIC) == 0)
   503                     return new StaticError(sym);
   504                 else
   505                     return sym;
   506             } else if (sym.kind < bestSoFar.kind) {
   507                 bestSoFar = sym;
   508             }
   510             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
   511             env1 = env1.outer;
   512         }
   514         sym = findField(env, syms.predefClass.type, name, syms.predefClass);
   515         if (sym.exists())
   516             return sym;
   517         if (bestSoFar.exists())
   518             return bestSoFar;
   520         Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
   521         for (; e.scope != null; e = e.next()) {
   522             sym = e.sym;
   523             Type origin = e.getOrigin().owner.type;
   524             if (sym.kind == VAR) {
   525                 if (e.sym.owner.type != origin)
   526                     sym = sym.clone(e.getOrigin().owner);
   527                 return isAccessible(env, origin, sym)
   528                     ? sym : new AccessError(env, origin, sym);
   529             }
   530         }
   532         Symbol origin = null;
   533         e = env.toplevel.starImportScope.lookup(name);
   534         for (; e.scope != null; e = e.next()) {
   535             sym = e.sym;
   536             if (sym.kind != VAR)
   537                 continue;
   538             // invariant: sym.kind == VAR
   539             if (bestSoFar.kind < AMBIGUOUS && sym.owner != bestSoFar.owner)
   540                 return new AmbiguityError(bestSoFar, sym);
   541             else if (bestSoFar.kind >= VAR) {
   542                 origin = e.getOrigin().owner;
   543                 bestSoFar = isAccessible(env, origin.type, sym)
   544                     ? sym : new AccessError(env, origin.type, sym);
   545             }
   546         }
   547         if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type)
   548             return bestSoFar.clone(origin);
   549         else
   550             return bestSoFar;
   551     }
   553     Warner noteWarner = new Warner();
   555     /** Select the best method for a call site among two choices.
   556      *  @param env              The current environment.
   557      *  @param site             The original type from where the
   558      *                          selection takes place.
   559      *  @param argtypes         The invocation's value arguments,
   560      *  @param typeargtypes     The invocation's type arguments,
   561      *  @param sym              Proposed new best match.
   562      *  @param bestSoFar        Previously found best match.
   563      *  @param allowBoxing Allow boxing conversions of arguments.
   564      *  @param useVarargs Box trailing arguments into an array for varargs.
   565      */
   566     Symbol selectBest(Env<AttrContext> env,
   567                       Type site,
   568                       List<Type> argtypes,
   569                       List<Type> typeargtypes,
   570                       Symbol sym,
   571                       Symbol bestSoFar,
   572                       boolean allowBoxing,
   573                       boolean useVarargs,
   574                       boolean operator) {
   575         if (sym.kind == ERR) return bestSoFar;
   576         if (!sym.isInheritedIn(site.tsym, types)) return bestSoFar;
   577         assert sym.kind < AMBIGUOUS;
   578         try {
   579             if (rawInstantiate(env, site, sym, argtypes, typeargtypes,
   580                                allowBoxing, useVarargs, Warner.noWarnings) == null) {
   581                 // inapplicable
   582                 switch (bestSoFar.kind) {
   583                 case ABSENT_MTH: return wrongMethod.setWrongSym(sym);
   584                 case WRONG_MTH: return wrongMethods;
   585                 default: return bestSoFar;
   586                 }
   587             }
   588         } catch (Infer.InferenceException ex) {
   589             switch (bestSoFar.kind) {
   590             case ABSENT_MTH:
   591                 return wrongMethod.setWrongSym(sym, ex.getDiagnostic());
   592             case WRONG_MTH:
   593                 return wrongMethods;
   594             default:
   595                 return bestSoFar;
   596             }
   597         }
   598         if (!isAccessible(env, site, sym)) {
   599             return (bestSoFar.kind == ABSENT_MTH)
   600                 ? new AccessError(env, site, sym)
   601                 : bestSoFar;
   602         }
   603         return (bestSoFar.kind > AMBIGUOUS)
   604             ? sym
   605             : mostSpecific(sym, bestSoFar, env, site,
   606                            allowBoxing && operator, useVarargs);
   607     }
   609     /* Return the most specific of the two methods for a call,
   610      *  given that both are accessible and applicable.
   611      *  @param m1               A new candidate for most specific.
   612      *  @param m2               The previous most specific candidate.
   613      *  @param env              The current environment.
   614      *  @param site             The original type from where the selection
   615      *                          takes place.
   616      *  @param allowBoxing Allow boxing conversions of arguments.
   617      *  @param useVarargs Box trailing arguments into an array for varargs.
   618      */
   619     Symbol mostSpecific(Symbol m1,
   620                         Symbol m2,
   621                         Env<AttrContext> env,
   622                         final Type site,
   623                         boolean allowBoxing,
   624                         boolean useVarargs) {
   625         switch (m2.kind) {
   626         case MTH:
   627             if (m1 == m2) return m1;
   628             Type mt1 = types.memberType(site, m1);
   629             noteWarner.unchecked = false;
   630             boolean m1SignatureMoreSpecific =
   631                 (instantiate(env, site, m2, types.lowerBoundArgtypes(mt1), null,
   632                              allowBoxing, false, noteWarner) != null ||
   633                  useVarargs && instantiate(env, site, m2, types.lowerBoundArgtypes(mt1), null,
   634                                            allowBoxing, true, noteWarner) != null) &&
   635                 !noteWarner.unchecked;
   636             Type mt2 = types.memberType(site, m2);
   637             noteWarner.unchecked = false;
   638             boolean m2SignatureMoreSpecific =
   639                 (instantiate(env, site, m1, types.lowerBoundArgtypes(mt2), null,
   640                              allowBoxing, false, noteWarner) != null ||
   641                  useVarargs && instantiate(env, site, m1, types.lowerBoundArgtypes(mt2), null,
   642                                            allowBoxing, true, noteWarner) != null) &&
   643                 !noteWarner.unchecked;
   644             if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) {
   645                 if (!types.overrideEquivalent(mt1, mt2))
   646                     return new AmbiguityError(m1, m2);
   647                 // same signature; select (a) the non-bridge method, or
   648                 // (b) the one that overrides the other, or (c) the concrete
   649                 // one, or (d) merge both abstract signatures
   650                 if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE)) {
   651                     return ((m1.flags() & BRIDGE) != 0) ? m2 : m1;
   652                 }
   653                 // if one overrides or hides the other, use it
   654                 TypeSymbol m1Owner = (TypeSymbol)m1.owner;
   655                 TypeSymbol m2Owner = (TypeSymbol)m2.owner;
   656                 if (types.asSuper(m1Owner.type, m2Owner) != null &&
   657                     ((m1.owner.flags_field & INTERFACE) == 0 ||
   658                      (m2.owner.flags_field & INTERFACE) != 0) &&
   659                     m1.overrides(m2, m1Owner, types, false))
   660                     return m1;
   661                 if (types.asSuper(m2Owner.type, m1Owner) != null &&
   662                     ((m2.owner.flags_field & INTERFACE) == 0 ||
   663                      (m1.owner.flags_field & INTERFACE) != 0) &&
   664                     m2.overrides(m1, m2Owner, types, false))
   665                     return m2;
   666                 boolean m1Abstract = (m1.flags() & ABSTRACT) != 0;
   667                 boolean m2Abstract = (m2.flags() & ABSTRACT) != 0;
   668                 if (m1Abstract && !m2Abstract) return m2;
   669                 if (m2Abstract && !m1Abstract) return m1;
   670                 // both abstract or both concrete
   671                 if (!m1Abstract && !m2Abstract)
   672                     return new AmbiguityError(m1, m2);
   673                 // check that both signatures have the same erasure
   674                 if (!types.isSameTypes(m1.erasure(types).getParameterTypes(),
   675                                        m2.erasure(types).getParameterTypes()))
   676                     return new AmbiguityError(m1, m2);
   677                 // both abstract, neither overridden; merge throws clause and result type
   678                 Symbol mostSpecific;
   679                 Type result2 = mt2.getReturnType();
   680                 if (mt2.tag == FORALL)
   681                     result2 = types.subst(result2, ((ForAll)mt2).tvars, ((ForAll)mt1).tvars);
   682                 if (types.isSubtype(mt1.getReturnType(), result2)) {
   683                     mostSpecific = m1;
   684                 } else if (types.isSubtype(result2, mt1.getReturnType())) {
   685                     mostSpecific = m2;
   686                 } else {
   687                     // Theoretically, this can't happen, but it is possible
   688                     // due to error recovery or mixing incompatible class files
   689                     return new AmbiguityError(m1, m2);
   690                 }
   691                 MethodSymbol result = new MethodSymbol(
   692                         mostSpecific.flags(),
   693                         mostSpecific.name,
   694                         null,
   695                         mostSpecific.owner) {
   696                     @Override
   697                     public MethodSymbol implementation(TypeSymbol origin, Types types, boolean checkResult) {
   698                         if (origin == site.tsym)
   699                             return this;
   700                         else
   701                             return super.implementation(origin, types, checkResult);
   702                     }
   703                 };
   704                 result.type = (Type)mostSpecific.type.clone();
   705                 result.type.setThrown(chk.intersect(mt1.getThrownTypes(),
   706                                                     mt2.getThrownTypes()));
   707                 return result;
   708             }
   709             if (m1SignatureMoreSpecific) return m1;
   710             if (m2SignatureMoreSpecific) return m2;
   711             return new AmbiguityError(m1, m2);
   712         case AMBIGUOUS:
   713             AmbiguityError e = (AmbiguityError)m2;
   714             Symbol err1 = mostSpecific(m1, e.sym, env, site, allowBoxing, useVarargs);
   715             Symbol err2 = mostSpecific(m1, e.sym2, env, site, allowBoxing, useVarargs);
   716             if (err1 == err2) return err1;
   717             if (err1 == e.sym && err2 == e.sym2) return m2;
   718             if (err1 instanceof AmbiguityError &&
   719                 err2 instanceof AmbiguityError &&
   720                 ((AmbiguityError)err1).sym == ((AmbiguityError)err2).sym)
   721                 return new AmbiguityError(m1, m2);
   722             else
   723                 return new AmbiguityError(err1, err2);
   724         default:
   725             throw new AssertionError();
   726         }
   727     }
   729     /** Find best qualified method matching given name, type and value
   730      *  arguments.
   731      *  @param env       The current environment.
   732      *  @param site      The original type from where the selection
   733      *                   takes place.
   734      *  @param name      The method's name.
   735      *  @param argtypes  The method's value arguments.
   736      *  @param typeargtypes The method's type arguments
   737      *  @param allowBoxing Allow boxing conversions of arguments.
   738      *  @param useVarargs Box trailing arguments into an array for varargs.
   739      */
   740     Symbol findMethod(Env<AttrContext> env,
   741                       Type site,
   742                       Name name,
   743                       List<Type> argtypes,
   744                       List<Type> typeargtypes,
   745                       boolean allowBoxing,
   746                       boolean useVarargs,
   747                       boolean operator) {
   748         return findMethod(env,
   749                           site,
   750                           name,
   751                           argtypes,
   752                           typeargtypes,
   753                           site.tsym.type,
   754                           true,
   755                           methodNotFound,
   756                           allowBoxing,
   757                           useVarargs,
   758                           operator);
   759     }
   760     // where
   761     private Symbol findMethod(Env<AttrContext> env,
   762                               Type site,
   763                               Name name,
   764                               List<Type> argtypes,
   765                               List<Type> typeargtypes,
   766                               Type intype,
   767                               boolean abstractok,
   768                               Symbol bestSoFar,
   769                               boolean allowBoxing,
   770                               boolean useVarargs,
   771                               boolean operator) {
   772         for (Type ct = intype; ct.tag == CLASS || ct.tag == TYPEVAR; ct = types.supertype(ct)) {
   773             while (ct.tag == TYPEVAR)
   774                 ct = ct.getUpperBound();
   775             ClassSymbol c = (ClassSymbol)ct.tsym;
   776             if ((c.flags() & (ABSTRACT | INTERFACE | ENUM)) == 0)
   777                 abstractok = false;
   778             for (Scope.Entry e = c.members().lookup(name);
   779                  e.scope != null;
   780                  e = e.next()) {
   781                 //- System.out.println(" e " + e.sym);
   782                 if (e.sym.kind == MTH &&
   783                     (e.sym.flags_field & SYNTHETIC) == 0) {
   784                     bestSoFar = selectBest(env, site, argtypes, typeargtypes,
   785                                            e.sym, bestSoFar,
   786                                            allowBoxing,
   787                                            useVarargs,
   788                                            operator);
   789                 }
   790             }
   791             if (name == names.init)
   792                 break;
   793             //- System.out.println(" - " + bestSoFar);
   794             if (abstractok) {
   795                 Symbol concrete = methodNotFound;
   796                 if ((bestSoFar.flags() & ABSTRACT) == 0)
   797                     concrete = bestSoFar;
   798                 for (List<Type> l = types.interfaces(c.type);
   799                      l.nonEmpty();
   800                      l = l.tail) {
   801                     bestSoFar = findMethod(env, site, name, argtypes,
   802                                            typeargtypes,
   803                                            l.head, abstractok, bestSoFar,
   804                                            allowBoxing, useVarargs, operator);
   805                 }
   806                 if (concrete != bestSoFar &&
   807                     concrete.kind < ERR  && bestSoFar.kind < ERR &&
   808                     types.isSubSignature(concrete.type, bestSoFar.type))
   809                     bestSoFar = concrete;
   810             }
   811         }
   812         return bestSoFar;
   813     }
   815     /** Find unqualified method matching given name, type and value arguments.
   816      *  @param env       The current environment.
   817      *  @param name      The method's name.
   818      *  @param argtypes  The method's value arguments.
   819      *  @param typeargtypes  The method's type arguments.
   820      *  @param allowBoxing Allow boxing conversions of arguments.
   821      *  @param useVarargs Box trailing arguments into an array for varargs.
   822      */
   823     Symbol findFun(Env<AttrContext> env, Name name,
   824                    List<Type> argtypes, List<Type> typeargtypes,
   825                    boolean allowBoxing, boolean useVarargs) {
   826         Symbol bestSoFar = methodNotFound;
   827         Symbol sym;
   828         Env<AttrContext> env1 = env;
   829         boolean staticOnly = false;
   830         while (env1.outer != null) {
   831             if (isStatic(env1)) staticOnly = true;
   832             sym = findMethod(
   833                 env1, env1.enclClass.sym.type, name, argtypes, typeargtypes,
   834                 allowBoxing, useVarargs, false);
   835             if (sym.exists()) {
   836                 if (staticOnly &&
   837                     sym.kind == MTH &&
   838                     sym.owner.kind == TYP &&
   839                     (sym.flags() & STATIC) == 0) return new StaticError(sym);
   840                 else return sym;
   841             } else if (sym.kind < bestSoFar.kind) {
   842                 bestSoFar = sym;
   843             }
   844             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
   845             env1 = env1.outer;
   846         }
   848         sym = findMethod(env, syms.predefClass.type, name, argtypes,
   849                          typeargtypes, allowBoxing, useVarargs, false);
   850         if (sym.exists())
   851             return sym;
   853         Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
   854         for (; e.scope != null; e = e.next()) {
   855             sym = e.sym;
   856             Type origin = e.getOrigin().owner.type;
   857             if (sym.kind == MTH) {
   858                 if (e.sym.owner.type != origin)
   859                     sym = sym.clone(e.getOrigin().owner);
   860                 if (!isAccessible(env, origin, sym))
   861                     sym = new AccessError(env, origin, sym);
   862                 bestSoFar = selectBest(env, origin,
   863                                        argtypes, typeargtypes,
   864                                        sym, bestSoFar,
   865                                        allowBoxing, useVarargs, false);
   866             }
   867         }
   868         if (bestSoFar.exists())
   869             return bestSoFar;
   871         e = env.toplevel.starImportScope.lookup(name);
   872         for (; e.scope != null; e = e.next()) {
   873             sym = e.sym;
   874             Type origin = e.getOrigin().owner.type;
   875             if (sym.kind == MTH) {
   876                 if (e.sym.owner.type != origin)
   877                     sym = sym.clone(e.getOrigin().owner);
   878                 if (!isAccessible(env, origin, sym))
   879                     sym = new AccessError(env, origin, sym);
   880                 bestSoFar = selectBest(env, origin,
   881                                        argtypes, typeargtypes,
   882                                        sym, bestSoFar,
   883                                        allowBoxing, useVarargs, false);
   884             }
   885         }
   886         return bestSoFar;
   887     }
   889     /** Find or create an implicit method of exactly the given type (after erasure).
   890      *  Searches in a side table, not the main scope of the site.
   891      *  This emulates the lookup process required by JSR 292 in JVM.
   892      *  @param env       The current environment.
   893      *  @param site      The original type from where the selection
   894      *                   takes place.
   895      *  @param name      The method's name.
   896      *  @param argtypes  The method's value arguments.
   897      *  @param typeargtypes The method's type arguments
   898      */
   899     Symbol findImplicitMethod(Env<AttrContext> env,
   900                               Type site,
   901                               Name name,
   902                               List<Type> argtypes,
   903                               List<Type> typeargtypes) {
   904         assert allowInvokedynamic;
   905         assert site == syms.invokeDynamicType || (site == syms.methodHandleType && name == names.invoke);
   906         ClassSymbol c = (ClassSymbol) site.tsym;
   907         Scope implicit = c.members().next;
   908         if (implicit == null) {
   909             c.members().next = implicit = new Scope(c);
   910         }
   911         Type restype;
   912         if (typeargtypes.isEmpty()) {
   913             restype = syms.objectType;
   914         } else {
   915             restype = typeargtypes.head;
   916             if (!typeargtypes.tail.isEmpty())
   917                 return methodNotFound;
   918         }
   919         List<Type> paramtypes = Type.map(argtypes, implicitArgType);
   920         MethodType mtype = new MethodType(paramtypes,
   921                                           restype,
   922                                           List.<Type>nil(),
   923                                           syms.methodClass);
   924         int flags = PUBLIC | ABSTRACT;
   925         if (site == syms.invokeDynamicType)  flags |= STATIC;
   926         Symbol m = null;
   927         for (Scope.Entry e = implicit.lookup(name);
   928              e.scope != null;
   929              e = e.next()) {
   930             Symbol sym = e.sym;
   931             assert sym.kind == MTH;
   932             if (types.isSameType(mtype, sym.type)
   933                 && (sym.flags() & STATIC) == (flags & STATIC)) {
   934                 m = sym;
   935                 break;
   936             }
   937         }
   938         if (m == null) {
   939             // create the desired method
   940             m = new MethodSymbol(flags, name, mtype, c);
   941             implicit.enter(m);
   942         }
   943         assert argumentsAcceptable(argtypes, types.memberType(site, m).getParameterTypes(),
   944                                    false, false, Warner.noWarnings);
   945         assert null != instantiate(env, site, m, argtypes, typeargtypes, false, false, Warner.noWarnings);
   946         return m;
   947     }
   948     //where
   949         Mapping implicitArgType = new Mapping ("implicitArgType") {
   950                 public Type apply(Type t) { return implicitArgType(t); }
   951             };
   952         Type implicitArgType(Type argType) {
   953             argType = types.erasure(argType);
   954             if (argType.tag == BOT)
   955                 // nulls type as the marker type Null (which has no instances)
   956                 // TO DO: figure out how to access java.lang.Null safely, else throw nice error
   957                 //argType = types.boxedClass(syms.botType).type;
   958                 argType = types.boxedClass(syms.voidType).type;  // REMOVE
   959             return argType;
   960         }
   962     /** Load toplevel or member class with given fully qualified name and
   963      *  verify that it is accessible.
   964      *  @param env       The current environment.
   965      *  @param name      The fully qualified name of the class to be loaded.
   966      */
   967     Symbol loadClass(Env<AttrContext> env, Name name) {
   968         try {
   969             ClassSymbol c = reader.loadClass(name);
   970             return isAccessible(env, c) ? c : new AccessError(c);
   971         } catch (ClassReader.BadClassFile err) {
   972             throw err;
   973         } catch (CompletionFailure ex) {
   974             return typeNotFound;
   975         }
   976     }
   978     /** Find qualified member type.
   979      *  @param env       The current environment.
   980      *  @param site      The original type from where the selection takes
   981      *                   place.
   982      *  @param name      The type's name.
   983      *  @param c         The class to search for the member type. This is
   984      *                   always a superclass or implemented interface of
   985      *                   site's class.
   986      */
   987     Symbol findMemberType(Env<AttrContext> env,
   988                           Type site,
   989                           Name name,
   990                           TypeSymbol c) {
   991         Symbol bestSoFar = typeNotFound;
   992         Symbol sym;
   993         Scope.Entry e = c.members().lookup(name);
   994         while (e.scope != null) {
   995             if (e.sym.kind == TYP) {
   996                 return isAccessible(env, site, e.sym)
   997                     ? e.sym
   998                     : new AccessError(env, site, e.sym);
   999             }
  1000             e = e.next();
  1002         Type st = types.supertype(c.type);
  1003         if (st != null && st.tag == CLASS) {
  1004             sym = findMemberType(env, site, name, st.tsym);
  1005             if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1007         for (List<Type> l = types.interfaces(c.type);
  1008              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
  1009              l = l.tail) {
  1010             sym = findMemberType(env, site, name, l.head.tsym);
  1011             if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
  1012                 sym.owner != bestSoFar.owner)
  1013                 bestSoFar = new AmbiguityError(bestSoFar, sym);
  1014             else if (sym.kind < bestSoFar.kind)
  1015                 bestSoFar = sym;
  1017         return bestSoFar;
  1020     /** Find a global type in given scope and load corresponding class.
  1021      *  @param env       The current environment.
  1022      *  @param scope     The scope in which to look for the type.
  1023      *  @param name      The type's name.
  1024      */
  1025     Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name) {
  1026         Symbol bestSoFar = typeNotFound;
  1027         for (Scope.Entry e = scope.lookup(name); e.scope != null; e = e.next()) {
  1028             Symbol sym = loadClass(env, e.sym.flatName());
  1029             if (bestSoFar.kind == TYP && sym.kind == TYP &&
  1030                 bestSoFar != sym)
  1031                 return new AmbiguityError(bestSoFar, sym);
  1032             else if (sym.kind < bestSoFar.kind)
  1033                 bestSoFar = sym;
  1035         return bestSoFar;
  1038     /** Find an unqualified type symbol.
  1039      *  @param env       The current environment.
  1040      *  @param name      The type's name.
  1041      */
  1042     Symbol findType(Env<AttrContext> env, Name name) {
  1043         Symbol bestSoFar = typeNotFound;
  1044         Symbol sym;
  1045         boolean staticOnly = false;
  1046         for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
  1047             if (isStatic(env1)) staticOnly = true;
  1048             for (Scope.Entry e = env1.info.scope.lookup(name);
  1049                  e.scope != null;
  1050                  e = e.next()) {
  1051                 if (e.sym.kind == TYP) {
  1052                     if (staticOnly &&
  1053                         e.sym.type.tag == TYPEVAR &&
  1054                         e.sym.owner.kind == TYP) return new StaticError(e.sym);
  1055                     return e.sym;
  1059             sym = findMemberType(env1, env1.enclClass.sym.type, name,
  1060                                  env1.enclClass.sym);
  1061             if (staticOnly && sym.kind == TYP &&
  1062                 sym.type.tag == CLASS &&
  1063                 sym.type.getEnclosingType().tag == CLASS &&
  1064                 env1.enclClass.sym.type.isParameterized() &&
  1065                 sym.type.getEnclosingType().isParameterized())
  1066                 return new StaticError(sym);
  1067             else if (sym.exists()) return sym;
  1068             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1070             JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass;
  1071             if ((encl.sym.flags() & STATIC) != 0)
  1072                 staticOnly = true;
  1075         if (env.tree.getTag() != JCTree.IMPORT) {
  1076             sym = findGlobalType(env, env.toplevel.namedImportScope, name);
  1077             if (sym.exists()) return sym;
  1078             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1080             sym = findGlobalType(env, env.toplevel.packge.members(), name);
  1081             if (sym.exists()) return sym;
  1082             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1084             sym = findGlobalType(env, env.toplevel.starImportScope, name);
  1085             if (sym.exists()) return sym;
  1086             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1089         return bestSoFar;
  1092     /** Find an unqualified identifier which matches a specified kind set.
  1093      *  @param env       The current environment.
  1094      *  @param name      The indentifier's name.
  1095      *  @param kind      Indicates the possible symbol kinds
  1096      *                   (a subset of VAL, TYP, PCK).
  1097      */
  1098     Symbol findIdent(Env<AttrContext> env, Name name, int kind) {
  1099         Symbol bestSoFar = typeNotFound;
  1100         Symbol sym;
  1102         if ((kind & VAR) != 0) {
  1103             sym = findVar(env, name);
  1104             if (sym.exists()) return sym;
  1105             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1108         if ((kind & TYP) != 0) {
  1109             sym = findType(env, name);
  1110             if (sym.exists()) return sym;
  1111             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1114         if ((kind & PCK) != 0) return reader.enterPackage(name);
  1115         else return bestSoFar;
  1118     /** Find an identifier in a package which matches a specified kind set.
  1119      *  @param env       The current environment.
  1120      *  @param name      The identifier's name.
  1121      *  @param kind      Indicates the possible symbol kinds
  1122      *                   (a nonempty subset of TYP, PCK).
  1123      */
  1124     Symbol findIdentInPackage(Env<AttrContext> env, TypeSymbol pck,
  1125                               Name name, int kind) {
  1126         Name fullname = TypeSymbol.formFullName(name, pck);
  1127         Symbol bestSoFar = typeNotFound;
  1128         PackageSymbol pack = null;
  1129         if ((kind & PCK) != 0) {
  1130             pack = reader.enterPackage(fullname);
  1131             if (pack.exists()) return pack;
  1133         if ((kind & TYP) != 0) {
  1134             Symbol sym = loadClass(env, fullname);
  1135             if (sym.exists()) {
  1136                 // don't allow programs to use flatnames
  1137                 if (name == sym.name) return sym;
  1139             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1141         return (pack != null) ? pack : bestSoFar;
  1144     /** Find an identifier among the members of a given type `site'.
  1145      *  @param env       The current environment.
  1146      *  @param site      The type containing the symbol to be found.
  1147      *  @param name      The identifier's name.
  1148      *  @param kind      Indicates the possible symbol kinds
  1149      *                   (a subset of VAL, TYP).
  1150      */
  1151     Symbol findIdentInType(Env<AttrContext> env, Type site,
  1152                            Name name, int kind) {
  1153         Symbol bestSoFar = typeNotFound;
  1154         Symbol sym;
  1155         if ((kind & VAR) != 0) {
  1156             sym = findField(env, site, name, site.tsym);
  1157             if (sym.exists()) return sym;
  1158             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1161         if ((kind & TYP) != 0) {
  1162             sym = findMemberType(env, site, name, site.tsym);
  1163             if (sym.exists()) return sym;
  1164             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1166         return bestSoFar;
  1169 /* ***************************************************************************
  1170  *  Access checking
  1171  *  The following methods convert ResolveErrors to ErrorSymbols, issuing
  1172  *  an error message in the process
  1173  ****************************************************************************/
  1175     /** If `sym' is a bad symbol: report error and return errSymbol
  1176      *  else pass through unchanged,
  1177      *  additional arguments duplicate what has been used in trying to find the
  1178      *  symbol (--> flyweight pattern). This improves performance since we
  1179      *  expect misses to happen frequently.
  1181      *  @param sym       The symbol that was found, or a ResolveError.
  1182      *  @param pos       The position to use for error reporting.
  1183      *  @param site      The original type from where the selection took place.
  1184      *  @param name      The symbol's name.
  1185      *  @param argtypes  The invocation's value arguments,
  1186      *                   if we looked for a method.
  1187      *  @param typeargtypes  The invocation's type arguments,
  1188      *                   if we looked for a method.
  1189      */
  1190     Symbol access(Symbol sym,
  1191                   DiagnosticPosition pos,
  1192                   Type site,
  1193                   Name name,
  1194                   boolean qualified,
  1195                   List<Type> argtypes,
  1196                   List<Type> typeargtypes) {
  1197         if (sym.kind >= AMBIGUOUS) {
  1198             ResolveError errSym = (ResolveError)sym;
  1199             if (!site.isErroneous() &&
  1200                 !Type.isErroneous(argtypes) &&
  1201                 (typeargtypes==null || !Type.isErroneous(typeargtypes)))
  1202                 logResolveError(errSym, pos, site, name, argtypes, typeargtypes);
  1203             sym = errSym.access(name, qualified ? site.tsym : syms.noSymbol);
  1205         return sym;
  1208     /** Same as above, but without type arguments and arguments.
  1209      */
  1210     Symbol access(Symbol sym,
  1211                   DiagnosticPosition pos,
  1212                   Type site,
  1213                   Name name,
  1214                   boolean qualified) {
  1215         if (sym.kind >= AMBIGUOUS)
  1216             return access(sym, pos, site, name, qualified, List.<Type>nil(), null);
  1217         else
  1218             return sym;
  1221     /** Check that sym is not an abstract method.
  1222      */
  1223     void checkNonAbstract(DiagnosticPosition pos, Symbol sym) {
  1224         if ((sym.flags() & ABSTRACT) != 0)
  1225             log.error(pos, "abstract.cant.be.accessed.directly",
  1226                       kindName(sym), sym, sym.location());
  1229 /* ***************************************************************************
  1230  *  Debugging
  1231  ****************************************************************************/
  1233     /** print all scopes starting with scope s and proceeding outwards.
  1234      *  used for debugging.
  1235      */
  1236     public void printscopes(Scope s) {
  1237         while (s != null) {
  1238             if (s.owner != null)
  1239                 System.err.print(s.owner + ": ");
  1240             for (Scope.Entry e = s.elems; e != null; e = e.sibling) {
  1241                 if ((e.sym.flags() & ABSTRACT) != 0)
  1242                     System.err.print("abstract ");
  1243                 System.err.print(e.sym + " ");
  1245             System.err.println();
  1246             s = s.next;
  1250     void printscopes(Env<AttrContext> env) {
  1251         while (env.outer != null) {
  1252             System.err.println("------------------------------");
  1253             printscopes(env.info.scope);
  1254             env = env.outer;
  1258     public void printscopes(Type t) {
  1259         while (t.tag == CLASS) {
  1260             printscopes(t.tsym.members());
  1261             t = types.supertype(t);
  1265 /* ***************************************************************************
  1266  *  Name resolution
  1267  *  Naming conventions are as for symbol lookup
  1268  *  Unlike the find... methods these methods will report access errors
  1269  ****************************************************************************/
  1271     /** Resolve an unqualified (non-method) identifier.
  1272      *  @param pos       The position to use for error reporting.
  1273      *  @param env       The environment current at the identifier use.
  1274      *  @param name      The identifier's name.
  1275      *  @param kind      The set of admissible symbol kinds for the identifier.
  1276      */
  1277     Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env,
  1278                         Name name, int kind) {
  1279         return access(
  1280             findIdent(env, name, kind),
  1281             pos, env.enclClass.sym.type, name, false);
  1284     /** Resolve an unqualified method identifier.
  1285      *  @param pos       The position to use for error reporting.
  1286      *  @param env       The environment current at the method invocation.
  1287      *  @param name      The identifier's name.
  1288      *  @param argtypes  The types of the invocation's value arguments.
  1289      *  @param typeargtypes  The types of the invocation's type arguments.
  1290      */
  1291     Symbol resolveMethod(DiagnosticPosition pos,
  1292                          Env<AttrContext> env,
  1293                          Name name,
  1294                          List<Type> argtypes,
  1295                          List<Type> typeargtypes) {
  1296         Symbol sym = methodNotFound;
  1297         List<MethodResolutionPhase> steps = methodResolutionSteps;
  1298         while (steps.nonEmpty() &&
  1299                steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  1300                sym.kind >= ERRONEOUS) {
  1301             sym = findFun(env, name, argtypes, typeargtypes,
  1302                     steps.head.isBoxingRequired,
  1303                     env.info.varArgs = steps.head.isVarargsRequired);
  1304             methodResolutionCache.put(steps.head, sym);
  1305             steps = steps.tail;
  1307         if (sym.kind >= AMBIGUOUS) {//if nothing is found return the 'first' error
  1308             MethodResolutionPhase errPhase =
  1309                     firstErroneousResolutionPhase();
  1310             sym = access(methodResolutionCache.get(errPhase),
  1311                     pos, env.enclClass.sym.type, name, false, argtypes, typeargtypes);
  1312             env.info.varArgs = errPhase.isVarargsRequired;
  1314         return sym;
  1317     /** Resolve a qualified method identifier
  1318      *  @param pos       The position to use for error reporting.
  1319      *  @param env       The environment current at the method invocation.
  1320      *  @param site      The type of the qualifying expression, in which
  1321      *                   identifier is searched.
  1322      *  @param name      The identifier's name.
  1323      *  @param argtypes  The types of the invocation's value arguments.
  1324      *  @param typeargtypes  The types of the invocation's type arguments.
  1325      */
  1326     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
  1327                                   Type site, Name name, List<Type> argtypes,
  1328                                   List<Type> typeargtypes) {
  1329         Symbol sym = methodNotFound;
  1330         List<MethodResolutionPhase> steps = methodResolutionSteps;
  1331         while (steps.nonEmpty() &&
  1332                steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  1333                sym.kind >= ERRONEOUS) {
  1334             sym = findMethod(env, site, name, argtypes, typeargtypes,
  1335                     steps.head.isBoxingRequired(),
  1336                     env.info.varArgs = steps.head.isVarargsRequired(), false);
  1337             methodResolutionCache.put(steps.head, sym);
  1338             steps = steps.tail;
  1340         if (sym.kind >= AMBIGUOUS &&
  1341             allowInvokedynamic &&
  1342             (site == syms.invokeDynamicType ||
  1343              site == syms.methodHandleType && name == names.invoke)) {
  1344             // lookup failed; supply an exactly-typed implicit method
  1345             sym = findImplicitMethod(env, site, name, argtypes, typeargtypes);
  1346             env.info.varArgs = false;
  1348         if (sym.kind >= AMBIGUOUS) {//if nothing is found return the 'first' error
  1349             MethodResolutionPhase errPhase =
  1350                     firstErroneousResolutionPhase();
  1351             sym = access(methodResolutionCache.get(errPhase),
  1352                     pos, site, name, true, argtypes, typeargtypes);
  1353             env.info.varArgs = errPhase.isVarargsRequired;
  1355         return sym;
  1358     /** Resolve a qualified method identifier, throw a fatal error if not
  1359      *  found.
  1360      *  @param pos       The position to use for error reporting.
  1361      *  @param env       The environment current at the method invocation.
  1362      *  @param site      The type of the qualifying expression, in which
  1363      *                   identifier is searched.
  1364      *  @param name      The identifier's name.
  1365      *  @param argtypes  The types of the invocation's value arguments.
  1366      *  @param typeargtypes  The types of the invocation's type arguments.
  1367      */
  1368     public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env,
  1369                                         Type site, Name name,
  1370                                         List<Type> argtypes,
  1371                                         List<Type> typeargtypes) {
  1372         Symbol sym = resolveQualifiedMethod(
  1373             pos, env, site, name, argtypes, typeargtypes);
  1374         if (sym.kind == MTH) return (MethodSymbol)sym;
  1375         else throw new FatalError(
  1376                  diags.fragment("fatal.err.cant.locate.meth",
  1377                                 name));
  1380     /** Resolve constructor.
  1381      *  @param pos       The position to use for error reporting.
  1382      *  @param env       The environment current at the constructor invocation.
  1383      *  @param site      The type of class for which a constructor is searched.
  1384      *  @param argtypes  The types of the constructor invocation's value
  1385      *                   arguments.
  1386      *  @param typeargtypes  The types of the constructor invocation's type
  1387      *                   arguments.
  1388      */
  1389     Symbol resolveConstructor(DiagnosticPosition pos,
  1390                               Env<AttrContext> env,
  1391                               Type site,
  1392                               List<Type> argtypes,
  1393                               List<Type> typeargtypes) {
  1394         Symbol sym = methodNotFound;
  1395         List<MethodResolutionPhase> steps = methodResolutionSteps;
  1396         while (steps.nonEmpty() &&
  1397                steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  1398                sym.kind >= ERRONEOUS) {
  1399             sym = resolveConstructor(pos, env, site, argtypes, typeargtypes,
  1400                     steps.head.isBoxingRequired(),
  1401                     env.info.varArgs = steps.head.isVarargsRequired());
  1402             methodResolutionCache.put(steps.head, sym);
  1403             steps = steps.tail;
  1405         if (sym.kind >= AMBIGUOUS) {//if nothing is found return the 'first' error
  1406             MethodResolutionPhase errPhase = firstErroneousResolutionPhase();
  1407             sym = access(methodResolutionCache.get(errPhase),
  1408                     pos, site, names.init, true, argtypes, typeargtypes);
  1409             env.info.varArgs = errPhase.isVarargsRequired();
  1411         return sym;
  1414     /** Resolve constructor using diamond inference.
  1415      *  @param pos       The position to use for error reporting.
  1416      *  @param env       The environment current at the constructor invocation.
  1417      *  @param site      The type of class for which a constructor is searched.
  1418      *                   The scope of this class has been touched in attribution.
  1419      *  @param argtypes  The types of the constructor invocation's value
  1420      *                   arguments.
  1421      *  @param typeargtypes  The types of the constructor invocation's type
  1422      *                   arguments.
  1423      */
  1424     Symbol resolveDiamond(DiagnosticPosition pos,
  1425                               Env<AttrContext> env,
  1426                               Type site,
  1427                               List<Type> argtypes,
  1428                               List<Type> typeargtypes, boolean reportErrors) {
  1429         Symbol sym = methodNotFound;
  1430         JCDiagnostic explanation = null;
  1431         List<MethodResolutionPhase> steps = methodResolutionSteps;
  1432         while (steps.nonEmpty() &&
  1433                steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  1434                sym.kind >= ERRONEOUS) {
  1435             sym = resolveConstructor(pos, env, site, argtypes, typeargtypes,
  1436                     steps.head.isBoxingRequired(),
  1437                     env.info.varArgs = steps.head.isVarargsRequired());
  1438             methodResolutionCache.put(steps.head, sym);
  1439             if (sym.kind == WRONG_MTH &&
  1440                     ((InapplicableSymbolError)sym).explanation != null) {
  1441                 //if the symbol is an inapplicable method symbol, then the
  1442                 //explanation contains the reason for which inference failed
  1443                 explanation = ((InapplicableSymbolError)sym).explanation;
  1445             steps = steps.tail;
  1447         if (sym.kind >= AMBIGUOUS && reportErrors) {
  1448             String key = explanation == null ?
  1449                 "cant.apply.diamond" :
  1450                 "cant.apply.diamond.1";
  1451             log.error(pos, key, diags.fragment("diamond", site.tsym), explanation);
  1453         return sym;
  1456     /** Resolve constructor.
  1457      *  @param pos       The position to use for error reporting.
  1458      *  @param env       The environment current at the constructor invocation.
  1459      *  @param site      The type of class for which a constructor is searched.
  1460      *  @param argtypes  The types of the constructor invocation's value
  1461      *                   arguments.
  1462      *  @param typeargtypes  The types of the constructor invocation's type
  1463      *                   arguments.
  1464      *  @param allowBoxing Allow boxing and varargs conversions.
  1465      *  @param useVarargs Box trailing arguments into an array for varargs.
  1466      */
  1467     Symbol resolveConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  1468                               Type site, List<Type> argtypes,
  1469                               List<Type> typeargtypes,
  1470                               boolean allowBoxing,
  1471                               boolean useVarargs) {
  1472         Symbol sym = findMethod(env, site,
  1473                                 names.init, argtypes,
  1474                                 typeargtypes, allowBoxing,
  1475                                 useVarargs, false);
  1476         if ((sym.flags() & DEPRECATED) != 0 &&
  1477             (env.info.scope.owner.flags() & DEPRECATED) == 0 &&
  1478             env.info.scope.owner.outermostClass() != sym.outermostClass())
  1479             chk.warnDeprecated(pos, sym);
  1480         return sym;
  1483     /** Resolve a constructor, throw a fatal error if not found.
  1484      *  @param pos       The position to use for error reporting.
  1485      *  @param env       The environment current at the method invocation.
  1486      *  @param site      The type to be constructed.
  1487      *  @param argtypes  The types of the invocation's value arguments.
  1488      *  @param typeargtypes  The types of the invocation's type arguments.
  1489      */
  1490     public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  1491                                         Type site,
  1492                                         List<Type> argtypes,
  1493                                         List<Type> typeargtypes) {
  1494         Symbol sym = resolveConstructor(
  1495             pos, env, site, argtypes, typeargtypes);
  1496         if (sym.kind == MTH) return (MethodSymbol)sym;
  1497         else throw new FatalError(
  1498                  diags.fragment("fatal.err.cant.locate.ctor", site));
  1501     /** Resolve operator.
  1502      *  @param pos       The position to use for error reporting.
  1503      *  @param optag     The tag of the operation tree.
  1504      *  @param env       The environment current at the operation.
  1505      *  @param argtypes  The types of the operands.
  1506      */
  1507     Symbol resolveOperator(DiagnosticPosition pos, int optag,
  1508                            Env<AttrContext> env, List<Type> argtypes) {
  1509         Name name = treeinfo.operatorName(optag);
  1510         Symbol sym = findMethod(env, syms.predefClass.type, name, argtypes,
  1511                                 null, false, false, true);
  1512         if (boxingEnabled && sym.kind >= WRONG_MTHS)
  1513             sym = findMethod(env, syms.predefClass.type, name, argtypes,
  1514                              null, true, false, true);
  1515         return access(sym, pos, env.enclClass.sym.type, name,
  1516                       false, argtypes, null);
  1519     /** Resolve operator.
  1520      *  @param pos       The position to use for error reporting.
  1521      *  @param optag     The tag of the operation tree.
  1522      *  @param env       The environment current at the operation.
  1523      *  @param arg       The type of the operand.
  1524      */
  1525     Symbol resolveUnaryOperator(DiagnosticPosition pos, int optag, Env<AttrContext> env, Type arg) {
  1526         return resolveOperator(pos, optag, env, List.of(arg));
  1529     /** Resolve binary operator.
  1530      *  @param pos       The position to use for error reporting.
  1531      *  @param optag     The tag of the operation tree.
  1532      *  @param env       The environment current at the operation.
  1533      *  @param left      The types of the left operand.
  1534      *  @param right     The types of the right operand.
  1535      */
  1536     Symbol resolveBinaryOperator(DiagnosticPosition pos,
  1537                                  int optag,
  1538                                  Env<AttrContext> env,
  1539                                  Type left,
  1540                                  Type right) {
  1541         return resolveOperator(pos, optag, env, List.of(left, right));
  1544     /**
  1545      * Resolve `c.name' where name == this or name == super.
  1546      * @param pos           The position to use for error reporting.
  1547      * @param env           The environment current at the expression.
  1548      * @param c             The qualifier.
  1549      * @param name          The identifier's name.
  1550      */
  1551     Symbol resolveSelf(DiagnosticPosition pos,
  1552                        Env<AttrContext> env,
  1553                        TypeSymbol c,
  1554                        Name name) {
  1555         Env<AttrContext> env1 = env;
  1556         boolean staticOnly = false;
  1557         while (env1.outer != null) {
  1558             if (isStatic(env1)) staticOnly = true;
  1559             if (env1.enclClass.sym == c) {
  1560                 Symbol sym = env1.info.scope.lookup(name).sym;
  1561                 if (sym != null) {
  1562                     if (staticOnly) sym = new StaticError(sym);
  1563                     return access(sym, pos, env.enclClass.sym.type,
  1564                                   name, true);
  1567             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  1568             env1 = env1.outer;
  1570         log.error(pos, "not.encl.class", c);
  1571         return syms.errSymbol;
  1574     /**
  1575      * Resolve `c.this' for an enclosing class c that contains the
  1576      * named member.
  1577      * @param pos           The position to use for error reporting.
  1578      * @param env           The environment current at the expression.
  1579      * @param member        The member that must be contained in the result.
  1580      */
  1581     Symbol resolveSelfContaining(DiagnosticPosition pos,
  1582                                  Env<AttrContext> env,
  1583                                  Symbol member) {
  1584         Name name = names._this;
  1585         Env<AttrContext> env1 = env;
  1586         boolean staticOnly = false;
  1587         while (env1.outer != null) {
  1588             if (isStatic(env1)) staticOnly = true;
  1589             if (env1.enclClass.sym.isSubClass(member.owner, types) &&
  1590                 isAccessible(env, env1.enclClass.sym.type, member)) {
  1591                 Symbol sym = env1.info.scope.lookup(name).sym;
  1592                 if (sym != null) {
  1593                     if (staticOnly) sym = new StaticError(sym);
  1594                     return access(sym, pos, env.enclClass.sym.type,
  1595                                   name, true);
  1598             if ((env1.enclClass.sym.flags() & STATIC) != 0)
  1599                 staticOnly = true;
  1600             env1 = env1.outer;
  1602         log.error(pos, "encl.class.required", member);
  1603         return syms.errSymbol;
  1606     /**
  1607      * Resolve an appropriate implicit this instance for t's container.
  1608      * JLS2 8.8.5.1 and 15.9.2
  1609      */
  1610     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
  1611         Type thisType = (((t.tsym.owner.kind & (MTH|VAR)) != 0)
  1612                          ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
  1613                          : resolveSelfContaining(pos, env, t.tsym)).type;
  1614         if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
  1615             log.error(pos, "cant.ref.before.ctor.called", "this");
  1616         return thisType;
  1619 /* ***************************************************************************
  1620  *  ResolveError classes, indicating error situations when accessing symbols
  1621  ****************************************************************************/
  1623     public void logAccessError(Env<AttrContext> env, JCTree tree, Type type) {
  1624         AccessError error = new AccessError(env, type.getEnclosingType(), type.tsym);
  1625         logResolveError(error, tree.pos(), type.getEnclosingType(), null, null, null);
  1627     //where
  1628     private void logResolveError(ResolveError error,
  1629             DiagnosticPosition pos,
  1630             Type site,
  1631             Name name,
  1632             List<Type> argtypes,
  1633             List<Type> typeargtypes) {
  1634         JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
  1635                 pos, site, name, argtypes, typeargtypes);
  1636         if (d != null)
  1637             log.report(d);
  1640     private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
  1642     public Object methodArguments(List<Type> argtypes) {
  1643         return argtypes.isEmpty() ? noArgs : argtypes;
  1646     /**
  1647      * Root class for resolution errors. Subclass of ResolveError
  1648      * represent a different kinds of resolution error - as such they must
  1649      * specify how they map into concrete compiler diagnostics.
  1650      */
  1651     private abstract class ResolveError extends Symbol {
  1653         /** The name of the kind of error, for debugging only. */
  1654         final String debugName;
  1656         ResolveError(int kind, String debugName) {
  1657             super(kind, 0, null, null, null);
  1658             this.debugName = debugName;
  1661         @Override
  1662         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
  1663             throw new AssertionError();
  1666         @Override
  1667         public String toString() {
  1668             return debugName;
  1671         @Override
  1672         public boolean exists() {
  1673             return false;
  1676         /**
  1677          * Create an external representation for this erroneous symbol to be
  1678          * used during attribution - by default this returns the symbol of a
  1679          * brand new error type which stores the original type found
  1680          * during resolution.
  1682          * @param name     the name used during resolution
  1683          * @param location the location from which the symbol is accessed
  1684          */
  1685         protected Symbol access(Name name, TypeSymbol location) {
  1686             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  1689         /**
  1690          * Create a diagnostic representing this resolution error.
  1692          * @param dkind     The kind of the diagnostic to be created (e.g error).
  1693          * @param pos       The position to be used for error reporting.
  1694          * @param site      The original type from where the selection took place.
  1695          * @param name      The name of the symbol to be resolved.
  1696          * @param argtypes  The invocation's value arguments,
  1697          *                  if we looked for a method.
  1698          * @param typeargtypes  The invocation's type arguments,
  1699          *                      if we looked for a method.
  1700          */
  1701         abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  1702                 DiagnosticPosition pos,
  1703                 Type site,
  1704                 Name name,
  1705                 List<Type> argtypes,
  1706                 List<Type> typeargtypes);
  1708         /**
  1709          * A name designates an operator if it consists
  1710          * of a non-empty sequence of operator symbols +-~!/*%&|^<>=
  1711          */
  1712         boolean isOperator(Name name) {
  1713             int i = 0;
  1714             while (i < name.getByteLength() &&
  1715                    "+-~!*/%&|^<>=".indexOf(name.getByteAt(i)) >= 0) i++;
  1716             return i > 0 && i == name.getByteLength();
  1720     /**
  1721      * This class is the root class of all resolution errors caused by
  1722      * an invalid symbol being found during resolution.
  1723      */
  1724     abstract class InvalidSymbolError extends ResolveError {
  1726         /** The invalid symbol found during resolution */
  1727         Symbol sym;
  1729         InvalidSymbolError(int kind, Symbol sym, String debugName) {
  1730             super(kind, debugName);
  1731             this.sym = sym;
  1734         @Override
  1735         public boolean exists() {
  1736             return true;
  1739         @Override
  1740         public String toString() {
  1741              return super.toString() + " wrongSym=" + sym;
  1744         @Override
  1745         public Symbol access(Name name, TypeSymbol location) {
  1746             if (sym.kind >= AMBIGUOUS)
  1747                 return ((ResolveError)sym).access(name, location);
  1748             else if ((sym.kind & ERRONEOUS) == 0 && (sym.kind & TYP) != 0)
  1749                 return types.createErrorType(name, location, sym.type).tsym;
  1750             else
  1751                 return sym;
  1755     /**
  1756      * InvalidSymbolError error class indicating that a symbol matching a
  1757      * given name does not exists in a given site.
  1758      */
  1759     class SymbolNotFoundError extends ResolveError {
  1761         SymbolNotFoundError(int kind) {
  1762             super(kind, "symbol not found error");
  1765         @Override
  1766         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  1767                 DiagnosticPosition pos,
  1768                 Type site,
  1769                 Name name,
  1770                 List<Type> argtypes,
  1771                 List<Type> typeargtypes) {
  1772             argtypes = argtypes == null ? List.<Type>nil() : argtypes;
  1773             typeargtypes = typeargtypes == null ? List.<Type>nil() : typeargtypes;
  1774             if (name == names.error)
  1775                 return null;
  1777             if (isOperator(name)) {
  1778                 return diags.create(dkind, false, log.currentSource(), pos,
  1779                         "operator.cant.be.applied", name, argtypes);
  1781             boolean hasLocation = false;
  1782             if (!site.tsym.name.isEmpty()) {
  1783                 if (site.tsym.kind == PCK && !site.tsym.exists()) {
  1784                     return diags.create(dkind, false, log.currentSource(), pos,
  1785                         "doesnt.exist", site.tsym);
  1787                 hasLocation = true;
  1789             boolean isConstructor = kind == ABSENT_MTH &&
  1790                     name == names.table.names.init;
  1791             KindName kindname = isConstructor ? KindName.CONSTRUCTOR : absentKind(kind);
  1792             Name idname = isConstructor ? site.tsym.name : name;
  1793             String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation);
  1794             if (hasLocation) {
  1795                 return diags.create(dkind, false, log.currentSource(), pos,
  1796                         errKey, kindname, idname, //symbol kindname, name
  1797                         typeargtypes, argtypes, //type parameters and arguments (if any)
  1798                         typeKindName(site), site); //location kindname, type
  1800             else {
  1801                 return diags.create(dkind, false, log.currentSource(), pos,
  1802                         errKey, kindname, idname, //symbol kindname, name
  1803                         typeargtypes, argtypes); //type parameters and arguments (if any)
  1806         //where
  1807         private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) {
  1808             String key = "cant.resolve";
  1809             String suffix = hasLocation ? ".location" : "";
  1810             switch (kindname) {
  1811                 case METHOD:
  1812                 case CONSTRUCTOR: {
  1813                     suffix += ".args";
  1814                     suffix += hasTypeArgs ? ".params" : "";
  1817             return key + suffix;
  1821     /**
  1822      * InvalidSymbolError error class indicating that a given symbol
  1823      * (either a method, a constructor or an operand) is not applicable
  1824      * given an actual arguments/type argument list.
  1825      */
  1826     class InapplicableSymbolError extends InvalidSymbolError {
  1828         /** An auxiliary explanation set in case of instantiation errors. */
  1829         JCDiagnostic explanation;
  1831         InapplicableSymbolError(Symbol sym) {
  1832             super(WRONG_MTH, sym, "inapplicable symbol error");
  1835         /** Update sym and explanation and return this.
  1836          */
  1837         InapplicableSymbolError setWrongSym(Symbol sym, JCDiagnostic explanation) {
  1838             this.sym = sym;
  1839             this.explanation = explanation;
  1840             return this;
  1843         /** Update sym and return this.
  1844          */
  1845         InapplicableSymbolError setWrongSym(Symbol sym) {
  1846             this.sym = sym;
  1847             this.explanation = null;
  1848             return this;
  1851         @Override
  1852         public String toString() {
  1853             return super.toString() + " explanation=" + explanation;
  1856         @Override
  1857         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  1858                 DiagnosticPosition pos,
  1859                 Type site,
  1860                 Name name,
  1861                 List<Type> argtypes,
  1862                 List<Type> typeargtypes) {
  1863             if (name == names.error)
  1864                 return null;
  1866             if (isOperator(name)) {
  1867                 return diags.create(dkind, false, log.currentSource(),
  1868                         pos, "operator.cant.be.applied", name, argtypes);
  1870             else {
  1871                 Symbol ws = sym.asMemberOf(site, types);
  1872                 return diags.create(dkind, false, log.currentSource(), pos,
  1873                           "cant.apply.symbol" + (explanation != null ? ".1" : ""),
  1874                           kindName(ws),
  1875                           ws.name == names.init ? ws.owner.name : ws.name,
  1876                           methodArguments(ws.type.getParameterTypes()),
  1877                           methodArguments(argtypes),
  1878                           kindName(ws.owner),
  1879                           ws.owner.type,
  1880                           explanation);
  1884         @Override
  1885         public Symbol access(Name name, TypeSymbol location) {
  1886             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  1890     /**
  1891      * ResolveError error class indicating that a set of symbols
  1892      * (either methods, constructors or operands) is not applicable
  1893      * given an actual arguments/type argument list.
  1894      */
  1895     class InapplicableSymbolsError extends ResolveError {
  1896         InapplicableSymbolsError(Symbol sym) {
  1897             super(WRONG_MTHS, "inapplicable symbols");
  1900         @Override
  1901         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  1902                 DiagnosticPosition pos,
  1903                 Type site,
  1904                 Name name,
  1905                 List<Type> argtypes,
  1906                 List<Type> typeargtypes) {
  1907             return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
  1908                     site, name, argtypes, typeargtypes);
  1912     /**
  1913      * An InvalidSymbolError error class indicating that a symbol is not
  1914      * accessible from a given site
  1915      */
  1916     class AccessError extends InvalidSymbolError {
  1918         private Env<AttrContext> env;
  1919         private Type site;
  1921         AccessError(Symbol sym) {
  1922             this(null, null, sym);
  1925         AccessError(Env<AttrContext> env, Type site, Symbol sym) {
  1926             super(HIDDEN, sym, "access error");
  1927             this.env = env;
  1928             this.site = site;
  1929             if (debugResolve)
  1930                 log.error("proc.messager", sym + " @ " + site + " is inaccessible.");
  1933         @Override
  1934         public boolean exists() {
  1935             return false;
  1938         @Override
  1939         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  1940                 DiagnosticPosition pos,
  1941                 Type site,
  1942                 Name name,
  1943                 List<Type> argtypes,
  1944                 List<Type> typeargtypes) {
  1945             if (sym.owner.type.tag == ERROR)
  1946                 return null;
  1948             if (sym.name == names.init && sym.owner != site.tsym) {
  1949                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
  1950                         pos, site, name, argtypes, typeargtypes);
  1952             else if ((sym.flags() & PUBLIC) != 0
  1953                 || (env != null && this.site != null
  1954                     && !isAccessible(env, this.site))) {
  1955                 return diags.create(dkind, false, log.currentSource(),
  1956                         pos, "not.def.access.class.intf.cant.access",
  1957                     sym, sym.location());
  1959             else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) {
  1960                 return diags.create(dkind, false, log.currentSource(),
  1961                         pos, "report.access", sym,
  1962                         asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
  1963                         sym.location());
  1965             else {
  1966                 return diags.create(dkind, false, log.currentSource(),
  1967                         pos, "not.def.public.cant.access", sym, sym.location());
  1972     /**
  1973      * InvalidSymbolError error class indicating that an instance member
  1974      * has erroneously been accessed from a static context.
  1975      */
  1976     class StaticError extends InvalidSymbolError {
  1978         StaticError(Symbol sym) {
  1979             super(STATICERR, sym, "static error");
  1982         @Override
  1983         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  1984                 DiagnosticPosition pos,
  1985                 Type site,
  1986                 Name name,
  1987                 List<Type> argtypes,
  1988                 List<Type> typeargtypes) {
  1989             Symbol errSym = ((sym.kind == TYP && sym.type.tag == CLASS)
  1990                 ? types.erasure(sym.type).tsym
  1991                 : sym);
  1992             return diags.create(dkind, false, log.currentSource(), pos,
  1993                     "non-static.cant.be.ref", kindName(sym), errSym);
  1997     /**
  1998      * InvalidSymbolError error class indicating that a pair of symbols
  1999      * (either methods, constructors or operands) are ambiguous
  2000      * given an actual arguments/type argument list.
  2001      */
  2002     class AmbiguityError extends InvalidSymbolError {
  2004         /** The other maximally specific symbol */
  2005         Symbol sym2;
  2007         AmbiguityError(Symbol sym1, Symbol sym2) {
  2008             super(AMBIGUOUS, sym1, "ambiguity error");
  2009             this.sym2 = sym2;
  2012         @Override
  2013         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2014                 DiagnosticPosition pos,
  2015                 Type site,
  2016                 Name name,
  2017                 List<Type> argtypes,
  2018                 List<Type> typeargtypes) {
  2019             AmbiguityError pair = this;
  2020             while (true) {
  2021                 if (pair.sym.kind == AMBIGUOUS)
  2022                     pair = (AmbiguityError)pair.sym;
  2023                 else if (pair.sym2.kind == AMBIGUOUS)
  2024                     pair = (AmbiguityError)pair.sym2;
  2025                 else break;
  2027             Name sname = pair.sym.name;
  2028             if (sname == names.init) sname = pair.sym.owner.name;
  2029             return diags.create(dkind, false, log.currentSource(),
  2030                       pos, "ref.ambiguous", sname,
  2031                       kindName(pair.sym),
  2032                       pair.sym,
  2033                       pair.sym.location(site, types),
  2034                       kindName(pair.sym2),
  2035                       pair.sym2,
  2036                       pair.sym2.location(site, types));
  2040     enum MethodResolutionPhase {
  2041         BASIC(false, false),
  2042         BOX(true, false),
  2043         VARARITY(true, true);
  2045         boolean isBoxingRequired;
  2046         boolean isVarargsRequired;
  2048         MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) {
  2049            this.isBoxingRequired = isBoxingRequired;
  2050            this.isVarargsRequired = isVarargsRequired;
  2053         public boolean isBoxingRequired() {
  2054             return isBoxingRequired;
  2057         public boolean isVarargsRequired() {
  2058             return isVarargsRequired;
  2061         public boolean isApplicable(boolean boxingEnabled, boolean varargsEnabled) {
  2062             return (varargsEnabled || !isVarargsRequired) &&
  2063                    (boxingEnabled || !isBoxingRequired);
  2067     private Map<MethodResolutionPhase, Symbol> methodResolutionCache =
  2068         new HashMap<MethodResolutionPhase, Symbol>(MethodResolutionPhase.values().length);
  2070     final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
  2072     private MethodResolutionPhase firstErroneousResolutionPhase() {
  2073         MethodResolutionPhase bestSoFar = BASIC;
  2074         Symbol sym = methodNotFound;
  2075         List<MethodResolutionPhase> steps = methodResolutionSteps;
  2076         while (steps.nonEmpty() &&
  2077                steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  2078                sym.kind >= WRONG_MTHS) {
  2079             sym = methodResolutionCache.get(steps.head);
  2080             bestSoFar = steps.head;
  2081             steps = steps.tail;
  2083         return bestSoFar;

mercurial