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

Wed, 27 Jul 2011 19:00:53 +0100

author
mcimadamore
date
Wed, 27 Jul 2011 19:00:53 +0100
changeset 1059
0b5beb9562c6
parent 1006
a2d422d480cb
child 1110
366c233eb838
permissions
-rw-r--r--

7062745: Regression: difference in overload resolution when two methods are maximally specific
Summary: Fix most specific when two methods are maximally specific and only one has non-raw return type
Reviewed-by: jjg, dlsmith

     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.Set;
    49 import java.util.HashMap;
    50 import java.util.HashSet;
    52 /** Helper class for name resolution, used mostly by the attribution phase.
    53  *
    54  *  <p><b>This is NOT part of any supported API.
    55  *  If you write code that depends on this, you do so at your own risk.
    56  *  This code and its internal interfaces are subject to change or
    57  *  deletion without notice.</b>
    58  */
    59 public class Resolve {
    60     protected static final Context.Key<Resolve> resolveKey =
    61         new Context.Key<Resolve>();
    63     Names names;
    64     Log log;
    65     Symtab syms;
    66     Check chk;
    67     Infer infer;
    68     ClassReader reader;
    69     TreeInfo treeinfo;
    70     Types types;
    71     JCDiagnostic.Factory diags;
    72     public final boolean boxingEnabled; // = source.allowBoxing();
    73     public final boolean varargsEnabled; // = source.allowVarargs();
    74     public final boolean allowMethodHandles;
    75     private final boolean debugResolve;
    77     Scope polymorphicSignatureScope;
    79     public static Resolve instance(Context context) {
    80         Resolve instance = context.get(resolveKey);
    81         if (instance == null)
    82             instance = new Resolve(context);
    83         return instance;
    84     }
    86     protected Resolve(Context context) {
    87         context.put(resolveKey, this);
    88         syms = Symtab.instance(context);
    90         varNotFound = new
    91             SymbolNotFoundError(ABSENT_VAR);
    92         wrongMethod = new
    93             InapplicableSymbolError(syms.errSymbol);
    94         wrongMethods = new
    95             InapplicableSymbolsError(syms.errSymbol);
    96         methodNotFound = new
    97             SymbolNotFoundError(ABSENT_MTH);
    98         typeNotFound = new
    99             SymbolNotFoundError(ABSENT_TYP);
   101         names = Names.instance(context);
   102         log = Log.instance(context);
   103         chk = Check.instance(context);
   104         infer = Infer.instance(context);
   105         reader = ClassReader.instance(context);
   106         treeinfo = TreeInfo.instance(context);
   107         types = Types.instance(context);
   108         diags = JCDiagnostic.Factory.instance(context);
   109         Source source = Source.instance(context);
   110         boxingEnabled = source.allowBoxing();
   111         varargsEnabled = source.allowVarargs();
   112         Options options = Options.instance(context);
   113         debugResolve = options.isSet("debugresolve");
   114         Target target = Target.instance(context);
   115         allowMethodHandles = target.hasMethodHandles();
   116         polymorphicSignatureScope = new Scope(syms.noSymbol);
   118         inapplicableMethodException = new InapplicableMethodException(diags);
   119     }
   121     /** error symbols, which are returned when resolution fails
   122      */
   123     final SymbolNotFoundError varNotFound;
   124     final InapplicableSymbolError wrongMethod;
   125     final InapplicableSymbolsError wrongMethods;
   126     final SymbolNotFoundError methodNotFound;
   127     final SymbolNotFoundError typeNotFound;
   129 /* ************************************************************************
   130  * Identifier resolution
   131  *************************************************************************/
   133     /** An environment is "static" if its static level is greater than
   134      *  the one of its outer environment
   135      */
   136     static boolean isStatic(Env<AttrContext> env) {
   137         return env.info.staticLevel > env.outer.info.staticLevel;
   138     }
   140     /** An environment is an "initializer" if it is a constructor or
   141      *  an instance initializer.
   142      */
   143     static boolean isInitializer(Env<AttrContext> env) {
   144         Symbol owner = env.info.scope.owner;
   145         return owner.isConstructor() ||
   146             owner.owner.kind == TYP &&
   147             (owner.kind == VAR ||
   148              owner.kind == MTH && (owner.flags() & BLOCK) != 0) &&
   149             (owner.flags() & STATIC) == 0;
   150     }
   152     /** Is class accessible in given evironment?
   153      *  @param env    The current environment.
   154      *  @param c      The class whose accessibility is checked.
   155      */
   156     public boolean isAccessible(Env<AttrContext> env, TypeSymbol c) {
   157         return isAccessible(env, c, false);
   158     }
   160     public boolean isAccessible(Env<AttrContext> env, TypeSymbol c, boolean checkInner) {
   161         boolean isAccessible = false;
   162         switch ((short)(c.flags() & AccessFlags)) {
   163             case PRIVATE:
   164                 isAccessible =
   165                     env.enclClass.sym.outermostClass() ==
   166                     c.owner.outermostClass();
   167                 break;
   168             case 0:
   169                 isAccessible =
   170                     env.toplevel.packge == c.owner // fast special case
   171                     ||
   172                     env.toplevel.packge == c.packge()
   173                     ||
   174                     // Hack: this case is added since synthesized default constructors
   175                     // of anonymous classes should be allowed to access
   176                     // classes which would be inaccessible otherwise.
   177                     env.enclMethod != null &&
   178                     (env.enclMethod.mods.flags & ANONCONSTR) != 0;
   179                 break;
   180             default: // error recovery
   181             case PUBLIC:
   182                 isAccessible = true;
   183                 break;
   184             case PROTECTED:
   185                 isAccessible =
   186                     env.toplevel.packge == c.owner // fast special case
   187                     ||
   188                     env.toplevel.packge == c.packge()
   189                     ||
   190                     isInnerSubClass(env.enclClass.sym, c.owner);
   191                 break;
   192         }
   193         return (checkInner == false || c.type.getEnclosingType() == Type.noType) ?
   194             isAccessible :
   195             isAccessible && isAccessible(env, c.type.getEnclosingType(), checkInner);
   196     }
   197     //where
   198         /** Is given class a subclass of given base class, or an inner class
   199          *  of a subclass?
   200          *  Return null if no such class exists.
   201          *  @param c     The class which is the subclass or is contained in it.
   202          *  @param base  The base class
   203          */
   204         private boolean isInnerSubClass(ClassSymbol c, Symbol base) {
   205             while (c != null && !c.isSubClass(base, types)) {
   206                 c = c.owner.enclClass();
   207             }
   208             return c != null;
   209         }
   211     boolean isAccessible(Env<AttrContext> env, Type t) {
   212         return isAccessible(env, t, false);
   213     }
   215     boolean isAccessible(Env<AttrContext> env, Type t, boolean checkInner) {
   216         return (t.tag == ARRAY)
   217             ? isAccessible(env, types.elemtype(t))
   218             : isAccessible(env, t.tsym, checkInner);
   219     }
   221     /** Is symbol accessible as a member of given type in given evironment?
   222      *  @param env    The current environment.
   223      *  @param site   The type of which the tested symbol is regarded
   224      *                as a member.
   225      *  @param sym    The symbol.
   226      */
   227     public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym) {
   228         return isAccessible(env, site, sym, false);
   229     }
   230     public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym, boolean checkInner) {
   231         if (sym.name == names.init && sym.owner != site.tsym) return false;
   232         switch ((short)(sym.flags() & AccessFlags)) {
   233         case PRIVATE:
   234             return
   235                 (env.enclClass.sym == sym.owner // fast special case
   236                  ||
   237                  env.enclClass.sym.outermostClass() ==
   238                  sym.owner.outermostClass())
   239                 &&
   240                 sym.isInheritedIn(site.tsym, types);
   241         case 0:
   242             return
   243                 (env.toplevel.packge == sym.owner.owner // fast special case
   244                  ||
   245                  env.toplevel.packge == sym.packge())
   246                 &&
   247                 isAccessible(env, site, checkInner)
   248                 &&
   249                 sym.isInheritedIn(site.tsym, types)
   250                 &&
   251                 notOverriddenIn(site, sym);
   252         case PROTECTED:
   253             return
   254                 (env.toplevel.packge == sym.owner.owner // fast special case
   255                  ||
   256                  env.toplevel.packge == sym.packge()
   257                  ||
   258                  isProtectedAccessible(sym, env.enclClass.sym, site)
   259                  ||
   260                  // OK to select instance method or field from 'super' or type name
   261                  // (but type names should be disallowed elsewhere!)
   262                  env.info.selectSuper && (sym.flags() & STATIC) == 0 && sym.kind != TYP)
   263                 &&
   264                 isAccessible(env, site, checkInner)
   265                 &&
   266                 notOverriddenIn(site, sym);
   267         default: // this case includes erroneous combinations as well
   268             return isAccessible(env, site, checkInner) && notOverriddenIn(site, sym);
   269         }
   270     }
   271     //where
   272     /* `sym' is accessible only if not overridden by
   273      * another symbol which is a member of `site'
   274      * (because, if it is overridden, `sym' is not strictly
   275      * speaking a member of `site'). A polymorphic signature method
   276      * cannot be overridden (e.g. MH.invokeExact(Object[])).
   277      */
   278     private boolean notOverriddenIn(Type site, Symbol sym) {
   279         if (sym.kind != MTH || sym.isConstructor() || sym.isStatic())
   280             return true;
   281         else {
   282             Symbol s2 = ((MethodSymbol)sym).implementation(site.tsym, types, true);
   283             return (s2 == null || s2 == sym || sym.owner == s2.owner ||
   284                     s2.isPolymorphicSignatureGeneric() ||
   285                     !types.isSubSignature(types.memberType(site, s2), types.memberType(site, sym)));
   286         }
   287     }
   288     //where
   289         /** Is given protected symbol accessible if it is selected from given site
   290          *  and the selection takes place in given class?
   291          *  @param sym     The symbol with protected access
   292          *  @param c       The class where the access takes place
   293          *  @site          The type of the qualifier
   294          */
   295         private
   296         boolean isProtectedAccessible(Symbol sym, ClassSymbol c, Type site) {
   297             while (c != null &&
   298                    !(c.isSubClass(sym.owner, types) &&
   299                      (c.flags() & INTERFACE) == 0 &&
   300                      // In JLS 2e 6.6.2.1, the subclass restriction applies
   301                      // only to instance fields and methods -- types are excluded
   302                      // regardless of whether they are declared 'static' or not.
   303                      ((sym.flags() & STATIC) != 0 || sym.kind == TYP || site.tsym.isSubClass(c, types))))
   304                 c = c.owner.enclClass();
   305             return c != null;
   306         }
   308     /** Try to instantiate the type of a method so that it fits
   309      *  given type arguments and argument types. If succesful, return
   310      *  the method's instantiated type, else return null.
   311      *  The instantiation will take into account an additional leading
   312      *  formal parameter if the method is an instance method seen as a member
   313      *  of un underdetermined site In this case, we treat site as an additional
   314      *  parameter and the parameters of the class containing the method as
   315      *  additional type variables that get instantiated.
   316      *
   317      *  @param env         The current environment
   318      *  @param site        The type of which the method is a member.
   319      *  @param m           The method symbol.
   320      *  @param argtypes    The invocation's given value arguments.
   321      *  @param typeargtypes    The invocation's given type arguments.
   322      *  @param allowBoxing Allow boxing conversions of arguments.
   323      *  @param useVarargs Box trailing arguments into an array for varargs.
   324      */
   325     Type rawInstantiate(Env<AttrContext> env,
   326                         Type site,
   327                         Symbol m,
   328                         List<Type> argtypes,
   329                         List<Type> typeargtypes,
   330                         boolean allowBoxing,
   331                         boolean useVarargs,
   332                         Warner warn)
   333         throws Infer.InferenceException {
   334         boolean polymorphicSignature = m.isPolymorphicSignatureGeneric() && allowMethodHandles;
   335         if (useVarargs && (m.flags() & VARARGS) == 0)
   336             throw inapplicableMethodException.setMessage();
   337         Type mt = types.memberType(site, m);
   339         // tvars is the list of formal type variables for which type arguments
   340         // need to inferred.
   341         List<Type> tvars = null;
   342         if (env.info.tvars != null) {
   343             tvars = types.newInstances(env.info.tvars);
   344             mt = types.subst(mt, env.info.tvars, tvars);
   345         }
   346         if (typeargtypes == null) typeargtypes = List.nil();
   347         if (mt.tag != FORALL && typeargtypes.nonEmpty()) {
   348             // This is not a polymorphic method, but typeargs are supplied
   349             // which is fine, see JLS 15.12.2.1
   350         } else if (mt.tag == FORALL && typeargtypes.nonEmpty()) {
   351             ForAll pmt = (ForAll) mt;
   352             if (typeargtypes.length() != pmt.tvars.length())
   353                 throw inapplicableMethodException.setMessage("arg.length.mismatch"); // not enough args
   354             // Check type arguments are within bounds
   355             List<Type> formals = pmt.tvars;
   356             List<Type> actuals = typeargtypes;
   357             while (formals.nonEmpty() && actuals.nonEmpty()) {
   358                 List<Type> bounds = types.subst(types.getBounds((TypeVar)formals.head),
   359                                                 pmt.tvars, typeargtypes);
   360                 for (; bounds.nonEmpty(); bounds = bounds.tail)
   361                     if (!types.isSubtypeUnchecked(actuals.head, bounds.head, warn))
   362                         throw inapplicableMethodException.setMessage("explicit.param.do.not.conform.to.bounds",actuals.head, bounds);
   363                 formals = formals.tail;
   364                 actuals = actuals.tail;
   365             }
   366             mt = types.subst(pmt.qtype, pmt.tvars, typeargtypes);
   367         } else if (mt.tag == FORALL) {
   368             ForAll pmt = (ForAll) mt;
   369             List<Type> tvars1 = types.newInstances(pmt.tvars);
   370             tvars = tvars.appendList(tvars1);
   371             mt = types.subst(pmt.qtype, pmt.tvars, tvars1);
   372         }
   374         // find out whether we need to go the slow route via infer
   375         boolean instNeeded = tvars.tail != null || /*inlined: tvars.nonEmpty()*/
   376                 polymorphicSignature;
   377         for (List<Type> l = argtypes;
   378              l.tail != null/*inlined: l.nonEmpty()*/ && !instNeeded;
   379              l = l.tail) {
   380             if (l.head.tag == FORALL) instNeeded = true;
   381         }
   383         if (instNeeded)
   384             return polymorphicSignature ?
   385                 infer.instantiatePolymorphicSignatureInstance(env, site, m.name, (MethodSymbol)m, argtypes) :
   386                 infer.instantiateMethod(env,
   387                                     tvars,
   388                                     (MethodType)mt,
   389                                     m,
   390                                     argtypes,
   391                                     allowBoxing,
   392                                     useVarargs,
   393                                     warn);
   395         checkRawArgumentsAcceptable(env, argtypes, mt.getParameterTypes(),
   396                                 allowBoxing, useVarargs, warn);
   397         return mt;
   398     }
   400     /** Same but returns null instead throwing a NoInstanceException
   401      */
   402     Type instantiate(Env<AttrContext> env,
   403                      Type site,
   404                      Symbol m,
   405                      List<Type> argtypes,
   406                      List<Type> typeargtypes,
   407                      boolean allowBoxing,
   408                      boolean useVarargs,
   409                      Warner warn) {
   410         try {
   411             return rawInstantiate(env, site, m, argtypes, typeargtypes,
   412                                   allowBoxing, useVarargs, warn);
   413         } catch (InapplicableMethodException ex) {
   414             return null;
   415         }
   416     }
   418     /** Check if a parameter list accepts a list of args.
   419      */
   420     boolean argumentsAcceptable(Env<AttrContext> env,
   421                                 List<Type> argtypes,
   422                                 List<Type> formals,
   423                                 boolean allowBoxing,
   424                                 boolean useVarargs,
   425                                 Warner warn) {
   426         try {
   427             checkRawArgumentsAcceptable(env, argtypes, formals, allowBoxing, useVarargs, warn);
   428             return true;
   429         } catch (InapplicableMethodException ex) {
   430             return false;
   431         }
   432     }
   433     void checkRawArgumentsAcceptable(Env<AttrContext> env,
   434                                 List<Type> argtypes,
   435                                 List<Type> formals,
   436                                 boolean allowBoxing,
   437                                 boolean useVarargs,
   438                                 Warner warn) {
   439         Type varargsFormal = useVarargs ? formals.last() : null;
   440         if (varargsFormal == null &&
   441                 argtypes.size() != formals.size()) {
   442             throw inapplicableMethodException.setMessage("arg.length.mismatch"); // not enough args
   443         }
   445         while (argtypes.nonEmpty() && formals.head != varargsFormal) {
   446             boolean works = allowBoxing
   447                 ? types.isConvertible(argtypes.head, formals.head, warn)
   448                 : types.isSubtypeUnchecked(argtypes.head, formals.head, warn);
   449             if (!works)
   450                 throw inapplicableMethodException.setMessage("no.conforming.assignment.exists",
   451                         argtypes.head,
   452                         formals.head);
   453             argtypes = argtypes.tail;
   454             formals = formals.tail;
   455         }
   457         if (formals.head != varargsFormal)
   458             throw inapplicableMethodException.setMessage("arg.length.mismatch"); // not enough args
   460         if (useVarargs) {
   461             Type elt = types.elemtype(varargsFormal);
   462             while (argtypes.nonEmpty()) {
   463                 if (!types.isConvertible(argtypes.head, elt, warn))
   464                     throw inapplicableMethodException.setMessage("varargs.argument.mismatch",
   465                             argtypes.head,
   466                             elt);
   467                 argtypes = argtypes.tail;
   468             }
   469             //check varargs element type accessibility
   470             if (!isAccessible(env, elt)) {
   471                 Symbol location = env.enclClass.sym;
   472                 throw inapplicableMethodException.setMessage("inaccessible.varargs.type",
   473                             elt,
   474                             Kinds.kindName(location),
   475                             location);
   476             }
   477         }
   478         return;
   479     }
   480     // where
   481         public static class InapplicableMethodException extends RuntimeException {
   482             private static final long serialVersionUID = 0;
   484             JCDiagnostic diagnostic;
   485             JCDiagnostic.Factory diags;
   487             InapplicableMethodException(JCDiagnostic.Factory diags) {
   488                 this.diagnostic = null;
   489                 this.diags = diags;
   490             }
   491             InapplicableMethodException setMessage() {
   492                 this.diagnostic = null;
   493                 return this;
   494             }
   495             InapplicableMethodException setMessage(String key) {
   496                 this.diagnostic = key != null ? diags.fragment(key) : null;
   497                 return this;
   498             }
   499             InapplicableMethodException setMessage(String key, Object... args) {
   500                 this.diagnostic = key != null ? diags.fragment(key, args) : null;
   501                 return this;
   502             }
   503             InapplicableMethodException setMessage(JCDiagnostic diag) {
   504                 this.diagnostic = diag;
   505                 return this;
   506             }
   508             public JCDiagnostic getDiagnostic() {
   509                 return diagnostic;
   510             }
   511         }
   512         private final InapplicableMethodException inapplicableMethodException;
   514 /* ***************************************************************************
   515  *  Symbol lookup
   516  *  the following naming conventions for arguments are used
   517  *
   518  *       env      is the environment where the symbol was mentioned
   519  *       site     is the type of which the symbol is a member
   520  *       name     is the symbol's name
   521  *                if no arguments are given
   522  *       argtypes are the value arguments, if we search for a method
   523  *
   524  *  If no symbol was found, a ResolveError detailing the problem is returned.
   525  ****************************************************************************/
   527     /** Find field. Synthetic fields are always skipped.
   528      *  @param env     The current environment.
   529      *  @param site    The original type from where the selection takes place.
   530      *  @param name    The name of the field.
   531      *  @param c       The class to search for the field. This is always
   532      *                 a superclass or implemented interface of site's class.
   533      */
   534     Symbol findField(Env<AttrContext> env,
   535                      Type site,
   536                      Name name,
   537                      TypeSymbol c) {
   538         while (c.type.tag == TYPEVAR)
   539             c = c.type.getUpperBound().tsym;
   540         Symbol bestSoFar = varNotFound;
   541         Symbol sym;
   542         Scope.Entry e = c.members().lookup(name);
   543         while (e.scope != null) {
   544             if (e.sym.kind == VAR && (e.sym.flags_field & SYNTHETIC) == 0) {
   545                 return isAccessible(env, site, e.sym)
   546                     ? e.sym : new AccessError(env, site, e.sym);
   547             }
   548             e = e.next();
   549         }
   550         Type st = types.supertype(c.type);
   551         if (st != null && (st.tag == CLASS || st.tag == TYPEVAR)) {
   552             sym = findField(env, site, name, st.tsym);
   553             if (sym.kind < bestSoFar.kind) bestSoFar = sym;
   554         }
   555         for (List<Type> l = types.interfaces(c.type);
   556              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
   557              l = l.tail) {
   558             sym = findField(env, site, name, l.head.tsym);
   559             if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
   560                 sym.owner != bestSoFar.owner)
   561                 bestSoFar = new AmbiguityError(bestSoFar, sym);
   562             else if (sym.kind < bestSoFar.kind)
   563                 bestSoFar = sym;
   564         }
   565         return bestSoFar;
   566     }
   568     /** Resolve a field identifier, throw a fatal error if not found.
   569      *  @param pos       The position to use for error reporting.
   570      *  @param env       The environment current at the method invocation.
   571      *  @param site      The type of the qualifying expression, in which
   572      *                   identifier is searched.
   573      *  @param name      The identifier's name.
   574      */
   575     public VarSymbol resolveInternalField(DiagnosticPosition pos, Env<AttrContext> env,
   576                                           Type site, Name name) {
   577         Symbol sym = findField(env, site, name, site.tsym);
   578         if (sym.kind == VAR) return (VarSymbol)sym;
   579         else throw new FatalError(
   580                  diags.fragment("fatal.err.cant.locate.field",
   581                                 name));
   582     }
   584     /** Find unqualified variable or field with given name.
   585      *  Synthetic fields always skipped.
   586      *  @param env     The current environment.
   587      *  @param name    The name of the variable or field.
   588      */
   589     Symbol findVar(Env<AttrContext> env, Name name) {
   590         Symbol bestSoFar = varNotFound;
   591         Symbol sym;
   592         Env<AttrContext> env1 = env;
   593         boolean staticOnly = false;
   594         while (env1.outer != null) {
   595             if (isStatic(env1)) staticOnly = true;
   596             Scope.Entry e = env1.info.scope.lookup(name);
   597             while (e.scope != null &&
   598                    (e.sym.kind != VAR ||
   599                     (e.sym.flags_field & SYNTHETIC) != 0))
   600                 e = e.next();
   601             sym = (e.scope != null)
   602                 ? e.sym
   603                 : findField(
   604                     env1, env1.enclClass.sym.type, name, env1.enclClass.sym);
   605             if (sym.exists()) {
   606                 if (staticOnly &&
   607                     sym.kind == VAR &&
   608                     sym.owner.kind == TYP &&
   609                     (sym.flags() & STATIC) == 0)
   610                     return new StaticError(sym);
   611                 else
   612                     return sym;
   613             } else if (sym.kind < bestSoFar.kind) {
   614                 bestSoFar = sym;
   615             }
   617             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
   618             env1 = env1.outer;
   619         }
   621         sym = findField(env, syms.predefClass.type, name, syms.predefClass);
   622         if (sym.exists())
   623             return sym;
   624         if (bestSoFar.exists())
   625             return bestSoFar;
   627         Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
   628         for (; e.scope != null; e = e.next()) {
   629             sym = e.sym;
   630             Type origin = e.getOrigin().owner.type;
   631             if (sym.kind == VAR) {
   632                 if (e.sym.owner.type != origin)
   633                     sym = sym.clone(e.getOrigin().owner);
   634                 return isAccessible(env, origin, sym)
   635                     ? sym : new AccessError(env, origin, sym);
   636             }
   637         }
   639         Symbol origin = null;
   640         e = env.toplevel.starImportScope.lookup(name);
   641         for (; e.scope != null; e = e.next()) {
   642             sym = e.sym;
   643             if (sym.kind != VAR)
   644                 continue;
   645             // invariant: sym.kind == VAR
   646             if (bestSoFar.kind < AMBIGUOUS && sym.owner != bestSoFar.owner)
   647                 return new AmbiguityError(bestSoFar, sym);
   648             else if (bestSoFar.kind >= VAR) {
   649                 origin = e.getOrigin().owner;
   650                 bestSoFar = isAccessible(env, origin.type, sym)
   651                     ? sym : new AccessError(env, origin.type, sym);
   652             }
   653         }
   654         if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type)
   655             return bestSoFar.clone(origin);
   656         else
   657             return bestSoFar;
   658     }
   660     Warner noteWarner = new Warner();
   662     /** Select the best method for a call site among two choices.
   663      *  @param env              The current environment.
   664      *  @param site             The original type from where the
   665      *                          selection takes place.
   666      *  @param argtypes         The invocation's value arguments,
   667      *  @param typeargtypes     The invocation's type arguments,
   668      *  @param sym              Proposed new best match.
   669      *  @param bestSoFar        Previously found best match.
   670      *  @param allowBoxing Allow boxing conversions of arguments.
   671      *  @param useVarargs Box trailing arguments into an array for varargs.
   672      */
   673     @SuppressWarnings("fallthrough")
   674     Symbol selectBest(Env<AttrContext> env,
   675                       Type site,
   676                       List<Type> argtypes,
   677                       List<Type> typeargtypes,
   678                       Symbol sym,
   679                       Symbol bestSoFar,
   680                       boolean allowBoxing,
   681                       boolean useVarargs,
   682                       boolean operator) {
   683         if (sym.kind == ERR) return bestSoFar;
   684         if (!sym.isInheritedIn(site.tsym, types)) return bestSoFar;
   685         Assert.check(sym.kind < AMBIGUOUS);
   686         try {
   687             rawInstantiate(env, site, sym, argtypes, typeargtypes,
   688                                allowBoxing, useVarargs, Warner.noWarnings);
   689         } catch (InapplicableMethodException ex) {
   690             switch (bestSoFar.kind) {
   691             case ABSENT_MTH:
   692                 return wrongMethod.setWrongSym(sym, ex.getDiagnostic());
   693             case WRONG_MTH:
   694                 wrongMethods.addCandidate(currentStep, wrongMethod.sym, wrongMethod.explanation);
   695             case WRONG_MTHS:
   696                 return wrongMethods.addCandidate(currentStep, sym, ex.getDiagnostic());
   697             default:
   698                 return bestSoFar;
   699             }
   700         }
   701         if (!isAccessible(env, site, sym)) {
   702             return (bestSoFar.kind == ABSENT_MTH)
   703                 ? new AccessError(env, site, sym)
   704                 : bestSoFar;
   705             }
   706         return (bestSoFar.kind > AMBIGUOUS)
   707             ? sym
   708             : mostSpecific(sym, bestSoFar, env, site,
   709                            allowBoxing && operator, useVarargs);
   710     }
   712     /* Return the most specific of the two methods for a call,
   713      *  given that both are accessible and applicable.
   714      *  @param m1               A new candidate for most specific.
   715      *  @param m2               The previous most specific candidate.
   716      *  @param env              The current environment.
   717      *  @param site             The original type from where the selection
   718      *                          takes place.
   719      *  @param allowBoxing Allow boxing conversions of arguments.
   720      *  @param useVarargs Box trailing arguments into an array for varargs.
   721      */
   722     Symbol mostSpecific(Symbol m1,
   723                         Symbol m2,
   724                         Env<AttrContext> env,
   725                         final Type site,
   726                         boolean allowBoxing,
   727                         boolean useVarargs) {
   728         switch (m2.kind) {
   729         case MTH:
   730             if (m1 == m2) return m1;
   731             boolean m1SignatureMoreSpecific = signatureMoreSpecific(env, site, m1, m2, allowBoxing, useVarargs);
   732             boolean m2SignatureMoreSpecific = signatureMoreSpecific(env, site, m2, m1, allowBoxing, useVarargs);
   733             if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) {
   734                 Type mt1 = types.memberType(site, m1);
   735                 Type mt2 = types.memberType(site, m2);
   736                 if (!types.overrideEquivalent(mt1, mt2))
   737                     return ambiguityError(m1, m2);
   739                 // same signature; select (a) the non-bridge method, or
   740                 // (b) the one that overrides the other, or (c) the concrete
   741                 // one, or (d) merge both abstract signatures
   742                 if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE))
   743                     return ((m1.flags() & BRIDGE) != 0) ? m2 : m1;
   745                 // if one overrides or hides the other, use it
   746                 TypeSymbol m1Owner = (TypeSymbol)m1.owner;
   747                 TypeSymbol m2Owner = (TypeSymbol)m2.owner;
   748                 if (types.asSuper(m1Owner.type, m2Owner) != null &&
   749                     ((m1.owner.flags_field & INTERFACE) == 0 ||
   750                      (m2.owner.flags_field & INTERFACE) != 0) &&
   751                     m1.overrides(m2, m1Owner, types, false))
   752                     return m1;
   753                 if (types.asSuper(m2Owner.type, m1Owner) != null &&
   754                     ((m2.owner.flags_field & INTERFACE) == 0 ||
   755                      (m1.owner.flags_field & INTERFACE) != 0) &&
   756                     m2.overrides(m1, m2Owner, types, false))
   757                     return m2;
   758                 boolean m1Abstract = (m1.flags() & ABSTRACT) != 0;
   759                 boolean m2Abstract = (m2.flags() & ABSTRACT) != 0;
   760                 if (m1Abstract && !m2Abstract) return m2;
   761                 if (m2Abstract && !m1Abstract) return m1;
   762                 // both abstract or both concrete
   763                 if (!m1Abstract && !m2Abstract)
   764                     return ambiguityError(m1, m2);
   765                 // check that both signatures have the same erasure
   766                 if (!types.isSameTypes(m1.erasure(types).getParameterTypes(),
   767                                        m2.erasure(types).getParameterTypes()))
   768                     return ambiguityError(m1, m2);
   769                 // both abstract, neither overridden; merge throws clause and result type
   770                 Type mst = mostSpecificReturnType(mt1, mt2);
   771                 if (mst == null) {
   772                     // Theoretically, this can't happen, but it is possible
   773                     // due to error recovery or mixing incompatible class files
   774                     return ambiguityError(m1, m2);
   775                 }
   776                 Symbol mostSpecific = mst == mt1 ? m1 : m2;
   777                 List<Type> allThrown = chk.intersect(mt1.getThrownTypes(), mt2.getThrownTypes());
   778                 Type newSig = types.createMethodTypeWithThrown(mostSpecific.type, allThrown);
   779                 MethodSymbol result = new MethodSymbol(
   780                         mostSpecific.flags(),
   781                         mostSpecific.name,
   782                         newSig,
   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                 return result;
   793             }
   794             if (m1SignatureMoreSpecific) return m1;
   795             if (m2SignatureMoreSpecific) return m2;
   796             return ambiguityError(m1, m2);
   797         case AMBIGUOUS:
   798             AmbiguityError e = (AmbiguityError)m2;
   799             Symbol err1 = mostSpecific(m1, e.sym, env, site, allowBoxing, useVarargs);
   800             Symbol err2 = mostSpecific(m1, e.sym2, env, site, allowBoxing, useVarargs);
   801             if (err1 == err2) return err1;
   802             if (err1 == e.sym && err2 == e.sym2) return m2;
   803             if (err1 instanceof AmbiguityError &&
   804                 err2 instanceof AmbiguityError &&
   805                 ((AmbiguityError)err1).sym == ((AmbiguityError)err2).sym)
   806                 return ambiguityError(m1, m2);
   807             else
   808                 return ambiguityError(err1, err2);
   809         default:
   810             throw new AssertionError();
   811         }
   812     }
   813     //where
   814     private boolean signatureMoreSpecific(Env<AttrContext> env, Type site, Symbol m1, Symbol m2, boolean allowBoxing, boolean useVarargs) {
   815         noteWarner.clear();
   816         Type mtype1 = types.memberType(site, adjustVarargs(m1, m2, useVarargs));
   817         Type mtype2 = instantiate(env, site, adjustVarargs(m2, m1, useVarargs),
   818                 types.lowerBoundArgtypes(mtype1), null,
   819                 allowBoxing, false, noteWarner);
   820         return mtype2 != null &&
   821                 !noteWarner.hasLint(Lint.LintCategory.UNCHECKED);
   822     }
   823     //where
   824     private Symbol adjustVarargs(Symbol to, Symbol from, boolean useVarargs) {
   825         List<Type> fromArgs = from.type.getParameterTypes();
   826         List<Type> toArgs = to.type.getParameterTypes();
   827         if (useVarargs &&
   828                 (from.flags() & VARARGS) != 0 &&
   829                 (to.flags() & VARARGS) != 0) {
   830             Type varargsTypeFrom = fromArgs.last();
   831             Type varargsTypeTo = toArgs.last();
   832             ListBuffer<Type> args = ListBuffer.lb();
   833             if (toArgs.length() < fromArgs.length()) {
   834                 //if we are checking a varargs method 'from' against another varargs
   835                 //method 'to' (where arity of 'to' < arity of 'from') then expand signature
   836                 //of 'to' to 'fit' arity of 'from' (this means adding fake formals to 'to'
   837                 //until 'to' signature has the same arity as 'from')
   838                 while (fromArgs.head != varargsTypeFrom) {
   839                     args.append(toArgs.head == varargsTypeTo ? types.elemtype(varargsTypeTo) : toArgs.head);
   840                     fromArgs = fromArgs.tail;
   841                     toArgs = toArgs.head == varargsTypeTo ?
   842                         toArgs :
   843                         toArgs.tail;
   844                 }
   845             } else {
   846                 //formal argument list is same as original list where last
   847                 //argument (array type) is removed
   848                 args.appendList(toArgs.reverse().tail.reverse());
   849             }
   850             //append varargs element type as last synthetic formal
   851             args.append(types.elemtype(varargsTypeTo));
   852             Type mtype = types.createMethodTypeWithParameters(to.type, args.toList());
   853             return new MethodSymbol(to.flags_field & ~VARARGS, to.name, mtype, to.owner);
   854         } else {
   855             return to;
   856         }
   857     }
   858     //where
   859     Type mostSpecificReturnType(Type mt1, Type mt2) {
   860         Type rt1 = mt1.getReturnType();
   861         Type rt2 = mt2.getReturnType();
   863         if (mt1.tag == FORALL && mt2.tag == FORALL) {
   864             //if both are generic methods, adjust return type ahead of subtyping check
   865             rt1 = types.subst(rt1, mt1.getTypeArguments(), mt2.getTypeArguments());
   866         }
   867         //first use subtyping, then return type substitutability
   868         if (types.isSubtype(rt1, rt2)) {
   869             return mt1;
   870         } else if (types.isSubtype(rt2, rt1)) {
   871             return mt2;
   872         } else if (types.returnTypeSubstitutable(mt1, mt2)) {
   873             return mt1;
   874         } else if (types.returnTypeSubstitutable(mt2, mt1)) {
   875             return mt2;
   876         } else {
   877             return null;
   878         }
   879     }
   880     //where
   881     Symbol ambiguityError(Symbol m1, Symbol m2) {
   882         if (((m1.flags() | m2.flags()) & CLASH) != 0) {
   883             return (m1.flags() & CLASH) == 0 ? m1 : m2;
   884         } else {
   885             return new AmbiguityError(m1, m2);
   886         }
   887     }
   889     /** Find best qualified method matching given name, type and value
   890      *  arguments.
   891      *  @param env       The current environment.
   892      *  @param site      The original type from where the selection
   893      *                   takes place.
   894      *  @param name      The method's name.
   895      *  @param argtypes  The method's value arguments.
   896      *  @param typeargtypes The method's type arguments
   897      *  @param allowBoxing Allow boxing conversions of arguments.
   898      *  @param useVarargs Box trailing arguments into an array for varargs.
   899      */
   900     Symbol findMethod(Env<AttrContext> env,
   901                       Type site,
   902                       Name name,
   903                       List<Type> argtypes,
   904                       List<Type> typeargtypes,
   905                       boolean allowBoxing,
   906                       boolean useVarargs,
   907                       boolean operator) {
   908         Symbol bestSoFar = methodNotFound;
   909         return findMethod(env,
   910                           site,
   911                           name,
   912                           argtypes,
   913                           typeargtypes,
   914                           site.tsym.type,
   915                           true,
   916                           bestSoFar,
   917                           allowBoxing,
   918                           useVarargs,
   919                           operator,
   920                           new HashSet<TypeSymbol>());
   921     }
   922     // where
   923     private Symbol findMethod(Env<AttrContext> env,
   924                               Type site,
   925                               Name name,
   926                               List<Type> argtypes,
   927                               List<Type> typeargtypes,
   928                               Type intype,
   929                               boolean abstractok,
   930                               Symbol bestSoFar,
   931                               boolean allowBoxing,
   932                               boolean useVarargs,
   933                               boolean operator,
   934                               Set<TypeSymbol> seen) {
   935         for (Type ct = intype; ct.tag == CLASS || ct.tag == TYPEVAR; ct = types.supertype(ct)) {
   936             while (ct.tag == TYPEVAR)
   937                 ct = ct.getUpperBound();
   938             ClassSymbol c = (ClassSymbol)ct.tsym;
   939             if (!seen.add(c)) return bestSoFar;
   940             if ((c.flags() & (ABSTRACT | INTERFACE | ENUM)) == 0)
   941                 abstractok = false;
   942             for (Scope.Entry e = c.members().lookup(name);
   943                  e.scope != null;
   944                  e = e.next()) {
   945                 //- System.out.println(" e " + e.sym);
   946                 if (e.sym.kind == MTH &&
   947                     (e.sym.flags_field & SYNTHETIC) == 0) {
   948                     bestSoFar = selectBest(env, site, argtypes, typeargtypes,
   949                                            e.sym, bestSoFar,
   950                                            allowBoxing,
   951                                            useVarargs,
   952                                            operator);
   953                 }
   954             }
   955             if (name == names.init)
   956                 break;
   957             //- System.out.println(" - " + bestSoFar);
   958             if (abstractok) {
   959                 Symbol concrete = methodNotFound;
   960                 if ((bestSoFar.flags() & ABSTRACT) == 0)
   961                     concrete = bestSoFar;
   962                 for (List<Type> l = types.interfaces(c.type);
   963                      l.nonEmpty();
   964                      l = l.tail) {
   965                     bestSoFar = findMethod(env, site, name, argtypes,
   966                                            typeargtypes,
   967                                            l.head, abstractok, bestSoFar,
   968                                            allowBoxing, useVarargs, operator, seen);
   969                 }
   970                 if (concrete != bestSoFar &&
   971                     concrete.kind < ERR  && bestSoFar.kind < ERR &&
   972                     types.isSubSignature(concrete.type, bestSoFar.type))
   973                     bestSoFar = concrete;
   974             }
   975         }
   976         return bestSoFar;
   977     }
   979     /** Find unqualified method matching given name, type and value arguments.
   980      *  @param env       The current environment.
   981      *  @param name      The method's name.
   982      *  @param argtypes  The method's value arguments.
   983      *  @param typeargtypes  The method's type arguments.
   984      *  @param allowBoxing Allow boxing conversions of arguments.
   985      *  @param useVarargs Box trailing arguments into an array for varargs.
   986      */
   987     Symbol findFun(Env<AttrContext> env, Name name,
   988                    List<Type> argtypes, List<Type> typeargtypes,
   989                    boolean allowBoxing, boolean useVarargs) {
   990         Symbol bestSoFar = methodNotFound;
   991         Symbol sym;
   992         Env<AttrContext> env1 = env;
   993         boolean staticOnly = false;
   994         while (env1.outer != null) {
   995             if (isStatic(env1)) staticOnly = true;
   996             sym = findMethod(
   997                 env1, env1.enclClass.sym.type, name, argtypes, typeargtypes,
   998                 allowBoxing, useVarargs, false);
   999             if (sym.exists()) {
  1000                 if (staticOnly &&
  1001                     sym.kind == MTH &&
  1002                     sym.owner.kind == TYP &&
  1003                     (sym.flags() & STATIC) == 0) return new StaticError(sym);
  1004                 else return sym;
  1005             } else if (sym.kind < bestSoFar.kind) {
  1006                 bestSoFar = sym;
  1008             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  1009             env1 = env1.outer;
  1012         sym = findMethod(env, syms.predefClass.type, name, argtypes,
  1013                          typeargtypes, allowBoxing, useVarargs, false);
  1014         if (sym.exists())
  1015             return sym;
  1017         Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
  1018         for (; e.scope != null; e = e.next()) {
  1019             sym = e.sym;
  1020             Type origin = e.getOrigin().owner.type;
  1021             if (sym.kind == MTH) {
  1022                 if (e.sym.owner.type != origin)
  1023                     sym = sym.clone(e.getOrigin().owner);
  1024                 if (!isAccessible(env, origin, sym))
  1025                     sym = new AccessError(env, origin, sym);
  1026                 bestSoFar = selectBest(env, origin,
  1027                                        argtypes, typeargtypes,
  1028                                        sym, bestSoFar,
  1029                                        allowBoxing, useVarargs, false);
  1032         if (bestSoFar.exists())
  1033             return bestSoFar;
  1035         e = env.toplevel.starImportScope.lookup(name);
  1036         for (; e.scope != null; e = e.next()) {
  1037             sym = e.sym;
  1038             Type origin = e.getOrigin().owner.type;
  1039             if (sym.kind == MTH) {
  1040                 if (e.sym.owner.type != origin)
  1041                     sym = sym.clone(e.getOrigin().owner);
  1042                 if (!isAccessible(env, origin, sym))
  1043                     sym = new AccessError(env, origin, sym);
  1044                 bestSoFar = selectBest(env, origin,
  1045                                        argtypes, typeargtypes,
  1046                                        sym, bestSoFar,
  1047                                        allowBoxing, useVarargs, false);
  1050         return bestSoFar;
  1053     /** Load toplevel or member class with given fully qualified name and
  1054      *  verify that it is accessible.
  1055      *  @param env       The current environment.
  1056      *  @param name      The fully qualified name of the class to be loaded.
  1057      */
  1058     Symbol loadClass(Env<AttrContext> env, Name name) {
  1059         try {
  1060             ClassSymbol c = reader.loadClass(name);
  1061             return isAccessible(env, c) ? c : new AccessError(c);
  1062         } catch (ClassReader.BadClassFile err) {
  1063             throw err;
  1064         } catch (CompletionFailure ex) {
  1065             return typeNotFound;
  1069     /** Find qualified member type.
  1070      *  @param env       The current environment.
  1071      *  @param site      The original type from where the selection takes
  1072      *                   place.
  1073      *  @param name      The type's name.
  1074      *  @param c         The class to search for the member type. This is
  1075      *                   always a superclass or implemented interface of
  1076      *                   site's class.
  1077      */
  1078     Symbol findMemberType(Env<AttrContext> env,
  1079                           Type site,
  1080                           Name name,
  1081                           TypeSymbol c) {
  1082         Symbol bestSoFar = typeNotFound;
  1083         Symbol sym;
  1084         Scope.Entry e = c.members().lookup(name);
  1085         while (e.scope != null) {
  1086             if (e.sym.kind == TYP) {
  1087                 return isAccessible(env, site, e.sym)
  1088                     ? e.sym
  1089                     : new AccessError(env, site, e.sym);
  1091             e = e.next();
  1093         Type st = types.supertype(c.type);
  1094         if (st != null && st.tag == CLASS) {
  1095             sym = findMemberType(env, site, name, st.tsym);
  1096             if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1098         for (List<Type> l = types.interfaces(c.type);
  1099              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
  1100              l = l.tail) {
  1101             sym = findMemberType(env, site, name, l.head.tsym);
  1102             if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
  1103                 sym.owner != bestSoFar.owner)
  1104                 bestSoFar = new AmbiguityError(bestSoFar, sym);
  1105             else if (sym.kind < bestSoFar.kind)
  1106                 bestSoFar = sym;
  1108         return bestSoFar;
  1111     /** Find a global type in given scope and load corresponding class.
  1112      *  @param env       The current environment.
  1113      *  @param scope     The scope in which to look for the type.
  1114      *  @param name      The type's name.
  1115      */
  1116     Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name) {
  1117         Symbol bestSoFar = typeNotFound;
  1118         for (Scope.Entry e = scope.lookup(name); e.scope != null; e = e.next()) {
  1119             Symbol sym = loadClass(env, e.sym.flatName());
  1120             if (bestSoFar.kind == TYP && sym.kind == TYP &&
  1121                 bestSoFar != sym)
  1122                 return new AmbiguityError(bestSoFar, sym);
  1123             else if (sym.kind < bestSoFar.kind)
  1124                 bestSoFar = sym;
  1126         return bestSoFar;
  1129     /** Find an unqualified type symbol.
  1130      *  @param env       The current environment.
  1131      *  @param name      The type's name.
  1132      */
  1133     Symbol findType(Env<AttrContext> env, Name name) {
  1134         Symbol bestSoFar = typeNotFound;
  1135         Symbol sym;
  1136         boolean staticOnly = false;
  1137         for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
  1138             if (isStatic(env1)) staticOnly = true;
  1139             for (Scope.Entry e = env1.info.scope.lookup(name);
  1140                  e.scope != null;
  1141                  e = e.next()) {
  1142                 if (e.sym.kind == TYP) {
  1143                     if (staticOnly &&
  1144                         e.sym.type.tag == TYPEVAR &&
  1145                         e.sym.owner.kind == TYP) return new StaticError(e.sym);
  1146                     return e.sym;
  1150             sym = findMemberType(env1, env1.enclClass.sym.type, name,
  1151                                  env1.enclClass.sym);
  1152             if (staticOnly && sym.kind == TYP &&
  1153                 sym.type.tag == CLASS &&
  1154                 sym.type.getEnclosingType().tag == CLASS &&
  1155                 env1.enclClass.sym.type.isParameterized() &&
  1156                 sym.type.getEnclosingType().isParameterized())
  1157                 return new StaticError(sym);
  1158             else if (sym.exists()) return sym;
  1159             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1161             JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass;
  1162             if ((encl.sym.flags() & STATIC) != 0)
  1163                 staticOnly = true;
  1166         if (env.tree.getTag() != JCTree.IMPORT) {
  1167             sym = findGlobalType(env, env.toplevel.namedImportScope, name);
  1168             if (sym.exists()) return sym;
  1169             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1171             sym = findGlobalType(env, env.toplevel.packge.members(), name);
  1172             if (sym.exists()) return sym;
  1173             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1175             sym = findGlobalType(env, env.toplevel.starImportScope, name);
  1176             if (sym.exists()) return sym;
  1177             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1180         return bestSoFar;
  1183     /** Find an unqualified identifier which matches a specified kind set.
  1184      *  @param env       The current environment.
  1185      *  @param name      The indentifier's name.
  1186      *  @param kind      Indicates the possible symbol kinds
  1187      *                   (a subset of VAL, TYP, PCK).
  1188      */
  1189     Symbol findIdent(Env<AttrContext> env, Name name, int kind) {
  1190         Symbol bestSoFar = typeNotFound;
  1191         Symbol sym;
  1193         if ((kind & VAR) != 0) {
  1194             sym = findVar(env, name);
  1195             if (sym.exists()) return sym;
  1196             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1199         if ((kind & TYP) != 0) {
  1200             sym = findType(env, name);
  1201             if (sym.exists()) return sym;
  1202             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1205         if ((kind & PCK) != 0) return reader.enterPackage(name);
  1206         else return bestSoFar;
  1209     /** Find an identifier in a package which matches a specified kind set.
  1210      *  @param env       The current environment.
  1211      *  @param name      The identifier's name.
  1212      *  @param kind      Indicates the possible symbol kinds
  1213      *                   (a nonempty subset of TYP, PCK).
  1214      */
  1215     Symbol findIdentInPackage(Env<AttrContext> env, TypeSymbol pck,
  1216                               Name name, int kind) {
  1217         Name fullname = TypeSymbol.formFullName(name, pck);
  1218         Symbol bestSoFar = typeNotFound;
  1219         PackageSymbol pack = null;
  1220         if ((kind & PCK) != 0) {
  1221             pack = reader.enterPackage(fullname);
  1222             if (pack.exists()) return pack;
  1224         if ((kind & TYP) != 0) {
  1225             Symbol sym = loadClass(env, fullname);
  1226             if (sym.exists()) {
  1227                 // don't allow programs to use flatnames
  1228                 if (name == sym.name) return sym;
  1230             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1232         return (pack != null) ? pack : bestSoFar;
  1235     /** Find an identifier among the members of a given type `site'.
  1236      *  @param env       The current environment.
  1237      *  @param site      The type containing the symbol to be found.
  1238      *  @param name      The identifier's name.
  1239      *  @param kind      Indicates the possible symbol kinds
  1240      *                   (a subset of VAL, TYP).
  1241      */
  1242     Symbol findIdentInType(Env<AttrContext> env, Type site,
  1243                            Name name, int kind) {
  1244         Symbol bestSoFar = typeNotFound;
  1245         Symbol sym;
  1246         if ((kind & VAR) != 0) {
  1247             sym = findField(env, site, name, site.tsym);
  1248             if (sym.exists()) return sym;
  1249             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1252         if ((kind & TYP) != 0) {
  1253             sym = findMemberType(env, site, name, site.tsym);
  1254             if (sym.exists()) return sym;
  1255             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1257         return bestSoFar;
  1260 /* ***************************************************************************
  1261  *  Access checking
  1262  *  The following methods convert ResolveErrors to ErrorSymbols, issuing
  1263  *  an error message in the process
  1264  ****************************************************************************/
  1266     /** If `sym' is a bad symbol: report error and return errSymbol
  1267      *  else pass through unchanged,
  1268      *  additional arguments duplicate what has been used in trying to find the
  1269      *  symbol (--> flyweight pattern). This improves performance since we
  1270      *  expect misses to happen frequently.
  1272      *  @param sym       The symbol that was found, or a ResolveError.
  1273      *  @param pos       The position to use for error reporting.
  1274      *  @param site      The original type from where the selection took place.
  1275      *  @param name      The symbol's name.
  1276      *  @param argtypes  The invocation's value arguments,
  1277      *                   if we looked for a method.
  1278      *  @param typeargtypes  The invocation's type arguments,
  1279      *                   if we looked for a method.
  1280      */
  1281     Symbol access(Symbol sym,
  1282                   DiagnosticPosition pos,
  1283                   Symbol location,
  1284                   Type site,
  1285                   Name name,
  1286                   boolean qualified,
  1287                   List<Type> argtypes,
  1288                   List<Type> typeargtypes) {
  1289         if (sym.kind >= AMBIGUOUS) {
  1290             ResolveError errSym = (ResolveError)sym;
  1291             if (!site.isErroneous() &&
  1292                 !Type.isErroneous(argtypes) &&
  1293                 (typeargtypes==null || !Type.isErroneous(typeargtypes)))
  1294                 logResolveError(errSym, pos, location, site, name, argtypes, typeargtypes);
  1295             sym = errSym.access(name, qualified ? site.tsym : syms.noSymbol);
  1297         return sym;
  1300     /** Same as original access(), but without location.
  1301      */
  1302     Symbol access(Symbol sym,
  1303                   DiagnosticPosition pos,
  1304                   Type site,
  1305                   Name name,
  1306                   boolean qualified,
  1307                   List<Type> argtypes,
  1308                   List<Type> typeargtypes) {
  1309         return access(sym, pos, site.tsym, site, name, qualified, argtypes, typeargtypes);
  1312     /** Same as original access(), but without type arguments and arguments.
  1313      */
  1314     Symbol access(Symbol sym,
  1315                   DiagnosticPosition pos,
  1316                   Symbol location,
  1317                   Type site,
  1318                   Name name,
  1319                   boolean qualified) {
  1320         if (sym.kind >= AMBIGUOUS)
  1321             return access(sym, pos, location, site, name, qualified, List.<Type>nil(), null);
  1322         else
  1323             return sym;
  1326     /** Same as original access(), but without location, type arguments and arguments.
  1327      */
  1328     Symbol access(Symbol sym,
  1329                   DiagnosticPosition pos,
  1330                   Type site,
  1331                   Name name,
  1332                   boolean qualified) {
  1333         return access(sym, pos, site.tsym, site, name, qualified);
  1336     /** Check that sym is not an abstract method.
  1337      */
  1338     void checkNonAbstract(DiagnosticPosition pos, Symbol sym) {
  1339         if ((sym.flags() & ABSTRACT) != 0)
  1340             log.error(pos, "abstract.cant.be.accessed.directly",
  1341                       kindName(sym), sym, sym.location());
  1344 /* ***************************************************************************
  1345  *  Debugging
  1346  ****************************************************************************/
  1348     /** print all scopes starting with scope s and proceeding outwards.
  1349      *  used for debugging.
  1350      */
  1351     public void printscopes(Scope s) {
  1352         while (s != null) {
  1353             if (s.owner != null)
  1354                 System.err.print(s.owner + ": ");
  1355             for (Scope.Entry e = s.elems; e != null; e = e.sibling) {
  1356                 if ((e.sym.flags() & ABSTRACT) != 0)
  1357                     System.err.print("abstract ");
  1358                 System.err.print(e.sym + " ");
  1360             System.err.println();
  1361             s = s.next;
  1365     void printscopes(Env<AttrContext> env) {
  1366         while (env.outer != null) {
  1367             System.err.println("------------------------------");
  1368             printscopes(env.info.scope);
  1369             env = env.outer;
  1373     public void printscopes(Type t) {
  1374         while (t.tag == CLASS) {
  1375             printscopes(t.tsym.members());
  1376             t = types.supertype(t);
  1380 /* ***************************************************************************
  1381  *  Name resolution
  1382  *  Naming conventions are as for symbol lookup
  1383  *  Unlike the find... methods these methods will report access errors
  1384  ****************************************************************************/
  1386     /** Resolve an unqualified (non-method) identifier.
  1387      *  @param pos       The position to use for error reporting.
  1388      *  @param env       The environment current at the identifier use.
  1389      *  @param name      The identifier's name.
  1390      *  @param kind      The set of admissible symbol kinds for the identifier.
  1391      */
  1392     Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env,
  1393                         Name name, int kind) {
  1394         return access(
  1395             findIdent(env, name, kind),
  1396             pos, env.enclClass.sym.type, name, false);
  1399     /** Resolve an unqualified method identifier.
  1400      *  @param pos       The position to use for error reporting.
  1401      *  @param env       The environment current at the method invocation.
  1402      *  @param name      The identifier's name.
  1403      *  @param argtypes  The types of the invocation's value arguments.
  1404      *  @param typeargtypes  The types of the invocation's type arguments.
  1405      */
  1406     Symbol resolveMethod(DiagnosticPosition pos,
  1407                          Env<AttrContext> env,
  1408                          Name name,
  1409                          List<Type> argtypes,
  1410                          List<Type> typeargtypes) {
  1411         Symbol sym = startResolution();
  1412         List<MethodResolutionPhase> steps = methodResolutionSteps;
  1413         while (steps.nonEmpty() &&
  1414                steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  1415                sym.kind >= ERRONEOUS) {
  1416             currentStep = steps.head;
  1417             sym = findFun(env, name, argtypes, typeargtypes,
  1418                     steps.head.isBoxingRequired,
  1419                     env.info.varArgs = steps.head.isVarargsRequired);
  1420             methodResolutionCache.put(steps.head, sym);
  1421             steps = steps.tail;
  1423         if (sym.kind >= AMBIGUOUS) {//if nothing is found return the 'first' error
  1424             MethodResolutionPhase errPhase =
  1425                     firstErroneousResolutionPhase();
  1426             sym = access(methodResolutionCache.get(errPhase),
  1427                     pos, env.enclClass.sym.type, name, false, argtypes, typeargtypes);
  1428             env.info.varArgs = errPhase.isVarargsRequired;
  1430         return sym;
  1433     private Symbol startResolution() {
  1434         wrongMethod.clear();
  1435         wrongMethods.clear();
  1436         return methodNotFound;
  1439     /** Resolve a qualified method identifier
  1440      *  @param pos       The position to use for error reporting.
  1441      *  @param env       The environment current at the method invocation.
  1442      *  @param site      The type of the qualifying expression, in which
  1443      *                   identifier is searched.
  1444      *  @param name      The identifier's name.
  1445      *  @param argtypes  The types of the invocation's value arguments.
  1446      *  @param typeargtypes  The types of the invocation's type arguments.
  1447      */
  1448     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
  1449                                   Type site, Name name, List<Type> argtypes,
  1450                                   List<Type> typeargtypes) {
  1451         return resolveQualifiedMethod(pos, env, site.tsym, site, name, argtypes, typeargtypes);
  1453     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
  1454                                   Symbol location, Type site, Name name, List<Type> argtypes,
  1455                                   List<Type> typeargtypes) {
  1456         Symbol sym = startResolution();
  1457         List<MethodResolutionPhase> steps = methodResolutionSteps;
  1458         while (steps.nonEmpty() &&
  1459                steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  1460                sym.kind >= ERRONEOUS) {
  1461             currentStep = steps.head;
  1462             sym = findMethod(env, site, name, argtypes, typeargtypes,
  1463                     steps.head.isBoxingRequired(),
  1464                     env.info.varArgs = steps.head.isVarargsRequired(), false);
  1465             methodResolutionCache.put(steps.head, sym);
  1466             steps = steps.tail;
  1468         if (sym.kind >= AMBIGUOUS) {
  1469             if (site.tsym.isPolymorphicSignatureGeneric()) {
  1470                 //polymorphic receiver - synthesize new method symbol
  1471                 env.info.varArgs = false;
  1472                 sym = findPolymorphicSignatureInstance(env,
  1473                         site, name, null, argtypes);
  1475             else {
  1476                 //if nothing is found return the 'first' error
  1477                 MethodResolutionPhase errPhase =
  1478                         firstErroneousResolutionPhase();
  1479                 sym = access(methodResolutionCache.get(errPhase),
  1480                         pos, location, site, name, true, argtypes, typeargtypes);
  1481                 env.info.varArgs = errPhase.isVarargsRequired;
  1483         } else if (allowMethodHandles && sym.isPolymorphicSignatureGeneric()) {
  1484             //non-instantiated polymorphic signature - synthesize new method symbol
  1485             env.info.varArgs = false;
  1486             sym = findPolymorphicSignatureInstance(env,
  1487                     site, name, (MethodSymbol)sym, argtypes);
  1489         return sym;
  1492     /** Find or create an implicit method of exactly the given type (after erasure).
  1493      *  Searches in a side table, not the main scope of the site.
  1494      *  This emulates the lookup process required by JSR 292 in JVM.
  1495      *  @param env       Attribution environment
  1496      *  @param site      The original type from where the selection takes place.
  1497      *  @param name      The method's name.
  1498      *  @param spMethod  A template for the implicit method, or null.
  1499      *  @param argtypes  The required argument types.
  1500      *  @param typeargtypes  The required type arguments.
  1501      */
  1502     Symbol findPolymorphicSignatureInstance(Env<AttrContext> env, Type site,
  1503                                             Name name,
  1504                                             MethodSymbol spMethod,  // sig. poly. method or null if none
  1505                                             List<Type> argtypes) {
  1506         Type mtype = infer.instantiatePolymorphicSignatureInstance(env,
  1507                 site, name, spMethod, argtypes);
  1508         long flags = ABSTRACT | HYPOTHETICAL | POLYMORPHIC_SIGNATURE |
  1509                     (spMethod != null ?
  1510                         spMethod.flags() & Flags.AccessFlags :
  1511                         Flags.PUBLIC | Flags.STATIC);
  1512         Symbol m = null;
  1513         for (Scope.Entry e = polymorphicSignatureScope.lookup(name);
  1514              e.scope != null;
  1515              e = e.next()) {
  1516             Symbol sym = e.sym;
  1517             if (types.isSameType(mtype, sym.type) &&
  1518                 (sym.flags() & Flags.STATIC) == (flags & Flags.STATIC) &&
  1519                 types.isSameType(sym.owner.type, site)) {
  1520                m = sym;
  1521                break;
  1524         if (m == null) {
  1525             // create the desired method
  1526             m = new MethodSymbol(flags, name, mtype, site.tsym);
  1527             polymorphicSignatureScope.enter(m);
  1529         return m;
  1532     /** Resolve a qualified method identifier, throw a fatal error if not
  1533      *  found.
  1534      *  @param pos       The position to use for error reporting.
  1535      *  @param env       The environment current at the method invocation.
  1536      *  @param site      The type of the qualifying expression, in which
  1537      *                   identifier is searched.
  1538      *  @param name      The identifier's name.
  1539      *  @param argtypes  The types of the invocation's value arguments.
  1540      *  @param typeargtypes  The types of the invocation's type arguments.
  1541      */
  1542     public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env,
  1543                                         Type site, Name name,
  1544                                         List<Type> argtypes,
  1545                                         List<Type> typeargtypes) {
  1546         Symbol sym = resolveQualifiedMethod(
  1547             pos, env, site.tsym, site, name, argtypes, typeargtypes);
  1548         if (sym.kind == MTH) return (MethodSymbol)sym;
  1549         else throw new FatalError(
  1550                  diags.fragment("fatal.err.cant.locate.meth",
  1551                                 name));
  1554     /** Resolve constructor.
  1555      *  @param pos       The position to use for error reporting.
  1556      *  @param env       The environment current at the constructor invocation.
  1557      *  @param site      The type of class for which a constructor is searched.
  1558      *  @param argtypes  The types of the constructor invocation's value
  1559      *                   arguments.
  1560      *  @param typeargtypes  The types of the constructor invocation's type
  1561      *                   arguments.
  1562      */
  1563     Symbol resolveConstructor(DiagnosticPosition pos,
  1564                               Env<AttrContext> env,
  1565                               Type site,
  1566                               List<Type> argtypes,
  1567                               List<Type> typeargtypes) {
  1568         Symbol sym = startResolution();
  1569         List<MethodResolutionPhase> steps = methodResolutionSteps;
  1570         while (steps.nonEmpty() &&
  1571                steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  1572                sym.kind >= ERRONEOUS) {
  1573             currentStep = steps.head;
  1574             sym = resolveConstructor(pos, env, site, argtypes, typeargtypes,
  1575                     steps.head.isBoxingRequired(),
  1576                     env.info.varArgs = steps.head.isVarargsRequired());
  1577             methodResolutionCache.put(steps.head, sym);
  1578             steps = steps.tail;
  1580         if (sym.kind >= AMBIGUOUS) {//if nothing is found return the 'first' error
  1581             MethodResolutionPhase errPhase = firstErroneousResolutionPhase();
  1582             sym = access(methodResolutionCache.get(errPhase),
  1583                     pos, site, names.init, true, argtypes, typeargtypes);
  1584             env.info.varArgs = errPhase.isVarargsRequired();
  1586         return sym;
  1589     /** Resolve constructor using diamond inference.
  1590      *  @param pos       The position to use for error reporting.
  1591      *  @param env       The environment current at the constructor invocation.
  1592      *  @param site      The type of class for which a constructor is searched.
  1593      *                   The scope of this class has been touched in attribution.
  1594      *  @param argtypes  The types of the constructor invocation's value
  1595      *                   arguments.
  1596      *  @param typeargtypes  The types of the constructor invocation's type
  1597      *                   arguments.
  1598      */
  1599     Symbol resolveDiamond(DiagnosticPosition pos,
  1600                               Env<AttrContext> env,
  1601                               Type site,
  1602                               List<Type> argtypes,
  1603                               List<Type> typeargtypes) {
  1604         Symbol sym = startResolution();
  1605         List<MethodResolutionPhase> steps = methodResolutionSteps;
  1606         while (steps.nonEmpty() &&
  1607                steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  1608                sym.kind >= ERRONEOUS) {
  1609             currentStep = steps.head;
  1610             sym = resolveConstructor(pos, env, site, argtypes, typeargtypes,
  1611                     steps.head.isBoxingRequired(),
  1612                     env.info.varArgs = steps.head.isVarargsRequired());
  1613             methodResolutionCache.put(steps.head, sym);
  1614             steps = steps.tail;
  1616         if (sym.kind >= AMBIGUOUS) {
  1617             final JCDiagnostic details = sym.kind == WRONG_MTH ?
  1618                 ((InapplicableSymbolError)sym).explanation :
  1619                 null;
  1620             Symbol errSym = new ResolveError(WRONG_MTH, "diamond error") {
  1621                 @Override
  1622                 JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos,
  1623                         Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
  1624                     String key = details == null ?
  1625                         "cant.apply.diamond" :
  1626                         "cant.apply.diamond.1";
  1627                     return diags.create(dkind, log.currentSource(), pos, key,
  1628                             diags.fragment("diamond", site.tsym), details);
  1630             };
  1631             MethodResolutionPhase errPhase = firstErroneousResolutionPhase();
  1632             sym = access(errSym, pos, site, names.init, true, argtypes, typeargtypes);
  1633             env.info.varArgs = errPhase.isVarargsRequired();
  1635         return sym;
  1638     /** Resolve constructor.
  1639      *  @param pos       The position to use for error reporting.
  1640      *  @param env       The environment current at the constructor invocation.
  1641      *  @param site      The type of class for which a constructor is searched.
  1642      *  @param argtypes  The types of the constructor invocation's value
  1643      *                   arguments.
  1644      *  @param typeargtypes  The types of the constructor invocation's type
  1645      *                   arguments.
  1646      *  @param allowBoxing Allow boxing and varargs conversions.
  1647      *  @param useVarargs Box trailing arguments into an array for varargs.
  1648      */
  1649     Symbol resolveConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  1650                               Type site, List<Type> argtypes,
  1651                               List<Type> typeargtypes,
  1652                               boolean allowBoxing,
  1653                               boolean useVarargs) {
  1654         Symbol sym = findMethod(env, site,
  1655                                 names.init, argtypes,
  1656                                 typeargtypes, allowBoxing,
  1657                                 useVarargs, false);
  1658         chk.checkDeprecated(pos, env.info.scope.owner, sym);
  1659         return sym;
  1662     /** Resolve a constructor, throw a fatal error if not found.
  1663      *  @param pos       The position to use for error reporting.
  1664      *  @param env       The environment current at the method invocation.
  1665      *  @param site      The type to be constructed.
  1666      *  @param argtypes  The types of the invocation's value arguments.
  1667      *  @param typeargtypes  The types of the invocation's type arguments.
  1668      */
  1669     public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  1670                                         Type site,
  1671                                         List<Type> argtypes,
  1672                                         List<Type> typeargtypes) {
  1673         Symbol sym = resolveConstructor(
  1674             pos, env, site, argtypes, typeargtypes);
  1675         if (sym.kind == MTH) return (MethodSymbol)sym;
  1676         else throw new FatalError(
  1677                  diags.fragment("fatal.err.cant.locate.ctor", site));
  1680     /** Resolve operator.
  1681      *  @param pos       The position to use for error reporting.
  1682      *  @param optag     The tag of the operation tree.
  1683      *  @param env       The environment current at the operation.
  1684      *  @param argtypes  The types of the operands.
  1685      */
  1686     Symbol resolveOperator(DiagnosticPosition pos, int optag,
  1687                            Env<AttrContext> env, List<Type> argtypes) {
  1688         Name name = treeinfo.operatorName(optag);
  1689         Symbol sym = findMethod(env, syms.predefClass.type, name, argtypes,
  1690                                 null, false, false, true);
  1691         if (boxingEnabled && sym.kind >= WRONG_MTHS)
  1692             sym = findMethod(env, syms.predefClass.type, name, argtypes,
  1693                              null, true, false, true);
  1694         return access(sym, pos, env.enclClass.sym.type, name,
  1695                       false, argtypes, null);
  1698     /** Resolve operator.
  1699      *  @param pos       The position to use for error reporting.
  1700      *  @param optag     The tag of the operation tree.
  1701      *  @param env       The environment current at the operation.
  1702      *  @param arg       The type of the operand.
  1703      */
  1704     Symbol resolveUnaryOperator(DiagnosticPosition pos, int optag, Env<AttrContext> env, Type arg) {
  1705         return resolveOperator(pos, optag, env, List.of(arg));
  1708     /** Resolve binary operator.
  1709      *  @param pos       The position to use for error reporting.
  1710      *  @param optag     The tag of the operation tree.
  1711      *  @param env       The environment current at the operation.
  1712      *  @param left      The types of the left operand.
  1713      *  @param right     The types of the right operand.
  1714      */
  1715     Symbol resolveBinaryOperator(DiagnosticPosition pos,
  1716                                  int optag,
  1717                                  Env<AttrContext> env,
  1718                                  Type left,
  1719                                  Type right) {
  1720         return resolveOperator(pos, optag, env, List.of(left, right));
  1723     /**
  1724      * Resolve `c.name' where name == this or name == super.
  1725      * @param pos           The position to use for error reporting.
  1726      * @param env           The environment current at the expression.
  1727      * @param c             The qualifier.
  1728      * @param name          The identifier's name.
  1729      */
  1730     Symbol resolveSelf(DiagnosticPosition pos,
  1731                        Env<AttrContext> env,
  1732                        TypeSymbol c,
  1733                        Name name) {
  1734         Env<AttrContext> env1 = env;
  1735         boolean staticOnly = false;
  1736         while (env1.outer != null) {
  1737             if (isStatic(env1)) staticOnly = true;
  1738             if (env1.enclClass.sym == c) {
  1739                 Symbol sym = env1.info.scope.lookup(name).sym;
  1740                 if (sym != null) {
  1741                     if (staticOnly) sym = new StaticError(sym);
  1742                     return access(sym, pos, env.enclClass.sym.type,
  1743                                   name, true);
  1746             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  1747             env1 = env1.outer;
  1749         log.error(pos, "not.encl.class", c);
  1750         return syms.errSymbol;
  1753     /**
  1754      * Resolve `c.this' for an enclosing class c that contains the
  1755      * named member.
  1756      * @param pos           The position to use for error reporting.
  1757      * @param env           The environment current at the expression.
  1758      * @param member        The member that must be contained in the result.
  1759      */
  1760     Symbol resolveSelfContaining(DiagnosticPosition pos,
  1761                                  Env<AttrContext> env,
  1762                                  Symbol member,
  1763                                  boolean isSuperCall) {
  1764         Name name = names._this;
  1765         Env<AttrContext> env1 = isSuperCall ? env.outer : env;
  1766         boolean staticOnly = false;
  1767         if (env1 != null) {
  1768             while (env1 != null && env1.outer != null) {
  1769                 if (isStatic(env1)) staticOnly = true;
  1770                 if (env1.enclClass.sym.isSubClass(member.owner, types)) {
  1771                     Symbol sym = env1.info.scope.lookup(name).sym;
  1772                     if (sym != null) {
  1773                         if (staticOnly) sym = new StaticError(sym);
  1774                         return access(sym, pos, env.enclClass.sym.type,
  1775                                       name, true);
  1778                 if ((env1.enclClass.sym.flags() & STATIC) != 0)
  1779                     staticOnly = true;
  1780                 env1 = env1.outer;
  1783         log.error(pos, "encl.class.required", member);
  1784         return syms.errSymbol;
  1787     /**
  1788      * Resolve an appropriate implicit this instance for t's container.
  1789      * JLS 8.8.5.1 and 15.9.2
  1790      */
  1791     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
  1792         return resolveImplicitThis(pos, env, t, false);
  1795     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t, boolean isSuperCall) {
  1796         Type thisType = (((t.tsym.owner.kind & (MTH|VAR)) != 0)
  1797                          ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
  1798                          : resolveSelfContaining(pos, env, t.tsym, isSuperCall)).type;
  1799         if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
  1800             log.error(pos, "cant.ref.before.ctor.called", "this");
  1801         return thisType;
  1804 /* ***************************************************************************
  1805  *  ResolveError classes, indicating error situations when accessing symbols
  1806  ****************************************************************************/
  1808     public void logAccessError(Env<AttrContext> env, JCTree tree, Type type) {
  1809         AccessError error = new AccessError(env, type.getEnclosingType(), type.tsym);
  1810         logResolveError(error, tree.pos(), type.getEnclosingType().tsym, type.getEnclosingType(), null, null, null);
  1812     //where
  1813     private void logResolveError(ResolveError error,
  1814             DiagnosticPosition pos,
  1815             Symbol location,
  1816             Type site,
  1817             Name name,
  1818             List<Type> argtypes,
  1819             List<Type> typeargtypes) {
  1820         JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
  1821                 pos, location, site, name, argtypes, typeargtypes);
  1822         if (d != null) {
  1823             d.setFlag(DiagnosticFlag.RESOLVE_ERROR);
  1824             log.report(d);
  1828     private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
  1830     public Object methodArguments(List<Type> argtypes) {
  1831         return argtypes.isEmpty() ? noArgs : argtypes;
  1834     /**
  1835      * Root class for resolution errors. Subclass of ResolveError
  1836      * represent a different kinds of resolution error - as such they must
  1837      * specify how they map into concrete compiler diagnostics.
  1838      */
  1839     private abstract class ResolveError extends Symbol {
  1841         /** The name of the kind of error, for debugging only. */
  1842         final String debugName;
  1844         ResolveError(int kind, String debugName) {
  1845             super(kind, 0, null, null, null);
  1846             this.debugName = debugName;
  1849         @Override
  1850         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
  1851             throw new AssertionError();
  1854         @Override
  1855         public String toString() {
  1856             return debugName;
  1859         @Override
  1860         public boolean exists() {
  1861             return false;
  1864         /**
  1865          * Create an external representation for this erroneous symbol to be
  1866          * used during attribution - by default this returns the symbol of a
  1867          * brand new error type which stores the original type found
  1868          * during resolution.
  1870          * @param name     the name used during resolution
  1871          * @param location the location from which the symbol is accessed
  1872          */
  1873         protected Symbol access(Name name, TypeSymbol location) {
  1874             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  1877         /**
  1878          * Create a diagnostic representing this resolution error.
  1880          * @param dkind     The kind of the diagnostic to be created (e.g error).
  1881          * @param pos       The position to be used for error reporting.
  1882          * @param site      The original type from where the selection took place.
  1883          * @param name      The name of the symbol to be resolved.
  1884          * @param argtypes  The invocation's value arguments,
  1885          *                  if we looked for a method.
  1886          * @param typeargtypes  The invocation's type arguments,
  1887          *                      if we looked for a method.
  1888          */
  1889         abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  1890                 DiagnosticPosition pos,
  1891                 Symbol location,
  1892                 Type site,
  1893                 Name name,
  1894                 List<Type> argtypes,
  1895                 List<Type> typeargtypes);
  1897         /**
  1898          * A name designates an operator if it consists
  1899          * of a non-empty sequence of operator symbols +-~!/*%&|^<>=
  1900          */
  1901         boolean isOperator(Name name) {
  1902             int i = 0;
  1903             while (i < name.getByteLength() &&
  1904                    "+-~!*/%&|^<>=".indexOf(name.getByteAt(i)) >= 0) i++;
  1905             return i > 0 && i == name.getByteLength();
  1909     /**
  1910      * This class is the root class of all resolution errors caused by
  1911      * an invalid symbol being found during resolution.
  1912      */
  1913     abstract class InvalidSymbolError extends ResolveError {
  1915         /** The invalid symbol found during resolution */
  1916         Symbol sym;
  1918         InvalidSymbolError(int kind, Symbol sym, String debugName) {
  1919             super(kind, debugName);
  1920             this.sym = sym;
  1923         @Override
  1924         public boolean exists() {
  1925             return true;
  1928         @Override
  1929         public String toString() {
  1930              return super.toString() + " wrongSym=" + sym;
  1933         @Override
  1934         public Symbol access(Name name, TypeSymbol location) {
  1935             if (sym.kind >= AMBIGUOUS)
  1936                 return ((ResolveError)sym).access(name, location);
  1937             else if ((sym.kind & ERRONEOUS) == 0 && (sym.kind & TYP) != 0)
  1938                 return types.createErrorType(name, location, sym.type).tsym;
  1939             else
  1940                 return sym;
  1944     /**
  1945      * InvalidSymbolError error class indicating that a symbol matching a
  1946      * given name does not exists in a given site.
  1947      */
  1948     class SymbolNotFoundError extends ResolveError {
  1950         SymbolNotFoundError(int kind) {
  1951             super(kind, "symbol not found error");
  1954         @Override
  1955         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  1956                 DiagnosticPosition pos,
  1957                 Symbol location,
  1958                 Type site,
  1959                 Name name,
  1960                 List<Type> argtypes,
  1961                 List<Type> typeargtypes) {
  1962             argtypes = argtypes == null ? List.<Type>nil() : argtypes;
  1963             typeargtypes = typeargtypes == null ? List.<Type>nil() : typeargtypes;
  1964             if (name == names.error)
  1965                 return null;
  1967             if (isOperator(name)) {
  1968                 boolean isUnaryOp = argtypes.size() == 1;
  1969                 String key = argtypes.size() == 1 ?
  1970                     "operator.cant.be.applied" :
  1971                     "operator.cant.be.applied.1";
  1972                 Type first = argtypes.head;
  1973                 Type second = !isUnaryOp ? argtypes.tail.head : null;
  1974                 return diags.create(dkind, log.currentSource(), pos,
  1975                         key, name, first, second);
  1977             boolean hasLocation = false;
  1978             if (location == null) {
  1979                 location = site.tsym;
  1981             if (!location.name.isEmpty()) {
  1982                 if (location.kind == PCK && !site.tsym.exists()) {
  1983                     return diags.create(dkind, log.currentSource(), pos,
  1984                         "doesnt.exist", location);
  1986                 hasLocation = !location.name.equals(names._this) &&
  1987                         !location.name.equals(names._super);
  1989             boolean isConstructor = kind == ABSENT_MTH &&
  1990                     name == names.table.names.init;
  1991             KindName kindname = isConstructor ? KindName.CONSTRUCTOR : absentKind(kind);
  1992             Name idname = isConstructor ? site.tsym.name : name;
  1993             String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation);
  1994             if (hasLocation) {
  1995                 return diags.create(dkind, log.currentSource(), pos,
  1996                         errKey, kindname, idname, //symbol kindname, name
  1997                         typeargtypes, argtypes, //type parameters and arguments (if any)
  1998                         getLocationDiag(location, site)); //location kindname, type
  2000             else {
  2001                 return diags.create(dkind, log.currentSource(), pos,
  2002                         errKey, kindname, idname, //symbol kindname, name
  2003                         typeargtypes, argtypes); //type parameters and arguments (if any)
  2006         //where
  2007         private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) {
  2008             String key = "cant.resolve";
  2009             String suffix = hasLocation ? ".location" : "";
  2010             switch (kindname) {
  2011                 case METHOD:
  2012                 case CONSTRUCTOR: {
  2013                     suffix += ".args";
  2014                     suffix += hasTypeArgs ? ".params" : "";
  2017             return key + suffix;
  2019         private JCDiagnostic getLocationDiag(Symbol location, Type site) {
  2020             if (location.kind == VAR) {
  2021                 return diags.fragment("location.1",
  2022                     kindName(location),
  2023                     location,
  2024                     location.type);
  2025             } else {
  2026                 return diags.fragment("location",
  2027                     typeKindName(site),
  2028                     site,
  2029                     null);
  2034     /**
  2035      * InvalidSymbolError error class indicating that a given symbol
  2036      * (either a method, a constructor or an operand) is not applicable
  2037      * given an actual arguments/type argument list.
  2038      */
  2039     class InapplicableSymbolError extends InvalidSymbolError {
  2041         /** An auxiliary explanation set in case of instantiation errors. */
  2042         JCDiagnostic explanation;
  2044         InapplicableSymbolError(Symbol sym) {
  2045             super(WRONG_MTH, sym, "inapplicable symbol error");
  2048         /** Update sym and explanation and return this.
  2049          */
  2050         InapplicableSymbolError setWrongSym(Symbol sym, JCDiagnostic explanation) {
  2051             this.sym = sym;
  2052             if (this.sym == sym && explanation != null)
  2053                 this.explanation = explanation; //update the details
  2054             return this;
  2057         /** Update sym and return this.
  2058          */
  2059         InapplicableSymbolError setWrongSym(Symbol sym) {
  2060             this.sym = sym;
  2061             return this;
  2064         @Override
  2065         public String toString() {
  2066             return super.toString() + " explanation=" + explanation;
  2069         @Override
  2070         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2071                 DiagnosticPosition pos,
  2072                 Symbol location,
  2073                 Type site,
  2074                 Name name,
  2075                 List<Type> argtypes,
  2076                 List<Type> typeargtypes) {
  2077             if (name == names.error)
  2078                 return null;
  2080             if (isOperator(name)) {
  2081                 boolean isUnaryOp = argtypes.size() == 1;
  2082                 String key = argtypes.size() == 1 ?
  2083                     "operator.cant.be.applied" :
  2084                     "operator.cant.be.applied.1";
  2085                 Type first = argtypes.head;
  2086                 Type second = !isUnaryOp ? argtypes.tail.head : null;
  2087                 return diags.create(dkind, log.currentSource(), pos,
  2088                         key, name, first, second);
  2090             else {
  2091                 Symbol ws = sym.asMemberOf(site, types);
  2092                 return diags.create(dkind, log.currentSource(), pos,
  2093                           "cant.apply.symbol" + (explanation != null ? ".1" : ""),
  2094                           kindName(ws),
  2095                           ws.name == names.init ? ws.owner.name : ws.name,
  2096                           methodArguments(ws.type.getParameterTypes()),
  2097                           methodArguments(argtypes),
  2098                           kindName(ws.owner),
  2099                           ws.owner.type,
  2100                           explanation);
  2104         void clear() {
  2105             explanation = null;
  2108         @Override
  2109         public Symbol access(Name name, TypeSymbol location) {
  2110             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  2114     /**
  2115      * ResolveError error class indicating that a set of symbols
  2116      * (either methods, constructors or operands) is not applicable
  2117      * given an actual arguments/type argument list.
  2118      */
  2119     class InapplicableSymbolsError extends ResolveError {
  2121         private List<Candidate> candidates = List.nil();
  2123         InapplicableSymbolsError(Symbol sym) {
  2124             super(WRONG_MTHS, "inapplicable symbols");
  2127         @Override
  2128         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2129                 DiagnosticPosition pos,
  2130                 Symbol location,
  2131                 Type site,
  2132                 Name name,
  2133                 List<Type> argtypes,
  2134                 List<Type> typeargtypes) {
  2135             if (candidates.nonEmpty()) {
  2136                 JCDiagnostic err = diags.create(dkind,
  2137                         log.currentSource(),
  2138                         pos,
  2139                         "cant.apply.symbols",
  2140                         name == names.init ? KindName.CONSTRUCTOR : absentKind(kind),
  2141                         getName(),
  2142                         argtypes);
  2143                 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(site));
  2144             } else {
  2145                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
  2146                     location, site, name, argtypes, typeargtypes);
  2150         //where
  2151         List<JCDiagnostic> candidateDetails(Type site) {
  2152             List<JCDiagnostic> details = List.nil();
  2153             for (Candidate c : candidates)
  2154                 details = details.prepend(c.getDiagnostic(site));
  2155             return details.reverse();
  2158         Symbol addCandidate(MethodResolutionPhase currentStep, Symbol sym, JCDiagnostic details) {
  2159             Candidate c = new Candidate(currentStep, sym, details);
  2160             if (c.isValid() && !candidates.contains(c))
  2161                 candidates = candidates.append(c);
  2162             return this;
  2165         void clear() {
  2166             candidates = List.nil();
  2169         private Name getName() {
  2170             Symbol sym = candidates.head.sym;
  2171             return sym.name == names.init ?
  2172                 sym.owner.name :
  2173                 sym.name;
  2176         private class Candidate {
  2178             final MethodResolutionPhase step;
  2179             final Symbol sym;
  2180             final JCDiagnostic details;
  2182             private Candidate(MethodResolutionPhase step, Symbol sym, JCDiagnostic details) {
  2183                 this.step = step;
  2184                 this.sym = sym;
  2185                 this.details = details;
  2188             JCDiagnostic getDiagnostic(Type site) {
  2189                 return diags.fragment("inapplicable.method",
  2190                         Kinds.kindName(sym),
  2191                         sym.location(site, types),
  2192                         sym.asMemberOf(site, types),
  2193                         details);
  2196             @Override
  2197             public boolean equals(Object o) {
  2198                 if (o instanceof Candidate) {
  2199                     Symbol s1 = this.sym;
  2200                     Symbol s2 = ((Candidate)o).sym;
  2201                     if  ((s1 != s2 &&
  2202                         (s1.overrides(s2, s1.owner.type.tsym, types, false) ||
  2203                         (s2.overrides(s1, s2.owner.type.tsym, types, false)))) ||
  2204                         ((s1.isConstructor() || s2.isConstructor()) && s1.owner != s2.owner))
  2205                         return true;
  2207                 return false;
  2210             boolean isValid() {
  2211                 return  (((sym.flags() & VARARGS) != 0 && step == VARARITY) ||
  2212                           (sym.flags() & VARARGS) == 0 && step == (boxingEnabled ? BOX : BASIC));
  2217     /**
  2218      * An InvalidSymbolError error class indicating that a symbol is not
  2219      * accessible from a given site
  2220      */
  2221     class AccessError extends InvalidSymbolError {
  2223         private Env<AttrContext> env;
  2224         private Type site;
  2226         AccessError(Symbol sym) {
  2227             this(null, null, sym);
  2230         AccessError(Env<AttrContext> env, Type site, Symbol sym) {
  2231             super(HIDDEN, sym, "access error");
  2232             this.env = env;
  2233             this.site = site;
  2234             if (debugResolve)
  2235                 log.error("proc.messager", sym + " @ " + site + " is inaccessible.");
  2238         @Override
  2239         public boolean exists() {
  2240             return false;
  2243         @Override
  2244         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2245                 DiagnosticPosition pos,
  2246                 Symbol location,
  2247                 Type site,
  2248                 Name name,
  2249                 List<Type> argtypes,
  2250                 List<Type> typeargtypes) {
  2251             if (sym.owner.type.tag == ERROR)
  2252                 return null;
  2254             if (sym.name == names.init && sym.owner != site.tsym) {
  2255                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
  2256                         pos, location, site, name, argtypes, typeargtypes);
  2258             else if ((sym.flags() & PUBLIC) != 0
  2259                 || (env != null && this.site != null
  2260                     && !isAccessible(env, this.site))) {
  2261                 return diags.create(dkind, log.currentSource(),
  2262                         pos, "not.def.access.class.intf.cant.access",
  2263                     sym, sym.location());
  2265             else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) {
  2266                 return diags.create(dkind, log.currentSource(),
  2267                         pos, "report.access", sym,
  2268                         asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
  2269                         sym.location());
  2271             else {
  2272                 return diags.create(dkind, log.currentSource(),
  2273                         pos, "not.def.public.cant.access", sym, sym.location());
  2278     /**
  2279      * InvalidSymbolError error class indicating that an instance member
  2280      * has erroneously been accessed from a static context.
  2281      */
  2282     class StaticError extends InvalidSymbolError {
  2284         StaticError(Symbol sym) {
  2285             super(STATICERR, sym, "static error");
  2288         @Override
  2289         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2290                 DiagnosticPosition pos,
  2291                 Symbol location,
  2292                 Type site,
  2293                 Name name,
  2294                 List<Type> argtypes,
  2295                 List<Type> typeargtypes) {
  2296             Symbol errSym = ((sym.kind == TYP && sym.type.tag == CLASS)
  2297                 ? types.erasure(sym.type).tsym
  2298                 : sym);
  2299             return diags.create(dkind, log.currentSource(), pos,
  2300                     "non-static.cant.be.ref", kindName(sym), errSym);
  2304     /**
  2305      * InvalidSymbolError error class indicating that a pair of symbols
  2306      * (either methods, constructors or operands) are ambiguous
  2307      * given an actual arguments/type argument list.
  2308      */
  2309     class AmbiguityError extends InvalidSymbolError {
  2311         /** The other maximally specific symbol */
  2312         Symbol sym2;
  2314         AmbiguityError(Symbol sym1, Symbol sym2) {
  2315             super(AMBIGUOUS, sym1, "ambiguity error");
  2316             this.sym2 = sym2;
  2319         @Override
  2320         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2321                 DiagnosticPosition pos,
  2322                 Symbol location,
  2323                 Type site,
  2324                 Name name,
  2325                 List<Type> argtypes,
  2326                 List<Type> typeargtypes) {
  2327             AmbiguityError pair = this;
  2328             while (true) {
  2329                 if (pair.sym.kind == AMBIGUOUS)
  2330                     pair = (AmbiguityError)pair.sym;
  2331                 else if (pair.sym2.kind == AMBIGUOUS)
  2332                     pair = (AmbiguityError)pair.sym2;
  2333                 else break;
  2335             Name sname = pair.sym.name;
  2336             if (sname == names.init) sname = pair.sym.owner.name;
  2337             return diags.create(dkind, log.currentSource(),
  2338                       pos, "ref.ambiguous", sname,
  2339                       kindName(pair.sym),
  2340                       pair.sym,
  2341                       pair.sym.location(site, types),
  2342                       kindName(pair.sym2),
  2343                       pair.sym2,
  2344                       pair.sym2.location(site, types));
  2348     enum MethodResolutionPhase {
  2349         BASIC(false, false),
  2350         BOX(true, false),
  2351         VARARITY(true, true);
  2353         boolean isBoxingRequired;
  2354         boolean isVarargsRequired;
  2356         MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) {
  2357            this.isBoxingRequired = isBoxingRequired;
  2358            this.isVarargsRequired = isVarargsRequired;
  2361         public boolean isBoxingRequired() {
  2362             return isBoxingRequired;
  2365         public boolean isVarargsRequired() {
  2366             return isVarargsRequired;
  2369         public boolean isApplicable(boolean boxingEnabled, boolean varargsEnabled) {
  2370             return (varargsEnabled || !isVarargsRequired) &&
  2371                    (boxingEnabled || !isBoxingRequired);
  2375     private Map<MethodResolutionPhase, Symbol> methodResolutionCache =
  2376         new HashMap<MethodResolutionPhase, Symbol>(MethodResolutionPhase.values().length);
  2378     final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
  2380     private MethodResolutionPhase currentStep = null;
  2382     private MethodResolutionPhase firstErroneousResolutionPhase() {
  2383         MethodResolutionPhase bestSoFar = BASIC;
  2384         Symbol sym = methodNotFound;
  2385         List<MethodResolutionPhase> steps = methodResolutionSteps;
  2386         while (steps.nonEmpty() &&
  2387                steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  2388                sym.kind >= WRONG_MTHS) {
  2389             sym = methodResolutionCache.get(steps.head);
  2390             bestSoFar = steps.head;
  2391             steps = steps.tail;
  2393         return bestSoFar;

mercurial