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

Thu, 03 Feb 2011 09:36:28 +0000

author
mcimadamore
date
Thu, 03 Feb 2011 09:36:28 +0000
changeset 853
875262e89b52
parent 852
899f7c3d9426
child 855
afe226180744
permissions
-rw-r--r--

5017953: spurious cascaded diagnostics when name not found
Summary: when an operator is applied to one or more erroneous operands, spurious diagnostics are generated
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 1999, 2011, 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     private final boolean debugResolve;
    75     Scope polymorphicSignatureScope;
    77     public static Resolve instance(Context context) {
    78         Resolve instance = context.get(resolveKey);
    79         if (instance == null)
    80             instance = new Resolve(context);
    81         return instance;
    82     }
    84     protected Resolve(Context context) {
    85         context.put(resolveKey, this);
    86         syms = Symtab.instance(context);
    88         varNotFound = new
    89             SymbolNotFoundError(ABSENT_VAR);
    90         wrongMethod = new
    91             InapplicableSymbolError(syms.errSymbol);
    92         wrongMethods = new
    93             InapplicableSymbolsError(syms.errSymbol);
    94         methodNotFound = new
    95             SymbolNotFoundError(ABSENT_MTH);
    96         typeNotFound = new
    97             SymbolNotFoundError(ABSENT_TYP);
    99         names = Names.instance(context);
   100         log = Log.instance(context);
   101         chk = Check.instance(context);
   102         infer = Infer.instance(context);
   103         reader = ClassReader.instance(context);
   104         treeinfo = TreeInfo.instance(context);
   105         types = Types.instance(context);
   106         diags = JCDiagnostic.Factory.instance(context);
   107         Source source = Source.instance(context);
   108         boxingEnabled = source.allowBoxing();
   109         varargsEnabled = source.allowVarargs();
   110         Options options = Options.instance(context);
   111         debugResolve = options.isSet("debugresolve");
   112         Target target = Target.instance(context);
   113         allowMethodHandles = target.hasMethodHandles();
   114         polymorphicSignatureScope = new Scope(syms.noSymbol);
   116         inapplicableMethodException = new InapplicableMethodException(diags);
   117     }
   119     /** error symbols, which are returned when resolution fails
   120      */
   121     final SymbolNotFoundError varNotFound;
   122     final InapplicableSymbolError wrongMethod;
   123     final InapplicableSymbolsError wrongMethods;
   124     final SymbolNotFoundError methodNotFound;
   125     final SymbolNotFoundError typeNotFound;
   127 /* ************************************************************************
   128  * Identifier resolution
   129  *************************************************************************/
   131     /** An environment is "static" if its static level is greater than
   132      *  the one of its outer environment
   133      */
   134     static boolean isStatic(Env<AttrContext> env) {
   135         return env.info.staticLevel > env.outer.info.staticLevel;
   136     }
   138     /** An environment is an "initializer" if it is a constructor or
   139      *  an instance initializer.
   140      */
   141     static boolean isInitializer(Env<AttrContext> env) {
   142         Symbol owner = env.info.scope.owner;
   143         return owner.isConstructor() ||
   144             owner.owner.kind == TYP &&
   145             (owner.kind == VAR ||
   146              owner.kind == MTH && (owner.flags() & BLOCK) != 0) &&
   147             (owner.flags() & STATIC) == 0;
   148     }
   150     /** Is class accessible in given evironment?
   151      *  @param env    The current environment.
   152      *  @param c      The class whose accessibility is checked.
   153      */
   154     public boolean isAccessible(Env<AttrContext> env, TypeSymbol c) {
   155         return isAccessible(env, c, false);
   156     }
   158     public boolean isAccessible(Env<AttrContext> env, TypeSymbol c, boolean checkInner) {
   159         boolean isAccessible = false;
   160         switch ((short)(c.flags() & AccessFlags)) {
   161             case PRIVATE:
   162                 isAccessible =
   163                     env.enclClass.sym.outermostClass() ==
   164                     c.owner.outermostClass();
   165                 break;
   166             case 0:
   167                 isAccessible =
   168                     env.toplevel.packge == c.owner // fast special case
   169                     ||
   170                     env.toplevel.packge == c.packge()
   171                     ||
   172                     // Hack: this case is added since synthesized default constructors
   173                     // of anonymous classes should be allowed to access
   174                     // classes which would be inaccessible otherwise.
   175                     env.enclMethod != null &&
   176                     (env.enclMethod.mods.flags & ANONCONSTR) != 0;
   177                 break;
   178             default: // error recovery
   179             case PUBLIC:
   180                 isAccessible = true;
   181                 break;
   182             case PROTECTED:
   183                 isAccessible =
   184                     env.toplevel.packge == c.owner // fast special case
   185                     ||
   186                     env.toplevel.packge == c.packge()
   187                     ||
   188                     isInnerSubClass(env.enclClass.sym, c.owner);
   189                 break;
   190         }
   191         return (checkInner == false || c.type.getEnclosingType() == Type.noType) ?
   192             isAccessible :
   193             isAccessible && isAccessible(env, c.type.getEnclosingType(), checkInner);
   194     }
   195     //where
   196         /** Is given class a subclass of given base class, or an inner class
   197          *  of a subclass?
   198          *  Return null if no such class exists.
   199          *  @param c     The class which is the subclass or is contained in it.
   200          *  @param base  The base class
   201          */
   202         private boolean isInnerSubClass(ClassSymbol c, Symbol base) {
   203             while (c != null && !c.isSubClass(base, types)) {
   204                 c = c.owner.enclClass();
   205             }
   206             return c != null;
   207         }
   209     boolean isAccessible(Env<AttrContext> env, Type t) {
   210         return isAccessible(env, t, false);
   211     }
   213     boolean isAccessible(Env<AttrContext> env, Type t, boolean checkInner) {
   214         return (t.tag == ARRAY)
   215             ? isAccessible(env, types.elemtype(t))
   216             : isAccessible(env, t.tsym, checkInner);
   217     }
   219     /** Is symbol accessible as a member of given type in given evironment?
   220      *  @param env    The current environment.
   221      *  @param site   The type of which the tested symbol is regarded
   222      *                as a member.
   223      *  @param sym    The symbol.
   224      */
   225     public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym) {
   226         return isAccessible(env, site, sym, false);
   227     }
   228     public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym, boolean checkInner) {
   229         if (sym.name == names.init && sym.owner != site.tsym) return false;
   230         switch ((short)(sym.flags() & AccessFlags)) {
   231         case PRIVATE:
   232             return
   233                 (env.enclClass.sym == sym.owner // fast special case
   234                  ||
   235                  env.enclClass.sym.outermostClass() ==
   236                  sym.owner.outermostClass())
   237                 &&
   238                 sym.isInheritedIn(site.tsym, types);
   239         case 0:
   240             return
   241                 (env.toplevel.packge == sym.owner.owner // fast special case
   242                  ||
   243                  env.toplevel.packge == sym.packge())
   244                 &&
   245                 isAccessible(env, site, checkInner)
   246                 &&
   247                 sym.isInheritedIn(site.tsym, types)
   248                 &&
   249                 notOverriddenIn(site, sym);
   250         case PROTECTED:
   251             return
   252                 (env.toplevel.packge == sym.owner.owner // fast special case
   253                  ||
   254                  env.toplevel.packge == sym.packge()
   255                  ||
   256                  isProtectedAccessible(sym, env.enclClass.sym, site)
   257                  ||
   258                  // OK to select instance method or field from 'super' or type name
   259                  // (but type names should be disallowed elsewhere!)
   260                  env.info.selectSuper && (sym.flags() & STATIC) == 0 && sym.kind != TYP)
   261                 &&
   262                 isAccessible(env, site, checkInner)
   263                 &&
   264                 notOverriddenIn(site, sym);
   265         default: // this case includes erroneous combinations as well
   266             return isAccessible(env, site, checkInner) && notOverriddenIn(site, sym);
   267         }
   268     }
   269     //where
   270     /* `sym' is accessible only if not overridden by
   271      * another symbol which is a member of `site'
   272      * (because, if it is overridden, `sym' is not strictly
   273      * speaking a member of `site'). A polymorphic signature method
   274      * cannot be overridden (e.g. MH.invokeExact(Object[])).
   275      */
   276     private boolean notOverriddenIn(Type site, Symbol sym) {
   277         if (sym.kind != MTH || sym.isConstructor() || sym.isStatic())
   278             return true;
   279         else {
   280             Symbol s2 = ((MethodSymbol)sym).implementation(site.tsym, types, true);
   281             return (s2 == null || s2 == sym || sym.owner == s2.owner ||
   282                     s2.isPolymorphicSignatureGeneric() ||
   283                     !types.isSubSignature(types.memberType(site, s2), types.memberType(site, sym)));
   284         }
   285     }
   286     //where
   287         /** Is given protected symbol accessible if it is selected from given site
   288          *  and the selection takes place in given class?
   289          *  @param sym     The symbol with protected access
   290          *  @param c       The class where the access takes place
   291          *  @site          The type of the qualifier
   292          */
   293         private
   294         boolean isProtectedAccessible(Symbol sym, ClassSymbol c, Type site) {
   295             while (c != null &&
   296                    !(c.isSubClass(sym.owner, types) &&
   297                      (c.flags() & INTERFACE) == 0 &&
   298                      // In JLS 2e 6.6.2.1, the subclass restriction applies
   299                      // only to instance fields and methods -- types are excluded
   300                      // regardless of whether they are declared 'static' or not.
   301                      ((sym.flags() & STATIC) != 0 || sym.kind == TYP || site.tsym.isSubClass(c, types))))
   302                 c = c.owner.enclClass();
   303             return c != null;
   304         }
   306     /** Try to instantiate the type of a method so that it fits
   307      *  given type arguments and argument types. If succesful, return
   308      *  the method's instantiated type, else return null.
   309      *  The instantiation will take into account an additional leading
   310      *  formal parameter if the method is an instance method seen as a member
   311      *  of un underdetermined site In this case, we treat site as an additional
   312      *  parameter and the parameters of the class containing the method as
   313      *  additional type variables that get instantiated.
   314      *
   315      *  @param env         The current environment
   316      *  @param site        The type of which the method is a member.
   317      *  @param m           The method symbol.
   318      *  @param argtypes    The invocation's given value arguments.
   319      *  @param typeargtypes    The invocation's given type arguments.
   320      *  @param allowBoxing Allow boxing conversions of arguments.
   321      *  @param useVarargs Box trailing arguments into an array for varargs.
   322      */
   323     Type rawInstantiate(Env<AttrContext> env,
   324                         Type site,
   325                         Symbol m,
   326                         List<Type> argtypes,
   327                         List<Type> typeargtypes,
   328                         boolean allowBoxing,
   329                         boolean useVarargs,
   330                         Warner warn)
   331         throws Infer.InferenceException {
   332         boolean polymorphicSignature = m.isPolymorphicSignatureGeneric() && allowMethodHandles;
   333         if (useVarargs && (m.flags() & VARARGS) == 0)
   334             throw inapplicableMethodException.setMessage();
   335         Type mt = types.memberType(site, m);
   337         // tvars is the list of formal type variables for which type arguments
   338         // need to inferred.
   339         List<Type> tvars = env.info.tvars;
   340         if (typeargtypes == null) typeargtypes = List.nil();
   341         if (mt.tag != FORALL && typeargtypes.nonEmpty()) {
   342             // This is not a polymorphic method, but typeargs are supplied
   343             // which is fine, see JLS3 15.12.2.1
   344         } else if (mt.tag == FORALL && typeargtypes.nonEmpty()) {
   345             ForAll pmt = (ForAll) mt;
   346             if (typeargtypes.length() != pmt.tvars.length())
   347                 throw inapplicableMethodException.setMessage("arg.length.mismatch"); // not enough args
   348             // Check type arguments are within bounds
   349             List<Type> formals = pmt.tvars;
   350             List<Type> actuals = typeargtypes;
   351             while (formals.nonEmpty() && actuals.nonEmpty()) {
   352                 List<Type> bounds = types.subst(types.getBounds((TypeVar)formals.head),
   353                                                 pmt.tvars, typeargtypes);
   354                 for (; bounds.nonEmpty(); bounds = bounds.tail)
   355                     if (!types.isSubtypeUnchecked(actuals.head, bounds.head, warn))
   356                         throw inapplicableMethodException.setMessage("explicit.param.do.not.conform.to.bounds",actuals.head, bounds);
   357                 formals = formals.tail;
   358                 actuals = actuals.tail;
   359             }
   360             mt = types.subst(pmt.qtype, pmt.tvars, typeargtypes);
   361         } else if (mt.tag == FORALL) {
   362             ForAll pmt = (ForAll) mt;
   363             List<Type> tvars1 = types.newInstances(pmt.tvars);
   364             tvars = tvars.appendList(tvars1);
   365             mt = types.subst(pmt.qtype, pmt.tvars, tvars1);
   366         }
   368         // find out whether we need to go the slow route via infer
   369         boolean instNeeded = tvars.tail != null || /*inlined: tvars.nonEmpty()*/
   370                 polymorphicSignature;
   371         for (List<Type> l = argtypes;
   372              l.tail != null/*inlined: l.nonEmpty()*/ && !instNeeded;
   373              l = l.tail) {
   374             if (l.head.tag == FORALL) instNeeded = true;
   375         }
   377         if (instNeeded)
   378             return polymorphicSignature ?
   379                 infer.instantiatePolymorphicSignatureInstance(env, site, m.name, (MethodSymbol)m, argtypes) :
   380                 infer.instantiateMethod(env,
   381                                     tvars,
   382                                     (MethodType)mt,
   383                                     m,
   384                                     argtypes,
   385                                     allowBoxing,
   386                                     useVarargs,
   387                                     warn);
   389         checkRawArgumentsAcceptable(env, argtypes, mt.getParameterTypes(),
   390                                 allowBoxing, useVarargs, warn);
   391         return mt;
   392     }
   394     /** Same but returns null instead throwing a NoInstanceException
   395      */
   396     Type instantiate(Env<AttrContext> env,
   397                      Type site,
   398                      Symbol m,
   399                      List<Type> argtypes,
   400                      List<Type> typeargtypes,
   401                      boolean allowBoxing,
   402                      boolean useVarargs,
   403                      Warner warn) {
   404         try {
   405             return rawInstantiate(env, site, m, argtypes, typeargtypes,
   406                                   allowBoxing, useVarargs, warn);
   407         } catch (InapplicableMethodException ex) {
   408             return null;
   409         }
   410     }
   412     /** Check if a parameter list accepts a list of args.
   413      */
   414     boolean argumentsAcceptable(Env<AttrContext> env,
   415                                 List<Type> argtypes,
   416                                 List<Type> formals,
   417                                 boolean allowBoxing,
   418                                 boolean useVarargs,
   419                                 Warner warn) {
   420         try {
   421             checkRawArgumentsAcceptable(env, argtypes, formals, allowBoxing, useVarargs, warn);
   422             return true;
   423         } catch (InapplicableMethodException ex) {
   424             return false;
   425         }
   426     }
   427     void checkRawArgumentsAcceptable(Env<AttrContext> env,
   428                                 List<Type> argtypes,
   429                                 List<Type> formals,
   430                                 boolean allowBoxing,
   431                                 boolean useVarargs,
   432                                 Warner warn) {
   433         Type varargsFormal = useVarargs ? formals.last() : null;
   434         if (varargsFormal == null &&
   435                 argtypes.size() != formals.size()) {
   436             throw inapplicableMethodException.setMessage("arg.length.mismatch"); // not enough args
   437         }
   439         while (argtypes.nonEmpty() && formals.head != varargsFormal) {
   440             boolean works = allowBoxing
   441                 ? types.isConvertible(argtypes.head, formals.head, warn)
   442                 : types.isSubtypeUnchecked(argtypes.head, formals.head, warn);
   443             if (!works)
   444                 throw inapplicableMethodException.setMessage("no.conforming.assignment.exists",
   445                         argtypes.head,
   446                         formals.head);
   447             argtypes = argtypes.tail;
   448             formals = formals.tail;
   449         }
   451         if (formals.head != varargsFormal)
   452             throw inapplicableMethodException.setMessage("arg.length.mismatch"); // not enough args
   454         if (useVarargs) {
   455             //note: if applicability check is triggered by most specific test,
   456             //the last argument of a varargs is _not_ an array type (see JLS 15.12.2.5)
   457             Type elt = types.elemtypeOrType(varargsFormal);
   458             while (argtypes.nonEmpty()) {
   459                 if (!types.isConvertible(argtypes.head, elt, warn))
   460                     throw inapplicableMethodException.setMessage("varargs.argument.mismatch",
   461                             argtypes.head,
   462                             elt);
   463                 argtypes = argtypes.tail;
   464             }
   465             //check varargs element type accessibility
   466             if (!isAccessible(env, elt)) {
   467                 Symbol location = env.enclClass.sym;
   468                 throw inapplicableMethodException.setMessage("inaccessible.varargs.type",
   469                             elt,
   470                             Kinds.kindName(location),
   471                             location);
   472             }
   473         }
   474         return;
   475     }
   476     // where
   477         public static class InapplicableMethodException extends RuntimeException {
   478             private static final long serialVersionUID = 0;
   480             JCDiagnostic diagnostic;
   481             JCDiagnostic.Factory diags;
   483             InapplicableMethodException(JCDiagnostic.Factory diags) {
   484                 this.diagnostic = null;
   485                 this.diags = diags;
   486             }
   487             InapplicableMethodException setMessage() {
   488                 this.diagnostic = null;
   489                 return this;
   490             }
   491             InapplicableMethodException setMessage(String key) {
   492                 this.diagnostic = key != null ? diags.fragment(key) : null;
   493                 return this;
   494             }
   495             InapplicableMethodException setMessage(String key, Object... args) {
   496                 this.diagnostic = key != null ? diags.fragment(key, args) : null;
   497                 return this;
   498             }
   499             InapplicableMethodException setMessage(JCDiagnostic diag) {
   500                 this.diagnostic = diag;
   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.check(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             boolean m1SignatureMoreSpecific = signatureMoreSpecific(env, site, m1, m2, allowBoxing, useVarargs);
   728             boolean m2SignatureMoreSpecific = signatureMoreSpecific(env, site, m2, m1, allowBoxing, useVarargs);
   729             if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) {
   730                 Type mt1 = types.memberType(site, m1);
   731                 Type mt2 = types.memberType(site, m2);
   732                 if (!types.overrideEquivalent(mt1, mt2))
   733                     return ambiguityError(m1, m2);
   735                 // same signature; select (a) the non-bridge method, or
   736                 // (b) the one that overrides the other, or (c) the concrete
   737                 // one, or (d) merge both abstract signatures
   738                 if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE))
   739                     return ((m1.flags() & BRIDGE) != 0) ? m2 : m1;
   741                 // if one overrides or hides the other, use it
   742                 TypeSymbol m1Owner = (TypeSymbol)m1.owner;
   743                 TypeSymbol m2Owner = (TypeSymbol)m2.owner;
   744                 if (types.asSuper(m1Owner.type, m2Owner) != null &&
   745                     ((m1.owner.flags_field & INTERFACE) == 0 ||
   746                      (m2.owner.flags_field & INTERFACE) != 0) &&
   747                     m1.overrides(m2, m1Owner, types, false))
   748                     return m1;
   749                 if (types.asSuper(m2Owner.type, m1Owner) != null &&
   750                     ((m2.owner.flags_field & INTERFACE) == 0 ||
   751                      (m1.owner.flags_field & INTERFACE) != 0) &&
   752                     m2.overrides(m1, m2Owner, types, false))
   753                     return m2;
   754                 boolean m1Abstract = (m1.flags() & ABSTRACT) != 0;
   755                 boolean m2Abstract = (m2.flags() & ABSTRACT) != 0;
   756                 if (m1Abstract && !m2Abstract) return m2;
   757                 if (m2Abstract && !m1Abstract) return m1;
   758                 // both abstract or both concrete
   759                 if (!m1Abstract && !m2Abstract)
   760                     return ambiguityError(m1, m2);
   761                 // check that both signatures have the same erasure
   762                 if (!types.isSameTypes(m1.erasure(types).getParameterTypes(),
   763                                        m2.erasure(types).getParameterTypes()))
   764                     return ambiguityError(m1, m2);
   765                 // both abstract, neither overridden; merge throws clause and result type
   766                 Symbol mostSpecific;
   767                 Type result2 = mt2.getReturnType();
   768                 if (mt2.tag == FORALL)
   769                     result2 = types.subst(result2, ((ForAll)mt2).tvars, ((ForAll)mt1).tvars);
   770                 if (types.isSubtype(mt1.getReturnType(), result2))
   771                     mostSpecific = m1;
   772                 else if (types.isSubtype(result2, mt1.getReturnType()))
   773                     mostSpecific = m2;
   774                 else {
   775                     // Theoretically, this can't happen, but it is possible
   776                     // due to error recovery or mixing incompatible class files
   777                     return ambiguityError(m1, m2);
   778                 }
   779                 MethodSymbol result = new MethodSymbol(
   780                         mostSpecific.flags(),
   781                         mostSpecific.name,
   782                         null,
   783                         mostSpecific.owner) {
   784                     @Override
   785                     public MethodSymbol implementation(TypeSymbol origin, Types types, boolean checkResult) {
   786                         if (origin == site.tsym)
   787                             return this;
   788                         else
   789                             return super.implementation(origin, types, checkResult);
   790                     }
   791                 };
   792                 result.type = (Type)mostSpecific.type.clone();
   793                 result.type.setThrown(chk.intersect(mt1.getThrownTypes(),
   794                                                     mt2.getThrownTypes()));
   795                 return result;
   796             }
   797             if (m1SignatureMoreSpecific) return m1;
   798             if (m2SignatureMoreSpecific) return m2;
   799             return ambiguityError(m1, m2);
   800         case AMBIGUOUS:
   801             AmbiguityError e = (AmbiguityError)m2;
   802             Symbol err1 = mostSpecific(m1, e.sym, env, site, allowBoxing, useVarargs);
   803             Symbol err2 = mostSpecific(m1, e.sym2, env, site, allowBoxing, useVarargs);
   804             if (err1 == err2) return err1;
   805             if (err1 == e.sym && err2 == e.sym2) return m2;
   806             if (err1 instanceof AmbiguityError &&
   807                 err2 instanceof AmbiguityError &&
   808                 ((AmbiguityError)err1).sym == ((AmbiguityError)err2).sym)
   809                 return ambiguityError(m1, m2);
   810             else
   811                 return ambiguityError(err1, err2);
   812         default:
   813             throw new AssertionError();
   814         }
   815     }
   816     //where
   817     private boolean signatureMoreSpecific(Env<AttrContext> env, Type site, Symbol m1, Symbol m2, boolean allowBoxing, boolean useVarargs) {
   818         noteWarner.clear();
   819         Type mtype1 = types.memberType(site, adjustVarargs(m1, m2, useVarargs));
   820         return (instantiate(env, site, adjustVarargs(m2, m1, useVarargs), types.lowerBoundArgtypes(mtype1), null,
   821                              allowBoxing, false, noteWarner) != null ||
   822                  useVarargs && instantiate(env, site, adjustVarargs(m2, m1, useVarargs), types.lowerBoundArgtypes(mtype1), null,
   823                                            allowBoxing, true, noteWarner) != null) &&
   824                 !noteWarner.hasLint(Lint.LintCategory.UNCHECKED);
   825     }
   826     //where
   827     private Symbol adjustVarargs(Symbol to, Symbol from, boolean useVarargs) {
   828         List<Type> fromArgs = from.type.getParameterTypes();
   829         List<Type> toArgs = to.type.getParameterTypes();
   830         if (useVarargs &&
   831                 (from.flags() & VARARGS) != 0 &&
   832                 (to.flags() & VARARGS) != 0) {
   833             Type varargsTypeFrom = fromArgs.last();
   834             Type varargsTypeTo = toArgs.last();
   835             ListBuffer<Type> args = ListBuffer.lb();
   836             if (toArgs.length() < fromArgs.length()) {
   837                 //if we are checking a varargs method 'from' against another varargs
   838                 //method 'to' (where arity of 'to' < arity of 'from') then expand signature
   839                 //of 'to' to 'fit' arity of 'from' (this means adding fake formals to 'to'
   840                 //until 'to' signature has the same arity as 'from')
   841                 while (fromArgs.head != varargsTypeFrom) {
   842                     args.append(toArgs.head == varargsTypeTo ? types.elemtype(varargsTypeTo) : toArgs.head);
   843                     fromArgs = fromArgs.tail;
   844                     toArgs = toArgs.head == varargsTypeTo ?
   845                         toArgs :
   846                         toArgs.tail;
   847                 }
   848             } else {
   849                 //formal argument list is same as original list where last
   850                 //argument (array type) is removed
   851                 args.appendList(toArgs.reverse().tail.reverse());
   852             }
   853             //append varargs element type as last synthetic formal
   854             args.append(types.elemtype(varargsTypeTo));
   855             MethodSymbol msym = new MethodSymbol(to.flags_field,
   856                                                  to.name,
   857                                                  (Type)to.type.clone(), //see: 6990136
   858                                                  to.owner);
   859             MethodType mtype = msym.type.asMethodType();
   860             mtype.argtypes = args.toList();
   861             return msym;
   862         } else {
   863             return to;
   864         }
   865     }
   866     //where
   867     Symbol ambiguityError(Symbol m1, Symbol m2) {
   868         if (((m1.flags() | m2.flags()) & CLASH) != 0) {
   869             return (m1.flags() & CLASH) == 0 ? m1 : m2;
   870         } else {
   871             return new AmbiguityError(m1, m2);
   872         }
   873     }
   875     /** Find best qualified method matching given name, type and value
   876      *  arguments.
   877      *  @param env       The current environment.
   878      *  @param site      The original type from where the selection
   879      *                   takes place.
   880      *  @param name      The method's name.
   881      *  @param argtypes  The method's value arguments.
   882      *  @param typeargtypes The method's type arguments
   883      *  @param allowBoxing Allow boxing conversions of arguments.
   884      *  @param useVarargs Box trailing arguments into an array for varargs.
   885      */
   886     Symbol findMethod(Env<AttrContext> env,
   887                       Type site,
   888                       Name name,
   889                       List<Type> argtypes,
   890                       List<Type> typeargtypes,
   891                       boolean allowBoxing,
   892                       boolean useVarargs,
   893                       boolean operator) {
   894         Symbol bestSoFar = methodNotFound;
   895         return findMethod(env,
   896                           site,
   897                           name,
   898                           argtypes,
   899                           typeargtypes,
   900                           site.tsym.type,
   901                           true,
   902                           bestSoFar,
   903                           allowBoxing,
   904                           useVarargs,
   905                           operator);
   906     }
   907     // where
   908     private Symbol findMethod(Env<AttrContext> env,
   909                               Type site,
   910                               Name name,
   911                               List<Type> argtypes,
   912                               List<Type> typeargtypes,
   913                               Type intype,
   914                               boolean abstractok,
   915                               Symbol bestSoFar,
   916                               boolean allowBoxing,
   917                               boolean useVarargs,
   918                               boolean operator) {
   919         for (Type ct = intype; ct.tag == CLASS || ct.tag == TYPEVAR; ct = types.supertype(ct)) {
   920             while (ct.tag == TYPEVAR)
   921                 ct = ct.getUpperBound();
   922             ClassSymbol c = (ClassSymbol)ct.tsym;
   923             if ((c.flags() & (ABSTRACT | INTERFACE | ENUM)) == 0)
   924                 abstractok = false;
   925             for (Scope.Entry e = c.members().lookup(name);
   926                  e.scope != null;
   927                  e = e.next()) {
   928                 //- System.out.println(" e " + e.sym);
   929                 if (e.sym.kind == MTH &&
   930                     (e.sym.flags_field & SYNTHETIC) == 0) {
   931                     bestSoFar = selectBest(env, site, argtypes, typeargtypes,
   932                                            e.sym, bestSoFar,
   933                                            allowBoxing,
   934                                            useVarargs,
   935                                            operator);
   936                 }
   937             }
   938             if (name == names.init)
   939                 break;
   940             //- System.out.println(" - " + bestSoFar);
   941             if (abstractok) {
   942                 Symbol concrete = methodNotFound;
   943                 if ((bestSoFar.flags() & ABSTRACT) == 0)
   944                     concrete = bestSoFar;
   945                 for (List<Type> l = types.interfaces(c.type);
   946                      l.nonEmpty();
   947                      l = l.tail) {
   948                     bestSoFar = findMethod(env, site, name, argtypes,
   949                                            typeargtypes,
   950                                            l.head, abstractok, bestSoFar,
   951                                            allowBoxing, useVarargs, operator);
   952                 }
   953                 if (concrete != bestSoFar &&
   954                     concrete.kind < ERR  && bestSoFar.kind < ERR &&
   955                     types.isSubSignature(concrete.type, bestSoFar.type))
   956                     bestSoFar = concrete;
   957             }
   958         }
   959         return bestSoFar;
   960     }
   962     /** Find unqualified method matching given name, type and value arguments.
   963      *  @param env       The current environment.
   964      *  @param name      The method's name.
   965      *  @param argtypes  The method's value arguments.
   966      *  @param typeargtypes  The method's type arguments.
   967      *  @param allowBoxing Allow boxing conversions of arguments.
   968      *  @param useVarargs Box trailing arguments into an array for varargs.
   969      */
   970     Symbol findFun(Env<AttrContext> env, Name name,
   971                    List<Type> argtypes, List<Type> typeargtypes,
   972                    boolean allowBoxing, boolean useVarargs) {
   973         Symbol bestSoFar = methodNotFound;
   974         Symbol sym;
   975         Env<AttrContext> env1 = env;
   976         boolean staticOnly = false;
   977         while (env1.outer != null) {
   978             if (isStatic(env1)) staticOnly = true;
   979             sym = findMethod(
   980                 env1, env1.enclClass.sym.type, name, argtypes, typeargtypes,
   981                 allowBoxing, useVarargs, false);
   982             if (sym.exists()) {
   983                 if (staticOnly &&
   984                     sym.kind == MTH &&
   985                     sym.owner.kind == TYP &&
   986                     (sym.flags() & STATIC) == 0) return new StaticError(sym);
   987                 else return sym;
   988             } else if (sym.kind < bestSoFar.kind) {
   989                 bestSoFar = sym;
   990             }
   991             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
   992             env1 = env1.outer;
   993         }
   995         sym = findMethod(env, syms.predefClass.type, name, argtypes,
   996                          typeargtypes, allowBoxing, useVarargs, false);
   997         if (sym.exists())
   998             return sym;
  1000         Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
  1001         for (; e.scope != null; e = e.next()) {
  1002             sym = e.sym;
  1003             Type origin = e.getOrigin().owner.type;
  1004             if (sym.kind == MTH) {
  1005                 if (e.sym.owner.type != origin)
  1006                     sym = sym.clone(e.getOrigin().owner);
  1007                 if (!isAccessible(env, origin, sym))
  1008                     sym = new AccessError(env, origin, sym);
  1009                 bestSoFar = selectBest(env, origin,
  1010                                        argtypes, typeargtypes,
  1011                                        sym, bestSoFar,
  1012                                        allowBoxing, useVarargs, false);
  1015         if (bestSoFar.exists())
  1016             return bestSoFar;
  1018         e = env.toplevel.starImportScope.lookup(name);
  1019         for (; e.scope != null; e = e.next()) {
  1020             sym = e.sym;
  1021             Type origin = e.getOrigin().owner.type;
  1022             if (sym.kind == MTH) {
  1023                 if (e.sym.owner.type != origin)
  1024                     sym = sym.clone(e.getOrigin().owner);
  1025                 if (!isAccessible(env, origin, sym))
  1026                     sym = new AccessError(env, origin, sym);
  1027                 bestSoFar = selectBest(env, origin,
  1028                                        argtypes, typeargtypes,
  1029                                        sym, bestSoFar,
  1030                                        allowBoxing, useVarargs, false);
  1033         return bestSoFar;
  1036     /** Load toplevel or member class with given fully qualified name and
  1037      *  verify that it is accessible.
  1038      *  @param env       The current environment.
  1039      *  @param name      The fully qualified name of the class to be loaded.
  1040      */
  1041     Symbol loadClass(Env<AttrContext> env, Name name) {
  1042         try {
  1043             ClassSymbol c = reader.loadClass(name);
  1044             return isAccessible(env, c) ? c : new AccessError(c);
  1045         } catch (ClassReader.BadClassFile err) {
  1046             throw err;
  1047         } catch (CompletionFailure ex) {
  1048             return typeNotFound;
  1052     /** Find qualified member type.
  1053      *  @param env       The current environment.
  1054      *  @param site      The original type from where the selection takes
  1055      *                   place.
  1056      *  @param name      The type's name.
  1057      *  @param c         The class to search for the member type. This is
  1058      *                   always a superclass or implemented interface of
  1059      *                   site's class.
  1060      */
  1061     Symbol findMemberType(Env<AttrContext> env,
  1062                           Type site,
  1063                           Name name,
  1064                           TypeSymbol c) {
  1065         Symbol bestSoFar = typeNotFound;
  1066         Symbol sym;
  1067         Scope.Entry e = c.members().lookup(name);
  1068         while (e.scope != null) {
  1069             if (e.sym.kind == TYP) {
  1070                 return isAccessible(env, site, e.sym)
  1071                     ? e.sym
  1072                     : new AccessError(env, site, e.sym);
  1074             e = e.next();
  1076         Type st = types.supertype(c.type);
  1077         if (st != null && st.tag == CLASS) {
  1078             sym = findMemberType(env, site, name, st.tsym);
  1079             if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1081         for (List<Type> l = types.interfaces(c.type);
  1082              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
  1083              l = l.tail) {
  1084             sym = findMemberType(env, site, name, l.head.tsym);
  1085             if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
  1086                 sym.owner != bestSoFar.owner)
  1087                 bestSoFar = new AmbiguityError(bestSoFar, sym);
  1088             else if (sym.kind < bestSoFar.kind)
  1089                 bestSoFar = sym;
  1091         return bestSoFar;
  1094     /** Find a global type in given scope and load corresponding class.
  1095      *  @param env       The current environment.
  1096      *  @param scope     The scope in which to look for the type.
  1097      *  @param name      The type's name.
  1098      */
  1099     Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name) {
  1100         Symbol bestSoFar = typeNotFound;
  1101         for (Scope.Entry e = scope.lookup(name); e.scope != null; e = e.next()) {
  1102             Symbol sym = loadClass(env, e.sym.flatName());
  1103             if (bestSoFar.kind == TYP && sym.kind == TYP &&
  1104                 bestSoFar != sym)
  1105                 return new AmbiguityError(bestSoFar, sym);
  1106             else if (sym.kind < bestSoFar.kind)
  1107                 bestSoFar = sym;
  1109         return bestSoFar;
  1112     /** Find an unqualified type symbol.
  1113      *  @param env       The current environment.
  1114      *  @param name      The type's name.
  1115      */
  1116     Symbol findType(Env<AttrContext> env, Name name) {
  1117         Symbol bestSoFar = typeNotFound;
  1118         Symbol sym;
  1119         boolean staticOnly = false;
  1120         for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
  1121             if (isStatic(env1)) staticOnly = true;
  1122             for (Scope.Entry e = env1.info.scope.lookup(name);
  1123                  e.scope != null;
  1124                  e = e.next()) {
  1125                 if (e.sym.kind == TYP) {
  1126                     if (staticOnly &&
  1127                         e.sym.type.tag == TYPEVAR &&
  1128                         e.sym.owner.kind == TYP) return new StaticError(e.sym);
  1129                     return e.sym;
  1133             sym = findMemberType(env1, env1.enclClass.sym.type, name,
  1134                                  env1.enclClass.sym);
  1135             if (staticOnly && sym.kind == TYP &&
  1136                 sym.type.tag == CLASS &&
  1137                 sym.type.getEnclosingType().tag == CLASS &&
  1138                 env1.enclClass.sym.type.isParameterized() &&
  1139                 sym.type.getEnclosingType().isParameterized())
  1140                 return new StaticError(sym);
  1141             else if (sym.exists()) return sym;
  1142             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1144             JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass;
  1145             if ((encl.sym.flags() & STATIC) != 0)
  1146                 staticOnly = true;
  1149         if (env.tree.getTag() != JCTree.IMPORT) {
  1150             sym = findGlobalType(env, env.toplevel.namedImportScope, name);
  1151             if (sym.exists()) return sym;
  1152             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1154             sym = findGlobalType(env, env.toplevel.packge.members(), name);
  1155             if (sym.exists()) return sym;
  1156             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1158             sym = findGlobalType(env, env.toplevel.starImportScope, name);
  1159             if (sym.exists()) return sym;
  1160             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1163         return bestSoFar;
  1166     /** Find an unqualified identifier which matches a specified kind set.
  1167      *  @param env       The current environment.
  1168      *  @param name      The indentifier's name.
  1169      *  @param kind      Indicates the possible symbol kinds
  1170      *                   (a subset of VAL, TYP, PCK).
  1171      */
  1172     Symbol findIdent(Env<AttrContext> env, Name name, int kind) {
  1173         Symbol bestSoFar = typeNotFound;
  1174         Symbol sym;
  1176         if ((kind & VAR) != 0) {
  1177             sym = findVar(env, name);
  1178             if (sym.exists()) return sym;
  1179             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1182         if ((kind & TYP) != 0) {
  1183             sym = findType(env, name);
  1184             if (sym.exists()) return sym;
  1185             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1188         if ((kind & PCK) != 0) return reader.enterPackage(name);
  1189         else return bestSoFar;
  1192     /** Find an identifier in a package which matches a specified kind set.
  1193      *  @param env       The current environment.
  1194      *  @param name      The identifier's name.
  1195      *  @param kind      Indicates the possible symbol kinds
  1196      *                   (a nonempty subset of TYP, PCK).
  1197      */
  1198     Symbol findIdentInPackage(Env<AttrContext> env, TypeSymbol pck,
  1199                               Name name, int kind) {
  1200         Name fullname = TypeSymbol.formFullName(name, pck);
  1201         Symbol bestSoFar = typeNotFound;
  1202         PackageSymbol pack = null;
  1203         if ((kind & PCK) != 0) {
  1204             pack = reader.enterPackage(fullname);
  1205             if (pack.exists()) return pack;
  1207         if ((kind & TYP) != 0) {
  1208             Symbol sym = loadClass(env, fullname);
  1209             if (sym.exists()) {
  1210                 // don't allow programs to use flatnames
  1211                 if (name == sym.name) return sym;
  1213             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1215         return (pack != null) ? pack : bestSoFar;
  1218     /** Find an identifier among the members of a given type `site'.
  1219      *  @param env       The current environment.
  1220      *  @param site      The type containing the symbol to be found.
  1221      *  @param name      The identifier's name.
  1222      *  @param kind      Indicates the possible symbol kinds
  1223      *                   (a subset of VAL, TYP).
  1224      */
  1225     Symbol findIdentInType(Env<AttrContext> env, Type site,
  1226                            Name name, int kind) {
  1227         Symbol bestSoFar = typeNotFound;
  1228         Symbol sym;
  1229         if ((kind & VAR) != 0) {
  1230             sym = findField(env, site, name, site.tsym);
  1231             if (sym.exists()) return sym;
  1232             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1235         if ((kind & TYP) != 0) {
  1236             sym = findMemberType(env, site, name, site.tsym);
  1237             if (sym.exists()) return sym;
  1238             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1240         return bestSoFar;
  1243 /* ***************************************************************************
  1244  *  Access checking
  1245  *  The following methods convert ResolveErrors to ErrorSymbols, issuing
  1246  *  an error message in the process
  1247  ****************************************************************************/
  1249     /** If `sym' is a bad symbol: report error and return errSymbol
  1250      *  else pass through unchanged,
  1251      *  additional arguments duplicate what has been used in trying to find the
  1252      *  symbol (--> flyweight pattern). This improves performance since we
  1253      *  expect misses to happen frequently.
  1255      *  @param sym       The symbol that was found, or a ResolveError.
  1256      *  @param pos       The position to use for error reporting.
  1257      *  @param site      The original type from where the selection took place.
  1258      *  @param name      The symbol's name.
  1259      *  @param argtypes  The invocation's value arguments,
  1260      *                   if we looked for a method.
  1261      *  @param typeargtypes  The invocation's type arguments,
  1262      *                   if we looked for a method.
  1263      */
  1264     Symbol access(Symbol sym,
  1265                   DiagnosticPosition pos,
  1266                   Symbol location,
  1267                   Type site,
  1268                   Name name,
  1269                   boolean qualified,
  1270                   List<Type> argtypes,
  1271                   List<Type> typeargtypes) {
  1272         if (sym.kind >= AMBIGUOUS) {
  1273             ResolveError errSym = (ResolveError)sym;
  1274             if (!site.isErroneous() &&
  1275                 !Type.isErroneous(argtypes) &&
  1276                 (typeargtypes==null || !Type.isErroneous(typeargtypes)))
  1277                 logResolveError(errSym, pos, location, site, name, argtypes, typeargtypes);
  1278             sym = errSym.access(name, qualified ? site.tsym : syms.noSymbol);
  1280         return sym;
  1283     /** Same as original access(), but without location.
  1284      */
  1285     Symbol access(Symbol sym,
  1286                   DiagnosticPosition pos,
  1287                   Type site,
  1288                   Name name,
  1289                   boolean qualified,
  1290                   List<Type> argtypes,
  1291                   List<Type> typeargtypes) {
  1292         return access(sym, pos, site.tsym, site, name, qualified, argtypes, typeargtypes);
  1295     /** Same as original access(), but without type arguments and arguments.
  1296      */
  1297     Symbol access(Symbol sym,
  1298                   DiagnosticPosition pos,
  1299                   Symbol location,
  1300                   Type site,
  1301                   Name name,
  1302                   boolean qualified) {
  1303         if (sym.kind >= AMBIGUOUS)
  1304             return access(sym, pos, location, site, name, qualified, List.<Type>nil(), null);
  1305         else
  1306             return sym;
  1309     /** Same as original access(), but without location, type arguments and arguments.
  1310      */
  1311     Symbol access(Symbol sym,
  1312                   DiagnosticPosition pos,
  1313                   Type site,
  1314                   Name name,
  1315                   boolean qualified) {
  1316         return access(sym, pos, site.tsym, site, name, qualified);
  1319     /** Check that sym is not an abstract method.
  1320      */
  1321     void checkNonAbstract(DiagnosticPosition pos, Symbol sym) {
  1322         if ((sym.flags() & ABSTRACT) != 0)
  1323             log.error(pos, "abstract.cant.be.accessed.directly",
  1324                       kindName(sym), sym, sym.location());
  1327 /* ***************************************************************************
  1328  *  Debugging
  1329  ****************************************************************************/
  1331     /** print all scopes starting with scope s and proceeding outwards.
  1332      *  used for debugging.
  1333      */
  1334     public void printscopes(Scope s) {
  1335         while (s != null) {
  1336             if (s.owner != null)
  1337                 System.err.print(s.owner + ": ");
  1338             for (Scope.Entry e = s.elems; e != null; e = e.sibling) {
  1339                 if ((e.sym.flags() & ABSTRACT) != 0)
  1340                     System.err.print("abstract ");
  1341                 System.err.print(e.sym + " ");
  1343             System.err.println();
  1344             s = s.next;
  1348     void printscopes(Env<AttrContext> env) {
  1349         while (env.outer != null) {
  1350             System.err.println("------------------------------");
  1351             printscopes(env.info.scope);
  1352             env = env.outer;
  1356     public void printscopes(Type t) {
  1357         while (t.tag == CLASS) {
  1358             printscopes(t.tsym.members());
  1359             t = types.supertype(t);
  1363 /* ***************************************************************************
  1364  *  Name resolution
  1365  *  Naming conventions are as for symbol lookup
  1366  *  Unlike the find... methods these methods will report access errors
  1367  ****************************************************************************/
  1369     /** Resolve an unqualified (non-method) identifier.
  1370      *  @param pos       The position to use for error reporting.
  1371      *  @param env       The environment current at the identifier use.
  1372      *  @param name      The identifier's name.
  1373      *  @param kind      The set of admissible symbol kinds for the identifier.
  1374      */
  1375     Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env,
  1376                         Name name, int kind) {
  1377         return access(
  1378             findIdent(env, name, kind),
  1379             pos, env.enclClass.sym.type, name, false);
  1382     /** Resolve an unqualified method identifier.
  1383      *  @param pos       The position to use for error reporting.
  1384      *  @param env       The environment current at the method invocation.
  1385      *  @param name      The identifier's name.
  1386      *  @param argtypes  The types of the invocation's value arguments.
  1387      *  @param typeargtypes  The types of the invocation's type arguments.
  1388      */
  1389     Symbol resolveMethod(DiagnosticPosition pos,
  1390                          Env<AttrContext> env,
  1391                          Name name,
  1392                          List<Type> argtypes,
  1393                          List<Type> typeargtypes) {
  1394         Symbol sym = startResolution();
  1395         List<MethodResolutionPhase> steps = methodResolutionSteps;
  1396         while (steps.nonEmpty() &&
  1397                steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  1398                sym.kind >= ERRONEOUS) {
  1399             currentStep = steps.head;
  1400             sym = findFun(env, name, argtypes, typeargtypes,
  1401                     steps.head.isBoxingRequired,
  1402                     env.info.varArgs = steps.head.isVarargsRequired);
  1403             methodResolutionCache.put(steps.head, sym);
  1404             steps = steps.tail;
  1406         if (sym.kind >= AMBIGUOUS) {//if nothing is found return the 'first' error
  1407             MethodResolutionPhase errPhase =
  1408                     firstErroneousResolutionPhase();
  1409             sym = access(methodResolutionCache.get(errPhase),
  1410                     pos, env.enclClass.sym.type, name, false, argtypes, typeargtypes);
  1411             env.info.varArgs = errPhase.isVarargsRequired;
  1413         return sym;
  1416     private Symbol startResolution() {
  1417         wrongMethod.clear();
  1418         wrongMethods.clear();
  1419         return methodNotFound;
  1422     /** Resolve a qualified method identifier
  1423      *  @param pos       The position to use for error reporting.
  1424      *  @param env       The environment current at the method invocation.
  1425      *  @param site      The type of the qualifying expression, in which
  1426      *                   identifier is searched.
  1427      *  @param name      The identifier's name.
  1428      *  @param argtypes  The types of the invocation's value arguments.
  1429      *  @param typeargtypes  The types of the invocation's type arguments.
  1430      */
  1431     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
  1432                                   Type site, Name name, List<Type> argtypes,
  1433                                   List<Type> typeargtypes) {
  1434         return resolveQualifiedMethod(pos, env, site.tsym, site, name, argtypes, typeargtypes);
  1436     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
  1437                                   Symbol location, Type site, Name name, List<Type> argtypes,
  1438                                   List<Type> typeargtypes) {
  1439         Symbol sym = startResolution();
  1440         List<MethodResolutionPhase> steps = methodResolutionSteps;
  1441         while (steps.nonEmpty() &&
  1442                steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  1443                sym.kind >= ERRONEOUS) {
  1444             currentStep = steps.head;
  1445             sym = findMethod(env, site, name, argtypes, typeargtypes,
  1446                     steps.head.isBoxingRequired(),
  1447                     env.info.varArgs = steps.head.isVarargsRequired(), false);
  1448             methodResolutionCache.put(steps.head, sym);
  1449             steps = steps.tail;
  1451         if (sym.kind >= AMBIGUOUS) {
  1452             if (site.tsym.isPolymorphicSignatureGeneric()) {
  1453                 //polymorphic receiver - synthesize new method symbol
  1454                 env.info.varArgs = false;
  1455                 sym = findPolymorphicSignatureInstance(env,
  1456                         site, name, null, argtypes);
  1458             else {
  1459                 //if nothing is found return the 'first' error
  1460                 MethodResolutionPhase errPhase =
  1461                         firstErroneousResolutionPhase();
  1462                 sym = access(methodResolutionCache.get(errPhase),
  1463                         pos, location, site, name, true, argtypes, typeargtypes);
  1464                 env.info.varArgs = errPhase.isVarargsRequired;
  1466         } else if (allowMethodHandles && sym.isPolymorphicSignatureGeneric()) {
  1467             //non-instantiated polymorphic signature - synthesize new method symbol
  1468             env.info.varArgs = false;
  1469             sym = findPolymorphicSignatureInstance(env,
  1470                     site, name, (MethodSymbol)sym, argtypes);
  1472         return sym;
  1475     /** Find or create an implicit method of exactly the given type (after erasure).
  1476      *  Searches in a side table, not the main scope of the site.
  1477      *  This emulates the lookup process required by JSR 292 in JVM.
  1478      *  @param env       Attribution environment
  1479      *  @param site      The original type from where the selection takes place.
  1480      *  @param name      The method's name.
  1481      *  @param spMethod  A template for the implicit method, or null.
  1482      *  @param argtypes  The required argument types.
  1483      *  @param typeargtypes  The required type arguments.
  1484      */
  1485     Symbol findPolymorphicSignatureInstance(Env<AttrContext> env, Type site,
  1486                                             Name name,
  1487                                             MethodSymbol spMethod,  // sig. poly. method or null if none
  1488                                             List<Type> argtypes) {
  1489         Type mtype = infer.instantiatePolymorphicSignatureInstance(env,
  1490                 site, name, spMethod, argtypes);
  1491         long flags = ABSTRACT | HYPOTHETICAL | POLYMORPHIC_SIGNATURE |
  1492                     (spMethod != null ?
  1493                         spMethod.flags() & Flags.AccessFlags :
  1494                         Flags.PUBLIC | Flags.STATIC);
  1495         Symbol m = null;
  1496         for (Scope.Entry e = polymorphicSignatureScope.lookup(name);
  1497              e.scope != null;
  1498              e = e.next()) {
  1499             Symbol sym = e.sym;
  1500             if (types.isSameType(mtype, sym.type) &&
  1501                 (sym.flags() & Flags.STATIC) == (flags & Flags.STATIC) &&
  1502                 types.isSameType(sym.owner.type, site)) {
  1503                m = sym;
  1504                break;
  1507         if (m == null) {
  1508             // create the desired method
  1509             m = new MethodSymbol(flags, name, mtype, site.tsym);
  1510             polymorphicSignatureScope.enter(m);
  1512         return m;
  1515     /** Resolve a qualified method identifier, throw a fatal error if not
  1516      *  found.
  1517      *  @param pos       The position to use for error reporting.
  1518      *  @param env       The environment current at the method invocation.
  1519      *  @param site      The type of the qualifying expression, in which
  1520      *                   identifier is searched.
  1521      *  @param name      The identifier's name.
  1522      *  @param argtypes  The types of the invocation's value arguments.
  1523      *  @param typeargtypes  The types of the invocation's type arguments.
  1524      */
  1525     public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env,
  1526                                         Type site, Name name,
  1527                                         List<Type> argtypes,
  1528                                         List<Type> typeargtypes) {
  1529         Symbol sym = resolveQualifiedMethod(
  1530             pos, env, site.tsym, site, name, argtypes, typeargtypes);
  1531         if (sym.kind == MTH) return (MethodSymbol)sym;
  1532         else throw new FatalError(
  1533                  diags.fragment("fatal.err.cant.locate.meth",
  1534                                 name));
  1537     /** Resolve constructor.
  1538      *  @param pos       The position to use for error reporting.
  1539      *  @param env       The environment current at the constructor invocation.
  1540      *  @param site      The type of class for which a constructor is searched.
  1541      *  @param argtypes  The types of the constructor invocation's value
  1542      *                   arguments.
  1543      *  @param typeargtypes  The types of the constructor invocation's type
  1544      *                   arguments.
  1545      */
  1546     Symbol resolveConstructor(DiagnosticPosition pos,
  1547                               Env<AttrContext> env,
  1548                               Type site,
  1549                               List<Type> argtypes,
  1550                               List<Type> typeargtypes) {
  1551         Symbol sym = startResolution();
  1552         List<MethodResolutionPhase> steps = methodResolutionSteps;
  1553         while (steps.nonEmpty() &&
  1554                steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  1555                sym.kind >= ERRONEOUS) {
  1556             currentStep = steps.head;
  1557             sym = resolveConstructor(pos, env, site, argtypes, typeargtypes,
  1558                     steps.head.isBoxingRequired(),
  1559                     env.info.varArgs = steps.head.isVarargsRequired());
  1560             methodResolutionCache.put(steps.head, sym);
  1561             steps = steps.tail;
  1563         if (sym.kind >= AMBIGUOUS) {//if nothing is found return the 'first' error
  1564             MethodResolutionPhase errPhase = firstErroneousResolutionPhase();
  1565             sym = access(methodResolutionCache.get(errPhase),
  1566                     pos, site, names.init, true, argtypes, typeargtypes);
  1567             env.info.varArgs = errPhase.isVarargsRequired();
  1569         return sym;
  1572     /** Resolve constructor using diamond inference.
  1573      *  @param pos       The position to use for error reporting.
  1574      *  @param env       The environment current at the constructor invocation.
  1575      *  @param site      The type of class for which a constructor is searched.
  1576      *                   The scope of this class has been touched in attribution.
  1577      *  @param argtypes  The types of the constructor invocation's value
  1578      *                   arguments.
  1579      *  @param typeargtypes  The types of the constructor invocation's type
  1580      *                   arguments.
  1581      */
  1582     Symbol resolveDiamond(DiagnosticPosition pos,
  1583                               Env<AttrContext> env,
  1584                               Type site,
  1585                               List<Type> argtypes,
  1586                               List<Type> typeargtypes) {
  1587         Symbol sym = startResolution();
  1588         List<MethodResolutionPhase> steps = methodResolutionSteps;
  1589         while (steps.nonEmpty() &&
  1590                steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  1591                sym.kind >= ERRONEOUS) {
  1592             currentStep = steps.head;
  1593             sym = resolveConstructor(pos, env, site, argtypes, typeargtypes,
  1594                     steps.head.isBoxingRequired(),
  1595                     env.info.varArgs = steps.head.isVarargsRequired());
  1596             methodResolutionCache.put(steps.head, sym);
  1597             steps = steps.tail;
  1599         if (sym.kind >= AMBIGUOUS) {
  1600             final JCDiagnostic details = sym.kind == WRONG_MTH ?
  1601                 ((InapplicableSymbolError)sym).explanation :
  1602                 null;
  1603             Symbol errSym = new ResolveError(WRONG_MTH, "diamond error") {
  1604                 @Override
  1605                 JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos,
  1606                         Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
  1607                     String key = details == null ?
  1608                         "cant.apply.diamond" :
  1609                         "cant.apply.diamond.1";
  1610                     return diags.create(dkind, log.currentSource(), pos, key,
  1611                             diags.fragment("diamond", site.tsym), details);
  1613             };
  1614             MethodResolutionPhase errPhase = firstErroneousResolutionPhase();
  1615             sym = access(errSym, pos, site, names.init, true, argtypes, typeargtypes);
  1616             env.info.varArgs = errPhase.isVarargsRequired();
  1618         return sym;
  1621     /** Resolve constructor.
  1622      *  @param pos       The position to use for error reporting.
  1623      *  @param env       The environment current at the constructor invocation.
  1624      *  @param site      The type of class for which a constructor is searched.
  1625      *  @param argtypes  The types of the constructor invocation's value
  1626      *                   arguments.
  1627      *  @param typeargtypes  The types of the constructor invocation's type
  1628      *                   arguments.
  1629      *  @param allowBoxing Allow boxing and varargs conversions.
  1630      *  @param useVarargs Box trailing arguments into an array for varargs.
  1631      */
  1632     Symbol resolveConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  1633                               Type site, List<Type> argtypes,
  1634                               List<Type> typeargtypes,
  1635                               boolean allowBoxing,
  1636                               boolean useVarargs) {
  1637         Symbol sym = findMethod(env, site,
  1638                                 names.init, argtypes,
  1639                                 typeargtypes, allowBoxing,
  1640                                 useVarargs, false);
  1641         chk.checkDeprecated(pos, env.info.scope.owner, sym);
  1642         return sym;
  1645     /** Resolve a constructor, throw a fatal error if not found.
  1646      *  @param pos       The position to use for error reporting.
  1647      *  @param env       The environment current at the method invocation.
  1648      *  @param site      The type to be constructed.
  1649      *  @param argtypes  The types of the invocation's value arguments.
  1650      *  @param typeargtypes  The types of the invocation's type arguments.
  1651      */
  1652     public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  1653                                         Type site,
  1654                                         List<Type> argtypes,
  1655                                         List<Type> typeargtypes) {
  1656         Symbol sym = resolveConstructor(
  1657             pos, env, site, argtypes, typeargtypes);
  1658         if (sym.kind == MTH) return (MethodSymbol)sym;
  1659         else throw new FatalError(
  1660                  diags.fragment("fatal.err.cant.locate.ctor", site));
  1663     /** Resolve operator.
  1664      *  @param pos       The position to use for error reporting.
  1665      *  @param optag     The tag of the operation tree.
  1666      *  @param env       The environment current at the operation.
  1667      *  @param argtypes  The types of the operands.
  1668      */
  1669     Symbol resolveOperator(DiagnosticPosition pos, int optag,
  1670                            Env<AttrContext> env, List<Type> argtypes) {
  1671         Name name = treeinfo.operatorName(optag);
  1672         Symbol sym = findMethod(env, syms.predefClass.type, name, argtypes,
  1673                                 null, false, false, true);
  1674         if (boxingEnabled && sym.kind >= WRONG_MTHS)
  1675             sym = findMethod(env, syms.predefClass.type, name, argtypes,
  1676                              null, true, false, true);
  1677         return access(sym, pos, env.enclClass.sym.type, name,
  1678                       false, argtypes, null);
  1681     /** Resolve operator.
  1682      *  @param pos       The position to use for error reporting.
  1683      *  @param optag     The tag of the operation tree.
  1684      *  @param env       The environment current at the operation.
  1685      *  @param arg       The type of the operand.
  1686      */
  1687     Symbol resolveUnaryOperator(DiagnosticPosition pos, int optag, Env<AttrContext> env, Type arg) {
  1688         return resolveOperator(pos, optag, env, List.of(arg));
  1691     /** Resolve binary operator.
  1692      *  @param pos       The position to use for error reporting.
  1693      *  @param optag     The tag of the operation tree.
  1694      *  @param env       The environment current at the operation.
  1695      *  @param left      The types of the left operand.
  1696      *  @param right     The types of the right operand.
  1697      */
  1698     Symbol resolveBinaryOperator(DiagnosticPosition pos,
  1699                                  int optag,
  1700                                  Env<AttrContext> env,
  1701                                  Type left,
  1702                                  Type right) {
  1703         return resolveOperator(pos, optag, env, List.of(left, right));
  1706     /**
  1707      * Resolve `c.name' where name == this or name == super.
  1708      * @param pos           The position to use for error reporting.
  1709      * @param env           The environment current at the expression.
  1710      * @param c             The qualifier.
  1711      * @param name          The identifier's name.
  1712      */
  1713     Symbol resolveSelf(DiagnosticPosition pos,
  1714                        Env<AttrContext> env,
  1715                        TypeSymbol c,
  1716                        Name name) {
  1717         Env<AttrContext> env1 = env;
  1718         boolean staticOnly = false;
  1719         while (env1.outer != null) {
  1720             if (isStatic(env1)) staticOnly = true;
  1721             if (env1.enclClass.sym == c) {
  1722                 Symbol sym = env1.info.scope.lookup(name).sym;
  1723                 if (sym != null) {
  1724                     if (staticOnly) sym = new StaticError(sym);
  1725                     return access(sym, pos, env.enclClass.sym.type,
  1726                                   name, true);
  1729             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  1730             env1 = env1.outer;
  1732         log.error(pos, "not.encl.class", c);
  1733         return syms.errSymbol;
  1736     /**
  1737      * Resolve `c.this' for an enclosing class c that contains the
  1738      * named member.
  1739      * @param pos           The position to use for error reporting.
  1740      * @param env           The environment current at the expression.
  1741      * @param member        The member that must be contained in the result.
  1742      */
  1743     Symbol resolveSelfContaining(DiagnosticPosition pos,
  1744                                  Env<AttrContext> env,
  1745                                  Symbol member) {
  1746         Name name = names._this;
  1747         Env<AttrContext> env1 = env;
  1748         boolean staticOnly = false;
  1749         while (env1.outer != null) {
  1750             if (isStatic(env1)) staticOnly = true;
  1751             if (env1.enclClass.sym.isSubClass(member.owner, types) &&
  1752                 isAccessible(env, env1.enclClass.sym.type, member)) {
  1753                 Symbol sym = env1.info.scope.lookup(name).sym;
  1754                 if (sym != null) {
  1755                     if (staticOnly) sym = new StaticError(sym);
  1756                     return access(sym, pos, env.enclClass.sym.type,
  1757                                   name, true);
  1760             if ((env1.enclClass.sym.flags() & STATIC) != 0)
  1761                 staticOnly = true;
  1762             env1 = env1.outer;
  1764         log.error(pos, "encl.class.required", member);
  1765         return syms.errSymbol;
  1768     /**
  1769      * Resolve an appropriate implicit this instance for t's container.
  1770      * JLS2 8.8.5.1 and 15.9.2
  1771      */
  1772     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
  1773         Type thisType = (((t.tsym.owner.kind & (MTH|VAR)) != 0)
  1774                          ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
  1775                          : resolveSelfContaining(pos, env, t.tsym)).type;
  1776         if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
  1777             log.error(pos, "cant.ref.before.ctor.called", "this");
  1778         return thisType;
  1781 /* ***************************************************************************
  1782  *  ResolveError classes, indicating error situations when accessing symbols
  1783  ****************************************************************************/
  1785     public void logAccessError(Env<AttrContext> env, JCTree tree, Type type) {
  1786         AccessError error = new AccessError(env, type.getEnclosingType(), type.tsym);
  1787         logResolveError(error, tree.pos(), type.getEnclosingType().tsym, type.getEnclosingType(), null, null, null);
  1789     //where
  1790     private void logResolveError(ResolveError error,
  1791             DiagnosticPosition pos,
  1792             Symbol location,
  1793             Type site,
  1794             Name name,
  1795             List<Type> argtypes,
  1796             List<Type> typeargtypes) {
  1797         JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
  1798                 pos, location, site, name, argtypes, typeargtypes);
  1799         if (d != null) {
  1800             d.setFlag(DiagnosticFlag.RESOLVE_ERROR);
  1801             log.report(d);
  1805     private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
  1807     public Object methodArguments(List<Type> argtypes) {
  1808         return argtypes.isEmpty() ? noArgs : argtypes;
  1811     /**
  1812      * Root class for resolution errors. Subclass of ResolveError
  1813      * represent a different kinds of resolution error - as such they must
  1814      * specify how they map into concrete compiler diagnostics.
  1815      */
  1816     private abstract class ResolveError extends Symbol {
  1818         /** The name of the kind of error, for debugging only. */
  1819         final String debugName;
  1821         ResolveError(int kind, String debugName) {
  1822             super(kind, 0, null, null, null);
  1823             this.debugName = debugName;
  1826         @Override
  1827         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
  1828             throw new AssertionError();
  1831         @Override
  1832         public String toString() {
  1833             return debugName;
  1836         @Override
  1837         public boolean exists() {
  1838             return false;
  1841         /**
  1842          * Create an external representation for this erroneous symbol to be
  1843          * used during attribution - by default this returns the symbol of a
  1844          * brand new error type which stores the original type found
  1845          * during resolution.
  1847          * @param name     the name used during resolution
  1848          * @param location the location from which the symbol is accessed
  1849          */
  1850         protected Symbol access(Name name, TypeSymbol location) {
  1851             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  1854         /**
  1855          * Create a diagnostic representing this resolution error.
  1857          * @param dkind     The kind of the diagnostic to be created (e.g error).
  1858          * @param pos       The position to be used for error reporting.
  1859          * @param site      The original type from where the selection took place.
  1860          * @param name      The name of the symbol to be resolved.
  1861          * @param argtypes  The invocation's value arguments,
  1862          *                  if we looked for a method.
  1863          * @param typeargtypes  The invocation's type arguments,
  1864          *                      if we looked for a method.
  1865          */
  1866         abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  1867                 DiagnosticPosition pos,
  1868                 Symbol location,
  1869                 Type site,
  1870                 Name name,
  1871                 List<Type> argtypes,
  1872                 List<Type> typeargtypes);
  1874         /**
  1875          * A name designates an operator if it consists
  1876          * of a non-empty sequence of operator symbols +-~!/*%&|^<>=
  1877          */
  1878         boolean isOperator(Name name) {
  1879             int i = 0;
  1880             while (i < name.getByteLength() &&
  1881                    "+-~!*/%&|^<>=".indexOf(name.getByteAt(i)) >= 0) i++;
  1882             return i > 0 && i == name.getByteLength();
  1886     /**
  1887      * This class is the root class of all resolution errors caused by
  1888      * an invalid symbol being found during resolution.
  1889      */
  1890     abstract class InvalidSymbolError extends ResolveError {
  1892         /** The invalid symbol found during resolution */
  1893         Symbol sym;
  1895         InvalidSymbolError(int kind, Symbol sym, String debugName) {
  1896             super(kind, debugName);
  1897             this.sym = sym;
  1900         @Override
  1901         public boolean exists() {
  1902             return true;
  1905         @Override
  1906         public String toString() {
  1907              return super.toString() + " wrongSym=" + sym;
  1910         @Override
  1911         public Symbol access(Name name, TypeSymbol location) {
  1912             if (sym.kind >= AMBIGUOUS)
  1913                 return ((ResolveError)sym).access(name, location);
  1914             else if ((sym.kind & ERRONEOUS) == 0 && (sym.kind & TYP) != 0)
  1915                 return types.createErrorType(name, location, sym.type).tsym;
  1916             else
  1917                 return sym;
  1921     /**
  1922      * InvalidSymbolError error class indicating that a symbol matching a
  1923      * given name does not exists in a given site.
  1924      */
  1925     class SymbolNotFoundError extends ResolveError {
  1927         SymbolNotFoundError(int kind) {
  1928             super(kind, "symbol not found error");
  1931         @Override
  1932         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  1933                 DiagnosticPosition pos,
  1934                 Symbol location,
  1935                 Type site,
  1936                 Name name,
  1937                 List<Type> argtypes,
  1938                 List<Type> typeargtypes) {
  1939             argtypes = argtypes == null ? List.<Type>nil() : argtypes;
  1940             typeargtypes = typeargtypes == null ? List.<Type>nil() : typeargtypes;
  1941             if (name == names.error)
  1942                 return null;
  1944             if (isOperator(name)) {
  1945                 boolean isUnaryOp = argtypes.size() == 1;
  1946                 String key = argtypes.size() == 1 ?
  1947                     "operator.cant.be.applied" :
  1948                     "operator.cant.be.applied.1";
  1949                 Type first = argtypes.head;
  1950                 Type second = !isUnaryOp ? argtypes.tail.head : null;
  1951                 return diags.create(dkind, log.currentSource(), pos,
  1952                         key, name, first, second);
  1954             boolean hasLocation = false;
  1955             if (!location.name.isEmpty()) {
  1956                 if (location.kind == PCK && !site.tsym.exists()) {
  1957                     return diags.create(dkind, log.currentSource(), pos,
  1958                         "doesnt.exist", location);
  1960                 hasLocation = !location.name.equals(names._this) &&
  1961                         !location.name.equals(names._super);
  1963             boolean isConstructor = kind == ABSENT_MTH &&
  1964                     name == names.table.names.init;
  1965             KindName kindname = isConstructor ? KindName.CONSTRUCTOR : absentKind(kind);
  1966             Name idname = isConstructor ? site.tsym.name : name;
  1967             String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation);
  1968             if (hasLocation) {
  1969                 return diags.create(dkind, log.currentSource(), pos,
  1970                         errKey, kindname, idname, //symbol kindname, name
  1971                         typeargtypes, argtypes, //type parameters and arguments (if any)
  1972                         getLocationDiag(location)); //location kindname, type
  1974             else {
  1975                 return diags.create(dkind, log.currentSource(), pos,
  1976                         errKey, kindname, idname, //symbol kindname, name
  1977                         typeargtypes, argtypes); //type parameters and arguments (if any)
  1980         //where
  1981         private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) {
  1982             String key = "cant.resolve";
  1983             String suffix = hasLocation ? ".location" : "";
  1984             switch (kindname) {
  1985                 case METHOD:
  1986                 case CONSTRUCTOR: {
  1987                     suffix += ".args";
  1988                     suffix += hasTypeArgs ? ".params" : "";
  1991             return key + suffix;
  1993         private JCDiagnostic getLocationDiag(Symbol location) {
  1994             boolean isVar = location.kind == VAR;
  1995             String key = isVar ?
  1996                 "location.1" :
  1997                 "location";
  1998             return diags.fragment(key,
  1999                     kindName(location),
  2000                     location,
  2001                     isVar ? location.type : null);
  2005     /**
  2006      * InvalidSymbolError error class indicating that a given symbol
  2007      * (either a method, a constructor or an operand) is not applicable
  2008      * given an actual arguments/type argument list.
  2009      */
  2010     class InapplicableSymbolError extends InvalidSymbolError {
  2012         /** An auxiliary explanation set in case of instantiation errors. */
  2013         JCDiagnostic explanation;
  2015         InapplicableSymbolError(Symbol sym) {
  2016             super(WRONG_MTH, sym, "inapplicable symbol error");
  2019         /** Update sym and explanation and return this.
  2020          */
  2021         InapplicableSymbolError setWrongSym(Symbol sym, JCDiagnostic explanation) {
  2022             this.sym = sym;
  2023             if (this.sym == sym && explanation != null)
  2024                 this.explanation = explanation; //update the details
  2025             return this;
  2028         /** Update sym and return this.
  2029          */
  2030         InapplicableSymbolError setWrongSym(Symbol sym) {
  2031             this.sym = sym;
  2032             return this;
  2035         @Override
  2036         public String toString() {
  2037             return super.toString() + " explanation=" + explanation;
  2040         @Override
  2041         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2042                 DiagnosticPosition pos,
  2043                 Symbol location,
  2044                 Type site,
  2045                 Name name,
  2046                 List<Type> argtypes,
  2047                 List<Type> typeargtypes) {
  2048             if (name == names.error)
  2049                 return null;
  2051             if (isOperator(name)) {
  2052                 boolean isUnaryOp = argtypes.size() == 1;
  2053                 String key = argtypes.size() == 1 ?
  2054                     "operator.cant.be.applied" :
  2055                     "operator.cant.be.applied.1";
  2056                 Type first = argtypes.head;
  2057                 Type second = !isUnaryOp ? argtypes.tail.head : null;
  2058                 return diags.create(dkind, log.currentSource(), pos,
  2059                         key, name, first, second);
  2061             else {
  2062                 Symbol ws = sym.asMemberOf(site, types);
  2063                 return diags.create(dkind, log.currentSource(), pos,
  2064                           "cant.apply.symbol" + (explanation != null ? ".1" : ""),
  2065                           kindName(ws),
  2066                           ws.name == names.init ? ws.owner.name : ws.name,
  2067                           methodArguments(ws.type.getParameterTypes()),
  2068                           methodArguments(argtypes),
  2069                           kindName(ws.owner),
  2070                           ws.owner.type,
  2071                           explanation);
  2075         void clear() {
  2076             explanation = null;
  2079         @Override
  2080         public Symbol access(Name name, TypeSymbol location) {
  2081             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  2085     /**
  2086      * ResolveError error class indicating that a set of symbols
  2087      * (either methods, constructors or operands) is not applicable
  2088      * given an actual arguments/type argument list.
  2089      */
  2090     class InapplicableSymbolsError extends ResolveError {
  2092         private List<Candidate> candidates = List.nil();
  2094         InapplicableSymbolsError(Symbol sym) {
  2095             super(WRONG_MTHS, "inapplicable symbols");
  2098         @Override
  2099         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2100                 DiagnosticPosition pos,
  2101                 Symbol location,
  2102                 Type site,
  2103                 Name name,
  2104                 List<Type> argtypes,
  2105                 List<Type> typeargtypes) {
  2106             if (candidates.nonEmpty()) {
  2107                 JCDiagnostic err = diags.create(dkind,
  2108                         log.currentSource(),
  2109                         pos,
  2110                         "cant.apply.symbols",
  2111                         name == names.init ? KindName.CONSTRUCTOR : absentKind(kind),
  2112                         getName(),
  2113                         argtypes);
  2114                 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(site));
  2115             } else {
  2116                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
  2117                     location, site, name, argtypes, typeargtypes);
  2121         //where
  2122         List<JCDiagnostic> candidateDetails(Type site) {
  2123             List<JCDiagnostic> details = List.nil();
  2124             for (Candidate c : candidates)
  2125                 details = details.prepend(c.getDiagnostic(site));
  2126             return details.reverse();
  2129         Symbol addCandidate(MethodResolutionPhase currentStep, Symbol sym, JCDiagnostic details) {
  2130             Candidate c = new Candidate(currentStep, sym, details);
  2131             if (c.isValid() && !candidates.contains(c))
  2132                 candidates = candidates.append(c);
  2133             return this;
  2136         void clear() {
  2137             candidates = List.nil();
  2140         private Name getName() {
  2141             Symbol sym = candidates.head.sym;
  2142             return sym.name == names.init ?
  2143                 sym.owner.name :
  2144                 sym.name;
  2147         private class Candidate {
  2149             final MethodResolutionPhase step;
  2150             final Symbol sym;
  2151             final JCDiagnostic details;
  2153             private Candidate(MethodResolutionPhase step, Symbol sym, JCDiagnostic details) {
  2154                 this.step = step;
  2155                 this.sym = sym;
  2156                 this.details = details;
  2159             JCDiagnostic getDiagnostic(Type site) {
  2160                 return diags.fragment("inapplicable.method",
  2161                         Kinds.kindName(sym),
  2162                         sym.location(site, types),
  2163                         sym.asMemberOf(site, types),
  2164                         details);
  2167             @Override
  2168             public boolean equals(Object o) {
  2169                 if (o instanceof Candidate) {
  2170                     Symbol s1 = this.sym;
  2171                     Symbol s2 = ((Candidate)o).sym;
  2172                     if  ((s1 != s2 &&
  2173                         (s1.overrides(s2, s1.owner.type.tsym, types, false) ||
  2174                         (s2.overrides(s1, s2.owner.type.tsym, types, false)))) ||
  2175                         ((s1.isConstructor() || s2.isConstructor()) && s1.owner != s2.owner))
  2176                         return true;
  2178                 return false;
  2181             boolean isValid() {
  2182                 return  (((sym.flags() & VARARGS) != 0 && step == VARARITY) ||
  2183                           (sym.flags() & VARARGS) == 0 && step == (boxingEnabled ? BOX : BASIC));
  2188     /**
  2189      * An InvalidSymbolError error class indicating that a symbol is not
  2190      * accessible from a given site
  2191      */
  2192     class AccessError extends InvalidSymbolError {
  2194         private Env<AttrContext> env;
  2195         private Type site;
  2197         AccessError(Symbol sym) {
  2198             this(null, null, sym);
  2201         AccessError(Env<AttrContext> env, Type site, Symbol sym) {
  2202             super(HIDDEN, sym, "access error");
  2203             this.env = env;
  2204             this.site = site;
  2205             if (debugResolve)
  2206                 log.error("proc.messager", sym + " @ " + site + " is inaccessible.");
  2209         @Override
  2210         public boolean exists() {
  2211             return false;
  2214         @Override
  2215         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2216                 DiagnosticPosition pos,
  2217                 Symbol location,
  2218                 Type site,
  2219                 Name name,
  2220                 List<Type> argtypes,
  2221                 List<Type> typeargtypes) {
  2222             if (sym.owner.type.tag == ERROR)
  2223                 return null;
  2225             if (sym.name == names.init && sym.owner != site.tsym) {
  2226                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
  2227                         pos, location, site, name, argtypes, typeargtypes);
  2229             else if ((sym.flags() & PUBLIC) != 0
  2230                 || (env != null && this.site != null
  2231                     && !isAccessible(env, this.site))) {
  2232                 return diags.create(dkind, log.currentSource(),
  2233                         pos, "not.def.access.class.intf.cant.access",
  2234                     sym, sym.location());
  2236             else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) {
  2237                 return diags.create(dkind, log.currentSource(),
  2238                         pos, "report.access", sym,
  2239                         asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
  2240                         sym.location());
  2242             else {
  2243                 return diags.create(dkind, log.currentSource(),
  2244                         pos, "not.def.public.cant.access", sym, sym.location());
  2249     /**
  2250      * InvalidSymbolError error class indicating that an instance member
  2251      * has erroneously been accessed from a static context.
  2252      */
  2253     class StaticError extends InvalidSymbolError {
  2255         StaticError(Symbol sym) {
  2256             super(STATICERR, sym, "static error");
  2259         @Override
  2260         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2261                 DiagnosticPosition pos,
  2262                 Symbol location,
  2263                 Type site,
  2264                 Name name,
  2265                 List<Type> argtypes,
  2266                 List<Type> typeargtypes) {
  2267             Symbol errSym = ((sym.kind == TYP && sym.type.tag == CLASS)
  2268                 ? types.erasure(sym.type).tsym
  2269                 : sym);
  2270             return diags.create(dkind, log.currentSource(), pos,
  2271                     "non-static.cant.be.ref", kindName(sym), errSym);
  2275     /**
  2276      * InvalidSymbolError error class indicating that a pair of symbols
  2277      * (either methods, constructors or operands) are ambiguous
  2278      * given an actual arguments/type argument list.
  2279      */
  2280     class AmbiguityError extends InvalidSymbolError {
  2282         /** The other maximally specific symbol */
  2283         Symbol sym2;
  2285         AmbiguityError(Symbol sym1, Symbol sym2) {
  2286             super(AMBIGUOUS, sym1, "ambiguity error");
  2287             this.sym2 = sym2;
  2290         @Override
  2291         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2292                 DiagnosticPosition pos,
  2293                 Symbol location,
  2294                 Type site,
  2295                 Name name,
  2296                 List<Type> argtypes,
  2297                 List<Type> typeargtypes) {
  2298             AmbiguityError pair = this;
  2299             while (true) {
  2300                 if (pair.sym.kind == AMBIGUOUS)
  2301                     pair = (AmbiguityError)pair.sym;
  2302                 else if (pair.sym2.kind == AMBIGUOUS)
  2303                     pair = (AmbiguityError)pair.sym2;
  2304                 else break;
  2306             Name sname = pair.sym.name;
  2307             if (sname == names.init) sname = pair.sym.owner.name;
  2308             return diags.create(dkind, log.currentSource(),
  2309                       pos, "ref.ambiguous", sname,
  2310                       kindName(pair.sym),
  2311                       pair.sym,
  2312                       pair.sym.location(site, types),
  2313                       kindName(pair.sym2),
  2314                       pair.sym2,
  2315                       pair.sym2.location(site, types));
  2319     enum MethodResolutionPhase {
  2320         BASIC(false, false),
  2321         BOX(true, false),
  2322         VARARITY(true, true);
  2324         boolean isBoxingRequired;
  2325         boolean isVarargsRequired;
  2327         MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) {
  2328            this.isBoxingRequired = isBoxingRequired;
  2329            this.isVarargsRequired = isVarargsRequired;
  2332         public boolean isBoxingRequired() {
  2333             return isBoxingRequired;
  2336         public boolean isVarargsRequired() {
  2337             return isVarargsRequired;
  2340         public boolean isApplicable(boolean boxingEnabled, boolean varargsEnabled) {
  2341             return (varargsEnabled || !isVarargsRequired) &&
  2342                    (boxingEnabled || !isBoxingRequired);
  2346     private Map<MethodResolutionPhase, Symbol> methodResolutionCache =
  2347         new HashMap<MethodResolutionPhase, Symbol>(MethodResolutionPhase.values().length);
  2349     final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
  2351     private MethodResolutionPhase currentStep = null;
  2353     private MethodResolutionPhase firstErroneousResolutionPhase() {
  2354         MethodResolutionPhase bestSoFar = BASIC;
  2355         Symbol sym = methodNotFound;
  2356         List<MethodResolutionPhase> steps = methodResolutionSteps;
  2357         while (steps.nonEmpty() &&
  2358                steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  2359                sym.kind >= WRONG_MTHS) {
  2360             sym = methodResolutionCache.get(steps.head);
  2361             bestSoFar = steps.head;
  2362             steps = steps.tail;
  2364         return bestSoFar;

mercurial