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

Wed, 19 Oct 2011 16:56:05 +0100

author
mcimadamore
date
Wed, 19 Oct 2011 16:56:05 +0100
changeset 1110
366c233eb838
parent 1059
0b5beb9562c6
child 1114
05814303a056
permissions
-rw-r--r--

7102515: javac running very very long and not returning
Summary: Verbose resolution diagnostics slow down with operator resolution
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.comp;
    28 import com.sun.tools.javac.util.*;
    29 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    30 import com.sun.tools.javac.code.*;
    31 import com.sun.tools.javac.jvm.*;
    32 import com.sun.tools.javac.tree.*;
    33 import com.sun.tools.javac.api.Formattable.LocalizedString;
    34 import static com.sun.tools.javac.comp.Resolve.MethodResolutionPhase.*;
    36 import com.sun.tools.javac.code.Type.*;
    37 import com.sun.tools.javac.code.Symbol.*;
    38 import com.sun.tools.javac.tree.JCTree.*;
    40 import static com.sun.tools.javac.code.Flags.*;
    41 import static com.sun.tools.javac.code.Kinds.*;
    42 import static com.sun.tools.javac.code.TypeTags.*;
    43 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
    44 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType;
    45 import javax.lang.model.element.ElementVisitor;
    47 import java.util.Map;
    48 import java.util.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                 if (operator) return bestSoFar;
   695                 wrongMethods.addCandidate(currentStep, wrongMethod.sym, wrongMethod.explanation);
   696             case WRONG_MTHS:
   697                 return wrongMethods.addCandidate(currentStep, sym, ex.getDiagnostic());
   698             default:
   699                 return bestSoFar;
   700             }
   701         }
   702         if (!isAccessible(env, site, sym)) {
   703             return (bestSoFar.kind == ABSENT_MTH)
   704                 ? new AccessError(env, site, sym)
   705                 : bestSoFar;
   706             }
   707         return (bestSoFar.kind > AMBIGUOUS)
   708             ? sym
   709             : mostSpecific(sym, bestSoFar, env, site,
   710                            allowBoxing && operator, useVarargs);
   711     }
   713     /* Return the most specific of the two methods for a call,
   714      *  given that both are accessible and applicable.
   715      *  @param m1               A new candidate for most specific.
   716      *  @param m2               The previous most specific candidate.
   717      *  @param env              The current environment.
   718      *  @param site             The original type from where the selection
   719      *                          takes place.
   720      *  @param allowBoxing Allow boxing conversions of arguments.
   721      *  @param useVarargs Box trailing arguments into an array for varargs.
   722      */
   723     Symbol mostSpecific(Symbol m1,
   724                         Symbol m2,
   725                         Env<AttrContext> env,
   726                         final Type site,
   727                         boolean allowBoxing,
   728                         boolean useVarargs) {
   729         switch (m2.kind) {
   730         case MTH:
   731             if (m1 == m2) return m1;
   732             boolean m1SignatureMoreSpecific = signatureMoreSpecific(env, site, m1, m2, allowBoxing, useVarargs);
   733             boolean m2SignatureMoreSpecific = signatureMoreSpecific(env, site, m2, m1, allowBoxing, useVarargs);
   734             if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) {
   735                 Type mt1 = types.memberType(site, m1);
   736                 Type mt2 = types.memberType(site, m2);
   737                 if (!types.overrideEquivalent(mt1, mt2))
   738                     return ambiguityError(m1, m2);
   740                 // same signature; select (a) the non-bridge method, or
   741                 // (b) the one that overrides the other, or (c) the concrete
   742                 // one, or (d) merge both abstract signatures
   743                 if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE))
   744                     return ((m1.flags() & BRIDGE) != 0) ? m2 : m1;
   746                 // if one overrides or hides the other, use it
   747                 TypeSymbol m1Owner = (TypeSymbol)m1.owner;
   748                 TypeSymbol m2Owner = (TypeSymbol)m2.owner;
   749                 if (types.asSuper(m1Owner.type, m2Owner) != null &&
   750                     ((m1.owner.flags_field & INTERFACE) == 0 ||
   751                      (m2.owner.flags_field & INTERFACE) != 0) &&
   752                     m1.overrides(m2, m1Owner, types, false))
   753                     return m1;
   754                 if (types.asSuper(m2Owner.type, m1Owner) != null &&
   755                     ((m2.owner.flags_field & INTERFACE) == 0 ||
   756                      (m1.owner.flags_field & INTERFACE) != 0) &&
   757                     m2.overrides(m1, m2Owner, types, false))
   758                     return m2;
   759                 boolean m1Abstract = (m1.flags() & ABSTRACT) != 0;
   760                 boolean m2Abstract = (m2.flags() & ABSTRACT) != 0;
   761                 if (m1Abstract && !m2Abstract) return m2;
   762                 if (m2Abstract && !m1Abstract) return m1;
   763                 // both abstract or both concrete
   764                 if (!m1Abstract && !m2Abstract)
   765                     return ambiguityError(m1, m2);
   766                 // check that both signatures have the same erasure
   767                 if (!types.isSameTypes(m1.erasure(types).getParameterTypes(),
   768                                        m2.erasure(types).getParameterTypes()))
   769                     return ambiguityError(m1, m2);
   770                 // both abstract, neither overridden; merge throws clause and result type
   771                 Type mst = mostSpecificReturnType(mt1, mt2);
   772                 if (mst == null) {
   773                     // Theoretically, this can't happen, but it is possible
   774                     // due to error recovery or mixing incompatible class files
   775                     return ambiguityError(m1, m2);
   776                 }
   777                 Symbol mostSpecific = mst == mt1 ? m1 : m2;
   778                 List<Type> allThrown = chk.intersect(mt1.getThrownTypes(), mt2.getThrownTypes());
   779                 Type newSig = types.createMethodTypeWithThrown(mostSpecific.type, allThrown);
   780                 MethodSymbol result = new MethodSymbol(
   781                         mostSpecific.flags(),
   782                         mostSpecific.name,
   783                         newSig,
   784                         mostSpecific.owner) {
   785                     @Override
   786                     public MethodSymbol implementation(TypeSymbol origin, Types types, boolean checkResult) {
   787                         if (origin == site.tsym)
   788                             return this;
   789                         else
   790                             return super.implementation(origin, types, checkResult);
   791                     }
   792                 };
   793                 return result;
   794             }
   795             if (m1SignatureMoreSpecific) return m1;
   796             if (m2SignatureMoreSpecific) return m2;
   797             return ambiguityError(m1, m2);
   798         case AMBIGUOUS:
   799             AmbiguityError e = (AmbiguityError)m2;
   800             Symbol err1 = mostSpecific(m1, e.sym, env, site, allowBoxing, useVarargs);
   801             Symbol err2 = mostSpecific(m1, e.sym2, env, site, allowBoxing, useVarargs);
   802             if (err1 == err2) return err1;
   803             if (err1 == e.sym && err2 == e.sym2) return m2;
   804             if (err1 instanceof AmbiguityError &&
   805                 err2 instanceof AmbiguityError &&
   806                 ((AmbiguityError)err1).sym == ((AmbiguityError)err2).sym)
   807                 return ambiguityError(m1, m2);
   808             else
   809                 return ambiguityError(err1, err2);
   810         default:
   811             throw new AssertionError();
   812         }
   813     }
   814     //where
   815     private boolean signatureMoreSpecific(Env<AttrContext> env, Type site, Symbol m1, Symbol m2, boolean allowBoxing, boolean useVarargs) {
   816         noteWarner.clear();
   817         Type mtype1 = types.memberType(site, adjustVarargs(m1, m2, useVarargs));
   818         Type mtype2 = instantiate(env, site, adjustVarargs(m2, m1, useVarargs),
   819                 types.lowerBoundArgtypes(mtype1), null,
   820                 allowBoxing, false, noteWarner);
   821         return mtype2 != null &&
   822                 !noteWarner.hasLint(Lint.LintCategory.UNCHECKED);
   823     }
   824     //where
   825     private Symbol adjustVarargs(Symbol to, Symbol from, boolean useVarargs) {
   826         List<Type> fromArgs = from.type.getParameterTypes();
   827         List<Type> toArgs = to.type.getParameterTypes();
   828         if (useVarargs &&
   829                 (from.flags() & VARARGS) != 0 &&
   830                 (to.flags() & VARARGS) != 0) {
   831             Type varargsTypeFrom = fromArgs.last();
   832             Type varargsTypeTo = toArgs.last();
   833             ListBuffer<Type> args = ListBuffer.lb();
   834             if (toArgs.length() < fromArgs.length()) {
   835                 //if we are checking a varargs method 'from' against another varargs
   836                 //method 'to' (where arity of 'to' < arity of 'from') then expand signature
   837                 //of 'to' to 'fit' arity of 'from' (this means adding fake formals to 'to'
   838                 //until 'to' signature has the same arity as 'from')
   839                 while (fromArgs.head != varargsTypeFrom) {
   840                     args.append(toArgs.head == varargsTypeTo ? types.elemtype(varargsTypeTo) : toArgs.head);
   841                     fromArgs = fromArgs.tail;
   842                     toArgs = toArgs.head == varargsTypeTo ?
   843                         toArgs :
   844                         toArgs.tail;
   845                 }
   846             } else {
   847                 //formal argument list is same as original list where last
   848                 //argument (array type) is removed
   849                 args.appendList(toArgs.reverse().tail.reverse());
   850             }
   851             //append varargs element type as last synthetic formal
   852             args.append(types.elemtype(varargsTypeTo));
   853             Type mtype = types.createMethodTypeWithParameters(to.type, args.toList());
   854             return new MethodSymbol(to.flags_field & ~VARARGS, to.name, mtype, to.owner);
   855         } else {
   856             return to;
   857         }
   858     }
   859     //where
   860     Type mostSpecificReturnType(Type mt1, Type mt2) {
   861         Type rt1 = mt1.getReturnType();
   862         Type rt2 = mt2.getReturnType();
   864         if (mt1.tag == FORALL && mt2.tag == FORALL) {
   865             //if both are generic methods, adjust return type ahead of subtyping check
   866             rt1 = types.subst(rt1, mt1.getTypeArguments(), mt2.getTypeArguments());
   867         }
   868         //first use subtyping, then return type substitutability
   869         if (types.isSubtype(rt1, rt2)) {
   870             return mt1;
   871         } else if (types.isSubtype(rt2, rt1)) {
   872             return mt2;
   873         } else if (types.returnTypeSubstitutable(mt1, mt2)) {
   874             return mt1;
   875         } else if (types.returnTypeSubstitutable(mt2, mt1)) {
   876             return mt2;
   877         } else {
   878             return null;
   879         }
   880     }
   881     //where
   882     Symbol ambiguityError(Symbol m1, Symbol m2) {
   883         if (((m1.flags() | m2.flags()) & CLASH) != 0) {
   884             return (m1.flags() & CLASH) == 0 ? m1 : m2;
   885         } else {
   886             return new AmbiguityError(m1, m2);
   887         }
   888     }
   890     /** Find best qualified method matching given name, type and value
   891      *  arguments.
   892      *  @param env       The current environment.
   893      *  @param site      The original type from where the selection
   894      *                   takes place.
   895      *  @param name      The method's name.
   896      *  @param argtypes  The method's value arguments.
   897      *  @param typeargtypes The method's type arguments
   898      *  @param allowBoxing Allow boxing conversions of arguments.
   899      *  @param useVarargs Box trailing arguments into an array for varargs.
   900      */
   901     Symbol findMethod(Env<AttrContext> env,
   902                       Type site,
   903                       Name name,
   904                       List<Type> argtypes,
   905                       List<Type> typeargtypes,
   906                       boolean allowBoxing,
   907                       boolean useVarargs,
   908                       boolean operator) {
   909         Symbol bestSoFar = methodNotFound;
   910         return findMethod(env,
   911                           site,
   912                           name,
   913                           argtypes,
   914                           typeargtypes,
   915                           site.tsym.type,
   916                           true,
   917                           bestSoFar,
   918                           allowBoxing,
   919                           useVarargs,
   920                           operator,
   921                           new HashSet<TypeSymbol>());
   922     }
   923     // where
   924     private Symbol findMethod(Env<AttrContext> env,
   925                               Type site,
   926                               Name name,
   927                               List<Type> argtypes,
   928                               List<Type> typeargtypes,
   929                               Type intype,
   930                               boolean abstractok,
   931                               Symbol bestSoFar,
   932                               boolean allowBoxing,
   933                               boolean useVarargs,
   934                               boolean operator,
   935                               Set<TypeSymbol> seen) {
   936         for (Type ct = intype; ct.tag == CLASS || ct.tag == TYPEVAR; ct = types.supertype(ct)) {
   937             while (ct.tag == TYPEVAR)
   938                 ct = ct.getUpperBound();
   939             ClassSymbol c = (ClassSymbol)ct.tsym;
   940             if (!seen.add(c)) return bestSoFar;
   941             if ((c.flags() & (ABSTRACT | INTERFACE | ENUM)) == 0)
   942                 abstractok = false;
   943             for (Scope.Entry e = c.members().lookup(name);
   944                  e.scope != null;
   945                  e = e.next()) {
   946                 //- System.out.println(" e " + e.sym);
   947                 if (e.sym.kind == MTH &&
   948                     (e.sym.flags_field & SYNTHETIC) == 0) {
   949                     bestSoFar = selectBest(env, site, argtypes, typeargtypes,
   950                                            e.sym, bestSoFar,
   951                                            allowBoxing,
   952                                            useVarargs,
   953                                            operator);
   954                 }
   955             }
   956             if (name == names.init)
   957                 break;
   958             //- System.out.println(" - " + bestSoFar);
   959             if (abstractok) {
   960                 Symbol concrete = methodNotFound;
   961                 if ((bestSoFar.flags() & ABSTRACT) == 0)
   962                     concrete = bestSoFar;
   963                 for (List<Type> l = types.interfaces(c.type);
   964                      l.nonEmpty();
   965                      l = l.tail) {
   966                     bestSoFar = findMethod(env, site, name, argtypes,
   967                                            typeargtypes,
   968                                            l.head, abstractok, bestSoFar,
   969                                            allowBoxing, useVarargs, operator, seen);
   970                 }
   971                 if (concrete != bestSoFar &&
   972                     concrete.kind < ERR  && bestSoFar.kind < ERR &&
   973                     types.isSubSignature(concrete.type, bestSoFar.type))
   974                     bestSoFar = concrete;
   975             }
   976         }
   977         return bestSoFar;
   978     }
   980     /** Find unqualified method matching given name, type and value arguments.
   981      *  @param env       The current environment.
   982      *  @param name      The method's name.
   983      *  @param argtypes  The method's value arguments.
   984      *  @param typeargtypes  The method's type arguments.
   985      *  @param allowBoxing Allow boxing conversions of arguments.
   986      *  @param useVarargs Box trailing arguments into an array for varargs.
   987      */
   988     Symbol findFun(Env<AttrContext> env, Name name,
   989                    List<Type> argtypes, List<Type> typeargtypes,
   990                    boolean allowBoxing, boolean useVarargs) {
   991         Symbol bestSoFar = methodNotFound;
   992         Symbol sym;
   993         Env<AttrContext> env1 = env;
   994         boolean staticOnly = false;
   995         while (env1.outer != null) {
   996             if (isStatic(env1)) staticOnly = true;
   997             sym = findMethod(
   998                 env1, env1.enclClass.sym.type, name, argtypes, typeargtypes,
   999                 allowBoxing, useVarargs, false);
  1000             if (sym.exists()) {
  1001                 if (staticOnly &&
  1002                     sym.kind == MTH &&
  1003                     sym.owner.kind == TYP &&
  1004                     (sym.flags() & STATIC) == 0) return new StaticError(sym);
  1005                 else return sym;
  1006             } else if (sym.kind < bestSoFar.kind) {
  1007                 bestSoFar = sym;
  1009             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  1010             env1 = env1.outer;
  1013         sym = findMethod(env, syms.predefClass.type, name, argtypes,
  1014                          typeargtypes, allowBoxing, useVarargs, false);
  1015         if (sym.exists())
  1016             return sym;
  1018         Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
  1019         for (; e.scope != null; e = e.next()) {
  1020             sym = e.sym;
  1021             Type origin = e.getOrigin().owner.type;
  1022             if (sym.kind == MTH) {
  1023                 if (e.sym.owner.type != origin)
  1024                     sym = sym.clone(e.getOrigin().owner);
  1025                 if (!isAccessible(env, origin, sym))
  1026                     sym = new AccessError(env, origin, sym);
  1027                 bestSoFar = selectBest(env, origin,
  1028                                        argtypes, typeargtypes,
  1029                                        sym, bestSoFar,
  1030                                        allowBoxing, useVarargs, false);
  1033         if (bestSoFar.exists())
  1034             return bestSoFar;
  1036         e = env.toplevel.starImportScope.lookup(name);
  1037         for (; e.scope != null; e = e.next()) {
  1038             sym = e.sym;
  1039             Type origin = e.getOrigin().owner.type;
  1040             if (sym.kind == MTH) {
  1041                 if (e.sym.owner.type != origin)
  1042                     sym = sym.clone(e.getOrigin().owner);
  1043                 if (!isAccessible(env, origin, sym))
  1044                     sym = new AccessError(env, origin, sym);
  1045                 bestSoFar = selectBest(env, origin,
  1046                                        argtypes, typeargtypes,
  1047                                        sym, bestSoFar,
  1048                                        allowBoxing, useVarargs, false);
  1051         return bestSoFar;
  1054     /** Load toplevel or member class with given fully qualified name and
  1055      *  verify that it is accessible.
  1056      *  @param env       The current environment.
  1057      *  @param name      The fully qualified name of the class to be loaded.
  1058      */
  1059     Symbol loadClass(Env<AttrContext> env, Name name) {
  1060         try {
  1061             ClassSymbol c = reader.loadClass(name);
  1062             return isAccessible(env, c) ? c : new AccessError(c);
  1063         } catch (ClassReader.BadClassFile err) {
  1064             throw err;
  1065         } catch (CompletionFailure ex) {
  1066             return typeNotFound;
  1070     /** Find qualified member type.
  1071      *  @param env       The current environment.
  1072      *  @param site      The original type from where the selection takes
  1073      *                   place.
  1074      *  @param name      The type's name.
  1075      *  @param c         The class to search for the member type. This is
  1076      *                   always a superclass or implemented interface of
  1077      *                   site's class.
  1078      */
  1079     Symbol findMemberType(Env<AttrContext> env,
  1080                           Type site,
  1081                           Name name,
  1082                           TypeSymbol c) {
  1083         Symbol bestSoFar = typeNotFound;
  1084         Symbol sym;
  1085         Scope.Entry e = c.members().lookup(name);
  1086         while (e.scope != null) {
  1087             if (e.sym.kind == TYP) {
  1088                 return isAccessible(env, site, e.sym)
  1089                     ? e.sym
  1090                     : new AccessError(env, site, e.sym);
  1092             e = e.next();
  1094         Type st = types.supertype(c.type);
  1095         if (st != null && st.tag == CLASS) {
  1096             sym = findMemberType(env, site, name, st.tsym);
  1097             if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1099         for (List<Type> l = types.interfaces(c.type);
  1100              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
  1101              l = l.tail) {
  1102             sym = findMemberType(env, site, name, l.head.tsym);
  1103             if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
  1104                 sym.owner != bestSoFar.owner)
  1105                 bestSoFar = new AmbiguityError(bestSoFar, sym);
  1106             else if (sym.kind < bestSoFar.kind)
  1107                 bestSoFar = sym;
  1109         return bestSoFar;
  1112     /** Find a global type in given scope and load corresponding class.
  1113      *  @param env       The current environment.
  1114      *  @param scope     The scope in which to look for the type.
  1115      *  @param name      The type's name.
  1116      */
  1117     Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name) {
  1118         Symbol bestSoFar = typeNotFound;
  1119         for (Scope.Entry e = scope.lookup(name); e.scope != null; e = e.next()) {
  1120             Symbol sym = loadClass(env, e.sym.flatName());
  1121             if (bestSoFar.kind == TYP && sym.kind == TYP &&
  1122                 bestSoFar != sym)
  1123                 return new AmbiguityError(bestSoFar, sym);
  1124             else if (sym.kind < bestSoFar.kind)
  1125                 bestSoFar = sym;
  1127         return bestSoFar;
  1130     /** Find an unqualified type symbol.
  1131      *  @param env       The current environment.
  1132      *  @param name      The type's name.
  1133      */
  1134     Symbol findType(Env<AttrContext> env, Name name) {
  1135         Symbol bestSoFar = typeNotFound;
  1136         Symbol sym;
  1137         boolean staticOnly = false;
  1138         for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
  1139             if (isStatic(env1)) staticOnly = true;
  1140             for (Scope.Entry e = env1.info.scope.lookup(name);
  1141                  e.scope != null;
  1142                  e = e.next()) {
  1143                 if (e.sym.kind == TYP) {
  1144                     if (staticOnly &&
  1145                         e.sym.type.tag == TYPEVAR &&
  1146                         e.sym.owner.kind == TYP) return new StaticError(e.sym);
  1147                     return e.sym;
  1151             sym = findMemberType(env1, env1.enclClass.sym.type, name,
  1152                                  env1.enclClass.sym);
  1153             if (staticOnly && sym.kind == TYP &&
  1154                 sym.type.tag == CLASS &&
  1155                 sym.type.getEnclosingType().tag == CLASS &&
  1156                 env1.enclClass.sym.type.isParameterized() &&
  1157                 sym.type.getEnclosingType().isParameterized())
  1158                 return new StaticError(sym);
  1159             else if (sym.exists()) return sym;
  1160             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1162             JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass;
  1163             if ((encl.sym.flags() & STATIC) != 0)
  1164                 staticOnly = true;
  1167         if (env.tree.getTag() != JCTree.IMPORT) {
  1168             sym = findGlobalType(env, env.toplevel.namedImportScope, name);
  1169             if (sym.exists()) return sym;
  1170             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1172             sym = findGlobalType(env, env.toplevel.packge.members(), name);
  1173             if (sym.exists()) return sym;
  1174             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1176             sym = findGlobalType(env, env.toplevel.starImportScope, name);
  1177             if (sym.exists()) return sym;
  1178             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1181         return bestSoFar;
  1184     /** Find an unqualified identifier which matches a specified kind set.
  1185      *  @param env       The current environment.
  1186      *  @param name      The indentifier's name.
  1187      *  @param kind      Indicates the possible symbol kinds
  1188      *                   (a subset of VAL, TYP, PCK).
  1189      */
  1190     Symbol findIdent(Env<AttrContext> env, Name name, int kind) {
  1191         Symbol bestSoFar = typeNotFound;
  1192         Symbol sym;
  1194         if ((kind & VAR) != 0) {
  1195             sym = findVar(env, name);
  1196             if (sym.exists()) return sym;
  1197             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1200         if ((kind & TYP) != 0) {
  1201             sym = findType(env, name);
  1202             if (sym.exists()) return sym;
  1203             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1206         if ((kind & PCK) != 0) return reader.enterPackage(name);
  1207         else return bestSoFar;
  1210     /** Find an identifier in a package which matches a specified kind set.
  1211      *  @param env       The current environment.
  1212      *  @param name      The identifier's name.
  1213      *  @param kind      Indicates the possible symbol kinds
  1214      *                   (a nonempty subset of TYP, PCK).
  1215      */
  1216     Symbol findIdentInPackage(Env<AttrContext> env, TypeSymbol pck,
  1217                               Name name, int kind) {
  1218         Name fullname = TypeSymbol.formFullName(name, pck);
  1219         Symbol bestSoFar = typeNotFound;
  1220         PackageSymbol pack = null;
  1221         if ((kind & PCK) != 0) {
  1222             pack = reader.enterPackage(fullname);
  1223             if (pack.exists()) return pack;
  1225         if ((kind & TYP) != 0) {
  1226             Symbol sym = loadClass(env, fullname);
  1227             if (sym.exists()) {
  1228                 // don't allow programs to use flatnames
  1229                 if (name == sym.name) return sym;
  1231             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1233         return (pack != null) ? pack : bestSoFar;
  1236     /** Find an identifier among the members of a given type `site'.
  1237      *  @param env       The current environment.
  1238      *  @param site      The type containing the symbol to be found.
  1239      *  @param name      The identifier's name.
  1240      *  @param kind      Indicates the possible symbol kinds
  1241      *                   (a subset of VAL, TYP).
  1242      */
  1243     Symbol findIdentInType(Env<AttrContext> env, Type site,
  1244                            Name name, int kind) {
  1245         Symbol bestSoFar = typeNotFound;
  1246         Symbol sym;
  1247         if ((kind & VAR) != 0) {
  1248             sym = findField(env, site, name, site.tsym);
  1249             if (sym.exists()) return sym;
  1250             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1253         if ((kind & TYP) != 0) {
  1254             sym = findMemberType(env, site, name, site.tsym);
  1255             if (sym.exists()) return sym;
  1256             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1258         return bestSoFar;
  1261 /* ***************************************************************************
  1262  *  Access checking
  1263  *  The following methods convert ResolveErrors to ErrorSymbols, issuing
  1264  *  an error message in the process
  1265  ****************************************************************************/
  1267     /** If `sym' is a bad symbol: report error and return errSymbol
  1268      *  else pass through unchanged,
  1269      *  additional arguments duplicate what has been used in trying to find the
  1270      *  symbol (--> flyweight pattern). This improves performance since we
  1271      *  expect misses to happen frequently.
  1273      *  @param sym       The symbol that was found, or a ResolveError.
  1274      *  @param pos       The position to use for error reporting.
  1275      *  @param site      The original type from where the selection took place.
  1276      *  @param name      The symbol's name.
  1277      *  @param argtypes  The invocation's value arguments,
  1278      *                   if we looked for a method.
  1279      *  @param typeargtypes  The invocation's type arguments,
  1280      *                   if we looked for a method.
  1281      */
  1282     Symbol access(Symbol sym,
  1283                   DiagnosticPosition pos,
  1284                   Symbol location,
  1285                   Type site,
  1286                   Name name,
  1287                   boolean qualified,
  1288                   List<Type> argtypes,
  1289                   List<Type> typeargtypes) {
  1290         if (sym.kind >= AMBIGUOUS) {
  1291             ResolveError errSym = (ResolveError)sym;
  1292             if (!site.isErroneous() &&
  1293                 !Type.isErroneous(argtypes) &&
  1294                 (typeargtypes==null || !Type.isErroneous(typeargtypes)))
  1295                 logResolveError(errSym, pos, location, site, name, argtypes, typeargtypes);
  1296             sym = errSym.access(name, qualified ? site.tsym : syms.noSymbol);
  1298         return sym;
  1301     /** Same as original access(), but without location.
  1302      */
  1303     Symbol access(Symbol sym,
  1304                   DiagnosticPosition pos,
  1305                   Type site,
  1306                   Name name,
  1307                   boolean qualified,
  1308                   List<Type> argtypes,
  1309                   List<Type> typeargtypes) {
  1310         return access(sym, pos, site.tsym, site, name, qualified, argtypes, typeargtypes);
  1313     /** Same as original access(), but without type arguments and arguments.
  1314      */
  1315     Symbol access(Symbol sym,
  1316                   DiagnosticPosition pos,
  1317                   Symbol location,
  1318                   Type site,
  1319                   Name name,
  1320                   boolean qualified) {
  1321         if (sym.kind >= AMBIGUOUS)
  1322             return access(sym, pos, location, site, name, qualified, List.<Type>nil(), null);
  1323         else
  1324             return sym;
  1327     /** Same as original access(), but without location, type arguments and arguments.
  1328      */
  1329     Symbol access(Symbol sym,
  1330                   DiagnosticPosition pos,
  1331                   Type site,
  1332                   Name name,
  1333                   boolean qualified) {
  1334         return access(sym, pos, site.tsym, site, name, qualified);
  1337     /** Check that sym is not an abstract method.
  1338      */
  1339     void checkNonAbstract(DiagnosticPosition pos, Symbol sym) {
  1340         if ((sym.flags() & ABSTRACT) != 0)
  1341             log.error(pos, "abstract.cant.be.accessed.directly",
  1342                       kindName(sym), sym, sym.location());
  1345 /* ***************************************************************************
  1346  *  Debugging
  1347  ****************************************************************************/
  1349     /** print all scopes starting with scope s and proceeding outwards.
  1350      *  used for debugging.
  1351      */
  1352     public void printscopes(Scope s) {
  1353         while (s != null) {
  1354             if (s.owner != null)
  1355                 System.err.print(s.owner + ": ");
  1356             for (Scope.Entry e = s.elems; e != null; e = e.sibling) {
  1357                 if ((e.sym.flags() & ABSTRACT) != 0)
  1358                     System.err.print("abstract ");
  1359                 System.err.print(e.sym + " ");
  1361             System.err.println();
  1362             s = s.next;
  1366     void printscopes(Env<AttrContext> env) {
  1367         while (env.outer != null) {
  1368             System.err.println("------------------------------");
  1369             printscopes(env.info.scope);
  1370             env = env.outer;
  1374     public void printscopes(Type t) {
  1375         while (t.tag == CLASS) {
  1376             printscopes(t.tsym.members());
  1377             t = types.supertype(t);
  1381 /* ***************************************************************************
  1382  *  Name resolution
  1383  *  Naming conventions are as for symbol lookup
  1384  *  Unlike the find... methods these methods will report access errors
  1385  ****************************************************************************/
  1387     /** Resolve an unqualified (non-method) identifier.
  1388      *  @param pos       The position to use for error reporting.
  1389      *  @param env       The environment current at the identifier use.
  1390      *  @param name      The identifier's name.
  1391      *  @param kind      The set of admissible symbol kinds for the identifier.
  1392      */
  1393     Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env,
  1394                         Name name, int kind) {
  1395         return access(
  1396             findIdent(env, name, kind),
  1397             pos, env.enclClass.sym.type, name, false);
  1400     /** Resolve an unqualified method identifier.
  1401      *  @param pos       The position to use for error reporting.
  1402      *  @param env       The environment current at the method invocation.
  1403      *  @param name      The identifier's name.
  1404      *  @param argtypes  The types of the invocation's value arguments.
  1405      *  @param typeargtypes  The types of the invocation's type arguments.
  1406      */
  1407     Symbol resolveMethod(DiagnosticPosition pos,
  1408                          Env<AttrContext> env,
  1409                          Name name,
  1410                          List<Type> argtypes,
  1411                          List<Type> typeargtypes) {
  1412         Symbol sym = startResolution();
  1413         List<MethodResolutionPhase> steps = methodResolutionSteps;
  1414         while (steps.nonEmpty() &&
  1415                steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  1416                sym.kind >= ERRONEOUS) {
  1417             currentStep = steps.head;
  1418             sym = findFun(env, name, argtypes, typeargtypes,
  1419                     steps.head.isBoxingRequired,
  1420                     env.info.varArgs = steps.head.isVarargsRequired);
  1421             methodResolutionCache.put(steps.head, sym);
  1422             steps = steps.tail;
  1424         if (sym.kind >= AMBIGUOUS) {//if nothing is found return the 'first' error
  1425             MethodResolutionPhase errPhase =
  1426                     firstErroneousResolutionPhase();
  1427             sym = access(methodResolutionCache.get(errPhase),
  1428                     pos, env.enclClass.sym.type, name, false, argtypes, typeargtypes);
  1429             env.info.varArgs = errPhase.isVarargsRequired;
  1431         return sym;
  1434     private Symbol startResolution() {
  1435         wrongMethod.clear();
  1436         wrongMethods.clear();
  1437         return methodNotFound;
  1440     /** Resolve a qualified method identifier
  1441      *  @param pos       The position to use for error reporting.
  1442      *  @param env       The environment current at the method invocation.
  1443      *  @param site      The type of the qualifying expression, in which
  1444      *                   identifier is searched.
  1445      *  @param name      The identifier's name.
  1446      *  @param argtypes  The types of the invocation's value arguments.
  1447      *  @param typeargtypes  The types of the invocation's type arguments.
  1448      */
  1449     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
  1450                                   Type site, Name name, List<Type> argtypes,
  1451                                   List<Type> typeargtypes) {
  1452         return resolveQualifiedMethod(pos, env, site.tsym, site, name, argtypes, typeargtypes);
  1454     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
  1455                                   Symbol location, Type site, Name name, List<Type> argtypes,
  1456                                   List<Type> typeargtypes) {
  1457         Symbol sym = startResolution();
  1458         List<MethodResolutionPhase> steps = methodResolutionSteps;
  1459         while (steps.nonEmpty() &&
  1460                steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  1461                sym.kind >= ERRONEOUS) {
  1462             currentStep = steps.head;
  1463             sym = findMethod(env, site, name, argtypes, typeargtypes,
  1464                     steps.head.isBoxingRequired(),
  1465                     env.info.varArgs = steps.head.isVarargsRequired(), false);
  1466             methodResolutionCache.put(steps.head, sym);
  1467             steps = steps.tail;
  1469         if (sym.kind >= AMBIGUOUS) {
  1470             if (site.tsym.isPolymorphicSignatureGeneric()) {
  1471                 //polymorphic receiver - synthesize new method symbol
  1472                 env.info.varArgs = false;
  1473                 sym = findPolymorphicSignatureInstance(env,
  1474                         site, name, null, argtypes);
  1476             else {
  1477                 //if nothing is found return the 'first' error
  1478                 MethodResolutionPhase errPhase =
  1479                         firstErroneousResolutionPhase();
  1480                 sym = access(methodResolutionCache.get(errPhase),
  1481                         pos, location, site, name, true, argtypes, typeargtypes);
  1482                 env.info.varArgs = errPhase.isVarargsRequired;
  1484         } else if (allowMethodHandles && sym.isPolymorphicSignatureGeneric()) {
  1485             //non-instantiated polymorphic signature - synthesize new method symbol
  1486             env.info.varArgs = false;
  1487             sym = findPolymorphicSignatureInstance(env,
  1488                     site, name, (MethodSymbol)sym, argtypes);
  1490         return sym;
  1493     /** Find or create an implicit method of exactly the given type (after erasure).
  1494      *  Searches in a side table, not the main scope of the site.
  1495      *  This emulates the lookup process required by JSR 292 in JVM.
  1496      *  @param env       Attribution environment
  1497      *  @param site      The original type from where the selection takes place.
  1498      *  @param name      The method's name.
  1499      *  @param spMethod  A template for the implicit method, or null.
  1500      *  @param argtypes  The required argument types.
  1501      *  @param typeargtypes  The required type arguments.
  1502      */
  1503     Symbol findPolymorphicSignatureInstance(Env<AttrContext> env, Type site,
  1504                                             Name name,
  1505                                             MethodSymbol spMethod,  // sig. poly. method or null if none
  1506                                             List<Type> argtypes) {
  1507         Type mtype = infer.instantiatePolymorphicSignatureInstance(env,
  1508                 site, name, spMethod, argtypes);
  1509         long flags = ABSTRACT | HYPOTHETICAL | POLYMORPHIC_SIGNATURE |
  1510                     (spMethod != null ?
  1511                         spMethod.flags() & Flags.AccessFlags :
  1512                         Flags.PUBLIC | Flags.STATIC);
  1513         Symbol m = null;
  1514         for (Scope.Entry e = polymorphicSignatureScope.lookup(name);
  1515              e.scope != null;
  1516              e = e.next()) {
  1517             Symbol sym = e.sym;
  1518             if (types.isSameType(mtype, sym.type) &&
  1519                 (sym.flags() & Flags.STATIC) == (flags & Flags.STATIC) &&
  1520                 types.isSameType(sym.owner.type, site)) {
  1521                m = sym;
  1522                break;
  1525         if (m == null) {
  1526             // create the desired method
  1527             m = new MethodSymbol(flags, name, mtype, site.tsym);
  1528             polymorphicSignatureScope.enter(m);
  1530         return m;
  1533     /** Resolve a qualified method identifier, throw a fatal error if not
  1534      *  found.
  1535      *  @param pos       The position to use for error reporting.
  1536      *  @param env       The environment current at the method invocation.
  1537      *  @param site      The type of the qualifying expression, in which
  1538      *                   identifier is searched.
  1539      *  @param name      The identifier's name.
  1540      *  @param argtypes  The types of the invocation's value arguments.
  1541      *  @param typeargtypes  The types of the invocation's type arguments.
  1542      */
  1543     public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env,
  1544                                         Type site, Name name,
  1545                                         List<Type> argtypes,
  1546                                         List<Type> typeargtypes) {
  1547         Symbol sym = resolveQualifiedMethod(
  1548             pos, env, site.tsym, site, name, argtypes, typeargtypes);
  1549         if (sym.kind == MTH) return (MethodSymbol)sym;
  1550         else throw new FatalError(
  1551                  diags.fragment("fatal.err.cant.locate.meth",
  1552                                 name));
  1555     /** Resolve constructor.
  1556      *  @param pos       The position to use for error reporting.
  1557      *  @param env       The environment current at the constructor invocation.
  1558      *  @param site      The type of class for which a constructor is searched.
  1559      *  @param argtypes  The types of the constructor invocation's value
  1560      *                   arguments.
  1561      *  @param typeargtypes  The types of the constructor invocation's type
  1562      *                   arguments.
  1563      */
  1564     Symbol resolveConstructor(DiagnosticPosition pos,
  1565                               Env<AttrContext> env,
  1566                               Type site,
  1567                               List<Type> argtypes,
  1568                               List<Type> typeargtypes) {
  1569         Symbol sym = startResolution();
  1570         List<MethodResolutionPhase> steps = methodResolutionSteps;
  1571         while (steps.nonEmpty() &&
  1572                steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  1573                sym.kind >= ERRONEOUS) {
  1574             currentStep = steps.head;
  1575             sym = resolveConstructor(pos, env, site, argtypes, typeargtypes,
  1576                     steps.head.isBoxingRequired(),
  1577                     env.info.varArgs = steps.head.isVarargsRequired());
  1578             methodResolutionCache.put(steps.head, sym);
  1579             steps = steps.tail;
  1581         if (sym.kind >= AMBIGUOUS) {//if nothing is found return the 'first' error
  1582             MethodResolutionPhase errPhase = firstErroneousResolutionPhase();
  1583             sym = access(methodResolutionCache.get(errPhase),
  1584                     pos, site, names.init, true, argtypes, typeargtypes);
  1585             env.info.varArgs = errPhase.isVarargsRequired();
  1587         return sym;
  1590     /** Resolve constructor using diamond inference.
  1591      *  @param pos       The position to use for error reporting.
  1592      *  @param env       The environment current at the constructor invocation.
  1593      *  @param site      The type of class for which a constructor is searched.
  1594      *                   The scope of this class has been touched in attribution.
  1595      *  @param argtypes  The types of the constructor invocation's value
  1596      *                   arguments.
  1597      *  @param typeargtypes  The types of the constructor invocation's type
  1598      *                   arguments.
  1599      */
  1600     Symbol resolveDiamond(DiagnosticPosition pos,
  1601                               Env<AttrContext> env,
  1602                               Type site,
  1603                               List<Type> argtypes,
  1604                               List<Type> typeargtypes) {
  1605         Symbol sym = startResolution();
  1606         List<MethodResolutionPhase> steps = methodResolutionSteps;
  1607         while (steps.nonEmpty() &&
  1608                steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  1609                sym.kind >= ERRONEOUS) {
  1610             currentStep = steps.head;
  1611             sym = resolveConstructor(pos, env, site, argtypes, typeargtypes,
  1612                     steps.head.isBoxingRequired(),
  1613                     env.info.varArgs = steps.head.isVarargsRequired());
  1614             methodResolutionCache.put(steps.head, sym);
  1615             steps = steps.tail;
  1617         if (sym.kind >= AMBIGUOUS) {
  1618             final JCDiagnostic details = sym.kind == WRONG_MTH ?
  1619                 ((InapplicableSymbolError)sym).explanation :
  1620                 null;
  1621             Symbol errSym = new ResolveError(WRONG_MTH, "diamond error") {
  1622                 @Override
  1623                 JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos,
  1624                         Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
  1625                     String key = details == null ?
  1626                         "cant.apply.diamond" :
  1627                         "cant.apply.diamond.1";
  1628                     return diags.create(dkind, log.currentSource(), pos, key,
  1629                             diags.fragment("diamond", site.tsym), details);
  1631             };
  1632             MethodResolutionPhase errPhase = firstErroneousResolutionPhase();
  1633             sym = access(errSym, pos, site, names.init, true, argtypes, typeargtypes);
  1634             env.info.varArgs = errPhase.isVarargsRequired();
  1636         return sym;
  1639     /** Resolve constructor.
  1640      *  @param pos       The position to use for error reporting.
  1641      *  @param env       The environment current at the constructor invocation.
  1642      *  @param site      The type of class for which a constructor is searched.
  1643      *  @param argtypes  The types of the constructor invocation's value
  1644      *                   arguments.
  1645      *  @param typeargtypes  The types of the constructor invocation's type
  1646      *                   arguments.
  1647      *  @param allowBoxing Allow boxing and varargs conversions.
  1648      *  @param useVarargs Box trailing arguments into an array for varargs.
  1649      */
  1650     Symbol resolveConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  1651                               Type site, List<Type> argtypes,
  1652                               List<Type> typeargtypes,
  1653                               boolean allowBoxing,
  1654                               boolean useVarargs) {
  1655         Symbol sym = findMethod(env, site,
  1656                                 names.init, argtypes,
  1657                                 typeargtypes, allowBoxing,
  1658                                 useVarargs, false);
  1659         chk.checkDeprecated(pos, env.info.scope.owner, sym);
  1660         return sym;
  1663     /** Resolve a constructor, throw a fatal error if not found.
  1664      *  @param pos       The position to use for error reporting.
  1665      *  @param env       The environment current at the method invocation.
  1666      *  @param site      The type to be constructed.
  1667      *  @param argtypes  The types of the invocation's value arguments.
  1668      *  @param typeargtypes  The types of the invocation's type arguments.
  1669      */
  1670     public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  1671                                         Type site,
  1672                                         List<Type> argtypes,
  1673                                         List<Type> typeargtypes) {
  1674         Symbol sym = resolveConstructor(
  1675             pos, env, site, argtypes, typeargtypes);
  1676         if (sym.kind == MTH) return (MethodSymbol)sym;
  1677         else throw new FatalError(
  1678                  diags.fragment("fatal.err.cant.locate.ctor", site));
  1681     /** Resolve operator.
  1682      *  @param pos       The position to use for error reporting.
  1683      *  @param optag     The tag of the operation tree.
  1684      *  @param env       The environment current at the operation.
  1685      *  @param argtypes  The types of the operands.
  1686      */
  1687     Symbol resolveOperator(DiagnosticPosition pos, int optag,
  1688                            Env<AttrContext> env, List<Type> argtypes) {
  1689         startResolution();
  1690         Name name = treeinfo.operatorName(optag);
  1691         Symbol sym = findMethod(env, syms.predefClass.type, name, argtypes,
  1692                                 null, false, false, true);
  1693         if (boxingEnabled && sym.kind >= WRONG_MTHS)
  1694             sym = findMethod(env, syms.predefClass.type, name, argtypes,
  1695                              null, true, false, true);
  1696         return access(sym, pos, env.enclClass.sym.type, name,
  1697                       false, argtypes, null);
  1700     /** Resolve operator.
  1701      *  @param pos       The position to use for error reporting.
  1702      *  @param optag     The tag of the operation tree.
  1703      *  @param env       The environment current at the operation.
  1704      *  @param arg       The type of the operand.
  1705      */
  1706     Symbol resolveUnaryOperator(DiagnosticPosition pos, int optag, Env<AttrContext> env, Type arg) {
  1707         return resolveOperator(pos, optag, env, List.of(arg));
  1710     /** Resolve binary operator.
  1711      *  @param pos       The position to use for error reporting.
  1712      *  @param optag     The tag of the operation tree.
  1713      *  @param env       The environment current at the operation.
  1714      *  @param left      The types of the left operand.
  1715      *  @param right     The types of the right operand.
  1716      */
  1717     Symbol resolveBinaryOperator(DiagnosticPosition pos,
  1718                                  int optag,
  1719                                  Env<AttrContext> env,
  1720                                  Type left,
  1721                                  Type right) {
  1722         return resolveOperator(pos, optag, env, List.of(left, right));
  1725     /**
  1726      * Resolve `c.name' where name == this or name == super.
  1727      * @param pos           The position to use for error reporting.
  1728      * @param env           The environment current at the expression.
  1729      * @param c             The qualifier.
  1730      * @param name          The identifier's name.
  1731      */
  1732     Symbol resolveSelf(DiagnosticPosition pos,
  1733                        Env<AttrContext> env,
  1734                        TypeSymbol c,
  1735                        Name name) {
  1736         Env<AttrContext> env1 = env;
  1737         boolean staticOnly = false;
  1738         while (env1.outer != null) {
  1739             if (isStatic(env1)) staticOnly = true;
  1740             if (env1.enclClass.sym == c) {
  1741                 Symbol sym = env1.info.scope.lookup(name).sym;
  1742                 if (sym != null) {
  1743                     if (staticOnly) sym = new StaticError(sym);
  1744                     return access(sym, pos, env.enclClass.sym.type,
  1745                                   name, true);
  1748             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  1749             env1 = env1.outer;
  1751         log.error(pos, "not.encl.class", c);
  1752         return syms.errSymbol;
  1755     /**
  1756      * Resolve `c.this' for an enclosing class c that contains the
  1757      * named member.
  1758      * @param pos           The position to use for error reporting.
  1759      * @param env           The environment current at the expression.
  1760      * @param member        The member that must be contained in the result.
  1761      */
  1762     Symbol resolveSelfContaining(DiagnosticPosition pos,
  1763                                  Env<AttrContext> env,
  1764                                  Symbol member,
  1765                                  boolean isSuperCall) {
  1766         Name name = names._this;
  1767         Env<AttrContext> env1 = isSuperCall ? env.outer : env;
  1768         boolean staticOnly = false;
  1769         if (env1 != null) {
  1770             while (env1 != null && env1.outer != null) {
  1771                 if (isStatic(env1)) staticOnly = true;
  1772                 if (env1.enclClass.sym.isSubClass(member.owner, types)) {
  1773                     Symbol sym = env1.info.scope.lookup(name).sym;
  1774                     if (sym != null) {
  1775                         if (staticOnly) sym = new StaticError(sym);
  1776                         return access(sym, pos, env.enclClass.sym.type,
  1777                                       name, true);
  1780                 if ((env1.enclClass.sym.flags() & STATIC) != 0)
  1781                     staticOnly = true;
  1782                 env1 = env1.outer;
  1785         log.error(pos, "encl.class.required", member);
  1786         return syms.errSymbol;
  1789     /**
  1790      * Resolve an appropriate implicit this instance for t's container.
  1791      * JLS 8.8.5.1 and 15.9.2
  1792      */
  1793     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
  1794         return resolveImplicitThis(pos, env, t, false);
  1797     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t, boolean isSuperCall) {
  1798         Type thisType = (((t.tsym.owner.kind & (MTH|VAR)) != 0)
  1799                          ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
  1800                          : resolveSelfContaining(pos, env, t.tsym, isSuperCall)).type;
  1801         if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
  1802             log.error(pos, "cant.ref.before.ctor.called", "this");
  1803         return thisType;
  1806 /* ***************************************************************************
  1807  *  ResolveError classes, indicating error situations when accessing symbols
  1808  ****************************************************************************/
  1810     public void logAccessError(Env<AttrContext> env, JCTree tree, Type type) {
  1811         AccessError error = new AccessError(env, type.getEnclosingType(), type.tsym);
  1812         logResolveError(error, tree.pos(), type.getEnclosingType().tsym, type.getEnclosingType(), null, null, null);
  1814     //where
  1815     private void logResolveError(ResolveError error,
  1816             DiagnosticPosition pos,
  1817             Symbol location,
  1818             Type site,
  1819             Name name,
  1820             List<Type> argtypes,
  1821             List<Type> typeargtypes) {
  1822         JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
  1823                 pos, location, site, name, argtypes, typeargtypes);
  1824         if (d != null) {
  1825             d.setFlag(DiagnosticFlag.RESOLVE_ERROR);
  1826             log.report(d);
  1830     private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
  1832     public Object methodArguments(List<Type> argtypes) {
  1833         return argtypes.isEmpty() ? noArgs : argtypes;
  1836     /**
  1837      * Root class for resolution errors. Subclass of ResolveError
  1838      * represent a different kinds of resolution error - as such they must
  1839      * specify how they map into concrete compiler diagnostics.
  1840      */
  1841     private abstract class ResolveError extends Symbol {
  1843         /** The name of the kind of error, for debugging only. */
  1844         final String debugName;
  1846         ResolveError(int kind, String debugName) {
  1847             super(kind, 0, null, null, null);
  1848             this.debugName = debugName;
  1851         @Override
  1852         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
  1853             throw new AssertionError();
  1856         @Override
  1857         public String toString() {
  1858             return debugName;
  1861         @Override
  1862         public boolean exists() {
  1863             return false;
  1866         /**
  1867          * Create an external representation for this erroneous symbol to be
  1868          * used during attribution - by default this returns the symbol of a
  1869          * brand new error type which stores the original type found
  1870          * during resolution.
  1872          * @param name     the name used during resolution
  1873          * @param location the location from which the symbol is accessed
  1874          */
  1875         protected Symbol access(Name name, TypeSymbol location) {
  1876             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  1879         /**
  1880          * Create a diagnostic representing this resolution error.
  1882          * @param dkind     The kind of the diagnostic to be created (e.g error).
  1883          * @param pos       The position to be used for error reporting.
  1884          * @param site      The original type from where the selection took place.
  1885          * @param name      The name of the symbol to be resolved.
  1886          * @param argtypes  The invocation's value arguments,
  1887          *                  if we looked for a method.
  1888          * @param typeargtypes  The invocation's type arguments,
  1889          *                      if we looked for a method.
  1890          */
  1891         abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  1892                 DiagnosticPosition pos,
  1893                 Symbol location,
  1894                 Type site,
  1895                 Name name,
  1896                 List<Type> argtypes,
  1897                 List<Type> typeargtypes);
  1899         /**
  1900          * A name designates an operator if it consists
  1901          * of a non-empty sequence of operator symbols +-~!/*%&|^<>=
  1902          */
  1903         boolean isOperator(Name name) {
  1904             int i = 0;
  1905             while (i < name.getByteLength() &&
  1906                    "+-~!*/%&|^<>=".indexOf(name.getByteAt(i)) >= 0) i++;
  1907             return i > 0 && i == name.getByteLength();
  1911     /**
  1912      * This class is the root class of all resolution errors caused by
  1913      * an invalid symbol being found during resolution.
  1914      */
  1915     abstract class InvalidSymbolError extends ResolveError {
  1917         /** The invalid symbol found during resolution */
  1918         Symbol sym;
  1920         InvalidSymbolError(int kind, Symbol sym, String debugName) {
  1921             super(kind, debugName);
  1922             this.sym = sym;
  1925         @Override
  1926         public boolean exists() {
  1927             return true;
  1930         @Override
  1931         public String toString() {
  1932              return super.toString() + " wrongSym=" + sym;
  1935         @Override
  1936         public Symbol access(Name name, TypeSymbol location) {
  1937             if (sym.kind >= AMBIGUOUS)
  1938                 return ((ResolveError)sym).access(name, location);
  1939             else if ((sym.kind & ERRONEOUS) == 0 && (sym.kind & TYP) != 0)
  1940                 return types.createErrorType(name, location, sym.type).tsym;
  1941             else
  1942                 return sym;
  1946     /**
  1947      * InvalidSymbolError error class indicating that a symbol matching a
  1948      * given name does not exists in a given site.
  1949      */
  1950     class SymbolNotFoundError extends ResolveError {
  1952         SymbolNotFoundError(int kind) {
  1953             super(kind, "symbol not found error");
  1956         @Override
  1957         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  1958                 DiagnosticPosition pos,
  1959                 Symbol location,
  1960                 Type site,
  1961                 Name name,
  1962                 List<Type> argtypes,
  1963                 List<Type> typeargtypes) {
  1964             argtypes = argtypes == null ? List.<Type>nil() : argtypes;
  1965             typeargtypes = typeargtypes == null ? List.<Type>nil() : typeargtypes;
  1966             if (name == names.error)
  1967                 return null;
  1969             if (isOperator(name)) {
  1970                 boolean isUnaryOp = argtypes.size() == 1;
  1971                 String key = argtypes.size() == 1 ?
  1972                     "operator.cant.be.applied" :
  1973                     "operator.cant.be.applied.1";
  1974                 Type first = argtypes.head;
  1975                 Type second = !isUnaryOp ? argtypes.tail.head : null;
  1976                 return diags.create(dkind, log.currentSource(), pos,
  1977                         key, name, first, second);
  1979             boolean hasLocation = false;
  1980             if (location == null) {
  1981                 location = site.tsym;
  1983             if (!location.name.isEmpty()) {
  1984                 if (location.kind == PCK && !site.tsym.exists()) {
  1985                     return diags.create(dkind, log.currentSource(), pos,
  1986                         "doesnt.exist", location);
  1988                 hasLocation = !location.name.equals(names._this) &&
  1989                         !location.name.equals(names._super);
  1991             boolean isConstructor = kind == ABSENT_MTH &&
  1992                     name == names.table.names.init;
  1993             KindName kindname = isConstructor ? KindName.CONSTRUCTOR : absentKind(kind);
  1994             Name idname = isConstructor ? site.tsym.name : name;
  1995             String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation);
  1996             if (hasLocation) {
  1997                 return diags.create(dkind, log.currentSource(), pos,
  1998                         errKey, kindname, idname, //symbol kindname, name
  1999                         typeargtypes, argtypes, //type parameters and arguments (if any)
  2000                         getLocationDiag(location, site)); //location kindname, type
  2002             else {
  2003                 return diags.create(dkind, log.currentSource(), pos,
  2004                         errKey, kindname, idname, //symbol kindname, name
  2005                         typeargtypes, argtypes); //type parameters and arguments (if any)
  2008         //where
  2009         private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) {
  2010             String key = "cant.resolve";
  2011             String suffix = hasLocation ? ".location" : "";
  2012             switch (kindname) {
  2013                 case METHOD:
  2014                 case CONSTRUCTOR: {
  2015                     suffix += ".args";
  2016                     suffix += hasTypeArgs ? ".params" : "";
  2019             return key + suffix;
  2021         private JCDiagnostic getLocationDiag(Symbol location, Type site) {
  2022             if (location.kind == VAR) {
  2023                 return diags.fragment("location.1",
  2024                     kindName(location),
  2025                     location,
  2026                     location.type);
  2027             } else {
  2028                 return diags.fragment("location",
  2029                     typeKindName(site),
  2030                     site,
  2031                     null);
  2036     /**
  2037      * InvalidSymbolError error class indicating that a given symbol
  2038      * (either a method, a constructor or an operand) is not applicable
  2039      * given an actual arguments/type argument list.
  2040      */
  2041     class InapplicableSymbolError extends InvalidSymbolError {
  2043         /** An auxiliary explanation set in case of instantiation errors. */
  2044         JCDiagnostic explanation;
  2046         InapplicableSymbolError(Symbol sym) {
  2047             super(WRONG_MTH, sym, "inapplicable symbol error");
  2050         /** Update sym and explanation and return this.
  2051          */
  2052         InapplicableSymbolError setWrongSym(Symbol sym, JCDiagnostic explanation) {
  2053             this.sym = sym;
  2054             if (this.sym == sym && explanation != null)
  2055                 this.explanation = explanation; //update the details
  2056             return this;
  2059         /** Update sym and return this.
  2060          */
  2061         InapplicableSymbolError setWrongSym(Symbol sym) {
  2062             this.sym = sym;
  2063             return this;
  2066         @Override
  2067         public String toString() {
  2068             return super.toString() + " explanation=" + explanation;
  2071         @Override
  2072         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2073                 DiagnosticPosition pos,
  2074                 Symbol location,
  2075                 Type site,
  2076                 Name name,
  2077                 List<Type> argtypes,
  2078                 List<Type> typeargtypes) {
  2079             if (name == names.error)
  2080                 return null;
  2082             if (isOperator(name)) {
  2083                 boolean isUnaryOp = argtypes.size() == 1;
  2084                 String key = argtypes.size() == 1 ?
  2085                     "operator.cant.be.applied" :
  2086                     "operator.cant.be.applied.1";
  2087                 Type first = argtypes.head;
  2088                 Type second = !isUnaryOp ? argtypes.tail.head : null;
  2089                 return diags.create(dkind, log.currentSource(), pos,
  2090                         key, name, first, second);
  2092             else {
  2093                 Symbol ws = sym.asMemberOf(site, types);
  2094                 return diags.create(dkind, log.currentSource(), pos,
  2095                           "cant.apply.symbol" + (explanation != null ? ".1" : ""),
  2096                           kindName(ws),
  2097                           ws.name == names.init ? ws.owner.name : ws.name,
  2098                           methodArguments(ws.type.getParameterTypes()),
  2099                           methodArguments(argtypes),
  2100                           kindName(ws.owner),
  2101                           ws.owner.type,
  2102                           explanation);
  2106         void clear() {
  2107             explanation = null;
  2110         @Override
  2111         public Symbol access(Name name, TypeSymbol location) {
  2112             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  2116     /**
  2117      * ResolveError error class indicating that a set of symbols
  2118      * (either methods, constructors or operands) is not applicable
  2119      * given an actual arguments/type argument list.
  2120      */
  2121     class InapplicableSymbolsError extends ResolveError {
  2123         private List<Candidate> candidates = List.nil();
  2125         InapplicableSymbolsError(Symbol sym) {
  2126             super(WRONG_MTHS, "inapplicable symbols");
  2129         @Override
  2130         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2131                 DiagnosticPosition pos,
  2132                 Symbol location,
  2133                 Type site,
  2134                 Name name,
  2135                 List<Type> argtypes,
  2136                 List<Type> typeargtypes) {
  2137             if (candidates.nonEmpty()) {
  2138                 JCDiagnostic err = diags.create(dkind,
  2139                         log.currentSource(),
  2140                         pos,
  2141                         "cant.apply.symbols",
  2142                         name == names.init ? KindName.CONSTRUCTOR : absentKind(kind),
  2143                         getName(),
  2144                         argtypes);
  2145                 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(site));
  2146             } else {
  2147                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
  2148                     location, site, name, argtypes, typeargtypes);
  2152         //where
  2153         List<JCDiagnostic> candidateDetails(Type site) {
  2154             List<JCDiagnostic> details = List.nil();
  2155             for (Candidate c : candidates)
  2156                 details = details.prepend(c.getDiagnostic(site));
  2157             return details.reverse();
  2160         Symbol addCandidate(MethodResolutionPhase currentStep, Symbol sym, JCDiagnostic details) {
  2161             Candidate c = new Candidate(currentStep, sym, details);
  2162             if (c.isValid() && !candidates.contains(c))
  2163                 candidates = candidates.append(c);
  2164             return this;
  2167         void clear() {
  2168             candidates = List.nil();
  2171         private Name getName() {
  2172             Symbol sym = candidates.head.sym;
  2173             return sym.name == names.init ?
  2174                 sym.owner.name :
  2175                 sym.name;
  2178         private class Candidate {
  2180             final MethodResolutionPhase step;
  2181             final Symbol sym;
  2182             final JCDiagnostic details;
  2184             private Candidate(MethodResolutionPhase step, Symbol sym, JCDiagnostic details) {
  2185                 this.step = step;
  2186                 this.sym = sym;
  2187                 this.details = details;
  2190             JCDiagnostic getDiagnostic(Type site) {
  2191                 return diags.fragment("inapplicable.method",
  2192                         Kinds.kindName(sym),
  2193                         sym.location(site, types),
  2194                         sym.asMemberOf(site, types),
  2195                         details);
  2198             @Override
  2199             public boolean equals(Object o) {
  2200                 if (o instanceof Candidate) {
  2201                     Symbol s1 = this.sym;
  2202                     Symbol s2 = ((Candidate)o).sym;
  2203                     if  ((s1 != s2 &&
  2204                         (s1.overrides(s2, s1.owner.type.tsym, types, false) ||
  2205                         (s2.overrides(s1, s2.owner.type.tsym, types, false)))) ||
  2206                         ((s1.isConstructor() || s2.isConstructor()) && s1.owner != s2.owner))
  2207                         return true;
  2209                 return false;
  2212             boolean isValid() {
  2213                 return  (((sym.flags() & VARARGS) != 0 && step == VARARITY) ||
  2214                           (sym.flags() & VARARGS) == 0 && step == (boxingEnabled ? BOX : BASIC));
  2219     /**
  2220      * An InvalidSymbolError error class indicating that a symbol is not
  2221      * accessible from a given site
  2222      */
  2223     class AccessError extends InvalidSymbolError {
  2225         private Env<AttrContext> env;
  2226         private Type site;
  2228         AccessError(Symbol sym) {
  2229             this(null, null, sym);
  2232         AccessError(Env<AttrContext> env, Type site, Symbol sym) {
  2233             super(HIDDEN, sym, "access error");
  2234             this.env = env;
  2235             this.site = site;
  2236             if (debugResolve)
  2237                 log.error("proc.messager", sym + " @ " + site + " is inaccessible.");
  2240         @Override
  2241         public boolean exists() {
  2242             return false;
  2245         @Override
  2246         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2247                 DiagnosticPosition pos,
  2248                 Symbol location,
  2249                 Type site,
  2250                 Name name,
  2251                 List<Type> argtypes,
  2252                 List<Type> typeargtypes) {
  2253             if (sym.owner.type.tag == ERROR)
  2254                 return null;
  2256             if (sym.name == names.init && sym.owner != site.tsym) {
  2257                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
  2258                         pos, location, site, name, argtypes, typeargtypes);
  2260             else if ((sym.flags() & PUBLIC) != 0
  2261                 || (env != null && this.site != null
  2262                     && !isAccessible(env, this.site))) {
  2263                 return diags.create(dkind, log.currentSource(),
  2264                         pos, "not.def.access.class.intf.cant.access",
  2265                     sym, sym.location());
  2267             else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) {
  2268                 return diags.create(dkind, log.currentSource(),
  2269                         pos, "report.access", sym,
  2270                         asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
  2271                         sym.location());
  2273             else {
  2274                 return diags.create(dkind, log.currentSource(),
  2275                         pos, "not.def.public.cant.access", sym, sym.location());
  2280     /**
  2281      * InvalidSymbolError error class indicating that an instance member
  2282      * has erroneously been accessed from a static context.
  2283      */
  2284     class StaticError extends InvalidSymbolError {
  2286         StaticError(Symbol sym) {
  2287             super(STATICERR, sym, "static error");
  2290         @Override
  2291         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2292                 DiagnosticPosition pos,
  2293                 Symbol location,
  2294                 Type site,
  2295                 Name name,
  2296                 List<Type> argtypes,
  2297                 List<Type> typeargtypes) {
  2298             Symbol errSym = ((sym.kind == TYP && sym.type.tag == CLASS)
  2299                 ? types.erasure(sym.type).tsym
  2300                 : sym);
  2301             return diags.create(dkind, log.currentSource(), pos,
  2302                     "non-static.cant.be.ref", kindName(sym), errSym);
  2306     /**
  2307      * InvalidSymbolError error class indicating that a pair of symbols
  2308      * (either methods, constructors or operands) are ambiguous
  2309      * given an actual arguments/type argument list.
  2310      */
  2311     class AmbiguityError extends InvalidSymbolError {
  2313         /** The other maximally specific symbol */
  2314         Symbol sym2;
  2316         AmbiguityError(Symbol sym1, Symbol sym2) {
  2317             super(AMBIGUOUS, sym1, "ambiguity error");
  2318             this.sym2 = sym2;
  2321         @Override
  2322         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2323                 DiagnosticPosition pos,
  2324                 Symbol location,
  2325                 Type site,
  2326                 Name name,
  2327                 List<Type> argtypes,
  2328                 List<Type> typeargtypes) {
  2329             AmbiguityError pair = this;
  2330             while (true) {
  2331                 if (pair.sym.kind == AMBIGUOUS)
  2332                     pair = (AmbiguityError)pair.sym;
  2333                 else if (pair.sym2.kind == AMBIGUOUS)
  2334                     pair = (AmbiguityError)pair.sym2;
  2335                 else break;
  2337             Name sname = pair.sym.name;
  2338             if (sname == names.init) sname = pair.sym.owner.name;
  2339             return diags.create(dkind, log.currentSource(),
  2340                       pos, "ref.ambiguous", sname,
  2341                       kindName(pair.sym),
  2342                       pair.sym,
  2343                       pair.sym.location(site, types),
  2344                       kindName(pair.sym2),
  2345                       pair.sym2,
  2346                       pair.sym2.location(site, types));
  2350     enum MethodResolutionPhase {
  2351         BASIC(false, false),
  2352         BOX(true, false),
  2353         VARARITY(true, true);
  2355         boolean isBoxingRequired;
  2356         boolean isVarargsRequired;
  2358         MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) {
  2359            this.isBoxingRequired = isBoxingRequired;
  2360            this.isVarargsRequired = isVarargsRequired;
  2363         public boolean isBoxingRequired() {
  2364             return isBoxingRequired;
  2367         public boolean isVarargsRequired() {
  2368             return isVarargsRequired;
  2371         public boolean isApplicable(boolean boxingEnabled, boolean varargsEnabled) {
  2372             return (varargsEnabled || !isVarargsRequired) &&
  2373                    (boxingEnabled || !isBoxingRequired);
  2377     private Map<MethodResolutionPhase, Symbol> methodResolutionCache =
  2378         new HashMap<MethodResolutionPhase, Symbol>(MethodResolutionPhase.values().length);
  2380     final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
  2382     private MethodResolutionPhase currentStep = null;
  2384     private MethodResolutionPhase firstErroneousResolutionPhase() {
  2385         MethodResolutionPhase bestSoFar = BASIC;
  2386         Symbol sym = methodNotFound;
  2387         List<MethodResolutionPhase> steps = methodResolutionSteps;
  2388         while (steps.nonEmpty() &&
  2389                steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
  2390                sym.kind >= WRONG_MTHS) {
  2391             sym = methodResolutionCache.get(steps.head);
  2392             bestSoFar = steps.head;
  2393             steps = steps.tail;
  2395         return bestSoFar;

mercurial