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

Fri, 12 Nov 2010 12:32:43 +0000

author
mcimadamore
date
Fri, 12 Nov 2010 12:32:43 +0000
changeset 741
58ceeff50af8
parent 700
7b413ac1a720
child 775
536ee9f126b1
permissions
-rw-r--r--

6598108: com.sun.source.util.Trees.isAccessible incorrect
Summary: JavacTrees' version of isAccessible should take into account enclosing class accessibility
Reviewed-by: jjg

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

mercurial