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

Fri, 29 Aug 2008 11:10:12 -0700

author
jjg
date
Fri, 29 Aug 2008 11:10:12 -0700
changeset 104
5e89c4ca637c
parent 89
b6d5f53b3b29
child 110
91eea580fbe9
permissions
-rw-r--r--

6597471: unused imports in javax.tools.JavaCompiler
6597531: unused imports and unused private const. in com.sun.tools.javac.Server.java
Reviewed-by: mcimadamore
Contributed-by: davide.angelocola@gmail.com

     1 /*
     2  * Copyright 1999-2008 Sun Microsystems, Inc.  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.  Sun designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    22  * CA 95054 USA or visit www.sun.com if you need additional information or
    23  * have any 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.*;
    34 import com.sun.tools.javac.code.Type.*;
    35 import com.sun.tools.javac.code.Symbol.*;
    36 import com.sun.tools.javac.tree.JCTree.*;
    38 import static com.sun.tools.javac.code.Flags.*;
    39 import static com.sun.tools.javac.code.Kinds.*;
    40 import static com.sun.tools.javac.code.TypeTags.*;
    41 import javax.lang.model.element.ElementVisitor;
    43 /** Helper class for name resolution, used mostly by the attribution phase.
    44  *
    45  *  <p><b>This is NOT part of any API supported by Sun Microsystems.  If
    46  *  you write code that depends on this, you do so at your own risk.
    47  *  This code and its internal interfaces are subject to change or
    48  *  deletion without notice.</b>
    49  */
    50 public class Resolve {
    51     protected static final Context.Key<Resolve> resolveKey =
    52         new Context.Key<Resolve>();
    54     Name.Table names;
    55     Log log;
    56     Symtab syms;
    57     Check chk;
    58     Infer infer;
    59     ClassReader reader;
    60     TreeInfo treeinfo;
    61     Types types;
    62     JCDiagnostic.Factory diags;
    63     public final boolean boxingEnabled; // = source.allowBoxing();
    64     public final boolean varargsEnabled; // = source.allowVarargs();
    65     private final boolean debugResolve;
    67     public static Resolve instance(Context context) {
    68         Resolve instance = context.get(resolveKey);
    69         if (instance == null)
    70             instance = new Resolve(context);
    71         return instance;
    72     }
    74     protected Resolve(Context context) {
    75         context.put(resolveKey, this);
    76         syms = Symtab.instance(context);
    78         varNotFound = new
    79             ResolveError(ABSENT_VAR, syms.errSymbol, "variable not found");
    80         wrongMethod = new
    81             ResolveError(WRONG_MTH, syms.errSymbol, "method not found");
    82         wrongMethods = new
    83             ResolveError(WRONG_MTHS, syms.errSymbol, "wrong methods");
    84         methodNotFound = new
    85             ResolveError(ABSENT_MTH, syms.errSymbol, "method not found");
    86         typeNotFound = new
    87             ResolveError(ABSENT_TYP, syms.errSymbol, "type not found");
    89         names = Name.Table.instance(context);
    90         log = Log.instance(context);
    91         chk = Check.instance(context);
    92         infer = Infer.instance(context);
    93         reader = ClassReader.instance(context);
    94         treeinfo = TreeInfo.instance(context);
    95         types = Types.instance(context);
    96         diags = JCDiagnostic.Factory.instance(context);
    97         Source source = Source.instance(context);
    98         boxingEnabled = source.allowBoxing();
    99         varargsEnabled = source.allowVarargs();
   100         Options options = Options.instance(context);
   101         debugResolve = options.get("debugresolve") != null;
   102     }
   104     /** error symbols, which are returned when resolution fails
   105      */
   106     final ResolveError varNotFound;
   107     final ResolveError wrongMethod;
   108     final ResolveError wrongMethods;
   109     final ResolveError methodNotFound;
   110     final ResolveError typeNotFound;
   112 /* ************************************************************************
   113  * Identifier resolution
   114  *************************************************************************/
   116     /** An environment is "static" if its static level is greater than
   117      *  the one of its outer environment
   118      */
   119     static boolean isStatic(Env<AttrContext> env) {
   120         return env.info.staticLevel > env.outer.info.staticLevel;
   121     }
   123     /** An environment is an "initializer" if it is a constructor or
   124      *  an instance initializer.
   125      */
   126     static boolean isInitializer(Env<AttrContext> env) {
   127         Symbol owner = env.info.scope.owner;
   128         return owner.isConstructor() ||
   129             owner.owner.kind == TYP &&
   130             (owner.kind == VAR ||
   131              owner.kind == MTH && (owner.flags() & BLOCK) != 0) &&
   132             (owner.flags() & STATIC) == 0;
   133     }
   135     /** Is class accessible in given evironment?
   136      *  @param env    The current environment.
   137      *  @param c      The class whose accessibility is checked.
   138      */
   139     public boolean isAccessible(Env<AttrContext> env, TypeSymbol c) {
   140         switch ((short)(c.flags() & AccessFlags)) {
   141         case PRIVATE:
   142             return
   143                 env.enclClass.sym.outermostClass() ==
   144                 c.owner.outermostClass();
   145         case 0:
   146             return
   147                 env.toplevel.packge == c.owner // fast special case
   148                 ||
   149                 env.toplevel.packge == c.packge()
   150                 ||
   151                 // Hack: this case is added since synthesized default constructors
   152                 // of anonymous classes should be allowed to access
   153                 // classes which would be inaccessible otherwise.
   154                 env.enclMethod != null &&
   155                 (env.enclMethod.mods.flags & ANONCONSTR) != 0;
   156         default: // error recovery
   157         case PUBLIC:
   158             return true;
   159         case PROTECTED:
   160             return
   161                 env.toplevel.packge == c.owner // fast special case
   162                 ||
   163                 env.toplevel.packge == c.packge()
   164                 ||
   165                 isInnerSubClass(env.enclClass.sym, c.owner);
   166         }
   167     }
   168     //where
   169         /** Is given class a subclass of given base class, or an inner class
   170          *  of a subclass?
   171          *  Return null if no such class exists.
   172          *  @param c     The class which is the subclass or is contained in it.
   173          *  @param base  The base class
   174          */
   175         private boolean isInnerSubClass(ClassSymbol c, Symbol base) {
   176             while (c != null && !c.isSubClass(base, types)) {
   177                 c = c.owner.enclClass();
   178             }
   179             return c != null;
   180         }
   182     boolean isAccessible(Env<AttrContext> env, Type t) {
   183         return (t.tag == ARRAY)
   184             ? isAccessible(env, types.elemtype(t))
   185             : isAccessible(env, t.tsym);
   186     }
   188     /** Is symbol accessible as a member of given type in given evironment?
   189      *  @param env    The current environment.
   190      *  @param site   The type of which the tested symbol is regarded
   191      *                as a member.
   192      *  @param sym    The symbol.
   193      */
   194     public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym) {
   195         if (sym.name == names.init && sym.owner != site.tsym) return false;
   196         ClassSymbol sub;
   197         switch ((short)(sym.flags() & AccessFlags)) {
   198         case PRIVATE:
   199             return
   200                 (env.enclClass.sym == sym.owner // fast special case
   201                  ||
   202                  env.enclClass.sym.outermostClass() ==
   203                  sym.owner.outermostClass())
   204                 &&
   205                 sym.isInheritedIn(site.tsym, types);
   206         case 0:
   207             return
   208                 (env.toplevel.packge == sym.owner.owner // fast special case
   209                  ||
   210                  env.toplevel.packge == sym.packge())
   211                 &&
   212                 isAccessible(env, site)
   213                 &&
   214                 sym.isInheritedIn(site.tsym, types);
   215         case PROTECTED:
   216             return
   217                 (env.toplevel.packge == sym.owner.owner // fast special case
   218                  ||
   219                  env.toplevel.packge == sym.packge()
   220                  ||
   221                  isProtectedAccessible(sym, env.enclClass.sym, site)
   222                  ||
   223                  // OK to select instance method or field from 'super' or type name
   224                  // (but type names should be disallowed elsewhere!)
   225                  env.info.selectSuper && (sym.flags() & STATIC) == 0 && sym.kind != TYP)
   226                 &&
   227                 isAccessible(env, site)
   228                 &&
   229                 // `sym' is accessible only if not overridden by
   230                 // another symbol which is a member of `site'
   231                 // (because, if it is overridden, `sym' is not strictly
   232                 // speaking a member of `site'.)
   233                 (sym.kind != MTH || sym.isConstructor() || sym.isStatic() ||
   234                  ((MethodSymbol)sym).implementation(site.tsym, types, true) == sym);
   235         default: // this case includes erroneous combinations as well
   236             return isAccessible(env, site);
   237         }
   238     }
   239     //where
   240         /** Is given protected symbol accessible if it is selected from given site
   241          *  and the selection takes place in given class?
   242          *  @param sym     The symbol with protected access
   243          *  @param c       The class where the access takes place
   244          *  @site          The type of the qualifier
   245          */
   246         private
   247         boolean isProtectedAccessible(Symbol sym, ClassSymbol c, Type site) {
   248             while (c != null &&
   249                    !(c.isSubClass(sym.owner, types) &&
   250                      (c.flags() & INTERFACE) == 0 &&
   251                      // In JLS 2e 6.6.2.1, the subclass restriction applies
   252                      // only to instance fields and methods -- types are excluded
   253                      // regardless of whether they are declared 'static' or not.
   254                      ((sym.flags() & STATIC) != 0 || sym.kind == TYP || site.tsym.isSubClass(c, types))))
   255                 c = c.owner.enclClass();
   256             return c != null;
   257         }
   259     /** Try to instantiate the type of a method so that it fits
   260      *  given type arguments and argument types. If succesful, return
   261      *  the method's instantiated type, else return null.
   262      *  The instantiation will take into account an additional leading
   263      *  formal parameter if the method is an instance method seen as a member
   264      *  of un underdetermined site In this case, we treat site as an additional
   265      *  parameter and the parameters of the class containing the method as
   266      *  additional type variables that get instantiated.
   267      *
   268      *  @param env         The current environment
   269      *  @param site        The type of which the method is a member.
   270      *  @param m           The method symbol.
   271      *  @param argtypes    The invocation's given value arguments.
   272      *  @param typeargtypes    The invocation's given type arguments.
   273      *  @param allowBoxing Allow boxing conversions of arguments.
   274      *  @param useVarargs Box trailing arguments into an array for varargs.
   275      */
   276     Type rawInstantiate(Env<AttrContext> env,
   277                         Type site,
   278                         Symbol m,
   279                         List<Type> argtypes,
   280                         List<Type> typeargtypes,
   281                         boolean allowBoxing,
   282                         boolean useVarargs,
   283                         Warner warn)
   284         throws Infer.NoInstanceException {
   285         if (useVarargs && (m.flags() & VARARGS) == 0) return null;
   286         Type mt = types.memberType(site, m);
   288         // tvars is the list of formal type variables for which type arguments
   289         // need to inferred.
   290         List<Type> tvars = env.info.tvars;
   291         if (typeargtypes == null) typeargtypes = List.nil();
   292         if (mt.tag != FORALL && typeargtypes.nonEmpty()) {
   293             // This is not a polymorphic method, but typeargs are supplied
   294             // which is fine, see JLS3 15.12.2.1
   295         } else if (mt.tag == FORALL && typeargtypes.nonEmpty()) {
   296             ForAll pmt = (ForAll) mt;
   297             if (typeargtypes.length() != pmt.tvars.length())
   298                 return null;
   299             // Check type arguments are within bounds
   300             List<Type> formals = pmt.tvars;
   301             List<Type> actuals = typeargtypes;
   302             while (formals.nonEmpty() && actuals.nonEmpty()) {
   303                 List<Type> bounds = types.subst(types.getBounds((TypeVar)formals.head),
   304                                                 pmt.tvars, typeargtypes);
   305                 for (; bounds.nonEmpty(); bounds = bounds.tail)
   306                     if (!types.isSubtypeUnchecked(actuals.head, bounds.head, warn))
   307                         return null;
   308                 formals = formals.tail;
   309                 actuals = actuals.tail;
   310             }
   311             mt = types.subst(pmt.qtype, pmt.tvars, typeargtypes);
   312         } else if (mt.tag == FORALL) {
   313             ForAll pmt = (ForAll) mt;
   314             List<Type> tvars1 = types.newInstances(pmt.tvars);
   315             tvars = tvars.appendList(tvars1);
   316             mt = types.subst(pmt.qtype, pmt.tvars, tvars1);
   317         }
   319         // find out whether we need to go the slow route via infer
   320         boolean instNeeded = tvars.tail != null/*inlined: tvars.nonEmpty()*/;
   321         for (List<Type> l = argtypes;
   322              l.tail != null/*inlined: l.nonEmpty()*/ && !instNeeded;
   323              l = l.tail) {
   324             if (l.head.tag == FORALL) instNeeded = true;
   325         }
   327         if (instNeeded)
   328             return
   329             infer.instantiateMethod(tvars,
   330                                     (MethodType)mt,
   331                                     argtypes,
   332                                     allowBoxing,
   333                                     useVarargs,
   334                                     warn);
   335         return
   336             argumentsAcceptable(argtypes, mt.getParameterTypes(),
   337                                 allowBoxing, useVarargs, warn)
   338             ? mt
   339             : null;
   340     }
   342     /** Same but returns null instead throwing a NoInstanceException
   343      */
   344     Type instantiate(Env<AttrContext> env,
   345                      Type site,
   346                      Symbol m,
   347                      List<Type> argtypes,
   348                      List<Type> typeargtypes,
   349                      boolean allowBoxing,
   350                      boolean useVarargs,
   351                      Warner warn) {
   352         try {
   353             return rawInstantiate(env, site, m, argtypes, typeargtypes,
   354                                   allowBoxing, useVarargs, warn);
   355         } catch (Infer.NoInstanceException ex) {
   356             return null;
   357         }
   358     }
   360     /** Check if a parameter list accepts a list of args.
   361      */
   362     boolean argumentsAcceptable(List<Type> argtypes,
   363                                 List<Type> formals,
   364                                 boolean allowBoxing,
   365                                 boolean useVarargs,
   366                                 Warner warn) {
   367         Type varargsFormal = useVarargs ? formals.last() : null;
   368         while (argtypes.nonEmpty() && formals.head != varargsFormal) {
   369             boolean works = allowBoxing
   370                 ? types.isConvertible(argtypes.head, formals.head, warn)
   371                 : types.isSubtypeUnchecked(argtypes.head, formals.head, warn);
   372             if (!works) return false;
   373             argtypes = argtypes.tail;
   374             formals = formals.tail;
   375         }
   376         if (formals.head != varargsFormal) return false; // not enough args
   377         if (!useVarargs)
   378             return argtypes.isEmpty();
   379         Type elt = types.elemtype(varargsFormal);
   380         while (argtypes.nonEmpty()) {
   381             if (!types.isConvertible(argtypes.head, elt, warn))
   382                 return false;
   383             argtypes = argtypes.tail;
   384         }
   385         return true;
   386     }
   388 /* ***************************************************************************
   389  *  Symbol lookup
   390  *  the following naming conventions for arguments are used
   391  *
   392  *       env      is the environment where the symbol was mentioned
   393  *       site     is the type of which the symbol is a member
   394  *       name     is the symbol's name
   395  *                if no arguments are given
   396  *       argtypes are the value arguments, if we search for a method
   397  *
   398  *  If no symbol was found, a ResolveError detailing the problem is returned.
   399  ****************************************************************************/
   401     /** Find field. Synthetic fields are always skipped.
   402      *  @param env     The current environment.
   403      *  @param site    The original type from where the selection takes place.
   404      *  @param name    The name of the field.
   405      *  @param c       The class to search for the field. This is always
   406      *                 a superclass or implemented interface of site's class.
   407      */
   408     Symbol findField(Env<AttrContext> env,
   409                      Type site,
   410                      Name name,
   411                      TypeSymbol c) {
   412         while (c.type.tag == TYPEVAR)
   413             c = c.type.getUpperBound().tsym;
   414         Symbol bestSoFar = varNotFound;
   415         Symbol sym;
   416         Scope.Entry e = c.members().lookup(name);
   417         while (e.scope != null) {
   418             if (e.sym.kind == VAR && (e.sym.flags_field & SYNTHETIC) == 0) {
   419                 return isAccessible(env, site, e.sym)
   420                     ? e.sym : new AccessError(env, site, e.sym);
   421             }
   422             e = e.next();
   423         }
   424         Type st = types.supertype(c.type);
   425         if (st != null && (st.tag == CLASS || st.tag == TYPEVAR)) {
   426             sym = findField(env, site, name, st.tsym);
   427             if (sym.kind < bestSoFar.kind) bestSoFar = sym;
   428         }
   429         for (List<Type> l = types.interfaces(c.type);
   430              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
   431              l = l.tail) {
   432             sym = findField(env, site, name, l.head.tsym);
   433             if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
   434                 sym.owner != bestSoFar.owner)
   435                 bestSoFar = new AmbiguityError(bestSoFar, sym);
   436             else if (sym.kind < bestSoFar.kind)
   437                 bestSoFar = sym;
   438         }
   439         return bestSoFar;
   440     }
   442     /** Resolve a field identifier, throw a fatal error if not found.
   443      *  @param pos       The position to use for error reporting.
   444      *  @param env       The environment current at the method invocation.
   445      *  @param site      The type of the qualifying expression, in which
   446      *                   identifier is searched.
   447      *  @param name      The identifier's name.
   448      */
   449     public VarSymbol resolveInternalField(DiagnosticPosition pos, Env<AttrContext> env,
   450                                           Type site, Name name) {
   451         Symbol sym = findField(env, site, name, site.tsym);
   452         if (sym.kind == VAR) return (VarSymbol)sym;
   453         else throw new FatalError(
   454                  diags.fragment("fatal.err.cant.locate.field",
   455                                 name));
   456     }
   458     /** Find unqualified variable or field with given name.
   459      *  Synthetic fields always skipped.
   460      *  @param env     The current environment.
   461      *  @param name    The name of the variable or field.
   462      */
   463     Symbol findVar(Env<AttrContext> env, Name name) {
   464         Symbol bestSoFar = varNotFound;
   465         Symbol sym;
   466         Env<AttrContext> env1 = env;
   467         boolean staticOnly = false;
   468         while (env1.outer != null) {
   469             if (isStatic(env1)) staticOnly = true;
   470             Scope.Entry e = env1.info.scope.lookup(name);
   471             while (e.scope != null &&
   472                    (e.sym.kind != VAR ||
   473                     (e.sym.flags_field & SYNTHETIC) != 0))
   474                 e = e.next();
   475             sym = (e.scope != null)
   476                 ? e.sym
   477                 : findField(
   478                     env1, env1.enclClass.sym.type, name, env1.enclClass.sym);
   479             if (sym.exists()) {
   480                 if (staticOnly &&
   481                     sym.kind == VAR &&
   482                     sym.owner.kind == TYP &&
   483                     (sym.flags() & STATIC) == 0)
   484                     return new StaticError(sym);
   485                 else
   486                     return sym;
   487             } else if (sym.kind < bestSoFar.kind) {
   488                 bestSoFar = sym;
   489             }
   491             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
   492             env1 = env1.outer;
   493         }
   495         sym = findField(env, syms.predefClass.type, name, syms.predefClass);
   496         if (sym.exists())
   497             return sym;
   498         if (bestSoFar.exists())
   499             return bestSoFar;
   501         Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
   502         for (; e.scope != null; e = e.next()) {
   503             sym = e.sym;
   504             Type origin = e.getOrigin().owner.type;
   505             if (sym.kind == VAR) {
   506                 if (e.sym.owner.type != origin)
   507                     sym = sym.clone(e.getOrigin().owner);
   508                 return isAccessible(env, origin, sym)
   509                     ? sym : new AccessError(env, origin, sym);
   510             }
   511         }
   513         Symbol origin = null;
   514         e = env.toplevel.starImportScope.lookup(name);
   515         for (; e.scope != null; e = e.next()) {
   516             sym = e.sym;
   517             if (sym.kind != VAR)
   518                 continue;
   519             // invariant: sym.kind == VAR
   520             if (bestSoFar.kind < AMBIGUOUS && sym.owner != bestSoFar.owner)
   521                 return new AmbiguityError(bestSoFar, sym);
   522             else if (bestSoFar.kind >= VAR) {
   523                 origin = e.getOrigin().owner;
   524                 bestSoFar = isAccessible(env, origin.type, sym)
   525                     ? sym : new AccessError(env, origin.type, sym);
   526             }
   527         }
   528         if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type)
   529             return bestSoFar.clone(origin);
   530         else
   531             return bestSoFar;
   532     }
   534     Warner noteWarner = new Warner();
   536     /** Select the best method for a call site among two choices.
   537      *  @param env              The current environment.
   538      *  @param site             The original type from where the
   539      *                          selection takes place.
   540      *  @param argtypes         The invocation's value arguments,
   541      *  @param typeargtypes     The invocation's type arguments,
   542      *  @param sym              Proposed new best match.
   543      *  @param bestSoFar        Previously found best match.
   544      *  @param allowBoxing Allow boxing conversions of arguments.
   545      *  @param useVarargs Box trailing arguments into an array for varargs.
   546      */
   547     Symbol selectBest(Env<AttrContext> env,
   548                       Type site,
   549                       List<Type> argtypes,
   550                       List<Type> typeargtypes,
   551                       Symbol sym,
   552                       Symbol bestSoFar,
   553                       boolean allowBoxing,
   554                       boolean useVarargs,
   555                       boolean operator) {
   556         if (sym.kind == ERR) return bestSoFar;
   557         if (!sym.isInheritedIn(site.tsym, types)) return bestSoFar;
   558         assert sym.kind < AMBIGUOUS;
   559         try {
   560             if (rawInstantiate(env, site, sym, argtypes, typeargtypes,
   561                                allowBoxing, useVarargs, Warner.noWarnings) == null) {
   562                 // inapplicable
   563                 switch (bestSoFar.kind) {
   564                 case ABSENT_MTH: return wrongMethod.setWrongSym(sym);
   565                 case WRONG_MTH: return wrongMethods;
   566                 default: return bestSoFar;
   567                 }
   568             }
   569         } catch (Infer.NoInstanceException ex) {
   570             switch (bestSoFar.kind) {
   571             case ABSENT_MTH:
   572                 return wrongMethod.setWrongSym(sym, ex.getDiagnostic());
   573             case WRONG_MTH:
   574                 return wrongMethods;
   575             default:
   576                 return bestSoFar;
   577             }
   578         }
   579         if (!isAccessible(env, site, sym)) {
   580             return (bestSoFar.kind == ABSENT_MTH)
   581                 ? new AccessError(env, site, sym)
   582                 : bestSoFar;
   583         }
   584         return (bestSoFar.kind > AMBIGUOUS)
   585             ? sym
   586             : mostSpecific(sym, bestSoFar, env, site,
   587                            allowBoxing && operator, useVarargs);
   588     }
   590     /* Return the most specific of the two methods for a call,
   591      *  given that both are accessible and applicable.
   592      *  @param m1               A new candidate for most specific.
   593      *  @param m2               The previous most specific candidate.
   594      *  @param env              The current environment.
   595      *  @param site             The original type from where the selection
   596      *                          takes place.
   597      *  @param allowBoxing Allow boxing conversions of arguments.
   598      *  @param useVarargs Box trailing arguments into an array for varargs.
   599      */
   600     Symbol mostSpecific(Symbol m1,
   601                         Symbol m2,
   602                         Env<AttrContext> env,
   603                         Type site,
   604                         boolean allowBoxing,
   605                         boolean useVarargs) {
   606         switch (m2.kind) {
   607         case MTH:
   608             if (m1 == m2) return m1;
   609             Type mt1 = types.memberType(site, m1);
   610             noteWarner.unchecked = false;
   611             boolean m1SignatureMoreSpecific =
   612                 (instantiate(env, site, m2, types.lowerBoundArgtypes(mt1), null,
   613                              allowBoxing, false, noteWarner) != null ||
   614                  useVarargs && instantiate(env, site, m2, types.lowerBoundArgtypes(mt1), null,
   615                                            allowBoxing, true, noteWarner) != null) &&
   616                 !noteWarner.unchecked;
   617             Type mt2 = types.memberType(site, m2);
   618             noteWarner.unchecked = false;
   619             boolean m2SignatureMoreSpecific =
   620                 (instantiate(env, site, m1, types.lowerBoundArgtypes(mt2), null,
   621                              allowBoxing, false, noteWarner) != null ||
   622                  useVarargs && instantiate(env, site, m1, types.lowerBoundArgtypes(mt2), null,
   623                                            allowBoxing, true, noteWarner) != null) &&
   624                 !noteWarner.unchecked;
   625             if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) {
   626                 if (!types.overrideEquivalent(mt1, mt2))
   627                     return new AmbiguityError(m1, m2);
   628                 // same signature; select (a) the non-bridge method, or
   629                 // (b) the one that overrides the other, or (c) the concrete
   630                 // one, or (d) merge both abstract signatures
   631                 if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE)) {
   632                     return ((m1.flags() & BRIDGE) != 0) ? m2 : m1;
   633                 }
   634                 // if one overrides or hides the other, use it
   635                 TypeSymbol m1Owner = (TypeSymbol)m1.owner;
   636                 TypeSymbol m2Owner = (TypeSymbol)m2.owner;
   637                 if (types.asSuper(m1Owner.type, m2Owner) != null &&
   638                     ((m1.owner.flags_field & INTERFACE) == 0 ||
   639                      (m2.owner.flags_field & INTERFACE) != 0) &&
   640                     m1.overrides(m2, m1Owner, types, false))
   641                     return m1;
   642                 if (types.asSuper(m2Owner.type, m1Owner) != null &&
   643                     ((m2.owner.flags_field & INTERFACE) == 0 ||
   644                      (m1.owner.flags_field & INTERFACE) != 0) &&
   645                     m2.overrides(m1, m2Owner, types, false))
   646                     return m2;
   647                 boolean m1Abstract = (m1.flags() & ABSTRACT) != 0;
   648                 boolean m2Abstract = (m2.flags() & ABSTRACT) != 0;
   649                 if (m1Abstract && !m2Abstract) return m2;
   650                 if (m2Abstract && !m1Abstract) return m1;
   651                 // both abstract or both concrete
   652                 if (!m1Abstract && !m2Abstract)
   653                     return new AmbiguityError(m1, m2);
   654                 // check for same erasure
   655                 if (!types.isSameType(m1.erasure(types), m2.erasure(types)))
   656                     return new AmbiguityError(m1, m2);
   657                 // both abstract, neither overridden; merge throws clause and result type
   658                 Symbol result;
   659                 Type result2 = mt2.getReturnType();;
   660                 if (mt2.tag == FORALL)
   661                     result2 = types.subst(result2, ((ForAll)mt2).tvars, ((ForAll)mt1).tvars);
   662                 if (types.isSubtype(mt1.getReturnType(), result2)) {
   663                     result = m1;
   664                 } else if (types.isSubtype(result2, mt1.getReturnType())) {
   665                     result = m2;
   666                 } else {
   667                     // Theoretically, this can't happen, but it is possible
   668                     // due to error recovery or mixing incompatible class files
   669                     return new AmbiguityError(m1, m2);
   670                 }
   671                 result = result.clone(result.owner);
   672                 result.type = (Type)result.type.clone();
   673                 result.type.setThrown(chk.intersect(mt1.getThrownTypes(),
   674                                                     mt2.getThrownTypes()));
   675                 return result;
   676             }
   677             if (m1SignatureMoreSpecific) return m1;
   678             if (m2SignatureMoreSpecific) return m2;
   679             return new AmbiguityError(m1, m2);
   680         case AMBIGUOUS:
   681             AmbiguityError e = (AmbiguityError)m2;
   682             Symbol err1 = mostSpecific(m1, e.sym1, env, site, allowBoxing, useVarargs);
   683             Symbol err2 = mostSpecific(m1, e.sym2, env, site, allowBoxing, useVarargs);
   684             if (err1 == err2) return err1;
   685             if (err1 == e.sym1 && err2 == e.sym2) return m2;
   686             if (err1 instanceof AmbiguityError &&
   687                 err2 instanceof AmbiguityError &&
   688                 ((AmbiguityError)err1).sym1 == ((AmbiguityError)err2).sym1)
   689                 return new AmbiguityError(m1, m2);
   690             else
   691                 return new AmbiguityError(err1, err2);
   692         default:
   693             throw new AssertionError();
   694         }
   695     }
   697     /** Find best qualified method matching given name, type and value
   698      *  arguments.
   699      *  @param env       The current environment.
   700      *  @param site      The original type from where the selection
   701      *                   takes place.
   702      *  @param name      The method's name.
   703      *  @param argtypes  The method's value arguments.
   704      *  @param typeargtypes The method's type arguments
   705      *  @param allowBoxing Allow boxing conversions of arguments.
   706      *  @param useVarargs Box trailing arguments into an array for varargs.
   707      */
   708     Symbol findMethod(Env<AttrContext> env,
   709                       Type site,
   710                       Name name,
   711                       List<Type> argtypes,
   712                       List<Type> typeargtypes,
   713                       boolean allowBoxing,
   714                       boolean useVarargs,
   715                       boolean operator) {
   716         return findMethod(env,
   717                           site,
   718                           name,
   719                           argtypes,
   720                           typeargtypes,
   721                           site.tsym.type,
   722                           true,
   723                           methodNotFound,
   724                           allowBoxing,
   725                           useVarargs,
   726                           operator);
   727     }
   728     // where
   729     private Symbol findMethod(Env<AttrContext> env,
   730                               Type site,
   731                               Name name,
   732                               List<Type> argtypes,
   733                               List<Type> typeargtypes,
   734                               Type intype,
   735                               boolean abstractok,
   736                               Symbol bestSoFar,
   737                               boolean allowBoxing,
   738                               boolean useVarargs,
   739                               boolean operator) {
   740         for (Type ct = intype; ct.tag == CLASS || ct.tag == TYPEVAR; ct = types.supertype(ct)) {
   741             while (ct.tag == TYPEVAR)
   742                 ct = ct.getUpperBound();
   743             ClassSymbol c = (ClassSymbol)ct.tsym;
   744             if ((c.flags() & (ABSTRACT | INTERFACE)) == 0)
   745                 abstractok = false;
   746             for (Scope.Entry e = c.members().lookup(name);
   747                  e.scope != null;
   748                  e = e.next()) {
   749                 //- System.out.println(" e " + e.sym);
   750                 if (e.sym.kind == MTH &&
   751                     (e.sym.flags_field & SYNTHETIC) == 0) {
   752                     bestSoFar = selectBest(env, site, argtypes, typeargtypes,
   753                                            e.sym, bestSoFar,
   754                                            allowBoxing,
   755                                            useVarargs,
   756                                            operator);
   757                 }
   758             }
   759             //- System.out.println(" - " + bestSoFar);
   760             if (abstractok) {
   761                 Symbol concrete = methodNotFound;
   762                 if ((bestSoFar.flags() & ABSTRACT) == 0)
   763                     concrete = bestSoFar;
   764                 for (List<Type> l = types.interfaces(c.type);
   765                      l.nonEmpty();
   766                      l = l.tail) {
   767                     bestSoFar = findMethod(env, site, name, argtypes,
   768                                            typeargtypes,
   769                                            l.head, abstractok, bestSoFar,
   770                                            allowBoxing, useVarargs, operator);
   771                 }
   772                 if (concrete != bestSoFar &&
   773                     concrete.kind < ERR  && bestSoFar.kind < ERR &&
   774                     types.isSubSignature(concrete.type, bestSoFar.type))
   775                     bestSoFar = concrete;
   776             }
   777         }
   778         return bestSoFar;
   779     }
   781     /** Find unqualified method matching given name, type and value arguments.
   782      *  @param env       The current environment.
   783      *  @param name      The method's name.
   784      *  @param argtypes  The method's value arguments.
   785      *  @param typeargtypes  The method's type arguments.
   786      *  @param allowBoxing Allow boxing conversions of arguments.
   787      *  @param useVarargs Box trailing arguments into an array for varargs.
   788      */
   789     Symbol findFun(Env<AttrContext> env, Name name,
   790                    List<Type> argtypes, List<Type> typeargtypes,
   791                    boolean allowBoxing, boolean useVarargs) {
   792         Symbol bestSoFar = methodNotFound;
   793         Symbol sym;
   794         Env<AttrContext> env1 = env;
   795         boolean staticOnly = false;
   796         while (env1.outer != null) {
   797             if (isStatic(env1)) staticOnly = true;
   798             sym = findMethod(
   799                 env1, env1.enclClass.sym.type, name, argtypes, typeargtypes,
   800                 allowBoxing, useVarargs, false);
   801             if (sym.exists()) {
   802                 if (staticOnly &&
   803                     sym.kind == MTH &&
   804                     sym.owner.kind == TYP &&
   805                     (sym.flags() & STATIC) == 0) return new StaticError(sym);
   806                 else return sym;
   807             } else if (sym.kind < bestSoFar.kind) {
   808                 bestSoFar = sym;
   809             }
   810             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
   811             env1 = env1.outer;
   812         }
   814         sym = findMethod(env, syms.predefClass.type, name, argtypes,
   815                          typeargtypes, allowBoxing, useVarargs, false);
   816         if (sym.exists())
   817             return sym;
   819         Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
   820         for (; e.scope != null; e = e.next()) {
   821             sym = e.sym;
   822             Type origin = e.getOrigin().owner.type;
   823             if (sym.kind == MTH) {
   824                 if (e.sym.owner.type != origin)
   825                     sym = sym.clone(e.getOrigin().owner);
   826                 if (!isAccessible(env, origin, sym))
   827                     sym = new AccessError(env, origin, sym);
   828                 bestSoFar = selectBest(env, origin,
   829                                        argtypes, typeargtypes,
   830                                        sym, bestSoFar,
   831                                        allowBoxing, useVarargs, false);
   832             }
   833         }
   834         if (bestSoFar.exists())
   835             return bestSoFar;
   837         e = env.toplevel.starImportScope.lookup(name);
   838         for (; e.scope != null; e = e.next()) {
   839             sym = e.sym;
   840             Type origin = e.getOrigin().owner.type;
   841             if (sym.kind == MTH) {
   842                 if (e.sym.owner.type != origin)
   843                     sym = sym.clone(e.getOrigin().owner);
   844                 if (!isAccessible(env, origin, sym))
   845                     sym = new AccessError(env, origin, sym);
   846                 bestSoFar = selectBest(env, origin,
   847                                        argtypes, typeargtypes,
   848                                        sym, bestSoFar,
   849                                        allowBoxing, useVarargs, false);
   850             }
   851         }
   852         return bestSoFar;
   853     }
   855     /** Load toplevel or member class with given fully qualified name and
   856      *  verify that it is accessible.
   857      *  @param env       The current environment.
   858      *  @param name      The fully qualified name of the class to be loaded.
   859      */
   860     Symbol loadClass(Env<AttrContext> env, Name name) {
   861         try {
   862             ClassSymbol c = reader.loadClass(name);
   863             return isAccessible(env, c) ? c : new AccessError(c);
   864         } catch (ClassReader.BadClassFile err) {
   865             throw err;
   866         } catch (CompletionFailure ex) {
   867             return typeNotFound;
   868         }
   869     }
   871     /** Find qualified member type.
   872      *  @param env       The current environment.
   873      *  @param site      The original type from where the selection takes
   874      *                   place.
   875      *  @param name      The type's name.
   876      *  @param c         The class to search for the member type. This is
   877      *                   always a superclass or implemented interface of
   878      *                   site's class.
   879      */
   880     Symbol findMemberType(Env<AttrContext> env,
   881                           Type site,
   882                           Name name,
   883                           TypeSymbol c) {
   884         Symbol bestSoFar = typeNotFound;
   885         Symbol sym;
   886         Scope.Entry e = c.members().lookup(name);
   887         while (e.scope != null) {
   888             if (e.sym.kind == TYP) {
   889                 return isAccessible(env, site, e.sym)
   890                     ? e.sym
   891                     : new AccessError(env, site, e.sym);
   892             }
   893             e = e.next();
   894         }
   895         Type st = types.supertype(c.type);
   896         if (st != null && st.tag == CLASS) {
   897             sym = findMemberType(env, site, name, st.tsym);
   898             if (sym.kind < bestSoFar.kind) bestSoFar = sym;
   899         }
   900         for (List<Type> l = types.interfaces(c.type);
   901              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
   902              l = l.tail) {
   903             sym = findMemberType(env, site, name, l.head.tsym);
   904             if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
   905                 sym.owner != bestSoFar.owner)
   906                 bestSoFar = new AmbiguityError(bestSoFar, sym);
   907             else if (sym.kind < bestSoFar.kind)
   908                 bestSoFar = sym;
   909         }
   910         return bestSoFar;
   911     }
   913     /** Find a global type in given scope and load corresponding class.
   914      *  @param env       The current environment.
   915      *  @param scope     The scope in which to look for the type.
   916      *  @param name      The type's name.
   917      */
   918     Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name) {
   919         Symbol bestSoFar = typeNotFound;
   920         for (Scope.Entry e = scope.lookup(name); e.scope != null; e = e.next()) {
   921             Symbol sym = loadClass(env, e.sym.flatName());
   922             if (bestSoFar.kind == TYP && sym.kind == TYP &&
   923                 bestSoFar != sym)
   924                 return new AmbiguityError(bestSoFar, sym);
   925             else if (sym.kind < bestSoFar.kind)
   926                 bestSoFar = sym;
   927         }
   928         return bestSoFar;
   929     }
   931     /** Find an unqualified type symbol.
   932      *  @param env       The current environment.
   933      *  @param name      The type's name.
   934      */
   935     Symbol findType(Env<AttrContext> env, Name name) {
   936         Symbol bestSoFar = typeNotFound;
   937         Symbol sym;
   938         boolean staticOnly = false;
   939         for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
   940             if (isStatic(env1)) staticOnly = true;
   941             for (Scope.Entry e = env1.info.scope.lookup(name);
   942                  e.scope != null;
   943                  e = e.next()) {
   944                 if (e.sym.kind == TYP) {
   945                     if (staticOnly &&
   946                         e.sym.type.tag == TYPEVAR &&
   947                         e.sym.owner.kind == TYP) return new StaticError(e.sym);
   948                     return e.sym;
   949                 }
   950             }
   952             sym = findMemberType(env1, env1.enclClass.sym.type, name,
   953                                  env1.enclClass.sym);
   954             if (staticOnly && sym.kind == TYP &&
   955                 sym.type.tag == CLASS &&
   956                 sym.type.getEnclosingType().tag == CLASS &&
   957                 env1.enclClass.sym.type.isParameterized() &&
   958                 sym.type.getEnclosingType().isParameterized())
   959                 return new StaticError(sym);
   960             else if (sym.exists()) return sym;
   961             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
   963             JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass;
   964             if ((encl.sym.flags() & STATIC) != 0)
   965                 staticOnly = true;
   966         }
   968         if (env.tree.getTag() != JCTree.IMPORT) {
   969             sym = findGlobalType(env, env.toplevel.namedImportScope, name);
   970             if (sym.exists()) return sym;
   971             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
   973             sym = findGlobalType(env, env.toplevel.packge.members(), name);
   974             if (sym.exists()) return sym;
   975             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
   977             sym = findGlobalType(env, env.toplevel.starImportScope, name);
   978             if (sym.exists()) return sym;
   979             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
   980         }
   982         return bestSoFar;
   983     }
   985     /** Find an unqualified identifier which matches a specified kind set.
   986      *  @param env       The current environment.
   987      *  @param name      The indentifier's name.
   988      *  @param kind      Indicates the possible symbol kinds
   989      *                   (a subset of VAL, TYP, PCK).
   990      */
   991     Symbol findIdent(Env<AttrContext> env, Name name, int kind) {
   992         Symbol bestSoFar = typeNotFound;
   993         Symbol sym;
   995         if ((kind & VAR) != 0) {
   996             sym = findVar(env, name);
   997             if (sym.exists()) return sym;
   998             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
   999         }
  1001         if ((kind & TYP) != 0) {
  1002             sym = findType(env, name);
  1003             if (sym.exists()) return sym;
  1004             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1007         if ((kind & PCK) != 0) return reader.enterPackage(name);
  1008         else return bestSoFar;
  1011     /** Find an identifier in a package which matches a specified kind set.
  1012      *  @param env       The current environment.
  1013      *  @param name      The identifier's name.
  1014      *  @param kind      Indicates the possible symbol kinds
  1015      *                   (a nonempty subset of TYP, PCK).
  1016      */
  1017     Symbol findIdentInPackage(Env<AttrContext> env, TypeSymbol pck,
  1018                               Name name, int kind) {
  1019         Name fullname = TypeSymbol.formFullName(name, pck);
  1020         Symbol bestSoFar = typeNotFound;
  1021         PackageSymbol pack = null;
  1022         if ((kind & PCK) != 0) {
  1023             pack = reader.enterPackage(fullname);
  1024             if (pack.exists()) return pack;
  1026         if ((kind & TYP) != 0) {
  1027             Symbol sym = loadClass(env, fullname);
  1028             if (sym.exists()) {
  1029                 // don't allow programs to use flatnames
  1030                 if (name == sym.name) return sym;
  1032             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1034         return (pack != null) ? pack : bestSoFar;
  1037     /** Find an identifier among the members of a given type `site'.
  1038      *  @param env       The current environment.
  1039      *  @param site      The type containing the symbol to be found.
  1040      *  @param name      The identifier's name.
  1041      *  @param kind      Indicates the possible symbol kinds
  1042      *                   (a subset of VAL, TYP).
  1043      */
  1044     Symbol findIdentInType(Env<AttrContext> env, Type site,
  1045                            Name name, int kind) {
  1046         Symbol bestSoFar = typeNotFound;
  1047         Symbol sym;
  1048         if ((kind & VAR) != 0) {
  1049             sym = findField(env, site, name, site.tsym);
  1050             if (sym.exists()) return sym;
  1051             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1054         if ((kind & TYP) != 0) {
  1055             sym = findMemberType(env, site, name, site.tsym);
  1056             if (sym.exists()) return sym;
  1057             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1059         return bestSoFar;
  1062 /* ***************************************************************************
  1063  *  Access checking
  1064  *  The following methods convert ResolveErrors to ErrorSymbols, issuing
  1065  *  an error message in the process
  1066  ****************************************************************************/
  1068     /** If `sym' is a bad symbol: report error and return errSymbol
  1069      *  else pass through unchanged,
  1070      *  additional arguments duplicate what has been used in trying to find the
  1071      *  symbol (--> flyweight pattern). This improves performance since we
  1072      *  expect misses to happen frequently.
  1074      *  @param sym       The symbol that was found, or a ResolveError.
  1075      *  @param pos       The position to use for error reporting.
  1076      *  @param site      The original type from where the selection took place.
  1077      *  @param name      The symbol's name.
  1078      *  @param argtypes  The invocation's value arguments,
  1079      *                   if we looked for a method.
  1080      *  @param typeargtypes  The invocation's type arguments,
  1081      *                   if we looked for a method.
  1082      */
  1083     Symbol access(Symbol sym,
  1084                   DiagnosticPosition pos,
  1085                   Type site,
  1086                   Name name,
  1087                   boolean qualified,
  1088                   List<Type> argtypes,
  1089                   List<Type> typeargtypes) {
  1090         if (sym.kind >= AMBIGUOUS) {
  1091 //          printscopes(site.tsym.members());//DEBUG
  1092             if (!site.isErroneous() &&
  1093                 !Type.isErroneous(argtypes) &&
  1094                 (typeargtypes==null || !Type.isErroneous(typeargtypes)))
  1095                 ((ResolveError)sym).report(log, pos, site, name, argtypes, typeargtypes);
  1096             do {
  1097                 sym = ((ResolveError)sym).sym;
  1098             } while (sym.kind >= AMBIGUOUS);
  1099             if (sym == syms.errSymbol // preserve the symbol name through errors
  1100                 || ((sym.kind & ERRONEOUS) == 0 // make sure an error symbol is returned
  1101                     && (sym.kind & TYP) != 0))
  1102                 sym = new ErrorType(name, qualified?site.tsym:syms.noSymbol).tsym;
  1104         return sym;
  1107     /** Same as above, but without type arguments and arguments.
  1108      */
  1109     Symbol access(Symbol sym,
  1110                   DiagnosticPosition pos,
  1111                   Type site,
  1112                   Name name,
  1113                   boolean qualified) {
  1114         if (sym.kind >= AMBIGUOUS)
  1115             return access(sym, pos, site, name, qualified, List.<Type>nil(), null);
  1116         else
  1117             return sym;
  1120     /** Check that sym is not an abstract method.
  1121      */
  1122     void checkNonAbstract(DiagnosticPosition pos, Symbol sym) {
  1123         if ((sym.flags() & ABSTRACT) != 0)
  1124             log.error(pos, "abstract.cant.be.accessed.directly",
  1125                       kindName(sym), sym, sym.location());
  1128 /* ***************************************************************************
  1129  *  Debugging
  1130  ****************************************************************************/
  1132     /** print all scopes starting with scope s and proceeding outwards.
  1133      *  used for debugging.
  1134      */
  1135     public void printscopes(Scope s) {
  1136         while (s != null) {
  1137             if (s.owner != null)
  1138                 System.err.print(s.owner + ": ");
  1139             for (Scope.Entry e = s.elems; e != null; e = e.sibling) {
  1140                 if ((e.sym.flags() & ABSTRACT) != 0)
  1141                     System.err.print("abstract ");
  1142                 System.err.print(e.sym + " ");
  1144             System.err.println();
  1145             s = s.next;
  1149     void printscopes(Env<AttrContext> env) {
  1150         while (env.outer != null) {
  1151             System.err.println("------------------------------");
  1152             printscopes(env.info.scope);
  1153             env = env.outer;
  1157     public void printscopes(Type t) {
  1158         while (t.tag == CLASS) {
  1159             printscopes(t.tsym.members());
  1160             t = types.supertype(t);
  1164 /* ***************************************************************************
  1165  *  Name resolution
  1166  *  Naming conventions are as for symbol lookup
  1167  *  Unlike the find... methods these methods will report access errors
  1168  ****************************************************************************/
  1170     /** Resolve an unqualified (non-method) identifier.
  1171      *  @param pos       The position to use for error reporting.
  1172      *  @param env       The environment current at the identifier use.
  1173      *  @param name      The identifier's name.
  1174      *  @param kind      The set of admissible symbol kinds for the identifier.
  1175      */
  1176     Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env,
  1177                         Name name, int kind) {
  1178         return access(
  1179             findIdent(env, name, kind),
  1180             pos, env.enclClass.sym.type, name, false);
  1183     /** Resolve an unqualified method identifier.
  1184      *  @param pos       The position to use for error reporting.
  1185      *  @param env       The environment current at the method invocation.
  1186      *  @param name      The identifier's name.
  1187      *  @param argtypes  The types of the invocation's value arguments.
  1188      *  @param typeargtypes  The types of the invocation's type arguments.
  1189      */
  1190     Symbol resolveMethod(DiagnosticPosition pos,
  1191                          Env<AttrContext> env,
  1192                          Name name,
  1193                          List<Type> argtypes,
  1194                          List<Type> typeargtypes) {
  1195         Symbol sym = findFun(env, name, argtypes, typeargtypes, false, env.info.varArgs=false);
  1196         if (varargsEnabled && sym.kind >= WRONG_MTHS) {
  1197             sym = findFun(env, name, argtypes, typeargtypes, true, false);
  1198             if (sym.kind >= WRONG_MTHS)
  1199                 sym = findFun(env, name, argtypes, typeargtypes, true, env.info.varArgs=true);
  1201         if (sym.kind >= AMBIGUOUS) {
  1202             sym = access(
  1203                 sym, pos, env.enclClass.sym.type, name, false, argtypes, typeargtypes);
  1205         return sym;
  1208     /** Resolve a qualified method identifier
  1209      *  @param pos       The position to use for error reporting.
  1210      *  @param env       The environment current at the method invocation.
  1211      *  @param site      The type of the qualifying expression, in which
  1212      *                   identifier is searched.
  1213      *  @param name      The identifier's name.
  1214      *  @param argtypes  The types of the invocation's value arguments.
  1215      *  @param typeargtypes  The types of the invocation's type arguments.
  1216      */
  1217     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
  1218                                   Type site, Name name, List<Type> argtypes,
  1219                                   List<Type> typeargtypes) {
  1220         Symbol sym = findMethod(env, site, name, argtypes, typeargtypes, false,
  1221                                 env.info.varArgs=false, false);
  1222         if (varargsEnabled && sym.kind >= WRONG_MTHS) {
  1223             sym = findMethod(env, site, name, argtypes, typeargtypes, true,
  1224                              false, false);
  1225             if (sym.kind >= WRONG_MTHS)
  1226                 sym = findMethod(env, site, name, argtypes, typeargtypes, true,
  1227                                  env.info.varArgs=true, false);
  1229         if (sym.kind >= AMBIGUOUS) {
  1230             sym = access(sym, pos, site, name, true, argtypes, typeargtypes);
  1232         return sym;
  1235     /** Resolve a qualified method identifier, throw a fatal error if not
  1236      *  found.
  1237      *  @param pos       The position to use for error reporting.
  1238      *  @param env       The environment current at the method invocation.
  1239      *  @param site      The type of the qualifying expression, in which
  1240      *                   identifier is searched.
  1241      *  @param name      The identifier's name.
  1242      *  @param argtypes  The types of the invocation's value arguments.
  1243      *  @param typeargtypes  The types of the invocation's type arguments.
  1244      */
  1245     public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env,
  1246                                         Type site, Name name,
  1247                                         List<Type> argtypes,
  1248                                         List<Type> typeargtypes) {
  1249         Symbol sym = resolveQualifiedMethod(
  1250             pos, env, site, name, argtypes, typeargtypes);
  1251         if (sym.kind == MTH) return (MethodSymbol)sym;
  1252         else throw new FatalError(
  1253                  diags.fragment("fatal.err.cant.locate.meth",
  1254                                 name));
  1257     /** Resolve constructor.
  1258      *  @param pos       The position to use for error reporting.
  1259      *  @param env       The environment current at the constructor invocation.
  1260      *  @param site      The type of class for which a constructor is searched.
  1261      *  @param argtypes  The types of the constructor invocation's value
  1262      *                   arguments.
  1263      *  @param typeargtypes  The types of the constructor invocation's type
  1264      *                   arguments.
  1265      */
  1266     Symbol resolveConstructor(DiagnosticPosition pos,
  1267                               Env<AttrContext> env,
  1268                               Type site,
  1269                               List<Type> argtypes,
  1270                               List<Type> typeargtypes) {
  1271         Symbol sym = resolveConstructor(pos, env, site, argtypes, typeargtypes, false, env.info.varArgs=false);
  1272         if (varargsEnabled && sym.kind >= WRONG_MTHS) {
  1273             sym = resolveConstructor(pos, env, site, argtypes, typeargtypes, true, false);
  1274             if (sym.kind >= WRONG_MTHS)
  1275                 sym = resolveConstructor(pos, env, site, argtypes, typeargtypes, true, env.info.varArgs=true);
  1277         if (sym.kind >= AMBIGUOUS) {
  1278             sym = access(sym, pos, site, names.init, true, argtypes, typeargtypes);
  1280         return sym;
  1283     /** Resolve constructor.
  1284      *  @param pos       The position to use for error reporting.
  1285      *  @param env       The environment current at the constructor invocation.
  1286      *  @param site      The type of class for which a constructor is searched.
  1287      *  @param argtypes  The types of the constructor invocation's value
  1288      *                   arguments.
  1289      *  @param typeargtypes  The types of the constructor invocation's type
  1290      *                   arguments.
  1291      *  @param allowBoxing Allow boxing and varargs conversions.
  1292      *  @param useVarargs Box trailing arguments into an array for varargs.
  1293      */
  1294     Symbol resolveConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  1295                               Type site, List<Type> argtypes,
  1296                               List<Type> typeargtypes,
  1297                               boolean allowBoxing,
  1298                               boolean useVarargs) {
  1299         Symbol sym = findMethod(env, site,
  1300                                 names.init, argtypes,
  1301                                 typeargtypes, allowBoxing,
  1302                                 useVarargs, false);
  1303         if ((sym.flags() & DEPRECATED) != 0 &&
  1304             (env.info.scope.owner.flags() & DEPRECATED) == 0 &&
  1305             env.info.scope.owner.outermostClass() != sym.outermostClass())
  1306             chk.warnDeprecated(pos, sym);
  1307         return sym;
  1310     /** Resolve a constructor, throw a fatal error if not found.
  1311      *  @param pos       The position to use for error reporting.
  1312      *  @param env       The environment current at the method invocation.
  1313      *  @param site      The type to be constructed.
  1314      *  @param argtypes  The types of the invocation's value arguments.
  1315      *  @param typeargtypes  The types of the invocation's type arguments.
  1316      */
  1317     public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  1318                                         Type site,
  1319                                         List<Type> argtypes,
  1320                                         List<Type> typeargtypes) {
  1321         Symbol sym = resolveConstructor(
  1322             pos, env, site, argtypes, typeargtypes);
  1323         if (sym.kind == MTH) return (MethodSymbol)sym;
  1324         else throw new FatalError(
  1325                  diags.fragment("fatal.err.cant.locate.ctor", site));
  1328     /** Resolve operator.
  1329      *  @param pos       The position to use for error reporting.
  1330      *  @param optag     The tag of the operation tree.
  1331      *  @param env       The environment current at the operation.
  1332      *  @param argtypes  The types of the operands.
  1333      */
  1334     Symbol resolveOperator(DiagnosticPosition pos, int optag,
  1335                            Env<AttrContext> env, List<Type> argtypes) {
  1336         Name name = treeinfo.operatorName(optag);
  1337         Symbol sym = findMethod(env, syms.predefClass.type, name, argtypes,
  1338                                 null, false, false, true);
  1339         if (boxingEnabled && sym.kind >= WRONG_MTHS)
  1340             sym = findMethod(env, syms.predefClass.type, name, argtypes,
  1341                              null, true, false, true);
  1342         return access(sym, pos, env.enclClass.sym.type, name,
  1343                       false, argtypes, null);
  1346     /** Resolve operator.
  1347      *  @param pos       The position to use for error reporting.
  1348      *  @param optag     The tag of the operation tree.
  1349      *  @param env       The environment current at the operation.
  1350      *  @param arg       The type of the operand.
  1351      */
  1352     Symbol resolveUnaryOperator(DiagnosticPosition pos, int optag, Env<AttrContext> env, Type arg) {
  1353         return resolveOperator(pos, optag, env, List.of(arg));
  1356     /** Resolve binary operator.
  1357      *  @param pos       The position to use for error reporting.
  1358      *  @param optag     The tag of the operation tree.
  1359      *  @param env       The environment current at the operation.
  1360      *  @param left      The types of the left operand.
  1361      *  @param right     The types of the right operand.
  1362      */
  1363     Symbol resolveBinaryOperator(DiagnosticPosition pos,
  1364                                  int optag,
  1365                                  Env<AttrContext> env,
  1366                                  Type left,
  1367                                  Type right) {
  1368         return resolveOperator(pos, optag, env, List.of(left, right));
  1371     /**
  1372      * Resolve `c.name' where name == this or name == super.
  1373      * @param pos           The position to use for error reporting.
  1374      * @param env           The environment current at the expression.
  1375      * @param c             The qualifier.
  1376      * @param name          The identifier's name.
  1377      */
  1378     Symbol resolveSelf(DiagnosticPosition pos,
  1379                        Env<AttrContext> env,
  1380                        TypeSymbol c,
  1381                        Name name) {
  1382         Env<AttrContext> env1 = env;
  1383         boolean staticOnly = false;
  1384         while (env1.outer != null) {
  1385             if (isStatic(env1)) staticOnly = true;
  1386             if (env1.enclClass.sym == c) {
  1387                 Symbol sym = env1.info.scope.lookup(name).sym;
  1388                 if (sym != null) {
  1389                     if (staticOnly) sym = new StaticError(sym);
  1390                     return access(sym, pos, env.enclClass.sym.type,
  1391                                   name, true);
  1394             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  1395             env1 = env1.outer;
  1397         log.error(pos, "not.encl.class", c);
  1398         return syms.errSymbol;
  1401     /**
  1402      * Resolve `c.this' for an enclosing class c that contains the
  1403      * named member.
  1404      * @param pos           The position to use for error reporting.
  1405      * @param env           The environment current at the expression.
  1406      * @param member        The member that must be contained in the result.
  1407      */
  1408     Symbol resolveSelfContaining(DiagnosticPosition pos,
  1409                                  Env<AttrContext> env,
  1410                                  Symbol member) {
  1411         Name name = names._this;
  1412         Env<AttrContext> env1 = env;
  1413         boolean staticOnly = false;
  1414         while (env1.outer != null) {
  1415             if (isStatic(env1)) staticOnly = true;
  1416             if (env1.enclClass.sym.isSubClass(member.owner, types) &&
  1417                 isAccessible(env, env1.enclClass.sym.type, member)) {
  1418                 Symbol sym = env1.info.scope.lookup(name).sym;
  1419                 if (sym != null) {
  1420                     if (staticOnly) sym = new StaticError(sym);
  1421                     return access(sym, pos, env.enclClass.sym.type,
  1422                                   name, true);
  1425             if ((env1.enclClass.sym.flags() & STATIC) != 0)
  1426                 staticOnly = true;
  1427             env1 = env1.outer;
  1429         log.error(pos, "encl.class.required", member);
  1430         return syms.errSymbol;
  1433     /**
  1434      * Resolve an appropriate implicit this instance for t's container.
  1435      * JLS2 8.8.5.1 and 15.9.2
  1436      */
  1437     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
  1438         Type thisType = (((t.tsym.owner.kind & (MTH|VAR)) != 0)
  1439                          ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
  1440                          : resolveSelfContaining(pos, env, t.tsym)).type;
  1441         if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
  1442             log.error(pos, "cant.ref.before.ctor.called", "this");
  1443         return thisType;
  1446 /* ***************************************************************************
  1447  *  ResolveError classes, indicating error situations when accessing symbols
  1448  ****************************************************************************/
  1450     public void logAccessError(Env<AttrContext> env, JCTree tree, Type type) {
  1451         AccessError error = new AccessError(env, type.getEnclosingType(), type.tsym);
  1452         error.report(log, tree.pos(), type.getEnclosingType(), null, null, null);
  1455     /** Root class for resolve errors.
  1456      *  Instances of this class indicate "Symbol not found".
  1457      *  Instances of subclass indicate other errors.
  1458      */
  1459     private class ResolveError extends Symbol {
  1461         ResolveError(int kind, Symbol sym, String debugName) {
  1462             super(kind, 0, null, null, null);
  1463             this.debugName = debugName;
  1464             this.sym = sym;
  1467         /** The name of the kind of error, for debugging only.
  1468          */
  1469         final String debugName;
  1471         /** The symbol that was determined by resolution, or errSymbol if none
  1472          *  was found.
  1473          */
  1474         final Symbol sym;
  1476         /** The symbol that was a close mismatch, or null if none was found.
  1477          *  wrongSym is currently set if a simgle method with the correct name, but
  1478          *  the wrong parameters was found.
  1479          */
  1480         Symbol wrongSym;
  1482         /** An auxiliary explanation set in case of instantiation errors.
  1483          */
  1484         JCDiagnostic explanation;
  1487         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
  1488             throw new AssertionError();
  1491         /** Print the (debug only) name of the kind of error.
  1492          */
  1493         public String toString() {
  1494             return debugName + " wrongSym=" + wrongSym + " explanation=" + explanation;
  1497         /** Update wrongSym and explanation and return this.
  1498          */
  1499         ResolveError setWrongSym(Symbol sym, JCDiagnostic explanation) {
  1500             this.wrongSym = sym;
  1501             this.explanation = explanation;
  1502             return this;
  1505         /** Update wrongSym and return this.
  1506          */
  1507         ResolveError setWrongSym(Symbol sym) {
  1508             this.wrongSym = sym;
  1509             this.explanation = null;
  1510             return this;
  1513         public boolean exists() {
  1514             switch (kind) {
  1515             case HIDDEN:
  1516             case ABSENT_VAR:
  1517             case ABSENT_MTH:
  1518             case ABSENT_TYP:
  1519                 return false;
  1520             default:
  1521                 return true;
  1525         /** Report error.
  1526          *  @param log       The error log to be used for error reporting.
  1527          *  @param pos       The position to be used for error reporting.
  1528          *  @param site      The original type from where the selection took place.
  1529          *  @param name      The name of the symbol to be resolved.
  1530          *  @param argtypes  The invocation's value arguments,
  1531          *                   if we looked for a method.
  1532          *  @param typeargtypes  The invocation's type arguments,
  1533          *                   if we looked for a method.
  1534          */
  1535         void report(Log log, DiagnosticPosition pos, Type site, Name name,
  1536                     List<Type> argtypes, List<Type> typeargtypes) {
  1537             if (argtypes == null)
  1538                 argtypes = List.nil();
  1539             if (typeargtypes == null)
  1540                 typeargtypes = List.nil();
  1541             if (name != name.table.error) {
  1542                 KindName kindname = absentKind(kind);
  1543                 Name idname = name;
  1544                 if (kind >= WRONG_MTHS && kind <= ABSENT_MTH) {
  1545                     if (isOperator(name)) {
  1546                         log.error(pos, "operator.cant.be.applied",
  1547                                   name, argtypes);
  1548                         return;
  1550                     if (name == name.table.init) {
  1551                         kindname = KindName.CONSTRUCTOR;
  1552                         idname = site.tsym.name;
  1555                 if (kind == WRONG_MTH) {
  1556                     Symbol ws = wrongSym.asMemberOf(site, types);
  1557                     log.error(pos,
  1558                               "cant.apply.symbol" + (explanation != null ? ".1" : ""),
  1559                               kindname,
  1560                               ws.name == names.init ? ws.owner.name : ws.name,
  1561                               ws.type.getParameterTypes(),
  1562                               argtypes,
  1563                               kindName(ws.owner),
  1564                               ws.owner.type,
  1565                               explanation);
  1566                 } else if (site.tsym.name.len != 0) {
  1567                     if (site.tsym.kind == PCK && !site.tsym.exists())
  1568                         log.error(pos, "doesnt.exist", site.tsym);
  1569                     else {
  1570                         String errKey = getErrorKey("cant.resolve.location",
  1571                                                     argtypes, typeargtypes,
  1572                                                     kindname);
  1573                         log.error(pos, errKey, kindname, idname, //symbol kindname, name
  1574                                   typeargtypes, argtypes, //type parameters and arguments (if any)
  1575                                   typeKindName(site), site); //location kindname, type
  1577                 } else {
  1578                     String errKey = getErrorKey("cant.resolve",
  1579                                                 argtypes, typeargtypes,
  1580                                                 kindname);
  1581                     log.error(pos, errKey, kindname, idname, //symbol kindname, name
  1582                               typeargtypes, argtypes); //type parameters and arguments (if any)
  1586         //where
  1587         String getErrorKey(String key, List<Type> argtypes, List<Type> typeargtypes, KindName kindname) {
  1588             String suffix = "";
  1589             switch (kindname) {
  1590                 case METHOD:
  1591                 case CONSTRUCTOR: {
  1592                     suffix += ".args";
  1593                     suffix += typeargtypes.nonEmpty() ? ".params" : "";
  1596             return key + suffix;
  1599         /** A name designates an operator if it consists
  1600          *  of a non-empty sequence of operator symbols +-~!/*%&|^<>=
  1601          */
  1602         boolean isOperator(Name name) {
  1603             int i = 0;
  1604             while (i < name.len &&
  1605                    "+-~!*/%&|^<>=".indexOf(name.byteAt(i)) >= 0) i++;
  1606             return i > 0 && i == name.len;
  1610     /** Resolve error class indicating that a symbol is not accessible.
  1611      */
  1612     class AccessError extends ResolveError {
  1614         AccessError(Symbol sym) {
  1615             this(null, null, sym);
  1618         AccessError(Env<AttrContext> env, Type site, Symbol sym) {
  1619             super(HIDDEN, sym, "access error");
  1620             this.env = env;
  1621             this.site = site;
  1622             if (debugResolve)
  1623                 log.error("proc.messager", sym + " @ " + site + " is inaccessible.");
  1626         private Env<AttrContext> env;
  1627         private Type site;
  1629         /** Report error.
  1630          *  @param log       The error log to be used for error reporting.
  1631          *  @param pos       The position to be used for error reporting.
  1632          *  @param site      The original type from where the selection took place.
  1633          *  @param name      The name of the symbol to be resolved.
  1634          *  @param argtypes  The invocation's value arguments,
  1635          *                   if we looked for a method.
  1636          *  @param typeargtypes  The invocation's type arguments,
  1637          *                   if we looked for a method.
  1638          */
  1639         void report(Log log, DiagnosticPosition pos, Type site, Name name,
  1640                     List<Type> argtypes, List<Type> typeargtypes) {
  1641             if (sym.owner.type.tag != ERROR) {
  1642                 if (sym.name == sym.name.table.init && sym.owner != site.tsym)
  1643                     new ResolveError(ABSENT_MTH, sym.owner, "absent method " + sym).report(
  1644                         log, pos, site, name, argtypes, typeargtypes);
  1645                 if ((sym.flags() & PUBLIC) != 0
  1646                     || (env != null && this.site != null
  1647                         && !isAccessible(env, this.site)))
  1648                     log.error(pos, "not.def.access.class.intf.cant.access",
  1649                         sym, sym.location());
  1650                 else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0)
  1651                     log.error(pos, "report.access", sym,
  1652                               asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
  1653                               sym.location());
  1654                 else
  1655                     log.error(pos, "not.def.public.cant.access",
  1656                               sym, sym.location());
  1661     /** Resolve error class indicating that an instance member was accessed
  1662      *  from a static context.
  1663      */
  1664     class StaticError extends ResolveError {
  1665         StaticError(Symbol sym) {
  1666             super(STATICERR, sym, "static error");
  1669         /** Report error.
  1670          *  @param log       The error log to be used for error reporting.
  1671          *  @param pos       The position to be used for error reporting.
  1672          *  @param site      The original type from where the selection took place.
  1673          *  @param name      The name of the symbol to be resolved.
  1674          *  @param argtypes  The invocation's value arguments,
  1675          *                   if we looked for a method.
  1676          *  @param typeargtypes  The invocation's type arguments,
  1677          *                   if we looked for a method.
  1678          */
  1679         void report(Log log,
  1680                     DiagnosticPosition pos,
  1681                     Type site,
  1682                     Name name,
  1683                     List<Type> argtypes,
  1684                     List<Type> typeargtypes) {
  1685             Symbol errSym = ((sym.kind == TYP && sym.type.tag == CLASS)
  1686                 ? types.erasure(sym.type).tsym
  1687                 : sym);
  1688             log.error(pos, "non-static.cant.be.ref",
  1689                       kindName(sym), errSym);
  1693     /** Resolve error class indicating an ambiguous reference.
  1694      */
  1695     class AmbiguityError extends ResolveError {
  1696         Symbol sym1;
  1697         Symbol sym2;
  1699         AmbiguityError(Symbol sym1, Symbol sym2) {
  1700             super(AMBIGUOUS, sym1, "ambiguity error");
  1701             this.sym1 = sym1;
  1702             this.sym2 = sym2;
  1705         /** Report error.
  1706          *  @param log       The error log to be used for error reporting.
  1707          *  @param pos       The position to be used for error reporting.
  1708          *  @param site      The original type from where the selection took place.
  1709          *  @param name      The name of the symbol to be resolved.
  1710          *  @param argtypes  The invocation's value arguments,
  1711          *                   if we looked for a method.
  1712          *  @param typeargtypes  The invocation's type arguments,
  1713          *                   if we looked for a method.
  1714          */
  1715         void report(Log log, DiagnosticPosition pos, Type site, Name name,
  1716                     List<Type> argtypes, List<Type> typeargtypes) {
  1717             AmbiguityError pair = this;
  1718             while (true) {
  1719                 if (pair.sym1.kind == AMBIGUOUS)
  1720                     pair = (AmbiguityError)pair.sym1;
  1721                 else if (pair.sym2.kind == AMBIGUOUS)
  1722                     pair = (AmbiguityError)pair.sym2;
  1723                 else break;
  1725             Name sname = pair.sym1.name;
  1726             if (sname == sname.table.init) sname = pair.sym1.owner.name;
  1727             log.error(pos, "ref.ambiguous", sname,
  1728                       kindName(pair.sym1),
  1729                       pair.sym1,
  1730                       pair.sym1.location(site, types),
  1731                       kindName(pair.sym2),
  1732                       pair.sym2,
  1733                       pair.sym2.location(site, types));

mercurial