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

Fri, 14 Jan 2011 09:45:04 +0000

author
mcimadamore
date
Fri, 14 Jan 2011 09:45:04 +0000
changeset 820
2d5aff89aaa3
parent 816
7c537f4298fb
child 829
ce6175cfe11e
permissions
-rw-r--r--

6992698: JSR 292: remove support for transient syntax in polymorphic signature calls
Summary: special syntax to denote indy return type through type parameters should be removed (and cast shall be used instead)
Reviewed-by: jjg, jrose

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

mercurial