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

Thu, 29 Jul 2010 15:57:43 +0100

author
mcimadamore
date
Thu, 29 Jul 2010 15:57:43 +0100
changeset 617
62f3f07002ea
parent 612
d1bd93028447
child 631
a2d8c7071f24
permissions
-rw-r--r--

6970833: Try-with-resource implementation throws an NPE during Flow analysis
Summary: Updated logic not to rely upon Symbol.implementation (which check in superinterfaces)
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.comp;
    28 import com.sun.tools.javac.util.*;
    29 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    30 import com.sun.tools.javac.code.*;
    31 import com.sun.tools.javac.jvm.*;
    32 import com.sun.tools.javac.tree.*;
    33 import com.sun.tools.javac.api.Formattable.LocalizedString;
    34 import static com.sun.tools.javac.comp.Resolve.MethodResolutionPhase.*;
    36 import com.sun.tools.javac.code.Type.*;
    37 import com.sun.tools.javac.code.Symbol.*;
    38 import com.sun.tools.javac.tree.JCTree.*;
    40 import static com.sun.tools.javac.code.Flags.*;
    41 import static com.sun.tools.javac.code.Kinds.*;
    42 import static com.sun.tools.javac.code.TypeTags.*;
    43 import 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 supported API.
    51  *  If 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 allowPolymorphicSignature;
    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         allowPolymorphicSignature = source.allowPolymorphicSignature() || 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         assert ((m.flags() & (POLYMORPHIC_SIGNATURE|HYPOTHETICAL)) != POLYMORPHIC_SIGNATURE);
   305         if (useVarargs && (m.flags() & VARARGS) == 0) return null;
   306         Type mt = types.memberType(site, m);
   308         // tvars is the list of formal type variables for which type arguments
   309         // need to inferred.
   310         List<Type> tvars = env.info.tvars;
   311         if (typeargtypes == null) typeargtypes = List.nil();
   312         if (mt.tag != FORALL && typeargtypes.nonEmpty()) {
   313             // This is not a polymorphic method, but typeargs are supplied
   314             // which is fine, see JLS3 15.12.2.1
   315         } else if (mt.tag == FORALL && typeargtypes.nonEmpty()) {
   316             ForAll pmt = (ForAll) mt;
   317             if (typeargtypes.length() != pmt.tvars.length())
   318                 return null;
   319             // Check type arguments are within bounds
   320             List<Type> formals = pmt.tvars;
   321             List<Type> actuals = typeargtypes;
   322             while (formals.nonEmpty() && actuals.nonEmpty()) {
   323                 List<Type> bounds = types.subst(types.getBounds((TypeVar)formals.head),
   324                                                 pmt.tvars, typeargtypes);
   325                 for (; bounds.nonEmpty(); bounds = bounds.tail)
   326                     if (!types.isSubtypeUnchecked(actuals.head, bounds.head, warn))
   327                         return null;
   328                 formals = formals.tail;
   329                 actuals = actuals.tail;
   330             }
   331             mt = types.subst(pmt.qtype, pmt.tvars, typeargtypes);
   332         } else if (mt.tag == FORALL) {
   333             ForAll pmt = (ForAll) mt;
   334             List<Type> tvars1 = types.newInstances(pmt.tvars);
   335             tvars = tvars.appendList(tvars1);
   336             mt = types.subst(pmt.qtype, pmt.tvars, tvars1);
   337         }
   339         // find out whether we need to go the slow route via infer
   340         boolean instNeeded = tvars.tail != null/*inlined: tvars.nonEmpty()*/;
   341         for (List<Type> l = argtypes;
   342              l.tail != null/*inlined: l.nonEmpty()*/ && !instNeeded;
   343              l = l.tail) {
   344             if (l.head.tag == FORALL) instNeeded = true;
   345         }
   347         if (instNeeded)
   348             return
   349             infer.instantiateMethod(env,
   350                                     tvars,
   351                                     (MethodType)mt,
   352                                     m,
   353                                     argtypes,
   354                                     allowBoxing,
   355                                     useVarargs,
   356                                     warn);
   357         return
   358             argumentsAcceptable(argtypes, mt.getParameterTypes(),
   359                                 allowBoxing, useVarargs, warn)
   360             ? mt
   361             : null;
   362     }
   364     /** Same but returns null instead throwing a NoInstanceException
   365      */
   366     Type instantiate(Env<AttrContext> env,
   367                      Type site,
   368                      Symbol m,
   369                      List<Type> argtypes,
   370                      List<Type> typeargtypes,
   371                      boolean allowBoxing,
   372                      boolean useVarargs,
   373                      Warner warn) {
   374         try {
   375             return rawInstantiate(env, site, m, argtypes, typeargtypes,
   376                                   allowBoxing, useVarargs, warn);
   377         } catch (Infer.InferenceException ex) {
   378             return null;
   379         }
   380     }
   382     /** Check if a parameter list accepts a list of args.
   383      */
   384     boolean argumentsAcceptable(List<Type> argtypes,
   385                                 List<Type> formals,
   386                                 boolean allowBoxing,
   387                                 boolean useVarargs,
   388                                 Warner warn) {
   389         Type varargsFormal = useVarargs ? formals.last() : null;
   390         while (argtypes.nonEmpty() && formals.head != varargsFormal) {
   391             boolean works = allowBoxing
   392                 ? types.isConvertible(argtypes.head, formals.head, warn)
   393                 : types.isSubtypeUnchecked(argtypes.head, formals.head, warn);
   394             if (!works) return false;
   395             argtypes = argtypes.tail;
   396             formals = formals.tail;
   397         }
   398         if (formals.head != varargsFormal) return false; // not enough args
   399         if (!useVarargs)
   400             return argtypes.isEmpty();
   401         Type elt = types.elemtype(varargsFormal);
   402         while (argtypes.nonEmpty()) {
   403             if (!types.isConvertible(argtypes.head, elt, warn))
   404                 return false;
   405             argtypes = argtypes.tail;
   406         }
   407         return true;
   408     }
   410 /* ***************************************************************************
   411  *  Symbol lookup
   412  *  the following naming conventions for arguments are used
   413  *
   414  *       env      is the environment where the symbol was mentioned
   415  *       site     is the type of which the symbol is a member
   416  *       name     is the symbol's name
   417  *                if no arguments are given
   418  *       argtypes are the value arguments, if we search for a method
   419  *
   420  *  If no symbol was found, a ResolveError detailing the problem is returned.
   421  ****************************************************************************/
   423     /** Find field. Synthetic fields are always skipped.
   424      *  @param env     The current environment.
   425      *  @param site    The original type from where the selection takes place.
   426      *  @param name    The name of the field.
   427      *  @param c       The class to search for the field. This is always
   428      *                 a superclass or implemented interface of site's class.
   429      */
   430     Symbol findField(Env<AttrContext> env,
   431                      Type site,
   432                      Name name,
   433                      TypeSymbol c) {
   434         while (c.type.tag == TYPEVAR)
   435             c = c.type.getUpperBound().tsym;
   436         Symbol bestSoFar = varNotFound;
   437         Symbol sym;
   438         Scope.Entry e = c.members().lookup(name);
   439         while (e.scope != null) {
   440             if (e.sym.kind == VAR && (e.sym.flags_field & SYNTHETIC) == 0) {
   441                 return isAccessible(env, site, e.sym)
   442                     ? e.sym : new AccessError(env, site, e.sym);
   443             }
   444             e = e.next();
   445         }
   446         Type st = types.supertype(c.type);
   447         if (st != null && (st.tag == CLASS || st.tag == TYPEVAR)) {
   448             sym = findField(env, site, name, st.tsym);
   449             if (sym.kind < bestSoFar.kind) bestSoFar = sym;
   450         }
   451         for (List<Type> l = types.interfaces(c.type);
   452              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
   453              l = l.tail) {
   454             sym = findField(env, site, name, l.head.tsym);
   455             if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
   456                 sym.owner != bestSoFar.owner)
   457                 bestSoFar = new AmbiguityError(bestSoFar, sym);
   458             else if (sym.kind < bestSoFar.kind)
   459                 bestSoFar = sym;
   460         }
   461         return bestSoFar;
   462     }
   464     /** Resolve a field identifier, throw a fatal error if not found.
   465      *  @param pos       The position to use for error reporting.
   466      *  @param env       The environment current at the method invocation.
   467      *  @param site      The type of the qualifying expression, in which
   468      *                   identifier is searched.
   469      *  @param name      The identifier's name.
   470      */
   471     public VarSymbol resolveInternalField(DiagnosticPosition pos, Env<AttrContext> env,
   472                                           Type site, Name name) {
   473         Symbol sym = findField(env, site, name, site.tsym);
   474         if (sym.kind == VAR) return (VarSymbol)sym;
   475         else throw new FatalError(
   476                  diags.fragment("fatal.err.cant.locate.field",
   477                                 name));
   478     }
   480     /** Find unqualified variable or field with given name.
   481      *  Synthetic fields always skipped.
   482      *  @param env     The current environment.
   483      *  @param name    The name of the variable or field.
   484      */
   485     Symbol findVar(Env<AttrContext> env, Name name) {
   486         Symbol bestSoFar = varNotFound;
   487         Symbol sym;
   488         Env<AttrContext> env1 = env;
   489         boolean staticOnly = false;
   490         while (env1.outer != null) {
   491             if (isStatic(env1)) staticOnly = true;
   492             Scope.Entry e = env1.info.scope.lookup(name);
   493             while (e.scope != null &&
   494                    (e.sym.kind != VAR ||
   495                     (e.sym.flags_field & SYNTHETIC) != 0))
   496                 e = e.next();
   497             sym = (e.scope != null)
   498                 ? e.sym
   499                 : findField(
   500                     env1, env1.enclClass.sym.type, name, env1.enclClass.sym);
   501             if (sym.exists()) {
   502                 if (staticOnly &&
   503                     sym.kind == VAR &&
   504                     sym.owner.kind == TYP &&
   505                     (sym.flags() & STATIC) == 0)
   506                     return new StaticError(sym);
   507                 else
   508                     return sym;
   509             } else if (sym.kind < bestSoFar.kind) {
   510                 bestSoFar = sym;
   511             }
   513             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
   514             env1 = env1.outer;
   515         }
   517         sym = findField(env, syms.predefClass.type, name, syms.predefClass);
   518         if (sym.exists())
   519             return sym;
   520         if (bestSoFar.exists())
   521             return bestSoFar;
   523         Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
   524         for (; e.scope != null; e = e.next()) {
   525             sym = e.sym;
   526             Type origin = e.getOrigin().owner.type;
   527             if (sym.kind == VAR) {
   528                 if (e.sym.owner.type != origin)
   529                     sym = sym.clone(e.getOrigin().owner);
   530                 return isAccessible(env, origin, sym)
   531                     ? sym : new AccessError(env, origin, sym);
   532             }
   533         }
   535         Symbol origin = null;
   536         e = env.toplevel.starImportScope.lookup(name);
   537         for (; e.scope != null; e = e.next()) {
   538             sym = e.sym;
   539             if (sym.kind != VAR)
   540                 continue;
   541             // invariant: sym.kind == VAR
   542             if (bestSoFar.kind < AMBIGUOUS && sym.owner != bestSoFar.owner)
   543                 return new AmbiguityError(bestSoFar, sym);
   544             else if (bestSoFar.kind >= VAR) {
   545                 origin = e.getOrigin().owner;
   546                 bestSoFar = isAccessible(env, origin.type, sym)
   547                     ? sym : new AccessError(env, origin.type, sym);
   548             }
   549         }
   550         if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type)
   551             return bestSoFar.clone(origin);
   552         else
   553             return bestSoFar;
   554     }
   556     Warner noteWarner = new Warner();
   558     /** Select the best method for a call site among two choices.
   559      *  @param env              The current environment.
   560      *  @param site             The original type from where the
   561      *                          selection takes place.
   562      *  @param argtypes         The invocation's value arguments,
   563      *  @param typeargtypes     The invocation's type arguments,
   564      *  @param sym              Proposed new best match.
   565      *  @param bestSoFar        Previously found best match.
   566      *  @param allowBoxing Allow boxing conversions of arguments.
   567      *  @param useVarargs Box trailing arguments into an array for varargs.
   568      */
   569     Symbol selectBest(Env<AttrContext> env,
   570                       Type site,
   571                       List<Type> argtypes,
   572                       List<Type> typeargtypes,
   573                       Symbol sym,
   574                       Symbol bestSoFar,
   575                       boolean allowBoxing,
   576                       boolean useVarargs,
   577                       boolean operator) {
   578         if (sym.kind == ERR) return bestSoFar;
   579         if (!sym.isInheritedIn(site.tsym, types)) return bestSoFar;
   580         assert sym.kind < AMBIGUOUS;
   581         if ((sym.flags() & POLYMORPHIC_SIGNATURE) != 0 && allowPolymorphicSignature) {
   582             assert(site.tag == CLASS);
   583             // Never match a MethodHandle.invoke directly.
   584             if (useVarargs | allowBoxing | operator)
   585                 return bestSoFar;
   586             // Supply an exactly-typed implicit method instead.
   587             sym = findPolymorphicSignatureInstance(env, sym.owner.type, sym.name, (MethodSymbol) sym, argtypes, typeargtypes);
   588         }
   589         try {
   590             if (rawInstantiate(env, site, sym, argtypes, typeargtypes,
   591                                allowBoxing, useVarargs, Warner.noWarnings) == null) {
   592                 // inapplicable
   593                 switch (bestSoFar.kind) {
   594                 case ABSENT_MTH: return wrongMethod.setWrongSym(sym);
   595                 case WRONG_MTH: return wrongMethods;
   596                 default: return bestSoFar;
   597                 }
   598             }
   599         } catch (Infer.InferenceException ex) {
   600             switch (bestSoFar.kind) {
   601             case ABSENT_MTH:
   602                 return wrongMethod.setWrongSym(sym, ex.getDiagnostic());
   603             case WRONG_MTH:
   604                 return wrongMethods;
   605             default:
   606                 return bestSoFar;
   607             }
   608         }
   609         if (!isAccessible(env, site, sym)) {
   610             return (bestSoFar.kind == ABSENT_MTH)
   611                 ? new AccessError(env, site, sym)
   612                 : bestSoFar;
   613         }
   614         return (bestSoFar.kind > AMBIGUOUS)
   615             ? sym
   616             : mostSpecific(sym, bestSoFar, env, site,
   617                            allowBoxing && operator, useVarargs);
   618     }
   620     /* Return the most specific of the two methods for a call,
   621      *  given that both are accessible and applicable.
   622      *  @param m1               A new candidate for most specific.
   623      *  @param m2               The previous most specific candidate.
   624      *  @param env              The current environment.
   625      *  @param site             The original type from where the selection
   626      *                          takes place.
   627      *  @param allowBoxing Allow boxing conversions of arguments.
   628      *  @param useVarargs Box trailing arguments into an array for varargs.
   629      */
   630     Symbol mostSpecific(Symbol m1,
   631                         Symbol m2,
   632                         Env<AttrContext> env,
   633                         final Type site,
   634                         boolean allowBoxing,
   635                         boolean useVarargs) {
   636         switch (m2.kind) {
   637         case MTH:
   638             if (m1 == m2) return m1;
   639             Type mt1 = types.memberType(site, m1);
   640             noteWarner.unchecked = false;
   641             boolean m1SignatureMoreSpecific =
   642                 (instantiate(env, site, m2, types.lowerBoundArgtypes(mt1), null,
   643                              allowBoxing, false, noteWarner) != null ||
   644                  useVarargs && instantiate(env, site, m2, types.lowerBoundArgtypes(mt1), null,
   645                                            allowBoxing, true, noteWarner) != null) &&
   646                 !noteWarner.unchecked;
   647             Type mt2 = types.memberType(site, m2);
   648             noteWarner.unchecked = false;
   649             boolean m2SignatureMoreSpecific =
   650                 (instantiate(env, site, m1, types.lowerBoundArgtypes(mt2), null,
   651                              allowBoxing, false, noteWarner) != null ||
   652                  useVarargs && instantiate(env, site, m1, types.lowerBoundArgtypes(mt2), null,
   653                                            allowBoxing, true, noteWarner) != null) &&
   654                 !noteWarner.unchecked;
   655             if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) {
   656                 if (!types.overrideEquivalent(mt1, mt2))
   657                     return new AmbiguityError(m1, m2);
   658                 // same signature; select (a) the non-bridge method, or
   659                 // (b) the one that overrides the other, or (c) the concrete
   660                 // one, or (d) merge both abstract signatures
   661                 if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE)) {
   662                     return ((m1.flags() & BRIDGE) != 0) ? m2 : m1;
   663                 }
   664                 // if one overrides or hides the other, use it
   665                 TypeSymbol m1Owner = (TypeSymbol)m1.owner;
   666                 TypeSymbol m2Owner = (TypeSymbol)m2.owner;
   667                 if (types.asSuper(m1Owner.type, m2Owner) != null &&
   668                     ((m1.owner.flags_field & INTERFACE) == 0 ||
   669                      (m2.owner.flags_field & INTERFACE) != 0) &&
   670                     m1.overrides(m2, m1Owner, types, false))
   671                     return m1;
   672                 if (types.asSuper(m2Owner.type, m1Owner) != null &&
   673                     ((m2.owner.flags_field & INTERFACE) == 0 ||
   674                      (m1.owner.flags_field & INTERFACE) != 0) &&
   675                     m2.overrides(m1, m2Owner, types, false))
   676                     return m2;
   677                 boolean m1Abstract = (m1.flags() & ABSTRACT) != 0;
   678                 boolean m2Abstract = (m2.flags() & ABSTRACT) != 0;
   679                 if (m1Abstract && !m2Abstract) return m2;
   680                 if (m2Abstract && !m1Abstract) return m1;
   681                 // both abstract or both concrete
   682                 if (!m1Abstract && !m2Abstract)
   683                     return new AmbiguityError(m1, m2);
   684                 // check that both signatures have the same erasure
   685                 if (!types.isSameTypes(m1.erasure(types).getParameterTypes(),
   686                                        m2.erasure(types).getParameterTypes()))
   687                     return new AmbiguityError(m1, m2);
   688                 // both abstract, neither overridden; merge throws clause and result type
   689                 Symbol mostSpecific;
   690                 Type result2 = mt2.getReturnType();
   691                 if (mt2.tag == FORALL)
   692                     result2 = types.subst(result2, ((ForAll)mt2).tvars, ((ForAll)mt1).tvars);
   693                 if (types.isSubtype(mt1.getReturnType(), result2)) {
   694                     mostSpecific = m1;
   695                 } else if (types.isSubtype(result2, mt1.getReturnType())) {
   696                     mostSpecific = m2;
   697                 } else {
   698                     // Theoretically, this can't happen, but it is possible
   699                     // due to error recovery or mixing incompatible class files
   700                     return new AmbiguityError(m1, m2);
   701                 }
   702                 MethodSymbol result = new MethodSymbol(
   703                         mostSpecific.flags(),
   704                         mostSpecific.name,
   705                         null,
   706                         mostSpecific.owner) {
   707                     @Override
   708                     public MethodSymbol implementation(TypeSymbol origin, Types types, boolean checkResult) {
   709                         if (origin == site.tsym)
   710                             return this;
   711                         else
   712                             return super.implementation(origin, types, checkResult);
   713                     }
   714                 };
   715                 result.type = (Type)mostSpecific.type.clone();
   716                 result.type.setThrown(chk.intersect(mt1.getThrownTypes(),
   717                                                     mt2.getThrownTypes()));
   718                 return result;
   719             }
   720             if (m1SignatureMoreSpecific) return m1;
   721             if (m2SignatureMoreSpecific) return m2;
   722             return new AmbiguityError(m1, m2);
   723         case AMBIGUOUS:
   724             AmbiguityError e = (AmbiguityError)m2;
   725             Symbol err1 = mostSpecific(m1, e.sym, env, site, allowBoxing, useVarargs);
   726             Symbol err2 = mostSpecific(m1, e.sym2, env, site, allowBoxing, useVarargs);
   727             if (err1 == err2) return err1;
   728             if (err1 == e.sym && err2 == e.sym2) return m2;
   729             if (err1 instanceof AmbiguityError &&
   730                 err2 instanceof AmbiguityError &&
   731                 ((AmbiguityError)err1).sym == ((AmbiguityError)err2).sym)
   732                 return new AmbiguityError(m1, m2);
   733             else
   734                 return new AmbiguityError(err1, err2);
   735         default:
   736             throw new AssertionError();
   737         }
   738     }
   740     /** Find best qualified method matching given name, type and value
   741      *  arguments.
   742      *  @param env       The current environment.
   743      *  @param site      The original type from where the selection
   744      *                   takes place.
   745      *  @param name      The method's name.
   746      *  @param argtypes  The method's value arguments.
   747      *  @param typeargtypes The method's type arguments
   748      *  @param allowBoxing Allow boxing conversions of arguments.
   749      *  @param useVarargs Box trailing arguments into an array for varargs.
   750      */
   751     Symbol findMethod(Env<AttrContext> env,
   752                       Type site,
   753                       Name name,
   754                       List<Type> argtypes,
   755                       List<Type> typeargtypes,
   756                       boolean allowBoxing,
   757                       boolean useVarargs,
   758                       boolean operator) {
   759         Symbol bestSoFar = methodNotFound;
   760         if ((site.tsym.flags() & POLYMORPHIC_SIGNATURE) != 0 &&
   761             allowPolymorphicSignature &&
   762             site.tag == CLASS &&
   763             !(useVarargs | allowBoxing | operator)) {
   764             // supply an exactly-typed implicit method in java.dyn.InvokeDynamic
   765             bestSoFar = findPolymorphicSignatureInstance(env, site, name, null, argtypes, typeargtypes);
   766         }
   767         return findMethod(env,
   768                           site,
   769                           name,
   770                           argtypes,
   771                           typeargtypes,
   772                           site.tsym.type,
   773                           true,
   774                           bestSoFar,
   775                           allowBoxing,
   776                           useVarargs,
   777                           operator);
   778     }
   779     // where
   780     private Symbol findMethod(Env<AttrContext> env,
   781                               Type site,
   782                               Name name,
   783                               List<Type> argtypes,
   784                               List<Type> typeargtypes,
   785                               Type intype,
   786                               boolean abstractok,
   787                               Symbol bestSoFar,
   788                               boolean allowBoxing,
   789                               boolean useVarargs,
   790                               boolean operator) {
   791         for (Type ct = intype; ct.tag == CLASS || ct.tag == TYPEVAR; ct = types.supertype(ct)) {
   792             while (ct.tag == TYPEVAR)
   793                 ct = ct.getUpperBound();
   794             ClassSymbol c = (ClassSymbol)ct.tsym;
   795             if ((c.flags() & (ABSTRACT | INTERFACE | ENUM)) == 0)
   796                 abstractok = false;
   797             for (Scope.Entry e = c.members().lookup(name);
   798                  e.scope != null;
   799                  e = e.next()) {
   800                 //- System.out.println(" e " + e.sym);
   801                 if (e.sym.kind == MTH &&
   802                     (e.sym.flags_field & SYNTHETIC) == 0) {
   803                     bestSoFar = selectBest(env, site, argtypes, typeargtypes,
   804                                            e.sym, bestSoFar,
   805                                            allowBoxing,
   806                                            useVarargs,
   807                                            operator);
   808                 }
   809             }
   810             if (name == names.init)
   811                 break;
   812             //- System.out.println(" - " + bestSoFar);
   813             if (abstractok) {
   814                 Symbol concrete = methodNotFound;
   815                 if ((bestSoFar.flags() & ABSTRACT) == 0)
   816                     concrete = bestSoFar;
   817                 for (List<Type> l = types.interfaces(c.type);
   818                      l.nonEmpty();
   819                      l = l.tail) {
   820                     bestSoFar = findMethod(env, site, name, argtypes,
   821                                            typeargtypes,
   822                                            l.head, abstractok, bestSoFar,
   823                                            allowBoxing, useVarargs, operator);
   824                 }
   825                 if (concrete != bestSoFar &&
   826                     concrete.kind < ERR  && bestSoFar.kind < ERR &&
   827                     types.isSubSignature(concrete.type, bestSoFar.type))
   828                     bestSoFar = concrete;
   829             }
   830         }
   831         return bestSoFar;
   832     }
   834     /** Find unqualified method matching given name, type and value arguments.
   835      *  @param env       The current environment.
   836      *  @param name      The method's name.
   837      *  @param argtypes  The method's value arguments.
   838      *  @param typeargtypes  The method's type arguments.
   839      *  @param allowBoxing Allow boxing conversions of arguments.
   840      *  @param useVarargs Box trailing arguments into an array for varargs.
   841      */
   842     Symbol findFun(Env<AttrContext> env, Name name,
   843                    List<Type> argtypes, List<Type> typeargtypes,
   844                    boolean allowBoxing, boolean useVarargs) {
   845         Symbol bestSoFar = methodNotFound;
   846         Symbol sym;
   847         Env<AttrContext> env1 = env;
   848         boolean staticOnly = false;
   849         while (env1.outer != null) {
   850             if (isStatic(env1)) staticOnly = true;
   851             sym = findMethod(
   852                 env1, env1.enclClass.sym.type, name, argtypes, typeargtypes,
   853                 allowBoxing, useVarargs, false);
   854             if (sym.exists()) {
   855                 if (staticOnly &&
   856                     sym.kind == MTH &&
   857                     sym.owner.kind == TYP &&
   858                     (sym.flags() & STATIC) == 0) return new StaticError(sym);
   859                 else return sym;
   860             } else if (sym.kind < bestSoFar.kind) {
   861                 bestSoFar = sym;
   862             }
   863             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
   864             env1 = env1.outer;
   865         }
   867         sym = findMethod(env, syms.predefClass.type, name, argtypes,
   868                          typeargtypes, allowBoxing, useVarargs, false);
   869         if (sym.exists())
   870             return sym;
   872         Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
   873         for (; e.scope != null; e = e.next()) {
   874             sym = e.sym;
   875             Type origin = e.getOrigin().owner.type;
   876             if (sym.kind == MTH) {
   877                 if (e.sym.owner.type != origin)
   878                     sym = sym.clone(e.getOrigin().owner);
   879                 if (!isAccessible(env, origin, sym))
   880                     sym = new AccessError(env, origin, sym);
   881                 bestSoFar = selectBest(env, origin,
   882                                        argtypes, typeargtypes,
   883                                        sym, bestSoFar,
   884                                        allowBoxing, useVarargs, false);
   885             }
   886         }
   887         if (bestSoFar.exists())
   888             return bestSoFar;
   890         e = env.toplevel.starImportScope.lookup(name);
   891         for (; e.scope != null; e = e.next()) {
   892             sym = e.sym;
   893             Type origin = e.getOrigin().owner.type;
   894             if (sym.kind == MTH) {
   895                 if (e.sym.owner.type != origin)
   896                     sym = sym.clone(e.getOrigin().owner);
   897                 if (!isAccessible(env, origin, sym))
   898                     sym = new AccessError(env, origin, sym);
   899                 bestSoFar = selectBest(env, origin,
   900                                        argtypes, typeargtypes,
   901                                        sym, bestSoFar,
   902                                        allowBoxing, useVarargs, false);
   903             }
   904         }
   905         return bestSoFar;
   906     }
   908     /** Find or create an implicit method of exactly the given type (after erasure).
   909      *  Searches in a side table, not the main scope of the site.
   910      *  This emulates the lookup process required by JSR 292 in JVM.
   911      *  @param env       The current environment.
   912      *  @param site      The original type from where the selection
   913      *                   takes place.
   914      *  @param name      The method's name.
   915      *  @param argtypes  The method's value arguments.
   916      *  @param typeargtypes The method's type arguments
   917      */
   918     Symbol findPolymorphicSignatureInstance(Env<AttrContext> env,
   919                                             Type site,
   920                                             Name name,
   921                                             MethodSymbol spMethod,  // sig. poly. method or null if none
   922                                             List<Type> argtypes,
   923                                             List<Type> typeargtypes) {
   924         assert allowPolymorphicSignature;
   925         //assert site == syms.invokeDynamicType || site == syms.methodHandleType : site;
   926         ClassSymbol c = (ClassSymbol) site.tsym;
   927         Scope implicit = c.members().next;
   928         if (implicit == null) {
   929             c.members().next = implicit = new Scope(c);
   930         }
   931         Type restype;
   932         if (typeargtypes.isEmpty()) {
   933             restype = syms.objectType;
   934         } else {
   935             restype = typeargtypes.head;
   936             if (!typeargtypes.tail.isEmpty())
   937                 return methodNotFound;
   938         }
   939         List<Type> paramtypes = Type.map(argtypes, implicitArgType);
   940         long flags;
   941         List<Type> exType;
   942         if (spMethod != null) {
   943             exType = spMethod.getThrownTypes();
   944             flags = spMethod.flags() & AccessFlags;
   945         } else {
   946             // make it throw all exceptions
   947             //assert(site == syms.invokeDynamicType);
   948             exType = List.of(syms.throwableType);
   949             flags = PUBLIC | STATIC;
   950         }
   951         MethodType mtype = new MethodType(paramtypes,
   952                                           restype,
   953                                           exType,
   954                                           syms.methodClass);
   955         flags |= ABSTRACT | HYPOTHETICAL | POLYMORPHIC_SIGNATURE;
   956         Symbol m = null;
   957         for (Scope.Entry e = implicit.lookup(name);
   958              e.scope != null;
   959              e = e.next()) {
   960             Symbol sym = e.sym;
   961             assert sym.kind == MTH;
   962             if (types.isSameType(mtype, sym.type)
   963                 && (sym.flags() & STATIC) == (flags & STATIC)) {
   964                 m = sym;
   965                 break;
   966             }
   967         }
   968         if (m == null) {
   969             // create the desired method
   970             m = new MethodSymbol(flags, name, mtype, c);
   971             implicit.enter(m);
   972         }
   973         assert argumentsAcceptable(argtypes, types.memberType(site, m).getParameterTypes(),
   974                                    false, false, Warner.noWarnings);
   975         assert null != instantiate(env, site, m, argtypes, typeargtypes, false, false, Warner.noWarnings);
   976         return m;
   977     }
   978     //where
   979         Mapping implicitArgType = new Mapping ("implicitArgType") {
   980                 public Type apply(Type t) { return implicitArgType(t); }
   981             };
   982         Type implicitArgType(Type argType) {
   983             argType = types.erasure(argType);
   984             if (argType.tag == BOT)
   985                 // nulls type as the marker type Null (which has no instances)
   986                 // TO DO: figure out how to access java.lang.Null safely, else throw nice error
   987                 //argType = types.boxedClass(syms.botType).type;
   988                 argType = types.boxedClass(syms.voidType).type;  // REMOVE
   989             return argType;
   990         }
   992     /** Load toplevel or member class with given fully qualified name and
   993      *  verify that it is accessible.
   994      *  @param env       The current environment.
   995      *  @param name      The fully qualified name of the class to be loaded.
   996      */
   997     Symbol loadClass(Env<AttrContext> env, Name name) {
   998         try {
   999             ClassSymbol c = reader.loadClass(name);
  1000             return isAccessible(env, c) ? c : new AccessError(c);
  1001         } catch (ClassReader.BadClassFile err) {
  1002             throw err;
  1003         } catch (CompletionFailure ex) {
  1004             return typeNotFound;
  1008     /** Find qualified member type.
  1009      *  @param env       The current environment.
  1010      *  @param site      The original type from where the selection takes
  1011      *                   place.
  1012      *  @param name      The type's name.
  1013      *  @param c         The class to search for the member type. This is
  1014      *                   always a superclass or implemented interface of
  1015      *                   site's class.
  1016      */
  1017     Symbol findMemberType(Env<AttrContext> env,
  1018                           Type site,
  1019                           Name name,
  1020                           TypeSymbol c) {
  1021         Symbol bestSoFar = typeNotFound;
  1022         Symbol sym;
  1023         Scope.Entry e = c.members().lookup(name);
  1024         while (e.scope != null) {
  1025             if (e.sym.kind == TYP) {
  1026                 return isAccessible(env, site, e.sym)
  1027                     ? e.sym
  1028                     : new AccessError(env, site, e.sym);
  1030             e = e.next();
  1032         Type st = types.supertype(c.type);
  1033         if (st != null && st.tag == CLASS) {
  1034             sym = findMemberType(env, site, name, st.tsym);
  1035             if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1037         for (List<Type> l = types.interfaces(c.type);
  1038              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
  1039              l = l.tail) {
  1040             sym = findMemberType(env, site, name, l.head.tsym);
  1041             if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
  1042                 sym.owner != bestSoFar.owner)
  1043                 bestSoFar = new AmbiguityError(bestSoFar, sym);
  1044             else if (sym.kind < bestSoFar.kind)
  1045                 bestSoFar = sym;
  1047         return bestSoFar;
  1050     /** Find a global type in given scope and load corresponding class.
  1051      *  @param env       The current environment.
  1052      *  @param scope     The scope in which to look for the type.
  1053      *  @param name      The type's name.
  1054      */
  1055     Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name) {
  1056         Symbol bestSoFar = typeNotFound;
  1057         for (Scope.Entry e = scope.lookup(name); e.scope != null; e = e.next()) {
  1058             Symbol sym = loadClass(env, e.sym.flatName());
  1059             if (bestSoFar.kind == TYP && sym.kind == TYP &&
  1060                 bestSoFar != sym)
  1061                 return new AmbiguityError(bestSoFar, sym);
  1062             else if (sym.kind < bestSoFar.kind)
  1063                 bestSoFar = sym;
  1065         return bestSoFar;
  1068     /** Find an unqualified type symbol.
  1069      *  @param env       The current environment.
  1070      *  @param name      The type's name.
  1071      */
  1072     Symbol findType(Env<AttrContext> env, Name name) {
  1073         Symbol bestSoFar = typeNotFound;
  1074         Symbol sym;
  1075         boolean staticOnly = false;
  1076         for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
  1077             if (isStatic(env1)) staticOnly = true;
  1078             for (Scope.Entry e = env1.info.scope.lookup(name);
  1079                  e.scope != null;
  1080                  e = e.next()) {
  1081                 if (e.sym.kind == TYP) {
  1082                     if (staticOnly &&
  1083                         e.sym.type.tag == TYPEVAR &&
  1084                         e.sym.owner.kind == TYP) return new StaticError(e.sym);
  1085                     return e.sym;
  1089             sym = findMemberType(env1, env1.enclClass.sym.type, name,
  1090                                  env1.enclClass.sym);
  1091             if (staticOnly && sym.kind == TYP &&
  1092                 sym.type.tag == CLASS &&
  1093                 sym.type.getEnclosingType().tag == CLASS &&
  1094                 env1.enclClass.sym.type.isParameterized() &&
  1095                 sym.type.getEnclosingType().isParameterized())
  1096                 return new StaticError(sym);
  1097             else if (sym.exists()) return sym;
  1098             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1100             JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass;
  1101             if ((encl.sym.flags() & STATIC) != 0)
  1102                 staticOnly = true;
  1105         if (env.tree.getTag() != JCTree.IMPORT) {
  1106             sym = findGlobalType(env, env.toplevel.namedImportScope, name);
  1107             if (sym.exists()) return sym;
  1108             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1110             sym = findGlobalType(env, env.toplevel.packge.members(), name);
  1111             if (sym.exists()) return sym;
  1112             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1114             sym = findGlobalType(env, env.toplevel.starImportScope, name);
  1115             if (sym.exists()) return sym;
  1116             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1119         return bestSoFar;
  1122     /** Find an unqualified identifier which matches a specified kind set.
  1123      *  @param env       The current environment.
  1124      *  @param name      The indentifier's name.
  1125      *  @param kind      Indicates the possible symbol kinds
  1126      *                   (a subset of VAL, TYP, PCK).
  1127      */
  1128     Symbol findIdent(Env<AttrContext> env, Name name, int kind) {
  1129         Symbol bestSoFar = typeNotFound;
  1130         Symbol sym;
  1132         if ((kind & VAR) != 0) {
  1133             sym = findVar(env, name);
  1134             if (sym.exists()) return sym;
  1135             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1138         if ((kind & TYP) != 0) {
  1139             sym = findType(env, name);
  1140             if (sym.exists()) return sym;
  1141             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1144         if ((kind & PCK) != 0) return reader.enterPackage(name);
  1145         else return bestSoFar;
  1148     /** Find an identifier in a package which matches a specified kind set.
  1149      *  @param env       The current environment.
  1150      *  @param name      The identifier's name.
  1151      *  @param kind      Indicates the possible symbol kinds
  1152      *                   (a nonempty subset of TYP, PCK).
  1153      */
  1154     Symbol findIdentInPackage(Env<AttrContext> env, TypeSymbol pck,
  1155                               Name name, int kind) {
  1156         Name fullname = TypeSymbol.formFullName(name, pck);
  1157         Symbol bestSoFar = typeNotFound;
  1158         PackageSymbol pack = null;
  1159         if ((kind & PCK) != 0) {
  1160             pack = reader.enterPackage(fullname);
  1161             if (pack.exists()) return pack;
  1163         if ((kind & TYP) != 0) {
  1164             Symbol sym = loadClass(env, fullname);
  1165             if (sym.exists()) {
  1166                 // don't allow programs to use flatnames
  1167                 if (name == sym.name) return sym;
  1169             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1171         return (pack != null) ? pack : bestSoFar;
  1174     /** Find an identifier among the members of a given type `site'.
  1175      *  @param env       The current environment.
  1176      *  @param site      The type containing the symbol to be found.
  1177      *  @param name      The identifier's name.
  1178      *  @param kind      Indicates the possible symbol kinds
  1179      *                   (a subset of VAL, TYP).
  1180      */
  1181     Symbol findIdentInType(Env<AttrContext> env, Type site,
  1182                            Name name, int kind) {
  1183         Symbol bestSoFar = typeNotFound;
  1184         Symbol sym;
  1185         if ((kind & VAR) != 0) {
  1186             sym = findField(env, site, name, site.tsym);
  1187             if (sym.exists()) return sym;
  1188             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1191         if ((kind & TYP) != 0) {
  1192             sym = findMemberType(env, site, name, site.tsym);
  1193             if (sym.exists()) return sym;
  1194             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1196         return bestSoFar;
  1199 /* ***************************************************************************
  1200  *  Access checking
  1201  *  The following methods convert ResolveErrors to ErrorSymbols, issuing
  1202  *  an error message in the process
  1203  ****************************************************************************/
  1205     /** If `sym' is a bad symbol: report error and return errSymbol
  1206      *  else pass through unchanged,
  1207      *  additional arguments duplicate what has been used in trying to find the
  1208      *  symbol (--> flyweight pattern). This improves performance since we
  1209      *  expect misses to happen frequently.
  1211      *  @param sym       The symbol that was found, or a ResolveError.
  1212      *  @param pos       The position to use for error reporting.
  1213      *  @param site      The original type from where the selection took place.
  1214      *  @param name      The symbol's name.
  1215      *  @param argtypes  The invocation's value arguments,
  1216      *                   if we looked for a method.
  1217      *  @param typeargtypes  The invocation's type arguments,
  1218      *                   if we looked for a method.
  1219      */
  1220     Symbol access(Symbol sym,
  1221                   DiagnosticPosition pos,
  1222                   Type site,
  1223                   Name name,
  1224                   boolean qualified,
  1225                   List<Type> argtypes,
  1226                   List<Type> typeargtypes) {
  1227         if (sym.kind >= AMBIGUOUS) {
  1228             ResolveError errSym = (ResolveError)sym;
  1229             if (!site.isErroneous() &&
  1230                 !Type.isErroneous(argtypes) &&
  1231                 (typeargtypes==null || !Type.isErroneous(typeargtypes)))
  1232                 logResolveError(errSym, pos, site, name, argtypes, typeargtypes);
  1233             sym = errSym.access(name, qualified ? site.tsym : syms.noSymbol);
  1235         return sym;
  1238     /** Same as above, but without type arguments and arguments.
  1239      */
  1240     Symbol access(Symbol sym,
  1241                   DiagnosticPosition pos,
  1242                   Type site,
  1243                   Name name,
  1244                   boolean qualified) {
  1245         if (sym.kind >= AMBIGUOUS)
  1246             return access(sym, pos, site, name, qualified, List.<Type>nil(), null);
  1247         else
  1248             return sym;
  1251     /** Check that sym is not an abstract method.
  1252      */
  1253     void checkNonAbstract(DiagnosticPosition pos, Symbol sym) {
  1254         if ((sym.flags() & ABSTRACT) != 0)
  1255             log.error(pos, "abstract.cant.be.accessed.directly",
  1256                       kindName(sym), sym, sym.location());
  1259 /* ***************************************************************************
  1260  *  Debugging
  1261  ****************************************************************************/
  1263     /** print all scopes starting with scope s and proceeding outwards.
  1264      *  used for debugging.
  1265      */
  1266     public void printscopes(Scope s) {
  1267         while (s != null) {
  1268             if (s.owner != null)
  1269                 System.err.print(s.owner + ": ");
  1270             for (Scope.Entry e = s.elems; e != null; e = e.sibling) {
  1271                 if ((e.sym.flags() & ABSTRACT) != 0)
  1272                     System.err.print("abstract ");
  1273                 System.err.print(e.sym + " ");
  1275             System.err.println();
  1276             s = s.next;
  1280     void printscopes(Env<AttrContext> env) {
  1281         while (env.outer != null) {
  1282             System.err.println("------------------------------");
  1283             printscopes(env.info.scope);
  1284             env = env.outer;
  1288     public void printscopes(Type t) {
  1289         while (t.tag == CLASS) {
  1290             printscopes(t.tsym.members());
  1291             t = types.supertype(t);
  1295 /* ***************************************************************************
  1296  *  Name resolution
  1297  *  Naming conventions are as for symbol lookup
  1298  *  Unlike the find... methods these methods will report access errors
  1299  ****************************************************************************/
  1301     /** Resolve an unqualified (non-method) identifier.
  1302      *  @param pos       The position to use for error reporting.
  1303      *  @param env       The environment current at the identifier use.
  1304      *  @param name      The identifier's name.
  1305      *  @param kind      The set of admissible symbol kinds for the identifier.
  1306      */
  1307     Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env,
  1308                         Name name, int kind) {
  1309         return access(
  1310             findIdent(env, name, kind),
  1311             pos, env.enclClass.sym.type, name, false);
  1314     /** Resolve an unqualified method identifier.
  1315      *  @param pos       The position to use for error reporting.
  1316      *  @param env       The environment current at the method invocation.
  1317      *  @param name      The identifier's name.
  1318      *  @param argtypes  The types of the invocation's value arguments.
  1319      *  @param typeargtypes  The types of the invocation's type arguments.
  1320      */
  1321     Symbol resolveMethod(DiagnosticPosition pos,
  1322                          Env<AttrContext> env,
  1323                          Name name,
  1324                          List<Type> argtypes,
  1325                          List<Type> typeargtypes) {
  1326         Symbol sym = methodNotFound;
  1327         List<MethodResolutionPhase> steps = methodResolutionSteps;
  1328         while (steps.nonEmpty() &&
  1329                steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  1330                sym.kind >= ERRONEOUS) {
  1331             sym = findFun(env, name, argtypes, typeargtypes,
  1332                     steps.head.isBoxingRequired,
  1333                     env.info.varArgs = steps.head.isVarargsRequired);
  1334             methodResolutionCache.put(steps.head, sym);
  1335             steps = steps.tail;
  1337         if (sym.kind >= AMBIGUOUS) {//if nothing is found return the 'first' error
  1338             MethodResolutionPhase errPhase =
  1339                     firstErroneousResolutionPhase();
  1340             sym = access(methodResolutionCache.get(errPhase),
  1341                     pos, env.enclClass.sym.type, name, false, argtypes, typeargtypes);
  1342             env.info.varArgs = errPhase.isVarargsRequired;
  1344         return sym;
  1347     /** Resolve a qualified method identifier
  1348      *  @param pos       The position to use for error reporting.
  1349      *  @param env       The environment current at the method invocation.
  1350      *  @param site      The type of the qualifying expression, in which
  1351      *                   identifier is searched.
  1352      *  @param name      The identifier's name.
  1353      *  @param argtypes  The types of the invocation's value arguments.
  1354      *  @param typeargtypes  The types of the invocation's type arguments.
  1355      */
  1356     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
  1357                                   Type site, Name name, List<Type> argtypes,
  1358                                   List<Type> typeargtypes) {
  1359         Symbol sym = methodNotFound;
  1360         List<MethodResolutionPhase> steps = methodResolutionSteps;
  1361         while (steps.nonEmpty() &&
  1362                steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  1363                sym.kind >= ERRONEOUS) {
  1364             sym = findMethod(env, site, name, argtypes, typeargtypes,
  1365                     steps.head.isBoxingRequired(),
  1366                     env.info.varArgs = steps.head.isVarargsRequired(), false);
  1367             methodResolutionCache.put(steps.head, sym);
  1368             steps = steps.tail;
  1370         if (sym.kind >= AMBIGUOUS) {//if nothing is found return the 'first' error
  1371             MethodResolutionPhase errPhase =
  1372                     firstErroneousResolutionPhase();
  1373             sym = access(methodResolutionCache.get(errPhase),
  1374                     pos, site, name, true, argtypes, typeargtypes);
  1375             env.info.varArgs = errPhase.isVarargsRequired;
  1377         return sym;
  1380     /** Resolve a qualified method identifier, throw a fatal error if not
  1381      *  found.
  1382      *  @param pos       The position to use for error reporting.
  1383      *  @param env       The environment current at the method invocation.
  1384      *  @param site      The type of the qualifying expression, in which
  1385      *                   identifier is searched.
  1386      *  @param name      The identifier's name.
  1387      *  @param argtypes  The types of the invocation's value arguments.
  1388      *  @param typeargtypes  The types of the invocation's type arguments.
  1389      */
  1390     public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env,
  1391                                         Type site, Name name,
  1392                                         List<Type> argtypes,
  1393                                         List<Type> typeargtypes) {
  1394         Symbol sym = resolveQualifiedMethod(
  1395             pos, env, site, name, argtypes, typeargtypes);
  1396         if (sym.kind == MTH) return (MethodSymbol)sym;
  1397         else throw new FatalError(
  1398                  diags.fragment("fatal.err.cant.locate.meth",
  1399                                 name));
  1402     /** Resolve constructor.
  1403      *  @param pos       The position to use for error reporting.
  1404      *  @param env       The environment current at the constructor invocation.
  1405      *  @param site      The type of class for which a constructor is searched.
  1406      *  @param argtypes  The types of the constructor invocation's value
  1407      *                   arguments.
  1408      *  @param typeargtypes  The types of the constructor invocation's type
  1409      *                   arguments.
  1410      */
  1411     Symbol resolveConstructor(DiagnosticPosition pos,
  1412                               Env<AttrContext> env,
  1413                               Type site,
  1414                               List<Type> argtypes,
  1415                               List<Type> typeargtypes) {
  1416         Symbol sym = methodNotFound;
  1417         List<MethodResolutionPhase> steps = methodResolutionSteps;
  1418         while (steps.nonEmpty() &&
  1419                steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  1420                sym.kind >= ERRONEOUS) {
  1421             sym = resolveConstructor(pos, env, site, argtypes, typeargtypes,
  1422                     steps.head.isBoxingRequired(),
  1423                     env.info.varArgs = steps.head.isVarargsRequired());
  1424             methodResolutionCache.put(steps.head, sym);
  1425             steps = steps.tail;
  1427         if (sym.kind >= AMBIGUOUS) {//if nothing is found return the 'first' error
  1428             MethodResolutionPhase errPhase = firstErroneousResolutionPhase();
  1429             sym = access(methodResolutionCache.get(errPhase),
  1430                     pos, site, names.init, true, argtypes, typeargtypes);
  1431             env.info.varArgs = errPhase.isVarargsRequired();
  1433         return sym;
  1436     /** Resolve constructor using diamond inference.
  1437      *  @param pos       The position to use for error reporting.
  1438      *  @param env       The environment current at the constructor invocation.
  1439      *  @param site      The type of class for which a constructor is searched.
  1440      *                   The scope of this class has been touched in attribution.
  1441      *  @param argtypes  The types of the constructor invocation's value
  1442      *                   arguments.
  1443      *  @param typeargtypes  The types of the constructor invocation's type
  1444      *                   arguments.
  1445      */
  1446     Symbol resolveDiamond(DiagnosticPosition pos,
  1447                               Env<AttrContext> env,
  1448                               Type site,
  1449                               List<Type> argtypes,
  1450                               List<Type> typeargtypes, boolean reportErrors) {
  1451         Symbol sym = methodNotFound;
  1452         JCDiagnostic explanation = null;
  1453         List<MethodResolutionPhase> steps = methodResolutionSteps;
  1454         while (steps.nonEmpty() &&
  1455                steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  1456                sym.kind >= ERRONEOUS) {
  1457             sym = resolveConstructor(pos, env, site, argtypes, typeargtypes,
  1458                     steps.head.isBoxingRequired(),
  1459                     env.info.varArgs = steps.head.isVarargsRequired());
  1460             methodResolutionCache.put(steps.head, sym);
  1461             if (sym.kind == WRONG_MTH &&
  1462                     ((InapplicableSymbolError)sym).explanation != null) {
  1463                 //if the symbol is an inapplicable method symbol, then the
  1464                 //explanation contains the reason for which inference failed
  1465                 explanation = ((InapplicableSymbolError)sym).explanation;
  1467             steps = steps.tail;
  1469         if (sym.kind >= AMBIGUOUS && reportErrors) {
  1470             String key = explanation == null ?
  1471                 "cant.apply.diamond" :
  1472                 "cant.apply.diamond.1";
  1473             log.error(pos, key, diags.fragment("diamond", site.tsym), explanation);
  1475         return sym;
  1478     /** Resolve constructor.
  1479      *  @param pos       The position to use for error reporting.
  1480      *  @param env       The environment current at the constructor invocation.
  1481      *  @param site      The type of class for which a constructor is searched.
  1482      *  @param argtypes  The types of the constructor invocation's value
  1483      *                   arguments.
  1484      *  @param typeargtypes  The types of the constructor invocation's type
  1485      *                   arguments.
  1486      *  @param allowBoxing Allow boxing and varargs conversions.
  1487      *  @param useVarargs Box trailing arguments into an array for varargs.
  1488      */
  1489     Symbol resolveConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  1490                               Type site, List<Type> argtypes,
  1491                               List<Type> typeargtypes,
  1492                               boolean allowBoxing,
  1493                               boolean useVarargs) {
  1494         Symbol sym = findMethod(env, site,
  1495                                 names.init, argtypes,
  1496                                 typeargtypes, allowBoxing,
  1497                                 useVarargs, false);
  1498         if ((sym.flags() & DEPRECATED) != 0 &&
  1499             (env.info.scope.owner.flags() & DEPRECATED) == 0 &&
  1500             env.info.scope.owner.outermostClass() != sym.outermostClass())
  1501             chk.warnDeprecated(pos, sym);
  1502         return sym;
  1505     /** Resolve a constructor, throw a fatal error if not found.
  1506      *  @param pos       The position to use for error reporting.
  1507      *  @param env       The environment current at the method invocation.
  1508      *  @param site      The type to be constructed.
  1509      *  @param argtypes  The types of the invocation's value arguments.
  1510      *  @param typeargtypes  The types of the invocation's type arguments.
  1511      */
  1512     public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  1513                                         Type site,
  1514                                         List<Type> argtypes,
  1515                                         List<Type> typeargtypes) {
  1516         Symbol sym = resolveConstructor(
  1517             pos, env, site, argtypes, typeargtypes);
  1518         if (sym.kind == MTH) return (MethodSymbol)sym;
  1519         else throw new FatalError(
  1520                  diags.fragment("fatal.err.cant.locate.ctor", site));
  1523     /** Resolve operator.
  1524      *  @param pos       The position to use for error reporting.
  1525      *  @param optag     The tag of the operation tree.
  1526      *  @param env       The environment current at the operation.
  1527      *  @param argtypes  The types of the operands.
  1528      */
  1529     Symbol resolveOperator(DiagnosticPosition pos, int optag,
  1530                            Env<AttrContext> env, List<Type> argtypes) {
  1531         Name name = treeinfo.operatorName(optag);
  1532         Symbol sym = findMethod(env, syms.predefClass.type, name, argtypes,
  1533                                 null, false, false, true);
  1534         if (boxingEnabled && sym.kind >= WRONG_MTHS)
  1535             sym = findMethod(env, syms.predefClass.type, name, argtypes,
  1536                              null, true, false, true);
  1537         return access(sym, pos, env.enclClass.sym.type, name,
  1538                       false, argtypes, null);
  1541     /** Resolve operator.
  1542      *  @param pos       The position to use for error reporting.
  1543      *  @param optag     The tag of the operation tree.
  1544      *  @param env       The environment current at the operation.
  1545      *  @param arg       The type of the operand.
  1546      */
  1547     Symbol resolveUnaryOperator(DiagnosticPosition pos, int optag, Env<AttrContext> env, Type arg) {
  1548         return resolveOperator(pos, optag, env, List.of(arg));
  1551     /** Resolve binary operator.
  1552      *  @param pos       The position to use for error reporting.
  1553      *  @param optag     The tag of the operation tree.
  1554      *  @param env       The environment current at the operation.
  1555      *  @param left      The types of the left operand.
  1556      *  @param right     The types of the right operand.
  1557      */
  1558     Symbol resolveBinaryOperator(DiagnosticPosition pos,
  1559                                  int optag,
  1560                                  Env<AttrContext> env,
  1561                                  Type left,
  1562                                  Type right) {
  1563         return resolveOperator(pos, optag, env, List.of(left, right));
  1566     /**
  1567      * Resolve `c.name' where name == this or name == super.
  1568      * @param pos           The position to use for error reporting.
  1569      * @param env           The environment current at the expression.
  1570      * @param c             The qualifier.
  1571      * @param name          The identifier's name.
  1572      */
  1573     Symbol resolveSelf(DiagnosticPosition pos,
  1574                        Env<AttrContext> env,
  1575                        TypeSymbol c,
  1576                        Name name) {
  1577         Env<AttrContext> env1 = env;
  1578         boolean staticOnly = false;
  1579         while (env1.outer != null) {
  1580             if (isStatic(env1)) staticOnly = true;
  1581             if (env1.enclClass.sym == c) {
  1582                 Symbol sym = env1.info.scope.lookup(name).sym;
  1583                 if (sym != null) {
  1584                     if (staticOnly) sym = new StaticError(sym);
  1585                     return access(sym, pos, env.enclClass.sym.type,
  1586                                   name, true);
  1589             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  1590             env1 = env1.outer;
  1592         log.error(pos, "not.encl.class", c);
  1593         return syms.errSymbol;
  1596     /**
  1597      * Resolve `c.this' for an enclosing class c that contains the
  1598      * named member.
  1599      * @param pos           The position to use for error reporting.
  1600      * @param env           The environment current at the expression.
  1601      * @param member        The member that must be contained in the result.
  1602      */
  1603     Symbol resolveSelfContaining(DiagnosticPosition pos,
  1604                                  Env<AttrContext> env,
  1605                                  Symbol member) {
  1606         Name name = names._this;
  1607         Env<AttrContext> env1 = env;
  1608         boolean staticOnly = false;
  1609         while (env1.outer != null) {
  1610             if (isStatic(env1)) staticOnly = true;
  1611             if (env1.enclClass.sym.isSubClass(member.owner, types) &&
  1612                 isAccessible(env, env1.enclClass.sym.type, member)) {
  1613                 Symbol sym = env1.info.scope.lookup(name).sym;
  1614                 if (sym != null) {
  1615                     if (staticOnly) sym = new StaticError(sym);
  1616                     return access(sym, pos, env.enclClass.sym.type,
  1617                                   name, true);
  1620             if ((env1.enclClass.sym.flags() & STATIC) != 0)
  1621                 staticOnly = true;
  1622             env1 = env1.outer;
  1624         log.error(pos, "encl.class.required", member);
  1625         return syms.errSymbol;
  1628     /**
  1629      * Resolve an appropriate implicit this instance for t's container.
  1630      * JLS2 8.8.5.1 and 15.9.2
  1631      */
  1632     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
  1633         Type thisType = (((t.tsym.owner.kind & (MTH|VAR)) != 0)
  1634                          ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
  1635                          : resolveSelfContaining(pos, env, t.tsym)).type;
  1636         if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
  1637             log.error(pos, "cant.ref.before.ctor.called", "this");
  1638         return thisType;
  1641 /* ***************************************************************************
  1642  *  ResolveError classes, indicating error situations when accessing symbols
  1643  ****************************************************************************/
  1645     public void logAccessError(Env<AttrContext> env, JCTree tree, Type type) {
  1646         AccessError error = new AccessError(env, type.getEnclosingType(), type.tsym);
  1647         logResolveError(error, tree.pos(), type.getEnclosingType(), null, null, null);
  1649     //where
  1650     private void logResolveError(ResolveError error,
  1651             DiagnosticPosition pos,
  1652             Type site,
  1653             Name name,
  1654             List<Type> argtypes,
  1655             List<Type> typeargtypes) {
  1656         JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
  1657                 pos, site, name, argtypes, typeargtypes);
  1658         if (d != null)
  1659             log.report(d);
  1662     private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
  1664     public Object methodArguments(List<Type> argtypes) {
  1665         return argtypes.isEmpty() ? noArgs : argtypes;
  1668     /**
  1669      * Root class for resolution errors. Subclass of ResolveError
  1670      * represent a different kinds of resolution error - as such they must
  1671      * specify how they map into concrete compiler diagnostics.
  1672      */
  1673     private abstract class ResolveError extends Symbol {
  1675         /** The name of the kind of error, for debugging only. */
  1676         final String debugName;
  1678         ResolveError(int kind, String debugName) {
  1679             super(kind, 0, null, null, null);
  1680             this.debugName = debugName;
  1683         @Override
  1684         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
  1685             throw new AssertionError();
  1688         @Override
  1689         public String toString() {
  1690             return debugName;
  1693         @Override
  1694         public boolean exists() {
  1695             return false;
  1698         /**
  1699          * Create an external representation for this erroneous symbol to be
  1700          * used during attribution - by default this returns the symbol of a
  1701          * brand new error type which stores the original type found
  1702          * during resolution.
  1704          * @param name     the name used during resolution
  1705          * @param location the location from which the symbol is accessed
  1706          */
  1707         protected Symbol access(Name name, TypeSymbol location) {
  1708             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  1711         /**
  1712          * Create a diagnostic representing this resolution error.
  1714          * @param dkind     The kind of the diagnostic to be created (e.g error).
  1715          * @param pos       The position to be used for error reporting.
  1716          * @param site      The original type from where the selection took place.
  1717          * @param name      The name of the symbol to be resolved.
  1718          * @param argtypes  The invocation's value arguments,
  1719          *                  if we looked for a method.
  1720          * @param typeargtypes  The invocation's type arguments,
  1721          *                      if we looked for a method.
  1722          */
  1723         abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  1724                 DiagnosticPosition pos,
  1725                 Type site,
  1726                 Name name,
  1727                 List<Type> argtypes,
  1728                 List<Type> typeargtypes);
  1730         /**
  1731          * A name designates an operator if it consists
  1732          * of a non-empty sequence of operator symbols +-~!/*%&|^<>=
  1733          */
  1734         boolean isOperator(Name name) {
  1735             int i = 0;
  1736             while (i < name.getByteLength() &&
  1737                    "+-~!*/%&|^<>=".indexOf(name.getByteAt(i)) >= 0) i++;
  1738             return i > 0 && i == name.getByteLength();
  1742     /**
  1743      * This class is the root class of all resolution errors caused by
  1744      * an invalid symbol being found during resolution.
  1745      */
  1746     abstract class InvalidSymbolError extends ResolveError {
  1748         /** The invalid symbol found during resolution */
  1749         Symbol sym;
  1751         InvalidSymbolError(int kind, Symbol sym, String debugName) {
  1752             super(kind, debugName);
  1753             this.sym = sym;
  1756         @Override
  1757         public boolean exists() {
  1758             return true;
  1761         @Override
  1762         public String toString() {
  1763              return super.toString() + " wrongSym=" + sym;
  1766         @Override
  1767         public Symbol access(Name name, TypeSymbol location) {
  1768             if (sym.kind >= AMBIGUOUS)
  1769                 return ((ResolveError)sym).access(name, location);
  1770             else if ((sym.kind & ERRONEOUS) == 0 && (sym.kind & TYP) != 0)
  1771                 return types.createErrorType(name, location, sym.type).tsym;
  1772             else
  1773                 return sym;
  1777     /**
  1778      * InvalidSymbolError error class indicating that a symbol matching a
  1779      * given name does not exists in a given site.
  1780      */
  1781     class SymbolNotFoundError extends ResolveError {
  1783         SymbolNotFoundError(int kind) {
  1784             super(kind, "symbol not found error");
  1787         @Override
  1788         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  1789                 DiagnosticPosition pos,
  1790                 Type site,
  1791                 Name name,
  1792                 List<Type> argtypes,
  1793                 List<Type> typeargtypes) {
  1794             argtypes = argtypes == null ? List.<Type>nil() : argtypes;
  1795             typeargtypes = typeargtypes == null ? List.<Type>nil() : typeargtypes;
  1796             if (name == names.error)
  1797                 return null;
  1799             if (isOperator(name)) {
  1800                 return diags.create(dkind, log.currentSource(), pos,
  1801                         "operator.cant.be.applied", name, argtypes);
  1803             boolean hasLocation = false;
  1804             if (!site.tsym.name.isEmpty()) {
  1805                 if (site.tsym.kind == PCK && !site.tsym.exists()) {
  1806                     return diags.create(dkind, log.currentSource(), pos,
  1807                         "doesnt.exist", site.tsym);
  1809                 hasLocation = true;
  1811             boolean isConstructor = kind == ABSENT_MTH &&
  1812                     name == names.table.names.init;
  1813             KindName kindname = isConstructor ? KindName.CONSTRUCTOR : absentKind(kind);
  1814             Name idname = isConstructor ? site.tsym.name : name;
  1815             String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation);
  1816             if (hasLocation) {
  1817                 return diags.create(dkind, log.currentSource(), pos,
  1818                         errKey, kindname, idname, //symbol kindname, name
  1819                         typeargtypes, argtypes, //type parameters and arguments (if any)
  1820                         typeKindName(site), site); //location kindname, type
  1822             else {
  1823                 return diags.create(dkind, log.currentSource(), pos,
  1824                         errKey, kindname, idname, //symbol kindname, name
  1825                         typeargtypes, argtypes); //type parameters and arguments (if any)
  1828         //where
  1829         private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) {
  1830             String key = "cant.resolve";
  1831             String suffix = hasLocation ? ".location" : "";
  1832             switch (kindname) {
  1833                 case METHOD:
  1834                 case CONSTRUCTOR: {
  1835                     suffix += ".args";
  1836                     suffix += hasTypeArgs ? ".params" : "";
  1839             return key + suffix;
  1843     /**
  1844      * InvalidSymbolError error class indicating that a given symbol
  1845      * (either a method, a constructor or an operand) is not applicable
  1846      * given an actual arguments/type argument list.
  1847      */
  1848     class InapplicableSymbolError extends InvalidSymbolError {
  1850         /** An auxiliary explanation set in case of instantiation errors. */
  1851         JCDiagnostic explanation;
  1853         InapplicableSymbolError(Symbol sym) {
  1854             super(WRONG_MTH, sym, "inapplicable symbol error");
  1857         /** Update sym and explanation and return this.
  1858          */
  1859         InapplicableSymbolError setWrongSym(Symbol sym, JCDiagnostic explanation) {
  1860             this.sym = sym;
  1861             this.explanation = explanation;
  1862             return this;
  1865         /** Update sym and return this.
  1866          */
  1867         InapplicableSymbolError setWrongSym(Symbol sym) {
  1868             this.sym = sym;
  1869             this.explanation = null;
  1870             return this;
  1873         @Override
  1874         public String toString() {
  1875             return super.toString() + " explanation=" + explanation;
  1878         @Override
  1879         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  1880                 DiagnosticPosition pos,
  1881                 Type site,
  1882                 Name name,
  1883                 List<Type> argtypes,
  1884                 List<Type> typeargtypes) {
  1885             if (name == names.error)
  1886                 return null;
  1888             if (isOperator(name)) {
  1889                 return diags.create(dkind, log.currentSource(),
  1890                         pos, "operator.cant.be.applied", name, argtypes);
  1892             else {
  1893                 Symbol ws = sym.asMemberOf(site, types);
  1894                 return diags.create(dkind, log.currentSource(), pos,
  1895                           "cant.apply.symbol" + (explanation != null ? ".1" : ""),
  1896                           kindName(ws),
  1897                           ws.name == names.init ? ws.owner.name : ws.name,
  1898                           methodArguments(ws.type.getParameterTypes()),
  1899                           methodArguments(argtypes),
  1900                           kindName(ws.owner),
  1901                           ws.owner.type,
  1902                           explanation);
  1906         @Override
  1907         public Symbol access(Name name, TypeSymbol location) {
  1908             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  1912     /**
  1913      * ResolveError error class indicating that a set of symbols
  1914      * (either methods, constructors or operands) is not applicable
  1915      * given an actual arguments/type argument list.
  1916      */
  1917     class InapplicableSymbolsError extends ResolveError {
  1918         InapplicableSymbolsError(Symbol sym) {
  1919             super(WRONG_MTHS, "inapplicable symbols");
  1922         @Override
  1923         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  1924                 DiagnosticPosition pos,
  1925                 Type site,
  1926                 Name name,
  1927                 List<Type> argtypes,
  1928                 List<Type> typeargtypes) {
  1929             return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
  1930                     site, name, argtypes, typeargtypes);
  1934     /**
  1935      * An InvalidSymbolError error class indicating that a symbol is not
  1936      * accessible from a given site
  1937      */
  1938     class AccessError extends InvalidSymbolError {
  1940         private Env<AttrContext> env;
  1941         private Type site;
  1943         AccessError(Symbol sym) {
  1944             this(null, null, sym);
  1947         AccessError(Env<AttrContext> env, Type site, Symbol sym) {
  1948             super(HIDDEN, sym, "access error");
  1949             this.env = env;
  1950             this.site = site;
  1951             if (debugResolve)
  1952                 log.error("proc.messager", sym + " @ " + site + " is inaccessible.");
  1955         @Override
  1956         public boolean exists() {
  1957             return false;
  1960         @Override
  1961         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  1962                 DiagnosticPosition pos,
  1963                 Type site,
  1964                 Name name,
  1965                 List<Type> argtypes,
  1966                 List<Type> typeargtypes) {
  1967             if (sym.owner.type.tag == ERROR)
  1968                 return null;
  1970             if (sym.name == names.init && sym.owner != site.tsym) {
  1971                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
  1972                         pos, site, name, argtypes, typeargtypes);
  1974             else if ((sym.flags() & PUBLIC) != 0
  1975                 || (env != null && this.site != null
  1976                     && !isAccessible(env, this.site))) {
  1977                 return diags.create(dkind, log.currentSource(),
  1978                         pos, "not.def.access.class.intf.cant.access",
  1979                     sym, sym.location());
  1981             else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) {
  1982                 return diags.create(dkind, log.currentSource(),
  1983                         pos, "report.access", sym,
  1984                         asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
  1985                         sym.location());
  1987             else {
  1988                 return diags.create(dkind, log.currentSource(),
  1989                         pos, "not.def.public.cant.access", sym, sym.location());
  1994     /**
  1995      * InvalidSymbolError error class indicating that an instance member
  1996      * has erroneously been accessed from a static context.
  1997      */
  1998     class StaticError extends InvalidSymbolError {
  2000         StaticError(Symbol sym) {
  2001             super(STATICERR, sym, "static error");
  2004         @Override
  2005         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2006                 DiagnosticPosition pos,
  2007                 Type site,
  2008                 Name name,
  2009                 List<Type> argtypes,
  2010                 List<Type> typeargtypes) {
  2011             Symbol errSym = ((sym.kind == TYP && sym.type.tag == CLASS)
  2012                 ? types.erasure(sym.type).tsym
  2013                 : sym);
  2014             return diags.create(dkind, log.currentSource(), pos,
  2015                     "non-static.cant.be.ref", kindName(sym), errSym);
  2019     /**
  2020      * InvalidSymbolError error class indicating that a pair of symbols
  2021      * (either methods, constructors or operands) are ambiguous
  2022      * given an actual arguments/type argument list.
  2023      */
  2024     class AmbiguityError extends InvalidSymbolError {
  2026         /** The other maximally specific symbol */
  2027         Symbol sym2;
  2029         AmbiguityError(Symbol sym1, Symbol sym2) {
  2030             super(AMBIGUOUS, sym1, "ambiguity error");
  2031             this.sym2 = sym2;
  2034         @Override
  2035         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2036                 DiagnosticPosition pos,
  2037                 Type site,
  2038                 Name name,
  2039                 List<Type> argtypes,
  2040                 List<Type> typeargtypes) {
  2041             AmbiguityError pair = this;
  2042             while (true) {
  2043                 if (pair.sym.kind == AMBIGUOUS)
  2044                     pair = (AmbiguityError)pair.sym;
  2045                 else if (pair.sym2.kind == AMBIGUOUS)
  2046                     pair = (AmbiguityError)pair.sym2;
  2047                 else break;
  2049             Name sname = pair.sym.name;
  2050             if (sname == names.init) sname = pair.sym.owner.name;
  2051             return diags.create(dkind, log.currentSource(),
  2052                       pos, "ref.ambiguous", sname,
  2053                       kindName(pair.sym),
  2054                       pair.sym,
  2055                       pair.sym.location(site, types),
  2056                       kindName(pair.sym2),
  2057                       pair.sym2,
  2058                       pair.sym2.location(site, types));
  2062     enum MethodResolutionPhase {
  2063         BASIC(false, false),
  2064         BOX(true, false),
  2065         VARARITY(true, true);
  2067         boolean isBoxingRequired;
  2068         boolean isVarargsRequired;
  2070         MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) {
  2071            this.isBoxingRequired = isBoxingRequired;
  2072            this.isVarargsRequired = isVarargsRequired;
  2075         public boolean isBoxingRequired() {
  2076             return isBoxingRequired;
  2079         public boolean isVarargsRequired() {
  2080             return isVarargsRequired;
  2083         public boolean isApplicable(boolean boxingEnabled, boolean varargsEnabled) {
  2084             return (varargsEnabled || !isVarargsRequired) &&
  2085                    (boxingEnabled || !isBoxingRequired);
  2089     private Map<MethodResolutionPhase, Symbol> methodResolutionCache =
  2090         new HashMap<MethodResolutionPhase, Symbol>(MethodResolutionPhase.values().length);
  2092     final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
  2094     private MethodResolutionPhase firstErroneousResolutionPhase() {
  2095         MethodResolutionPhase bestSoFar = BASIC;
  2096         Symbol sym = methodNotFound;
  2097         List<MethodResolutionPhase> steps = methodResolutionSteps;
  2098         while (steps.nonEmpty() &&
  2099                steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  2100                sym.kind >= WRONG_MTHS) {
  2101             sym = methodResolutionCache.get(steps.head);
  2102             bestSoFar = steps.head;
  2103             steps = steps.tail;
  2105         return bestSoFar;

mercurial