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

Tue, 18 Dec 2012 10:23:40 +0100

author
ohrstrom
date
Tue, 18 Dec 2012 10:23:40 +0100
changeset 1460
92fcf299cd09
parent 1456
f20568328a57
child 1479
38d3d1027f5a
permissions
-rw-r--r--

8004657: Add hooks to javac to enable reporting dependency information.
Reviewed-by: jjg, mcimadamore

     1 /*
     2  * Copyright (c) 1999, 2012, 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.api.Formattable.LocalizedString;
    29 import com.sun.tools.javac.code.*;
    30 import com.sun.tools.javac.code.Symbol.*;
    31 import com.sun.tools.javac.code.Type.*;
    32 import com.sun.tools.javac.comp.Attr.ResultInfo;
    33 import com.sun.tools.javac.comp.Check.CheckContext;
    34 import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
    35 import com.sun.tools.javac.comp.DeferredAttr.DeferredAttrContext;
    36 import com.sun.tools.javac.comp.DeferredAttr.DeferredType;
    37 import com.sun.tools.javac.comp.Infer.InferenceContext;
    38 import com.sun.tools.javac.comp.Infer.InferenceContext.FreeTypeListener;
    39 import com.sun.tools.javac.comp.Resolve.MethodResolutionContext.Candidate;
    40 import com.sun.tools.javac.jvm.*;
    41 import com.sun.tools.javac.tree.*;
    42 import com.sun.tools.javac.tree.JCTree.*;
    43 import com.sun.tools.javac.tree.JCTree.JCMemberReference.ReferenceKind;
    44 import com.sun.tools.javac.util.*;
    45 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
    46 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    47 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType;
    49 import java.util.Arrays;
    50 import java.util.Collection;
    51 import java.util.EnumMap;
    52 import java.util.EnumSet;
    53 import java.util.Iterator;
    54 import java.util.LinkedHashMap;
    55 import java.util.LinkedHashSet;
    56 import java.util.Map;
    57 import java.util.Set;
    59 import javax.lang.model.element.ElementVisitor;
    61 import static com.sun.tools.javac.code.Flags.*;
    62 import static com.sun.tools.javac.code.Flags.BLOCK;
    63 import static com.sun.tools.javac.code.Kinds.*;
    64 import static com.sun.tools.javac.code.Kinds.ERRONEOUS;
    65 import static com.sun.tools.javac.code.TypeTag.*;
    66 import static com.sun.tools.javac.comp.Resolve.MethodResolutionPhase.*;
    67 import static com.sun.tools.javac.tree.JCTree.Tag.*;
    69 /** Helper class for name resolution, used mostly by the attribution phase.
    70  *
    71  *  <p><b>This is NOT part of any supported API.
    72  *  If you write code that depends on this, you do so at your own risk.
    73  *  This code and its internal interfaces are subject to change or
    74  *  deletion without notice.</b>
    75  */
    76 public class Resolve {
    77     protected static final Context.Key<Resolve> resolveKey =
    78         new Context.Key<Resolve>();
    80     Names names;
    81     Log log;
    82     Symtab syms;
    83     Attr attr;
    84     DeferredAttr deferredAttr;
    85     Check chk;
    86     Infer infer;
    87     ClassReader reader;
    88     TreeInfo treeinfo;
    89     Types types;
    90     JCDiagnostic.Factory diags;
    91     public final boolean boxingEnabled; // = source.allowBoxing();
    92     public final boolean varargsEnabled; // = source.allowVarargs();
    93     public final boolean allowMethodHandles;
    94     public final boolean allowDefaultMethods;
    95     private final boolean debugResolve;
    96     final EnumSet<VerboseResolutionMode> verboseResolutionMode;
    98     Scope polymorphicSignatureScope;
   100     protected Resolve(Context context) {
   101         context.put(resolveKey, this);
   102         syms = Symtab.instance(context);
   104         varNotFound = new
   105             SymbolNotFoundError(ABSENT_VAR);
   106         methodNotFound = new
   107             SymbolNotFoundError(ABSENT_MTH);
   108         typeNotFound = new
   109             SymbolNotFoundError(ABSENT_TYP);
   111         names = Names.instance(context);
   112         log = Log.instance(context);
   113         attr = Attr.instance(context);
   114         deferredAttr = DeferredAttr.instance(context);
   115         chk = Check.instance(context);
   116         infer = Infer.instance(context);
   117         reader = ClassReader.instance(context);
   118         treeinfo = TreeInfo.instance(context);
   119         types = Types.instance(context);
   120         diags = JCDiagnostic.Factory.instance(context);
   121         Source source = Source.instance(context);
   122         boxingEnabled = source.allowBoxing();
   123         varargsEnabled = source.allowVarargs();
   124         Options options = Options.instance(context);
   125         debugResolve = options.isSet("debugresolve");
   126         verboseResolutionMode = VerboseResolutionMode.getVerboseResolutionMode(options);
   127         Target target = Target.instance(context);
   128         allowMethodHandles = target.hasMethodHandles();
   129         allowDefaultMethods = source.allowDefaultMethods();
   130         polymorphicSignatureScope = new Scope(syms.noSymbol);
   132         inapplicableMethodException = new InapplicableMethodException(diags);
   133     }
   135     /** error symbols, which are returned when resolution fails
   136      */
   137     private final SymbolNotFoundError varNotFound;
   138     private final SymbolNotFoundError methodNotFound;
   139     private final SymbolNotFoundError typeNotFound;
   141     public static Resolve instance(Context context) {
   142         Resolve instance = context.get(resolveKey);
   143         if (instance == null)
   144             instance = new Resolve(context);
   145         return instance;
   146     }
   148     // <editor-fold defaultstate="collapsed" desc="Verbose resolution diagnostics support">
   149     enum VerboseResolutionMode {
   150         SUCCESS("success"),
   151         FAILURE("failure"),
   152         APPLICABLE("applicable"),
   153         INAPPLICABLE("inapplicable"),
   154         DEFERRED_INST("deferred-inference"),
   155         PREDEF("predef"),
   156         OBJECT_INIT("object-init"),
   157         INTERNAL("internal");
   159         final String opt;
   161         private VerboseResolutionMode(String opt) {
   162             this.opt = opt;
   163         }
   165         static EnumSet<VerboseResolutionMode> getVerboseResolutionMode(Options opts) {
   166             String s = opts.get("verboseResolution");
   167             EnumSet<VerboseResolutionMode> res = EnumSet.noneOf(VerboseResolutionMode.class);
   168             if (s == null) return res;
   169             if (s.contains("all")) {
   170                 res = EnumSet.allOf(VerboseResolutionMode.class);
   171             }
   172             Collection<String> args = Arrays.asList(s.split(","));
   173             for (VerboseResolutionMode mode : values()) {
   174                 if (args.contains(mode.opt)) {
   175                     res.add(mode);
   176                 } else if (args.contains("-" + mode.opt)) {
   177                     res.remove(mode);
   178                 }
   179             }
   180             return res;
   181         }
   182     }
   184     void reportVerboseResolutionDiagnostic(DiagnosticPosition dpos, Name name, Type site,
   185             List<Type> argtypes, List<Type> typeargtypes, Symbol bestSoFar) {
   186         boolean success = bestSoFar.kind < ERRONEOUS;
   188         if (success && !verboseResolutionMode.contains(VerboseResolutionMode.SUCCESS)) {
   189             return;
   190         } else if (!success && !verboseResolutionMode.contains(VerboseResolutionMode.FAILURE)) {
   191             return;
   192         }
   194         if (bestSoFar.name == names.init &&
   195                 bestSoFar.owner == syms.objectType.tsym &&
   196                 !verboseResolutionMode.contains(VerboseResolutionMode.OBJECT_INIT)) {
   197             return; //skip diags for Object constructor resolution
   198         } else if (site == syms.predefClass.type &&
   199                 !verboseResolutionMode.contains(VerboseResolutionMode.PREDEF)) {
   200             return; //skip spurious diags for predef symbols (i.e. operators)
   201         } else if (currentResolutionContext.internalResolution &&
   202                 !verboseResolutionMode.contains(VerboseResolutionMode.INTERNAL)) {
   203             return;
   204         }
   206         int pos = 0;
   207         int mostSpecificPos = -1;
   208         ListBuffer<JCDiagnostic> subDiags = ListBuffer.lb();
   209         for (Candidate c : currentResolutionContext.candidates) {
   210             if (currentResolutionContext.step != c.step ||
   211                     (c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.APPLICABLE)) ||
   212                     (!c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.INAPPLICABLE))) {
   213                 continue;
   214             } else {
   215                 subDiags.append(c.isApplicable() ?
   216                         getVerboseApplicableCandidateDiag(pos, c.sym, c.mtype) :
   217                         getVerboseInapplicableCandidateDiag(pos, c.sym, c.details));
   218                 if (c.sym == bestSoFar)
   219                     mostSpecificPos = pos;
   220                 pos++;
   221             }
   222         }
   223         String key = success ? "verbose.resolve.multi" : "verbose.resolve.multi.1";
   224         List<Type> argtypes2 = Type.map(argtypes,
   225                     deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, bestSoFar, currentResolutionContext.step));
   226         JCDiagnostic main = diags.note(log.currentSource(), dpos, key, name,
   227                 site.tsym, mostSpecificPos, currentResolutionContext.step,
   228                 methodArguments(argtypes2),
   229                 methodArguments(typeargtypes));
   230         JCDiagnostic d = new JCDiagnostic.MultilineDiagnostic(main, subDiags.toList());
   231         log.report(d);
   232     }
   234     JCDiagnostic getVerboseApplicableCandidateDiag(int pos, Symbol sym, Type inst) {
   235         JCDiagnostic subDiag = null;
   236         if (sym.type.hasTag(FORALL)) {
   237             subDiag = diags.fragment("partial.inst.sig", inst);
   238         }
   240         String key = subDiag == null ?
   241                 "applicable.method.found" :
   242                 "applicable.method.found.1";
   244         return diags.fragment(key, pos, sym, subDiag);
   245     }
   247     JCDiagnostic getVerboseInapplicableCandidateDiag(int pos, Symbol sym, JCDiagnostic subDiag) {
   248         return diags.fragment("not.applicable.method.found", pos, sym, subDiag);
   249     }
   250     // </editor-fold>
   252 /* ************************************************************************
   253  * Identifier resolution
   254  *************************************************************************/
   256     /** An environment is "static" if its static level is greater than
   257      *  the one of its outer environment
   258      */
   259     protected static boolean isStatic(Env<AttrContext> env) {
   260         return env.info.staticLevel > env.outer.info.staticLevel;
   261     }
   263     /** An environment is an "initializer" if it is a constructor or
   264      *  an instance initializer.
   265      */
   266     static boolean isInitializer(Env<AttrContext> env) {
   267         Symbol owner = env.info.scope.owner;
   268         return owner.isConstructor() ||
   269             owner.owner.kind == TYP &&
   270             (owner.kind == VAR ||
   271              owner.kind == MTH && (owner.flags() & BLOCK) != 0) &&
   272             (owner.flags() & STATIC) == 0;
   273     }
   275     /** Is class accessible in given evironment?
   276      *  @param env    The current environment.
   277      *  @param c      The class whose accessibility is checked.
   278      */
   279     public boolean isAccessible(Env<AttrContext> env, TypeSymbol c) {
   280         return isAccessible(env, c, false);
   281     }
   283     public boolean isAccessible(Env<AttrContext> env, TypeSymbol c, boolean checkInner) {
   284         boolean isAccessible = false;
   285         switch ((short)(c.flags() & AccessFlags)) {
   286             case PRIVATE:
   287                 isAccessible =
   288                     env.enclClass.sym.outermostClass() ==
   289                     c.owner.outermostClass();
   290                 break;
   291             case 0:
   292                 isAccessible =
   293                     env.toplevel.packge == c.owner // fast special case
   294                     ||
   295                     env.toplevel.packge == c.packge()
   296                     ||
   297                     // Hack: this case is added since synthesized default constructors
   298                     // of anonymous classes should be allowed to access
   299                     // classes which would be inaccessible otherwise.
   300                     env.enclMethod != null &&
   301                     (env.enclMethod.mods.flags & ANONCONSTR) != 0;
   302                 break;
   303             default: // error recovery
   304             case PUBLIC:
   305                 isAccessible = true;
   306                 break;
   307             case PROTECTED:
   308                 isAccessible =
   309                     env.toplevel.packge == c.owner // fast special case
   310                     ||
   311                     env.toplevel.packge == c.packge()
   312                     ||
   313                     isInnerSubClass(env.enclClass.sym, c.owner);
   314                 break;
   315         }
   316         return (checkInner == false || c.type.getEnclosingType() == Type.noType) ?
   317             isAccessible :
   318             isAccessible && isAccessible(env, c.type.getEnclosingType(), checkInner);
   319     }
   320     //where
   321         /** Is given class a subclass of given base class, or an inner class
   322          *  of a subclass?
   323          *  Return null if no such class exists.
   324          *  @param c     The class which is the subclass or is contained in it.
   325          *  @param base  The base class
   326          */
   327         private boolean isInnerSubClass(ClassSymbol c, Symbol base) {
   328             while (c != null && !c.isSubClass(base, types)) {
   329                 c = c.owner.enclClass();
   330             }
   331             return c != null;
   332         }
   334     boolean isAccessible(Env<AttrContext> env, Type t) {
   335         return isAccessible(env, t, false);
   336     }
   338     boolean isAccessible(Env<AttrContext> env, Type t, boolean checkInner) {
   339         return (t.hasTag(ARRAY))
   340             ? isAccessible(env, types.elemtype(t))
   341             : isAccessible(env, t.tsym, checkInner);
   342     }
   344     /** Is symbol accessible as a member of given type in given evironment?
   345      *  @param env    The current environment.
   346      *  @param site   The type of which the tested symbol is regarded
   347      *                as a member.
   348      *  @param sym    The symbol.
   349      */
   350     public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym) {
   351         return isAccessible(env, site, sym, false);
   352     }
   353     public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym, boolean checkInner) {
   354         if (sym.name == names.init && sym.owner != site.tsym) return false;
   355         switch ((short)(sym.flags() & AccessFlags)) {
   356         case PRIVATE:
   357             return
   358                 (env.enclClass.sym == sym.owner // fast special case
   359                  ||
   360                  env.enclClass.sym.outermostClass() ==
   361                  sym.owner.outermostClass())
   362                 &&
   363                 sym.isInheritedIn(site.tsym, types);
   364         case 0:
   365             return
   366                 (env.toplevel.packge == sym.owner.owner // fast special case
   367                  ||
   368                  env.toplevel.packge == sym.packge())
   369                 &&
   370                 isAccessible(env, site, checkInner)
   371                 &&
   372                 sym.isInheritedIn(site.tsym, types)
   373                 &&
   374                 notOverriddenIn(site, sym);
   375         case PROTECTED:
   376             return
   377                 (env.toplevel.packge == sym.owner.owner // fast special case
   378                  ||
   379                  env.toplevel.packge == sym.packge()
   380                  ||
   381                  isProtectedAccessible(sym, env.enclClass.sym, site)
   382                  ||
   383                  // OK to select instance method or field from 'super' or type name
   384                  // (but type names should be disallowed elsewhere!)
   385                  env.info.selectSuper && (sym.flags() & STATIC) == 0 && sym.kind != TYP)
   386                 &&
   387                 isAccessible(env, site, checkInner)
   388                 &&
   389                 notOverriddenIn(site, sym);
   390         default: // this case includes erroneous combinations as well
   391             return isAccessible(env, site, checkInner) && notOverriddenIn(site, sym);
   392         }
   393     }
   394     //where
   395     /* `sym' is accessible only if not overridden by
   396      * another symbol which is a member of `site'
   397      * (because, if it is overridden, `sym' is not strictly
   398      * speaking a member of `site'). A polymorphic signature method
   399      * cannot be overridden (e.g. MH.invokeExact(Object[])).
   400      */
   401     private boolean notOverriddenIn(Type site, Symbol sym) {
   402         if (sym.kind != MTH || sym.isConstructor() || sym.isStatic())
   403             return true;
   404         else {
   405             Symbol s2 = ((MethodSymbol)sym).implementation(site.tsym, types, true);
   406             return (s2 == null || s2 == sym || sym.owner == s2.owner ||
   407                     !types.isSubSignature(types.memberType(site, s2), types.memberType(site, sym)));
   408         }
   409     }
   410     //where
   411         /** Is given protected symbol accessible if it is selected from given site
   412          *  and the selection takes place in given class?
   413          *  @param sym     The symbol with protected access
   414          *  @param c       The class where the access takes place
   415          *  @site          The type of the qualifier
   416          */
   417         private
   418         boolean isProtectedAccessible(Symbol sym, ClassSymbol c, Type site) {
   419             while (c != null &&
   420                    !(c.isSubClass(sym.owner, types) &&
   421                      (c.flags() & INTERFACE) == 0 &&
   422                      // In JLS 2e 6.6.2.1, the subclass restriction applies
   423                      // only to instance fields and methods -- types are excluded
   424                      // regardless of whether they are declared 'static' or not.
   425                      ((sym.flags() & STATIC) != 0 || sym.kind == TYP || site.tsym.isSubClass(c, types))))
   426                 c = c.owner.enclClass();
   427             return c != null;
   428         }
   430     /**
   431      * Performs a recursive scan of a type looking for accessibility problems
   432      * from current attribution environment
   433      */
   434     void checkAccessibleType(Env<AttrContext> env, Type t) {
   435         accessibilityChecker.visit(t, env);
   436     }
   438     /**
   439      * Accessibility type-visitor
   440      */
   441     Types.SimpleVisitor<Void, Env<AttrContext>> accessibilityChecker =
   442             new Types.SimpleVisitor<Void, Env<AttrContext>>() {
   444         void visit(List<Type> ts, Env<AttrContext> env) {
   445             for (Type t : ts) {
   446                 visit(t, env);
   447             }
   448         }
   450         public Void visitType(Type t, Env<AttrContext> env) {
   451             return null;
   452         }
   454         @Override
   455         public Void visitArrayType(ArrayType t, Env<AttrContext> env) {
   456             visit(t.elemtype, env);
   457             return null;
   458         }
   460         @Override
   461         public Void visitClassType(ClassType t, Env<AttrContext> env) {
   462             visit(t.getTypeArguments(), env);
   463             if (!isAccessible(env, t, true)) {
   464                 accessBase(new AccessError(t.tsym), env.tree.pos(), env.enclClass.sym, t, t.tsym.name, true);
   465             }
   466             return null;
   467         }
   469         @Override
   470         public Void visitWildcardType(WildcardType t, Env<AttrContext> env) {
   471             visit(t.type, env);
   472             return null;
   473         }
   475         @Override
   476         public Void visitMethodType(MethodType t, Env<AttrContext> env) {
   477             visit(t.getParameterTypes(), env);
   478             visit(t.getReturnType(), env);
   479             visit(t.getThrownTypes(), env);
   480             return null;
   481         }
   482     };
   484     /** Try to instantiate the type of a method so that it fits
   485      *  given type arguments and argument types. If succesful, return
   486      *  the method's instantiated type, else return null.
   487      *  The instantiation will take into account an additional leading
   488      *  formal parameter if the method is an instance method seen as a member
   489      *  of un underdetermined site In this case, we treat site as an additional
   490      *  parameter and the parameters of the class containing the method as
   491      *  additional type variables that get instantiated.
   492      *
   493      *  @param env         The current environment
   494      *  @param site        The type of which the method is a member.
   495      *  @param m           The method symbol.
   496      *  @param argtypes    The invocation's given value arguments.
   497      *  @param typeargtypes    The invocation's given type arguments.
   498      *  @param allowBoxing Allow boxing conversions of arguments.
   499      *  @param useVarargs Box trailing arguments into an array for varargs.
   500      */
   501     Type rawInstantiate(Env<AttrContext> env,
   502                         Type site,
   503                         Symbol m,
   504                         ResultInfo resultInfo,
   505                         List<Type> argtypes,
   506                         List<Type> typeargtypes,
   507                         boolean allowBoxing,
   508                         boolean useVarargs,
   509                         Warner warn) throws Infer.InferenceException {
   511         Type mt = types.memberType(site, m);
   512         // tvars is the list of formal type variables for which type arguments
   513         // need to inferred.
   514         List<Type> tvars = List.nil();
   515         if (typeargtypes == null) typeargtypes = List.nil();
   516         if (!mt.hasTag(FORALL) && typeargtypes.nonEmpty()) {
   517             // This is not a polymorphic method, but typeargs are supplied
   518             // which is fine, see JLS 15.12.2.1
   519         } else if (mt.hasTag(FORALL) && typeargtypes.nonEmpty()) {
   520             ForAll pmt = (ForAll) mt;
   521             if (typeargtypes.length() != pmt.tvars.length())
   522                 throw inapplicableMethodException.setMessage("arg.length.mismatch"); // not enough args
   523             // Check type arguments are within bounds
   524             List<Type> formals = pmt.tvars;
   525             List<Type> actuals = typeargtypes;
   526             while (formals.nonEmpty() && actuals.nonEmpty()) {
   527                 List<Type> bounds = types.subst(types.getBounds((TypeVar)formals.head),
   528                                                 pmt.tvars, typeargtypes);
   529                 for (; bounds.nonEmpty(); bounds = bounds.tail)
   530                     if (!types.isSubtypeUnchecked(actuals.head, bounds.head, warn))
   531                         throw inapplicableMethodException.setMessage("explicit.param.do.not.conform.to.bounds",actuals.head, bounds);
   532                 formals = formals.tail;
   533                 actuals = actuals.tail;
   534             }
   535             mt = types.subst(pmt.qtype, pmt.tvars, typeargtypes);
   536         } else if (mt.hasTag(FORALL)) {
   537             ForAll pmt = (ForAll) mt;
   538             List<Type> tvars1 = types.newInstances(pmt.tvars);
   539             tvars = tvars.appendList(tvars1);
   540             mt = types.subst(pmt.qtype, pmt.tvars, tvars1);
   541         }
   543         // find out whether we need to go the slow route via infer
   544         boolean instNeeded = tvars.tail != null; /*inlined: tvars.nonEmpty()*/
   545         for (List<Type> l = argtypes;
   546              l.tail != null/*inlined: l.nonEmpty()*/ && !instNeeded;
   547              l = l.tail) {
   548             if (l.head.hasTag(FORALL)) instNeeded = true;
   549         }
   551         if (instNeeded)
   552             return infer.instantiateMethod(env,
   553                                     tvars,
   554                                     (MethodType)mt,
   555                                     resultInfo,
   556                                     m,
   557                                     argtypes,
   558                                     allowBoxing,
   559                                     useVarargs,
   560                                     currentResolutionContext,
   561                                     warn);
   563         checkRawArgumentsAcceptable(env, m, argtypes, mt.getParameterTypes(),
   564                                 allowBoxing, useVarargs, warn);
   565         return mt;
   566     }
   568     Type checkMethod(Env<AttrContext> env,
   569                      Type site,
   570                      Symbol m,
   571                      ResultInfo resultInfo,
   572                      List<Type> argtypes,
   573                      List<Type> typeargtypes,
   574                      Warner warn) {
   575         MethodResolutionContext prevContext = currentResolutionContext;
   576         try {
   577             currentResolutionContext = new MethodResolutionContext();
   578             currentResolutionContext.attrMode = DeferredAttr.AttrMode.CHECK;
   579             MethodResolutionPhase step = currentResolutionContext.step = env.info.pendingResolutionPhase;
   580             return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
   581                     step.isBoxingRequired(), step.isVarargsRequired(), warn);
   582         }
   583         finally {
   584             currentResolutionContext = prevContext;
   585         }
   586     }
   588     /** Same but returns null instead throwing a NoInstanceException
   589      */
   590     Type instantiate(Env<AttrContext> env,
   591                      Type site,
   592                      Symbol m,
   593                      ResultInfo resultInfo,
   594                      List<Type> argtypes,
   595                      List<Type> typeargtypes,
   596                      boolean allowBoxing,
   597                      boolean useVarargs,
   598                      Warner warn) {
   599         try {
   600             return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
   601                                   allowBoxing, useVarargs, warn);
   602         } catch (InapplicableMethodException ex) {
   603             return null;
   604         }
   605     }
   607     /** Check if a parameter list accepts a list of args.
   608      */
   609     boolean argumentsAcceptable(Env<AttrContext> env,
   610                                 Symbol msym,
   611                                 List<Type> argtypes,
   612                                 List<Type> formals,
   613                                 boolean allowBoxing,
   614                                 boolean useVarargs,
   615                                 Warner warn) {
   616         try {
   617             checkRawArgumentsAcceptable(env, msym, argtypes, formals, allowBoxing, useVarargs, warn);
   618             return true;
   619         } catch (InapplicableMethodException ex) {
   620             return false;
   621         }
   622     }
   623     /**
   624      * A check handler is used by the main method applicability routine in order
   625      * to handle specific method applicability failures. It is assumed that a class
   626      * implementing this interface should throw exceptions that are a subtype of
   627      * InapplicableMethodException (see below). Such exception will terminate the
   628      * method applicability check and propagate important info outwards (for the
   629      * purpose of generating better diagnostics).
   630      */
   631     interface MethodCheckHandler {
   632         /* The number of actuals and formals differ */
   633         InapplicableMethodException arityMismatch();
   634         /* An actual argument type does not conform to the corresponding formal type */
   635         InapplicableMethodException argumentMismatch(boolean varargs, JCDiagnostic details);
   636         /* The element type of a varargs is not accessible in the current context */
   637         InapplicableMethodException inaccessibleVarargs(Symbol location, Type expected);
   638     }
   640     /**
   641      * Basic method check handler used within Resolve - all methods end up
   642      * throwing InapplicableMethodException; a diagnostic fragment that describes
   643      * the cause as to why the method is not applicable is set on the exception
   644      * before it is thrown.
   645      */
   646     MethodCheckHandler resolveHandler = new MethodCheckHandler() {
   647             public InapplicableMethodException arityMismatch() {
   648                 return inapplicableMethodException.setMessage("arg.length.mismatch");
   649             }
   650             public InapplicableMethodException argumentMismatch(boolean varargs, JCDiagnostic details) {
   651                 String key = varargs ?
   652                         "varargs.argument.mismatch" :
   653                         "no.conforming.assignment.exists";
   654                 return inapplicableMethodException.setMessage(key,
   655                         details);
   656             }
   657             public InapplicableMethodException inaccessibleVarargs(Symbol location, Type expected) {
   658                 return inapplicableMethodException.setMessage("inaccessible.varargs.type",
   659                         expected, Kinds.kindName(location), location);
   660             }
   661     };
   663     void checkRawArgumentsAcceptable(Env<AttrContext> env,
   664                                 Symbol msym,
   665                                 List<Type> argtypes,
   666                                 List<Type> formals,
   667                                 boolean allowBoxing,
   668                                 boolean useVarargs,
   669                                 Warner warn) {
   670         checkRawArgumentsAcceptable(env, msym, currentResolutionContext.attrMode(), infer.emptyContext, argtypes, formals,
   671                 allowBoxing, useVarargs, warn, resolveHandler);
   672     }
   674     /**
   675      * Main method applicability routine. Given a list of actual types A,
   676      * a list of formal types F, determines whether the types in A are
   677      * compatible (by method invocation conversion) with the types in F.
   678      *
   679      * Since this routine is shared between overload resolution and method
   680      * type-inference, a (possibly empty) inference context is used to convert
   681      * formal types to the corresponding 'undet' form ahead of a compatibility
   682      * check so that constraints can be propagated and collected.
   683      *
   684      * Moreover, if one or more types in A is a deferred type, this routine uses
   685      * DeferredAttr in order to perform deferred attribution. If one or more actual
   686      * deferred types are stuck, they are placed in a queue and revisited later
   687      * after the remainder of the arguments have been seen. If this is not sufficient
   688      * to 'unstuck' the argument, a cyclic inference error is called out.
   689      *
   690      * A method check handler (see above) is used in order to report errors.
   691      */
   692     void checkRawArgumentsAcceptable(final Env<AttrContext> env,
   693                                 Symbol msym,
   694                                 DeferredAttr.AttrMode mode,
   695                                 final Infer.InferenceContext inferenceContext,
   696                                 List<Type> argtypes,
   697                                 List<Type> formals,
   698                                 boolean allowBoxing,
   699                                 boolean useVarargs,
   700                                 Warner warn,
   701                                 final MethodCheckHandler handler) {
   702         Type varargsFormal = useVarargs ? formals.last() : null;
   704         if (varargsFormal == null &&
   705                 argtypes.size() != formals.size()) {
   706             throw handler.arityMismatch(); // not enough args
   707         }
   709         DeferredAttr.DeferredAttrContext deferredAttrContext =
   710                 deferredAttr.new DeferredAttrContext(mode, msym, currentResolutionContext.step, inferenceContext);
   712         while (argtypes.nonEmpty() && formals.head != varargsFormal) {
   713             ResultInfo mresult = methodCheckResult(formals.head, allowBoxing, false, inferenceContext, deferredAttrContext, handler, warn);
   714             mresult.check(null, argtypes.head);
   715             argtypes = argtypes.tail;
   716             formals = formals.tail;
   717         }
   719         if (formals.head != varargsFormal) {
   720             throw handler.arityMismatch(); // not enough args
   721         }
   723         if (useVarargs) {
   724             //note: if applicability check is triggered by most specific test,
   725             //the last argument of a varargs is _not_ an array type (see JLS 15.12.2.5)
   726             final Type elt = types.elemtype(varargsFormal);
   727             ResultInfo mresult = methodCheckResult(elt, allowBoxing, true, inferenceContext, deferredAttrContext, handler, warn);
   728             while (argtypes.nonEmpty()) {
   729                 mresult.check(null, argtypes.head);
   730                 argtypes = argtypes.tail;
   731             }
   732             //check varargs element type accessibility
   733             varargsAccessible(env, elt, handler, inferenceContext);
   734         }
   736         deferredAttrContext.complete();
   737     }
   739     void varargsAccessible(final Env<AttrContext> env, final Type t, final Resolve.MethodCheckHandler handler, final InferenceContext inferenceContext) {
   740         if (inferenceContext.free(t)) {
   741             inferenceContext.addFreeTypeListener(List.of(t), new FreeTypeListener() {
   742                 @Override
   743                 public void typesInferred(InferenceContext inferenceContext) {
   744                     varargsAccessible(env, inferenceContext.asInstType(t, types), handler, inferenceContext);
   745                 }
   746             });
   747         } else {
   748             if (!isAccessible(env, t)) {
   749                 Symbol location = env.enclClass.sym;
   750                 throw handler.inaccessibleVarargs(location, t);
   751             }
   752         }
   753     }
   755     /**
   756      * Check context to be used during method applicability checks. A method check
   757      * context might contain inference variables.
   758      */
   759     abstract class MethodCheckContext implements CheckContext {
   761         MethodCheckHandler handler;
   762         boolean useVarargs;
   763         Infer.InferenceContext inferenceContext;
   764         DeferredAttrContext deferredAttrContext;
   765         Warner rsWarner;
   767         public MethodCheckContext(MethodCheckHandler handler, boolean useVarargs,
   768                 Infer.InferenceContext inferenceContext, DeferredAttrContext deferredAttrContext, Warner rsWarner) {
   769             this.handler = handler;
   770             this.useVarargs = useVarargs;
   771             this.inferenceContext = inferenceContext;
   772             this.deferredAttrContext = deferredAttrContext;
   773             this.rsWarner = rsWarner;
   774         }
   776         public void report(DiagnosticPosition pos, JCDiagnostic details) {
   777             throw handler.argumentMismatch(useVarargs, details);
   778         }
   780         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
   781             return rsWarner;
   782         }
   784         public InferenceContext inferenceContext() {
   785             return inferenceContext;
   786         }
   788         public DeferredAttrContext deferredAttrContext() {
   789             return deferredAttrContext;
   790         }
   791     }
   793     /**
   794      * Subclass of method check context class that implements strict method conversion.
   795      * Strict method conversion checks compatibility between types using subtyping tests.
   796      */
   797     class StrictMethodContext extends MethodCheckContext {
   799         public StrictMethodContext(MethodCheckHandler handler, boolean useVarargs,
   800                 Infer.InferenceContext inferenceContext, DeferredAttrContext deferredAttrContext, Warner rsWarner) {
   801             super(handler, useVarargs, inferenceContext, deferredAttrContext, rsWarner);
   802         }
   804         public boolean compatible(Type found, Type req, Warner warn) {
   805             return types.isSubtypeUnchecked(found, inferenceContext.asFree(req, types), warn);
   806         }
   807     }
   809     /**
   810      * Subclass of method check context class that implements loose method conversion.
   811      * Loose method conversion checks compatibility between types using method conversion tests.
   812      */
   813     class LooseMethodContext extends MethodCheckContext {
   815         public LooseMethodContext(MethodCheckHandler handler, boolean useVarargs,
   816                 Infer.InferenceContext inferenceContext, DeferredAttrContext deferredAttrContext, Warner rsWarner) {
   817             super(handler, useVarargs, inferenceContext, deferredAttrContext, rsWarner);
   818         }
   820         public boolean compatible(Type found, Type req, Warner warn) {
   821             return types.isConvertible(found, inferenceContext.asFree(req, types), warn);
   822         }
   823     }
   825     /**
   826      * Create a method check context to be used during method applicability check
   827      */
   828     ResultInfo methodCheckResult(Type to, boolean allowBoxing, boolean useVarargs,
   829             Infer.InferenceContext inferenceContext, DeferredAttr.DeferredAttrContext deferredAttrContext,
   830             MethodCheckHandler methodHandler, Warner rsWarner) {
   831         MethodCheckContext checkContext = allowBoxing ?
   832                 new LooseMethodContext(methodHandler, useVarargs, inferenceContext, deferredAttrContext, rsWarner) :
   833                 new StrictMethodContext(methodHandler, useVarargs, inferenceContext, deferredAttrContext, rsWarner);
   834         return new MethodResultInfo(to, checkContext, deferredAttrContext);
   835     }
   837     class MethodResultInfo extends ResultInfo {
   839         DeferredAttr.DeferredAttrContext deferredAttrContext;
   841         public MethodResultInfo(Type pt, CheckContext checkContext, DeferredAttr.DeferredAttrContext deferredAttrContext) {
   842             attr.super(VAL, pt, checkContext);
   843             this.deferredAttrContext = deferredAttrContext;
   844         }
   846         @Override
   847         protected Type check(DiagnosticPosition pos, Type found) {
   848             if (found.hasTag(DEFERRED)) {
   849                 DeferredType dt = (DeferredType)found;
   850                 return dt.check(this);
   851             } else {
   852                 return super.check(pos, chk.checkNonVoid(pos, types.capture(types.upperBound(found.baseType()))));
   853             }
   854         }
   856         @Override
   857         protected MethodResultInfo dup(Type newPt) {
   858             return new MethodResultInfo(newPt, checkContext, deferredAttrContext);
   859         }
   861         @Override
   862         protected ResultInfo dup(CheckContext newContext) {
   863             return new MethodResultInfo(pt, newContext, deferredAttrContext);
   864         }
   865     }
   867     public static class InapplicableMethodException extends RuntimeException {
   868         private static final long serialVersionUID = 0;
   870         JCDiagnostic diagnostic;
   871         JCDiagnostic.Factory diags;
   873         InapplicableMethodException(JCDiagnostic.Factory diags) {
   874             this.diagnostic = null;
   875             this.diags = diags;
   876         }
   877         InapplicableMethodException setMessage() {
   878             return setMessage((JCDiagnostic)null);
   879         }
   880         InapplicableMethodException setMessage(String key) {
   881             return setMessage(key != null ? diags.fragment(key) : null);
   882         }
   883         InapplicableMethodException setMessage(String key, Object... args) {
   884             return setMessage(key != null ? diags.fragment(key, args) : null);
   885         }
   886         InapplicableMethodException setMessage(JCDiagnostic diag) {
   887             this.diagnostic = diag;
   888             return this;
   889         }
   891         public JCDiagnostic getDiagnostic() {
   892             return diagnostic;
   893         }
   894     }
   895     private final InapplicableMethodException inapplicableMethodException;
   897 /* ***************************************************************************
   898  *  Symbol lookup
   899  *  the following naming conventions for arguments are used
   900  *
   901  *       env      is the environment where the symbol was mentioned
   902  *       site     is the type of which the symbol is a member
   903  *       name     is the symbol's name
   904  *                if no arguments are given
   905  *       argtypes are the value arguments, if we search for a method
   906  *
   907  *  If no symbol was found, a ResolveError detailing the problem is returned.
   908  ****************************************************************************/
   910     /** Find field. Synthetic fields are always skipped.
   911      *  @param env     The current environment.
   912      *  @param site    The original type from where the selection takes place.
   913      *  @param name    The name of the field.
   914      *  @param c       The class to search for the field. This is always
   915      *                 a superclass or implemented interface of site's class.
   916      */
   917     Symbol findField(Env<AttrContext> env,
   918                      Type site,
   919                      Name name,
   920                      TypeSymbol c) {
   921         while (c.type.hasTag(TYPEVAR))
   922             c = c.type.getUpperBound().tsym;
   923         Symbol bestSoFar = varNotFound;
   924         Symbol sym;
   925         Scope.Entry e = c.members().lookup(name);
   926         while (e.scope != null) {
   927             if (e.sym.kind == VAR && (e.sym.flags_field & SYNTHETIC) == 0) {
   928                 return isAccessible(env, site, e.sym)
   929                     ? e.sym : new AccessError(env, site, e.sym);
   930             }
   931             e = e.next();
   932         }
   933         Type st = types.supertype(c.type);
   934         if (st != null && (st.hasTag(CLASS) || st.hasTag(TYPEVAR))) {
   935             sym = findField(env, site, name, st.tsym);
   936             if (sym.kind < bestSoFar.kind) bestSoFar = sym;
   937         }
   938         for (List<Type> l = types.interfaces(c.type);
   939              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
   940              l = l.tail) {
   941             sym = findField(env, site, name, l.head.tsym);
   942             if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
   943                 sym.owner != bestSoFar.owner)
   944                 bestSoFar = new AmbiguityError(bestSoFar, sym);
   945             else if (sym.kind < bestSoFar.kind)
   946                 bestSoFar = sym;
   947         }
   948         return bestSoFar;
   949     }
   951     /** Resolve a field identifier, throw a fatal error if not found.
   952      *  @param pos       The position to use for error reporting.
   953      *  @param env       The environment current at the method invocation.
   954      *  @param site      The type of the qualifying expression, in which
   955      *                   identifier is searched.
   956      *  @param name      The identifier's name.
   957      */
   958     public VarSymbol resolveInternalField(DiagnosticPosition pos, Env<AttrContext> env,
   959                                           Type site, Name name) {
   960         Symbol sym = findField(env, site, name, site.tsym);
   961         if (sym.kind == VAR) return (VarSymbol)sym;
   962         else throw new FatalError(
   963                  diags.fragment("fatal.err.cant.locate.field",
   964                                 name));
   965     }
   967     /** Find unqualified variable or field with given name.
   968      *  Synthetic fields always skipped.
   969      *  @param env     The current environment.
   970      *  @param name    The name of the variable or field.
   971      */
   972     Symbol findVar(Env<AttrContext> env, Name name) {
   973         Symbol bestSoFar = varNotFound;
   974         Symbol sym;
   975         Env<AttrContext> env1 = env;
   976         boolean staticOnly = false;
   977         while (env1.outer != null) {
   978             if (isStatic(env1)) staticOnly = true;
   979             Scope.Entry e = env1.info.scope.lookup(name);
   980             while (e.scope != null &&
   981                    (e.sym.kind != VAR ||
   982                     (e.sym.flags_field & SYNTHETIC) != 0))
   983                 e = e.next();
   984             sym = (e.scope != null)
   985                 ? e.sym
   986                 : findField(
   987                     env1, env1.enclClass.sym.type, name, env1.enclClass.sym);
   988             if (sym.exists()) {
   989                 if (staticOnly &&
   990                     sym.kind == VAR &&
   991                     sym.owner.kind == TYP &&
   992                     (sym.flags() & STATIC) == 0)
   993                     return new StaticError(sym);
   994                 else
   995                     return sym;
   996             } else if (sym.kind < bestSoFar.kind) {
   997                 bestSoFar = sym;
   998             }
  1000             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  1001             env1 = env1.outer;
  1004         sym = findField(env, syms.predefClass.type, name, syms.predefClass);
  1005         if (sym.exists())
  1006             return sym;
  1007         if (bestSoFar.exists())
  1008             return bestSoFar;
  1010         Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
  1011         for (; e.scope != null; e = e.next()) {
  1012             sym = e.sym;
  1013             Type origin = e.getOrigin().owner.type;
  1014             if (sym.kind == VAR) {
  1015                 if (e.sym.owner.type != origin)
  1016                     sym = sym.clone(e.getOrigin().owner);
  1017                 return isAccessible(env, origin, sym)
  1018                     ? sym : new AccessError(env, origin, sym);
  1022         Symbol origin = null;
  1023         e = env.toplevel.starImportScope.lookup(name);
  1024         for (; e.scope != null; e = e.next()) {
  1025             sym = e.sym;
  1026             if (sym.kind != VAR)
  1027                 continue;
  1028             // invariant: sym.kind == VAR
  1029             if (bestSoFar.kind < AMBIGUOUS && sym.owner != bestSoFar.owner)
  1030                 return new AmbiguityError(bestSoFar, sym);
  1031             else if (bestSoFar.kind >= VAR) {
  1032                 origin = e.getOrigin().owner;
  1033                 bestSoFar = isAccessible(env, origin.type, sym)
  1034                     ? sym : new AccessError(env, origin.type, sym);
  1037         if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type)
  1038             return bestSoFar.clone(origin);
  1039         else
  1040             return bestSoFar;
  1043     Warner noteWarner = new Warner();
  1045     /** Select the best method for a call site among two choices.
  1046      *  @param env              The current environment.
  1047      *  @param site             The original type from where the
  1048      *                          selection takes place.
  1049      *  @param argtypes         The invocation's value arguments,
  1050      *  @param typeargtypes     The invocation's type arguments,
  1051      *  @param sym              Proposed new best match.
  1052      *  @param bestSoFar        Previously found best match.
  1053      *  @param allowBoxing Allow boxing conversions of arguments.
  1054      *  @param useVarargs Box trailing arguments into an array for varargs.
  1055      */
  1056     @SuppressWarnings("fallthrough")
  1057     Symbol selectBest(Env<AttrContext> env,
  1058                       Type site,
  1059                       List<Type> argtypes,
  1060                       List<Type> typeargtypes,
  1061                       Symbol sym,
  1062                       Symbol bestSoFar,
  1063                       boolean allowBoxing,
  1064                       boolean useVarargs,
  1065                       boolean operator) {
  1066         if (sym.kind == ERR ||
  1067                 !sym.isInheritedIn(site.tsym, types) ||
  1068                 (useVarargs && (sym.flags() & VARARGS) == 0)) {
  1069             return bestSoFar;
  1071         Assert.check(sym.kind < AMBIGUOUS);
  1072         try {
  1073             Type mt = rawInstantiate(env, site, sym, null, argtypes, typeargtypes,
  1074                                allowBoxing, useVarargs, types.noWarnings);
  1075             if (!operator)
  1076                 currentResolutionContext.addApplicableCandidate(sym, mt);
  1077         } catch (InapplicableMethodException ex) {
  1078             if (!operator)
  1079                 currentResolutionContext.addInapplicableCandidate(sym, ex.getDiagnostic());
  1080             switch (bestSoFar.kind) {
  1081                 case ABSENT_MTH:
  1082                     return new InapplicableSymbolError(currentResolutionContext);
  1083                 case WRONG_MTH:
  1084                     if (operator) return bestSoFar;
  1085                     bestSoFar = new InapplicableSymbolsError(currentResolutionContext);
  1086                 default:
  1087                     return bestSoFar;
  1090         if (!isAccessible(env, site, sym)) {
  1091             return (bestSoFar.kind == ABSENT_MTH)
  1092                 ? new AccessError(env, site, sym)
  1093                 : bestSoFar;
  1095         return (bestSoFar.kind > AMBIGUOUS)
  1096             ? sym
  1097             : mostSpecific(argtypes, sym, bestSoFar, env, site,
  1098                            allowBoxing && operator, useVarargs);
  1101     /* Return the most specific of the two methods for a call,
  1102      *  given that both are accessible and applicable.
  1103      *  @param m1               A new candidate for most specific.
  1104      *  @param m2               The previous most specific candidate.
  1105      *  @param env              The current environment.
  1106      *  @param site             The original type from where the selection
  1107      *                          takes place.
  1108      *  @param allowBoxing Allow boxing conversions of arguments.
  1109      *  @param useVarargs Box trailing arguments into an array for varargs.
  1110      */
  1111     Symbol mostSpecific(List<Type> argtypes, Symbol m1,
  1112                         Symbol m2,
  1113                         Env<AttrContext> env,
  1114                         final Type site,
  1115                         boolean allowBoxing,
  1116                         boolean useVarargs) {
  1117         switch (m2.kind) {
  1118         case MTH:
  1119             if (m1 == m2) return m1;
  1120             boolean m1SignatureMoreSpecific =
  1121                     signatureMoreSpecific(argtypes, env, site, m1, m2, allowBoxing, useVarargs);
  1122             boolean m2SignatureMoreSpecific =
  1123                     signatureMoreSpecific(argtypes, env, site, m2, m1, allowBoxing, useVarargs);
  1124             if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) {
  1125                 Type mt1 = types.memberType(site, m1);
  1126                 Type mt2 = types.memberType(site, m2);
  1127                 if (!types.overrideEquivalent(mt1, mt2))
  1128                     return ambiguityError(m1, m2);
  1130                 // same signature; select (a) the non-bridge method, or
  1131                 // (b) the one that overrides the other, or (c) the concrete
  1132                 // one, or (d) merge both abstract signatures
  1133                 if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE))
  1134                     return ((m1.flags() & BRIDGE) != 0) ? m2 : m1;
  1136                 // if one overrides or hides the other, use it
  1137                 TypeSymbol m1Owner = (TypeSymbol)m1.owner;
  1138                 TypeSymbol m2Owner = (TypeSymbol)m2.owner;
  1139                 if (types.asSuper(m1Owner.type, m2Owner) != null &&
  1140                     ((m1.owner.flags_field & INTERFACE) == 0 ||
  1141                      (m2.owner.flags_field & INTERFACE) != 0) &&
  1142                     m1.overrides(m2, m1Owner, types, false))
  1143                     return m1;
  1144                 if (types.asSuper(m2Owner.type, m1Owner) != null &&
  1145                     ((m2.owner.flags_field & INTERFACE) == 0 ||
  1146                      (m1.owner.flags_field & INTERFACE) != 0) &&
  1147                     m2.overrides(m1, m2Owner, types, false))
  1148                     return m2;
  1149                 boolean m1Abstract = (m1.flags() & ABSTRACT) != 0;
  1150                 boolean m2Abstract = (m2.flags() & ABSTRACT) != 0;
  1151                 if (m1Abstract && !m2Abstract) return m2;
  1152                 if (m2Abstract && !m1Abstract) return m1;
  1153                 // both abstract or both concrete
  1154                 if (!m1Abstract && !m2Abstract)
  1155                     return ambiguityError(m1, m2);
  1156                 // check that both signatures have the same erasure
  1157                 if (!types.isSameTypes(m1.erasure(types).getParameterTypes(),
  1158                                        m2.erasure(types).getParameterTypes()))
  1159                     return ambiguityError(m1, m2);
  1160                 // both abstract, neither overridden; merge throws clause and result type
  1161                 Type mst = mostSpecificReturnType(mt1, mt2);
  1162                 if (mst == null) {
  1163                     // Theoretically, this can't happen, but it is possible
  1164                     // due to error recovery or mixing incompatible class files
  1165                     return ambiguityError(m1, m2);
  1167                 Symbol mostSpecific = mst == mt1 ? m1 : m2;
  1168                 List<Type> allThrown = chk.intersect(mt1.getThrownTypes(), mt2.getThrownTypes());
  1169                 Type newSig = types.createMethodTypeWithThrown(mostSpecific.type, allThrown);
  1170                 MethodSymbol result = new MethodSymbol(
  1171                         mostSpecific.flags(),
  1172                         mostSpecific.name,
  1173                         newSig,
  1174                         mostSpecific.owner) {
  1175                     @Override
  1176                     public MethodSymbol implementation(TypeSymbol origin, Types types, boolean checkResult) {
  1177                         if (origin == site.tsym)
  1178                             return this;
  1179                         else
  1180                             return super.implementation(origin, types, checkResult);
  1182                     };
  1183                 return result;
  1185             if (m1SignatureMoreSpecific) return m1;
  1186             if (m2SignatureMoreSpecific) return m2;
  1187             return ambiguityError(m1, m2);
  1188         case AMBIGUOUS:
  1189             AmbiguityError e = (AmbiguityError)m2;
  1190             Symbol err1 = mostSpecific(argtypes, m1, e.sym, env, site, allowBoxing, useVarargs);
  1191             Symbol err2 = mostSpecific(argtypes, m1, e.sym2, env, site, allowBoxing, useVarargs);
  1192             if (err1 == err2) return err1;
  1193             if (err1 == e.sym && err2 == e.sym2) return m2;
  1194             if (err1 instanceof AmbiguityError &&
  1195                 err2 instanceof AmbiguityError &&
  1196                 ((AmbiguityError)err1).sym == ((AmbiguityError)err2).sym)
  1197                 return ambiguityError(m1, m2);
  1198             else
  1199                 return ambiguityError(err1, err2);
  1200         default:
  1201             throw new AssertionError();
  1204     //where
  1205     private boolean signatureMoreSpecific(List<Type> actuals, Env<AttrContext> env, Type site, Symbol m1, Symbol m2, boolean allowBoxing, boolean useVarargs) {
  1206         Symbol m12 = adjustVarargs(m1, m2, useVarargs);
  1207         Symbol m22 = adjustVarargs(m2, m1, useVarargs);
  1208         Type mtype1 = types.memberType(site, m12);
  1209         Type mtype2 = types.memberType(site, m22);
  1211         //check if invocation is more specific
  1212         if (invocationMoreSpecific(env, site, m22, mtype1.getParameterTypes(), allowBoxing, useVarargs)) {
  1213             return true;
  1216         //perform structural check
  1218         List<Type> formals1 = mtype1.getParameterTypes();
  1219         Type lastFormal1 = formals1.last();
  1220         List<Type> formals2 = mtype2.getParameterTypes();
  1221         Type lastFormal2 = formals2.last();
  1222         ListBuffer<Type> newFormals = ListBuffer.lb();
  1224         boolean hasStructuralPoly = false;
  1225         for (Type actual : actuals) {
  1226             //perform formal argument adaptation in case actuals > formals (varargs)
  1227             Type f1 = formals1.isEmpty() ?
  1228                     lastFormal1 : formals1.head;
  1229             Type f2 = formals2.isEmpty() ?
  1230                     lastFormal2 : formals2.head;
  1232             //is this a structural actual argument?
  1233             boolean isStructuralPoly = actual.hasTag(DEFERRED) &&
  1234                     (((DeferredType)actual).tree.hasTag(LAMBDA) ||
  1235                     ((DeferredType)actual).tree.hasTag(REFERENCE));
  1237             Type newFormal = f1;
  1239             if (isStructuralPoly) {
  1240                 //for structural arguments only - check that corresponding formals
  1241                 //are related - if so replace formal with <null>
  1242                 hasStructuralPoly = true;
  1243                 DeferredType dt = (DeferredType)actual;
  1244                 Type t1 = deferredAttr.new DeferredTypeMap(AttrMode.SPECULATIVE, m1, currentResolutionContext.step).apply(dt);
  1245                 Type t2 = deferredAttr.new DeferredTypeMap(AttrMode.SPECULATIVE, m2, currentResolutionContext.step).apply(dt);
  1246                 if (t1.isErroneous() || t2.isErroneous() || !isStructuralSubtype(t1, t2)) {
  1247                     //not structural subtypes - simply fail
  1248                     return false;
  1249                 } else {
  1250                     newFormal = syms.botType;
  1254             newFormals.append(newFormal);
  1255             if (newFormals.length() > mtype2.getParameterTypes().length()) {
  1256                 //expand m2's type so as to fit the new formal arity (varargs)
  1257                 m22.type = types.createMethodTypeWithParameters(m22.type, m22.type.getParameterTypes().append(f2));
  1260             formals1 = formals1.isEmpty() ? formals1 : formals1.tail;
  1261             formals2 = formals2.isEmpty() ? formals2 : formals2.tail;
  1264         if (!hasStructuralPoly) {
  1265             //if no structural actual was found, we're done
  1266             return false;
  1268         //perform additional adaptation if actuals < formals (varargs)
  1269         for (Type t : formals1) {
  1270             newFormals.append(t);
  1272         //check if invocation (with tweaked args) is more specific
  1273         return invocationMoreSpecific(env, site, m22, newFormals.toList(), allowBoxing, useVarargs);
  1275     //where
  1276     private boolean invocationMoreSpecific(Env<AttrContext> env, Type site, Symbol m2, List<Type> argtypes1, boolean allowBoxing, boolean useVarargs) {
  1277         noteWarner.clear();
  1278         Type mst = instantiate(env, site, m2, null,
  1279                 types.lowerBounds(argtypes1), null,
  1280                 allowBoxing, false, noteWarner);
  1281         return mst != null &&
  1282                 !noteWarner.hasLint(Lint.LintCategory.UNCHECKED);
  1284     //where
  1285     private Symbol adjustVarargs(Symbol to, Symbol from, boolean useVarargs) {
  1286         List<Type> fromArgs = from.type.getParameterTypes();
  1287         List<Type> toArgs = to.type.getParameterTypes();
  1288         if (useVarargs &&
  1289                 (from.flags() & VARARGS) != 0 &&
  1290                 (to.flags() & VARARGS) != 0) {
  1291             Type varargsTypeFrom = fromArgs.last();
  1292             Type varargsTypeTo = toArgs.last();
  1293             ListBuffer<Type> args = ListBuffer.lb();
  1294             if (toArgs.length() < fromArgs.length()) {
  1295                 //if we are checking a varargs method 'from' against another varargs
  1296                 //method 'to' (where arity of 'to' < arity of 'from') then expand signature
  1297                 //of 'to' to 'fit' arity of 'from' (this means adding fake formals to 'to'
  1298                 //until 'to' signature has the same arity as 'from')
  1299                 while (fromArgs.head != varargsTypeFrom) {
  1300                     args.append(toArgs.head == varargsTypeTo ? types.elemtype(varargsTypeTo) : toArgs.head);
  1301                     fromArgs = fromArgs.tail;
  1302                     toArgs = toArgs.head == varargsTypeTo ?
  1303                         toArgs :
  1304                         toArgs.tail;
  1306             } else {
  1307                 //formal argument list is same as original list where last
  1308                 //argument (array type) is removed
  1309                 args.appendList(toArgs.reverse().tail.reverse());
  1311             //append varargs element type as last synthetic formal
  1312             args.append(types.elemtype(varargsTypeTo));
  1313             Type mtype = types.createMethodTypeWithParameters(to.type, args.toList());
  1314             return new MethodSymbol(to.flags_field & ~VARARGS, to.name, mtype, to.owner);
  1315         } else {
  1316             return to;
  1319     //where
  1320     boolean isStructuralSubtype(Type s, Type t) {
  1322         Type ret_s = types.findDescriptorType(s).getReturnType();
  1323         Type ret_t = types.findDescriptorType(t).getReturnType();
  1325         //covariant most specific check for function descriptor return type
  1326         if (!types.isSubtype(ret_s, ret_t)) {
  1327             return false;
  1330         List<Type> args_s = types.findDescriptorType(s).getParameterTypes();
  1331         List<Type> args_t = types.findDescriptorType(t).getParameterTypes();
  1333         //arity must be identical
  1334         if (args_s.length() != args_t.length()) {
  1335             return false;
  1338         //invariant most specific check for function descriptor parameter types
  1339         if (!types.isSameTypes(args_t, args_s)) {
  1340             return false;
  1343         return true;
  1345     //where
  1346     Type mostSpecificReturnType(Type mt1, Type mt2) {
  1347         Type rt1 = mt1.getReturnType();
  1348         Type rt2 = mt2.getReturnType();
  1350         if (mt1.hasTag(FORALL) && mt2.hasTag(FORALL)) {
  1351             //if both are generic methods, adjust return type ahead of subtyping check
  1352             rt1 = types.subst(rt1, mt1.getTypeArguments(), mt2.getTypeArguments());
  1354         //first use subtyping, then return type substitutability
  1355         if (types.isSubtype(rt1, rt2)) {
  1356             return mt1;
  1357         } else if (types.isSubtype(rt2, rt1)) {
  1358             return mt2;
  1359         } else if (types.returnTypeSubstitutable(mt1, mt2)) {
  1360             return mt1;
  1361         } else if (types.returnTypeSubstitutable(mt2, mt1)) {
  1362             return mt2;
  1363         } else {
  1364             return null;
  1367     //where
  1368     Symbol ambiguityError(Symbol m1, Symbol m2) {
  1369         if (((m1.flags() | m2.flags()) & CLASH) != 0) {
  1370             return (m1.flags() & CLASH) == 0 ? m1 : m2;
  1371         } else {
  1372             return new AmbiguityError(m1, m2);
  1376     Symbol findMethodInScope(Env<AttrContext> env,
  1377             Type site,
  1378             Name name,
  1379             List<Type> argtypes,
  1380             List<Type> typeargtypes,
  1381             Scope sc,
  1382             Symbol bestSoFar,
  1383             boolean allowBoxing,
  1384             boolean useVarargs,
  1385             boolean operator,
  1386             boolean abstractok) {
  1387         for (Symbol s : sc.getElementsByName(name, new LookupFilter(abstractok))) {
  1388             bestSoFar = selectBest(env, site, argtypes, typeargtypes, s,
  1389                     bestSoFar, allowBoxing, useVarargs, operator);
  1391         return bestSoFar;
  1393     //where
  1394         class LookupFilter implements Filter<Symbol> {
  1396             boolean abstractOk;
  1398             LookupFilter(boolean abstractOk) {
  1399                 this.abstractOk = abstractOk;
  1402             public boolean accepts(Symbol s) {
  1403                 long flags = s.flags();
  1404                 return s.kind == MTH &&
  1405                         (flags & SYNTHETIC) == 0 &&
  1406                         (abstractOk ||
  1407                         (flags & DEFAULT) != 0 ||
  1408                         (flags & ABSTRACT) == 0);
  1410         };
  1412     /** Find best qualified method matching given name, type and value
  1413      *  arguments.
  1414      *  @param env       The current environment.
  1415      *  @param site      The original type from where the selection
  1416      *                   takes place.
  1417      *  @param name      The method's name.
  1418      *  @param argtypes  The method's value arguments.
  1419      *  @param typeargtypes The method's type arguments
  1420      *  @param allowBoxing Allow boxing conversions of arguments.
  1421      *  @param useVarargs Box trailing arguments into an array for varargs.
  1422      */
  1423     Symbol findMethod(Env<AttrContext> env,
  1424                       Type site,
  1425                       Name name,
  1426                       List<Type> argtypes,
  1427                       List<Type> typeargtypes,
  1428                       boolean allowBoxing,
  1429                       boolean useVarargs,
  1430                       boolean operator) {
  1431         Symbol bestSoFar = methodNotFound;
  1432         bestSoFar = findMethod(env,
  1433                           site,
  1434                           name,
  1435                           argtypes,
  1436                           typeargtypes,
  1437                           site.tsym.type,
  1438                           bestSoFar,
  1439                           allowBoxing,
  1440                           useVarargs,
  1441                           operator);
  1442         reportVerboseResolutionDiagnostic(env.tree.pos(), name, site, argtypes, typeargtypes, bestSoFar);
  1443         return bestSoFar;
  1445     // where
  1446     private Symbol findMethod(Env<AttrContext> env,
  1447                               Type site,
  1448                               Name name,
  1449                               List<Type> argtypes,
  1450                               List<Type> typeargtypes,
  1451                               Type intype,
  1452                               Symbol bestSoFar,
  1453                               boolean allowBoxing,
  1454                               boolean useVarargs,
  1455                               boolean operator) {
  1456         @SuppressWarnings({"unchecked","rawtypes"})
  1457         List<Type>[] itypes = (List<Type>[])new List[] { List.<Type>nil(), List.<Type>nil() };
  1458         InterfaceLookupPhase iphase = InterfaceLookupPhase.ABSTRACT_OK;
  1459         for (TypeSymbol s : superclasses(intype)) {
  1460             bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
  1461                     s.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
  1462             if (name == names.init) return bestSoFar;
  1463             iphase = (iphase == null) ? null : iphase.update(s, this);
  1464             if (iphase != null) {
  1465                 for (Type itype : types.interfaces(s.type)) {
  1466                     itypes[iphase.ordinal()] = types.union(types.closure(itype), itypes[iphase.ordinal()]);
  1471         Symbol concrete = bestSoFar.kind < ERR &&
  1472                 (bestSoFar.flags() & ABSTRACT) == 0 ?
  1473                 bestSoFar : methodNotFound;
  1475         for (InterfaceLookupPhase iphase2 : InterfaceLookupPhase.values()) {
  1476             if (iphase2 == InterfaceLookupPhase.DEFAULT_OK && !allowDefaultMethods) break;
  1477             //keep searching for abstract methods
  1478             for (Type itype : itypes[iphase2.ordinal()]) {
  1479                 if (!itype.isInterface()) continue; //skip j.l.Object (included by Types.closure())
  1480                 if (iphase2 == InterfaceLookupPhase.DEFAULT_OK &&
  1481                         (itype.tsym.flags() & DEFAULT) == 0) continue;
  1482                 bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
  1483                         itype.tsym.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
  1484                 if (concrete != bestSoFar &&
  1485                         concrete.kind < ERR  && bestSoFar.kind < ERR &&
  1486                         types.isSubSignature(concrete.type, bestSoFar.type)) {
  1487                     //this is an hack - as javac does not do full membership checks
  1488                     //most specific ends up comparing abstract methods that might have
  1489                     //been implemented by some concrete method in a subclass and,
  1490                     //because of raw override, it is possible for an abstract method
  1491                     //to be more specific than the concrete method - so we need
  1492                     //to explicitly call that out (see CR 6178365)
  1493                     bestSoFar = concrete;
  1497         return bestSoFar;
  1500     enum InterfaceLookupPhase {
  1501         ABSTRACT_OK() {
  1502             @Override
  1503             InterfaceLookupPhase update(Symbol s, Resolve rs) {
  1504                 //We should not look for abstract methods if receiver is a concrete class
  1505                 //(as concrete classes are expected to implement all abstracts coming
  1506                 //from superinterfaces)
  1507                 if ((s.flags() & (ABSTRACT | INTERFACE | ENUM)) != 0) {
  1508                     return this;
  1509                 } else if (rs.allowDefaultMethods) {
  1510                     return DEFAULT_OK;
  1511                 } else {
  1512                     return null;
  1515         },
  1516         DEFAULT_OK() {
  1517             @Override
  1518             InterfaceLookupPhase update(Symbol s, Resolve rs) {
  1519                 return this;
  1521         };
  1523         abstract InterfaceLookupPhase update(Symbol s, Resolve rs);
  1526     /**
  1527      * Return an Iterable object to scan the superclasses of a given type.
  1528      * It's crucial that the scan is done lazily, as we don't want to accidentally
  1529      * access more supertypes than strictly needed (as this could trigger completion
  1530      * errors if some of the not-needed supertypes are missing/ill-formed).
  1531      */
  1532     Iterable<TypeSymbol> superclasses(final Type intype) {
  1533         return new Iterable<TypeSymbol>() {
  1534             public Iterator<TypeSymbol> iterator() {
  1535                 return new Iterator<TypeSymbol>() {
  1537                     List<TypeSymbol> seen = List.nil();
  1538                     TypeSymbol currentSym = symbolFor(intype);
  1539                     TypeSymbol prevSym = null;
  1541                     public boolean hasNext() {
  1542                         if (currentSym == syms.noSymbol) {
  1543                             currentSym = symbolFor(types.supertype(prevSym.type));
  1545                         return currentSym != null;
  1548                     public TypeSymbol next() {
  1549                         prevSym = currentSym;
  1550                         currentSym = syms.noSymbol;
  1551                         Assert.check(prevSym != null || prevSym != syms.noSymbol);
  1552                         return prevSym;
  1555                     public void remove() {
  1556                         throw new UnsupportedOperationException();
  1559                     TypeSymbol symbolFor(Type t) {
  1560                         if (!t.hasTag(CLASS) &&
  1561                                 !t.hasTag(TYPEVAR)) {
  1562                             return null;
  1564                         while (t.hasTag(TYPEVAR))
  1565                             t = t.getUpperBound();
  1566                         if (seen.contains(t.tsym)) {
  1567                             //degenerate case in which we have a circular
  1568                             //class hierarchy - because of ill-formed classfiles
  1569                             return null;
  1571                         seen = seen.prepend(t.tsym);
  1572                         return t.tsym;
  1574                 };
  1576         };
  1579     /** Find unqualified method matching given name, type and value arguments.
  1580      *  @param env       The current environment.
  1581      *  @param name      The method's name.
  1582      *  @param argtypes  The method's value arguments.
  1583      *  @param typeargtypes  The method's type arguments.
  1584      *  @param allowBoxing Allow boxing conversions of arguments.
  1585      *  @param useVarargs Box trailing arguments into an array for varargs.
  1586      */
  1587     Symbol findFun(Env<AttrContext> env, Name name,
  1588                    List<Type> argtypes, List<Type> typeargtypes,
  1589                    boolean allowBoxing, boolean useVarargs) {
  1590         Symbol bestSoFar = methodNotFound;
  1591         Symbol sym;
  1592         Env<AttrContext> env1 = env;
  1593         boolean staticOnly = false;
  1594         while (env1.outer != null) {
  1595             if (isStatic(env1)) staticOnly = true;
  1596             sym = findMethod(
  1597                 env1, env1.enclClass.sym.type, name, argtypes, typeargtypes,
  1598                 allowBoxing, useVarargs, false);
  1599             if (sym.exists()) {
  1600                 if (staticOnly &&
  1601                     sym.kind == MTH &&
  1602                     sym.owner.kind == TYP &&
  1603                     (sym.flags() & STATIC) == 0) return new StaticError(sym);
  1604                 else return sym;
  1605             } else if (sym.kind < bestSoFar.kind) {
  1606                 bestSoFar = sym;
  1608             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  1609             env1 = env1.outer;
  1612         sym = findMethod(env, syms.predefClass.type, name, argtypes,
  1613                          typeargtypes, allowBoxing, useVarargs, false);
  1614         if (sym.exists())
  1615             return sym;
  1617         Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
  1618         for (; e.scope != null; e = e.next()) {
  1619             sym = e.sym;
  1620             Type origin = e.getOrigin().owner.type;
  1621             if (sym.kind == MTH) {
  1622                 if (e.sym.owner.type != origin)
  1623                     sym = sym.clone(e.getOrigin().owner);
  1624                 if (!isAccessible(env, origin, sym))
  1625                     sym = new AccessError(env, origin, sym);
  1626                 bestSoFar = selectBest(env, origin,
  1627                                        argtypes, typeargtypes,
  1628                                        sym, bestSoFar,
  1629                                        allowBoxing, useVarargs, false);
  1632         if (bestSoFar.exists())
  1633             return bestSoFar;
  1635         e = env.toplevel.starImportScope.lookup(name);
  1636         for (; e.scope != null; e = e.next()) {
  1637             sym = e.sym;
  1638             Type origin = e.getOrigin().owner.type;
  1639             if (sym.kind == MTH) {
  1640                 if (e.sym.owner.type != origin)
  1641                     sym = sym.clone(e.getOrigin().owner);
  1642                 if (!isAccessible(env, origin, sym))
  1643                     sym = new AccessError(env, origin, sym);
  1644                 bestSoFar = selectBest(env, origin,
  1645                                        argtypes, typeargtypes,
  1646                                        sym, bestSoFar,
  1647                                        allowBoxing, useVarargs, false);
  1650         return bestSoFar;
  1653     /** Load toplevel or member class with given fully qualified name and
  1654      *  verify that it is accessible.
  1655      *  @param env       The current environment.
  1656      *  @param name      The fully qualified name of the class to be loaded.
  1657      */
  1658     Symbol loadClass(Env<AttrContext> env, Name name) {
  1659         try {
  1660             ClassSymbol c = reader.loadClass(name);
  1661             return isAccessible(env, c) ? c : new AccessError(c);
  1662         } catch (ClassReader.BadClassFile err) {
  1663             throw err;
  1664         } catch (CompletionFailure ex) {
  1665             return typeNotFound;
  1669     /** Find qualified member type.
  1670      *  @param env       The current environment.
  1671      *  @param site      The original type from where the selection takes
  1672      *                   place.
  1673      *  @param name      The type's name.
  1674      *  @param c         The class to search for the member type. This is
  1675      *                   always a superclass or implemented interface of
  1676      *                   site's class.
  1677      */
  1678     Symbol findMemberType(Env<AttrContext> env,
  1679                           Type site,
  1680                           Name name,
  1681                           TypeSymbol c) {
  1682         Symbol bestSoFar = typeNotFound;
  1683         Symbol sym;
  1684         Scope.Entry e = c.members().lookup(name);
  1685         while (e.scope != null) {
  1686             if (e.sym.kind == TYP) {
  1687                 return isAccessible(env, site, e.sym)
  1688                     ? e.sym
  1689                     : new AccessError(env, site, e.sym);
  1691             e = e.next();
  1693         Type st = types.supertype(c.type);
  1694         if (st != null && st.hasTag(CLASS)) {
  1695             sym = findMemberType(env, site, name, st.tsym);
  1696             if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1698         for (List<Type> l = types.interfaces(c.type);
  1699              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
  1700              l = l.tail) {
  1701             sym = findMemberType(env, site, name, l.head.tsym);
  1702             if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
  1703                 sym.owner != bestSoFar.owner)
  1704                 bestSoFar = new AmbiguityError(bestSoFar, sym);
  1705             else if (sym.kind < bestSoFar.kind)
  1706                 bestSoFar = sym;
  1708         return bestSoFar;
  1711     /** Find a global type in given scope and load corresponding class.
  1712      *  @param env       The current environment.
  1713      *  @param scope     The scope in which to look for the type.
  1714      *  @param name      The type's name.
  1715      */
  1716     Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name) {
  1717         Symbol bestSoFar = typeNotFound;
  1718         for (Scope.Entry e = scope.lookup(name); e.scope != null; e = e.next()) {
  1719             Symbol sym = loadClass(env, e.sym.flatName());
  1720             if (bestSoFar.kind == TYP && sym.kind == TYP &&
  1721                 bestSoFar != sym)
  1722                 return new AmbiguityError(bestSoFar, sym);
  1723             else if (sym.kind < bestSoFar.kind)
  1724                 bestSoFar = sym;
  1726         return bestSoFar;
  1729     /** Find an unqualified type symbol.
  1730      *  @param env       The current environment.
  1731      *  @param name      The type's name.
  1732      */
  1733     Symbol findType(Env<AttrContext> env, Name name) {
  1734         Symbol bestSoFar = typeNotFound;
  1735         Symbol sym;
  1736         boolean staticOnly = false;
  1737         for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
  1738             if (isStatic(env1)) staticOnly = true;
  1739             for (Scope.Entry e = env1.info.scope.lookup(name);
  1740                  e.scope != null;
  1741                  e = e.next()) {
  1742                 if (e.sym.kind == TYP) {
  1743                     if (staticOnly &&
  1744                         e.sym.type.hasTag(TYPEVAR) &&
  1745                         e.sym.owner.kind == TYP) return new StaticError(e.sym);
  1746                     return e.sym;
  1750             sym = findMemberType(env1, env1.enclClass.sym.type, name,
  1751                                  env1.enclClass.sym);
  1752             if (staticOnly && sym.kind == TYP &&
  1753                 sym.type.hasTag(CLASS) &&
  1754                 sym.type.getEnclosingType().hasTag(CLASS) &&
  1755                 env1.enclClass.sym.type.isParameterized() &&
  1756                 sym.type.getEnclosingType().isParameterized())
  1757                 return new StaticError(sym);
  1758             else if (sym.exists()) return sym;
  1759             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1761             JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass;
  1762             if ((encl.sym.flags() & STATIC) != 0)
  1763                 staticOnly = true;
  1766         if (!env.tree.hasTag(IMPORT)) {
  1767             sym = findGlobalType(env, env.toplevel.namedImportScope, name);
  1768             if (sym.exists()) return sym;
  1769             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1771             sym = findGlobalType(env, env.toplevel.packge.members(), name);
  1772             if (sym.exists()) return sym;
  1773             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1775             sym = findGlobalType(env, env.toplevel.starImportScope, name);
  1776             if (sym.exists()) return sym;
  1777             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1780         return bestSoFar;
  1783     /** Find an unqualified identifier which matches a specified kind set.
  1784      *  @param env       The current environment.
  1785      *  @param name      The identifier's name.
  1786      *  @param kind      Indicates the possible symbol kinds
  1787      *                   (a subset of VAL, TYP, PCK).
  1788      */
  1789     Symbol findIdent(Env<AttrContext> env, Name name, int kind) {
  1790         Symbol bestSoFar = typeNotFound;
  1791         Symbol sym;
  1793         if ((kind & VAR) != 0) {
  1794             sym = findVar(env, name);
  1795             if (sym.exists()) return sym;
  1796             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1799         if ((kind & TYP) != 0) {
  1800             sym = findType(env, name);
  1801             if (sym.kind==TYP) {
  1802                  reportDependence(env.enclClass.sym, sym);
  1804             if (sym.exists()) return sym;
  1805             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1808         if ((kind & PCK) != 0) return reader.enterPackage(name);
  1809         else return bestSoFar;
  1812     /** Report dependencies.
  1813      * @param from The enclosing class sym
  1814      * @param to   The found identifier that the class depends on.
  1815      */
  1816     public void reportDependence(Symbol from, Symbol to) {
  1817         // Override if you want to collect the reported dependencies.
  1820     /** Find an identifier in a package which matches a specified kind set.
  1821      *  @param env       The current environment.
  1822      *  @param name      The identifier's name.
  1823      *  @param kind      Indicates the possible symbol kinds
  1824      *                   (a nonempty subset of TYP, PCK).
  1825      */
  1826     Symbol findIdentInPackage(Env<AttrContext> env, TypeSymbol pck,
  1827                               Name name, int kind) {
  1828         Name fullname = TypeSymbol.formFullName(name, pck);
  1829         Symbol bestSoFar = typeNotFound;
  1830         PackageSymbol pack = null;
  1831         if ((kind & PCK) != 0) {
  1832             pack = reader.enterPackage(fullname);
  1833             if (pack.exists()) return pack;
  1835         if ((kind & TYP) != 0) {
  1836             Symbol sym = loadClass(env, fullname);
  1837             if (sym.exists()) {
  1838                 // don't allow programs to use flatnames
  1839                 if (name == sym.name) return sym;
  1841             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1843         return (pack != null) ? pack : bestSoFar;
  1846     /** Find an identifier among the members of a given type `site'.
  1847      *  @param env       The current environment.
  1848      *  @param site      The type containing the symbol to be found.
  1849      *  @param name      The identifier's name.
  1850      *  @param kind      Indicates the possible symbol kinds
  1851      *                   (a subset of VAL, TYP).
  1852      */
  1853     Symbol findIdentInType(Env<AttrContext> env, Type site,
  1854                            Name name, int kind) {
  1855         Symbol bestSoFar = typeNotFound;
  1856         Symbol sym;
  1857         if ((kind & VAR) != 0) {
  1858             sym = findField(env, site, name, site.tsym);
  1859             if (sym.exists()) return sym;
  1860             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1863         if ((kind & TYP) != 0) {
  1864             sym = findMemberType(env, site, name, site.tsym);
  1865             if (sym.exists()) return sym;
  1866             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1868         return bestSoFar;
  1871 /* ***************************************************************************
  1872  *  Access checking
  1873  *  The following methods convert ResolveErrors to ErrorSymbols, issuing
  1874  *  an error message in the process
  1875  ****************************************************************************/
  1877     /** If `sym' is a bad symbol: report error and return errSymbol
  1878      *  else pass through unchanged,
  1879      *  additional arguments duplicate what has been used in trying to find the
  1880      *  symbol {@literal (--> flyweight pattern)}. This improves performance since we
  1881      *  expect misses to happen frequently.
  1883      *  @param sym       The symbol that was found, or a ResolveError.
  1884      *  @param pos       The position to use for error reporting.
  1885      *  @param location  The symbol the served as a context for this lookup
  1886      *  @param site      The original type from where the selection took place.
  1887      *  @param name      The symbol's name.
  1888      *  @param qualified Did we get here through a qualified expression resolution?
  1889      *  @param argtypes  The invocation's value arguments,
  1890      *                   if we looked for a method.
  1891      *  @param typeargtypes  The invocation's type arguments,
  1892      *                   if we looked for a method.
  1893      *  @param logResolveHelper helper class used to log resolve errors
  1894      */
  1895     Symbol accessInternal(Symbol sym,
  1896                   DiagnosticPosition pos,
  1897                   Symbol location,
  1898                   Type site,
  1899                   Name name,
  1900                   boolean qualified,
  1901                   List<Type> argtypes,
  1902                   List<Type> typeargtypes,
  1903                   LogResolveHelper logResolveHelper) {
  1904         if (sym.kind >= AMBIGUOUS) {
  1905             ResolveError errSym = (ResolveError)sym;
  1906             sym = errSym.access(name, qualified ? site.tsym : syms.noSymbol);
  1907             argtypes = logResolveHelper.getArgumentTypes(errSym, sym, name, argtypes);
  1908             if (logResolveHelper.resolveDiagnosticNeeded(site, argtypes, typeargtypes)) {
  1909                 logResolveError(errSym, pos, location, site, name, argtypes, typeargtypes);
  1912         return sym;
  1915     /**
  1916      * Variant of the generalized access routine, to be used for generating method
  1917      * resolution diagnostics
  1918      */
  1919     Symbol accessMethod(Symbol sym,
  1920                   DiagnosticPosition pos,
  1921                   Symbol location,
  1922                   Type site,
  1923                   Name name,
  1924                   boolean qualified,
  1925                   List<Type> argtypes,
  1926                   List<Type> typeargtypes) {
  1927         return accessInternal(sym, pos, location, site, name, qualified, argtypes, typeargtypes, methodLogResolveHelper);
  1930     /** Same as original accessMethod(), but without location.
  1931      */
  1932     Symbol accessMethod(Symbol sym,
  1933                   DiagnosticPosition pos,
  1934                   Type site,
  1935                   Name name,
  1936                   boolean qualified,
  1937                   List<Type> argtypes,
  1938                   List<Type> typeargtypes) {
  1939         return accessMethod(sym, pos, site.tsym, site, name, qualified, argtypes, typeargtypes);
  1942     /**
  1943      * Variant of the generalized access routine, to be used for generating variable,
  1944      * type resolution diagnostics
  1945      */
  1946     Symbol accessBase(Symbol sym,
  1947                   DiagnosticPosition pos,
  1948                   Symbol location,
  1949                   Type site,
  1950                   Name name,
  1951                   boolean qualified) {
  1952         return accessInternal(sym, pos, location, site, name, qualified, List.<Type>nil(), null, basicLogResolveHelper);
  1955     /** Same as original accessBase(), but without location.
  1956      */
  1957     Symbol accessBase(Symbol sym,
  1958                   DiagnosticPosition pos,
  1959                   Type site,
  1960                   Name name,
  1961                   boolean qualified) {
  1962         return accessBase(sym, pos, site.tsym, site, name, qualified);
  1965     interface LogResolveHelper {
  1966         boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes);
  1967         List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes);
  1970     LogResolveHelper basicLogResolveHelper = new LogResolveHelper() {
  1971         public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
  1972             return !site.isErroneous();
  1974         public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
  1975             return argtypes;
  1977     };
  1979     LogResolveHelper methodLogResolveHelper = new LogResolveHelper() {
  1980         public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
  1981             return !site.isErroneous() &&
  1982                         !Type.isErroneous(argtypes) &&
  1983                         (typeargtypes == null || !Type.isErroneous(typeargtypes));
  1985         public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
  1986             return (syms.operatorNames.contains(name)) ?
  1987                     argtypes :
  1988                     Type.map(argtypes, new ResolveDeferredRecoveryMap(accessedSym));
  1991         class ResolveDeferredRecoveryMap extends DeferredAttr.RecoveryDeferredTypeMap {
  1993             public ResolveDeferredRecoveryMap(Symbol msym) {
  1994                 deferredAttr.super(AttrMode.SPECULATIVE, msym, currentResolutionContext.step);
  1997             @Override
  1998             protected Type typeOf(DeferredType dt) {
  1999                 Type res = super.typeOf(dt);
  2000                 if (!res.isErroneous()) {
  2001                     switch (TreeInfo.skipParens(dt.tree).getTag()) {
  2002                         case LAMBDA:
  2003                         case REFERENCE:
  2004                             return dt;
  2005                         case CONDEXPR:
  2006                             return res == Type.recoveryType ?
  2007                                     dt : res;
  2010                 return res;
  2013     };
  2015     /** Check that sym is not an abstract method.
  2016      */
  2017     void checkNonAbstract(DiagnosticPosition pos, Symbol sym) {
  2018         if ((sym.flags() & ABSTRACT) != 0 && (sym.flags() & DEFAULT) == 0)
  2019             log.error(pos, "abstract.cant.be.accessed.directly",
  2020                       kindName(sym), sym, sym.location());
  2023 /* ***************************************************************************
  2024  *  Debugging
  2025  ****************************************************************************/
  2027     /** print all scopes starting with scope s and proceeding outwards.
  2028      *  used for debugging.
  2029      */
  2030     public void printscopes(Scope s) {
  2031         while (s != null) {
  2032             if (s.owner != null)
  2033                 System.err.print(s.owner + ": ");
  2034             for (Scope.Entry e = s.elems; e != null; e = e.sibling) {
  2035                 if ((e.sym.flags() & ABSTRACT) != 0)
  2036                     System.err.print("abstract ");
  2037                 System.err.print(e.sym + " ");
  2039             System.err.println();
  2040             s = s.next;
  2044     void printscopes(Env<AttrContext> env) {
  2045         while (env.outer != null) {
  2046             System.err.println("------------------------------");
  2047             printscopes(env.info.scope);
  2048             env = env.outer;
  2052     public void printscopes(Type t) {
  2053         while (t.hasTag(CLASS)) {
  2054             printscopes(t.tsym.members());
  2055             t = types.supertype(t);
  2059 /* ***************************************************************************
  2060  *  Name resolution
  2061  *  Naming conventions are as for symbol lookup
  2062  *  Unlike the find... methods these methods will report access errors
  2063  ****************************************************************************/
  2065     /** Resolve an unqualified (non-method) identifier.
  2066      *  @param pos       The position to use for error reporting.
  2067      *  @param env       The environment current at the identifier use.
  2068      *  @param name      The identifier's name.
  2069      *  @param kind      The set of admissible symbol kinds for the identifier.
  2070      */
  2071     Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env,
  2072                         Name name, int kind) {
  2073         return accessBase(
  2074             findIdent(env, name, kind),
  2075             pos, env.enclClass.sym.type, name, false);
  2078     /** Resolve an unqualified method identifier.
  2079      *  @param pos       The position to use for error reporting.
  2080      *  @param env       The environment current at the method invocation.
  2081      *  @param name      The identifier's name.
  2082      *  @param argtypes  The types of the invocation's value arguments.
  2083      *  @param typeargtypes  The types of the invocation's type arguments.
  2084      */
  2085     Symbol resolveMethod(DiagnosticPosition pos,
  2086                          Env<AttrContext> env,
  2087                          Name name,
  2088                          List<Type> argtypes,
  2089                          List<Type> typeargtypes) {
  2090         return lookupMethod(env, pos, env.enclClass.sym, new BasicLookupHelper(name, env.enclClass.sym.type, argtypes, typeargtypes) {
  2091             @Override
  2092             Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2093                 return findFun(env, name, argtypes, typeargtypes,
  2094                         phase.isBoxingRequired(),
  2095                         phase.isVarargsRequired());
  2097         });
  2100     /** Resolve a qualified method identifier
  2101      *  @param pos       The position to use for error reporting.
  2102      *  @param env       The environment current at the method invocation.
  2103      *  @param site      The type of the qualifying expression, in which
  2104      *                   identifier is searched.
  2105      *  @param name      The identifier's name.
  2106      *  @param argtypes  The types of the invocation's value arguments.
  2107      *  @param typeargtypes  The types of the invocation's type arguments.
  2108      */
  2109     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
  2110                                   Type site, Name name, List<Type> argtypes,
  2111                                   List<Type> typeargtypes) {
  2112         return resolveQualifiedMethod(pos, env, site.tsym, site, name, argtypes, typeargtypes);
  2114     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
  2115                                   Symbol location, Type site, Name name, List<Type> argtypes,
  2116                                   List<Type> typeargtypes) {
  2117         return resolveQualifiedMethod(new MethodResolutionContext(), pos, env, location, site, name, argtypes, typeargtypes);
  2119     private Symbol resolveQualifiedMethod(MethodResolutionContext resolveContext,
  2120                                   DiagnosticPosition pos, Env<AttrContext> env,
  2121                                   Symbol location, Type site, Name name, List<Type> argtypes,
  2122                                   List<Type> typeargtypes) {
  2123         return lookupMethod(env, pos, location, resolveContext, new BasicLookupHelper(name, site, argtypes, typeargtypes) {
  2124             @Override
  2125             Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2126                 return findMethod(env, site, name, argtypes, typeargtypes,
  2127                         phase.isBoxingRequired(),
  2128                         phase.isVarargsRequired(), false);
  2130             @Override
  2131             Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2132                 if (sym.kind >= AMBIGUOUS) {
  2133                     sym = super.access(env, pos, location, sym);
  2134                 } else if (allowMethodHandles) {
  2135                     MethodSymbol msym = (MethodSymbol)sym;
  2136                     if (msym.isSignaturePolymorphic(types)) {
  2137                         return findPolymorphicSignatureInstance(env, sym, argtypes);
  2140                 return sym;
  2142         });
  2145     /** Find or create an implicit method of exactly the given type (after erasure).
  2146      *  Searches in a side table, not the main scope of the site.
  2147      *  This emulates the lookup process required by JSR 292 in JVM.
  2148      *  @param env       Attribution environment
  2149      *  @param spMethod  signature polymorphic method - i.e. MH.invokeExact
  2150      *  @param argtypes  The required argument types
  2151      */
  2152     Symbol findPolymorphicSignatureInstance(Env<AttrContext> env,
  2153                                             final Symbol spMethod,
  2154                                             List<Type> argtypes) {
  2155         Type mtype = infer.instantiatePolymorphicSignatureInstance(env,
  2156                 (MethodSymbol)spMethod, currentResolutionContext, argtypes);
  2157         for (Symbol sym : polymorphicSignatureScope.getElementsByName(spMethod.name)) {
  2158             if (types.isSameType(mtype, sym.type)) {
  2159                return sym;
  2163         // create the desired method
  2164         long flags = ABSTRACT | HYPOTHETICAL | spMethod.flags() & Flags.AccessFlags;
  2165         Symbol msym = new MethodSymbol(flags, spMethod.name, mtype, spMethod.owner) {
  2166             @Override
  2167             public Symbol baseSymbol() {
  2168                 return spMethod;
  2170         };
  2171         polymorphicSignatureScope.enter(msym);
  2172         return msym;
  2175     /** Resolve a qualified method identifier, throw a fatal error if not
  2176      *  found.
  2177      *  @param pos       The position to use for error reporting.
  2178      *  @param env       The environment current at the method invocation.
  2179      *  @param site      The type of the qualifying expression, in which
  2180      *                   identifier is searched.
  2181      *  @param name      The identifier's name.
  2182      *  @param argtypes  The types of the invocation's value arguments.
  2183      *  @param typeargtypes  The types of the invocation's type arguments.
  2184      */
  2185     public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env,
  2186                                         Type site, Name name,
  2187                                         List<Type> argtypes,
  2188                                         List<Type> typeargtypes) {
  2189         MethodResolutionContext resolveContext = new MethodResolutionContext();
  2190         resolveContext.internalResolution = true;
  2191         Symbol sym = resolveQualifiedMethod(resolveContext, pos, env, site.tsym,
  2192                 site, name, argtypes, typeargtypes);
  2193         if (sym.kind == MTH) return (MethodSymbol)sym;
  2194         else throw new FatalError(
  2195                  diags.fragment("fatal.err.cant.locate.meth",
  2196                                 name));
  2199     /** Resolve constructor.
  2200      *  @param pos       The position to use for error reporting.
  2201      *  @param env       The environment current at the constructor invocation.
  2202      *  @param site      The type of class for which a constructor is searched.
  2203      *  @param argtypes  The types of the constructor invocation's value
  2204      *                   arguments.
  2205      *  @param typeargtypes  The types of the constructor invocation's type
  2206      *                   arguments.
  2207      */
  2208     Symbol resolveConstructor(DiagnosticPosition pos,
  2209                               Env<AttrContext> env,
  2210                               Type site,
  2211                               List<Type> argtypes,
  2212                               List<Type> typeargtypes) {
  2213         return resolveConstructor(new MethodResolutionContext(), pos, env, site, argtypes, typeargtypes);
  2216     private Symbol resolveConstructor(MethodResolutionContext resolveContext,
  2217                               final DiagnosticPosition pos,
  2218                               Env<AttrContext> env,
  2219                               Type site,
  2220                               List<Type> argtypes,
  2221                               List<Type> typeargtypes) {
  2222         return lookupMethod(env, pos, site.tsym, resolveContext, new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
  2223             @Override
  2224             Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2225                 return findConstructor(pos, env, site, argtypes, typeargtypes,
  2226                         phase.isBoxingRequired(),
  2227                         phase.isVarargsRequired());
  2229         });
  2232     /** Resolve a constructor, throw a fatal error if not found.
  2233      *  @param pos       The position to use for error reporting.
  2234      *  @param env       The environment current at the method invocation.
  2235      *  @param site      The type to be constructed.
  2236      *  @param argtypes  The types of the invocation's value arguments.
  2237      *  @param typeargtypes  The types of the invocation's type arguments.
  2238      */
  2239     public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  2240                                         Type site,
  2241                                         List<Type> argtypes,
  2242                                         List<Type> typeargtypes) {
  2243         MethodResolutionContext resolveContext = new MethodResolutionContext();
  2244         resolveContext.internalResolution = true;
  2245         Symbol sym = resolveConstructor(resolveContext, pos, env, site, argtypes, typeargtypes);
  2246         if (sym.kind == MTH) return (MethodSymbol)sym;
  2247         else throw new FatalError(
  2248                  diags.fragment("fatal.err.cant.locate.ctor", site));
  2251     Symbol findConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  2252                               Type site, List<Type> argtypes,
  2253                               List<Type> typeargtypes,
  2254                               boolean allowBoxing,
  2255                               boolean useVarargs) {
  2256         Symbol sym = findMethod(env, site,
  2257                                     names.init, argtypes,
  2258                                     typeargtypes, allowBoxing,
  2259                                     useVarargs, false);
  2260         chk.checkDeprecated(pos, env.info.scope.owner, sym);
  2261         return sym;
  2264     /** Resolve constructor using diamond inference.
  2265      *  @param pos       The position to use for error reporting.
  2266      *  @param env       The environment current at the constructor invocation.
  2267      *  @param site      The type of class for which a constructor is searched.
  2268      *                   The scope of this class has been touched in attribution.
  2269      *  @param argtypes  The types of the constructor invocation's value
  2270      *                   arguments.
  2271      *  @param typeargtypes  The types of the constructor invocation's type
  2272      *                   arguments.
  2273      */
  2274     Symbol resolveDiamond(DiagnosticPosition pos,
  2275                               Env<AttrContext> env,
  2276                               Type site,
  2277                               List<Type> argtypes,
  2278                               List<Type> typeargtypes) {
  2279         return lookupMethod(env, pos, site.tsym, new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
  2280             @Override
  2281             Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2282                 return findDiamond(env, site, argtypes, typeargtypes,
  2283                         phase.isBoxingRequired(),
  2284                         phase.isVarargsRequired());
  2286             @Override
  2287             Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2288                 if (sym.kind >= AMBIGUOUS) {
  2289                     final JCDiagnostic details = sym.kind == WRONG_MTH ?
  2290                                     ((InapplicableSymbolError)sym).errCandidate().details :
  2291                                     null;
  2292                     sym = new InapplicableSymbolError(sym.kind, "diamondError", currentResolutionContext) {
  2293                         @Override
  2294                         JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos,
  2295                                 Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
  2296                             String key = details == null ?
  2297                                 "cant.apply.diamond" :
  2298                                 "cant.apply.diamond.1";
  2299                             return diags.create(dkind, log.currentSource(), pos, key,
  2300                                     diags.fragment("diamond", site.tsym), details);
  2302                     };
  2303                     sym = accessMethod(sym, pos, site, names.init, true, argtypes, typeargtypes);
  2304                     env.info.pendingResolutionPhase = currentResolutionContext.step;
  2306                 return sym;
  2308         });
  2311     /** This method scans all the constructor symbol in a given class scope -
  2312      *  assuming that the original scope contains a constructor of the kind:
  2313      *  {@code Foo(X x, Y y)}, where X,Y are class type-variables declared in Foo,
  2314      *  a method check is executed against the modified constructor type:
  2315      *  {@code <X,Y>Foo<X,Y>(X x, Y y)}. This is crucial in order to enable diamond
  2316      *  inference. The inferred return type of the synthetic constructor IS
  2317      *  the inferred type for the diamond operator.
  2318      */
  2319     private Symbol findDiamond(Env<AttrContext> env,
  2320                               Type site,
  2321                               List<Type> argtypes,
  2322                               List<Type> typeargtypes,
  2323                               boolean allowBoxing,
  2324                               boolean useVarargs) {
  2325         Symbol bestSoFar = methodNotFound;
  2326         for (Scope.Entry e = site.tsym.members().lookup(names.init);
  2327              e.scope != null;
  2328              e = e.next()) {
  2329             final Symbol sym = e.sym;
  2330             //- System.out.println(" e " + e.sym);
  2331             if (sym.kind == MTH &&
  2332                 (sym.flags_field & SYNTHETIC) == 0) {
  2333                     List<Type> oldParams = e.sym.type.hasTag(FORALL) ?
  2334                             ((ForAll)sym.type).tvars :
  2335                             List.<Type>nil();
  2336                     Type constrType = new ForAll(site.tsym.type.getTypeArguments().appendList(oldParams),
  2337                             types.createMethodTypeWithReturn(sym.type.asMethodType(), site));
  2338                     MethodSymbol newConstr = new MethodSymbol(sym.flags(), names.init, constrType, site.tsym) {
  2339                         @Override
  2340                         public Symbol baseSymbol() {
  2341                             return sym;
  2343                     };
  2344                     bestSoFar = selectBest(env, site, argtypes, typeargtypes,
  2345                             newConstr,
  2346                             bestSoFar,
  2347                             allowBoxing,
  2348                             useVarargs,
  2349                             false);
  2352         return bestSoFar;
  2357     /** Resolve operator.
  2358      *  @param pos       The position to use for error reporting.
  2359      *  @param optag     The tag of the operation tree.
  2360      *  @param env       The environment current at the operation.
  2361      *  @param argtypes  The types of the operands.
  2362      */
  2363     Symbol resolveOperator(DiagnosticPosition pos, JCTree.Tag optag,
  2364                            Env<AttrContext> env, List<Type> argtypes) {
  2365         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  2366         try {
  2367             currentResolutionContext = new MethodResolutionContext();
  2368             Name name = treeinfo.operatorName(optag);
  2369             Symbol sym = findMethod(env, syms.predefClass.type, name, argtypes,
  2370                                     null, false, false, true);
  2371             if (boxingEnabled && sym.kind >= WRONG_MTHS)
  2372                 sym = findMethod(env, syms.predefClass.type, name, argtypes,
  2373                                  null, true, false, true);
  2374             return accessMethod(sym, pos, env.enclClass.sym.type, name,
  2375                           false, argtypes, null);
  2377         finally {
  2378             currentResolutionContext = prevResolutionContext;
  2382     /** Resolve operator.
  2383      *  @param pos       The position to use for error reporting.
  2384      *  @param optag     The tag of the operation tree.
  2385      *  @param env       The environment current at the operation.
  2386      *  @param arg       The type of the operand.
  2387      */
  2388     Symbol resolveUnaryOperator(DiagnosticPosition pos, JCTree.Tag optag, Env<AttrContext> env, Type arg) {
  2389         return resolveOperator(pos, optag, env, List.of(arg));
  2392     /** Resolve binary operator.
  2393      *  @param pos       The position to use for error reporting.
  2394      *  @param optag     The tag of the operation tree.
  2395      *  @param env       The environment current at the operation.
  2396      *  @param left      The types of the left operand.
  2397      *  @param right     The types of the right operand.
  2398      */
  2399     Symbol resolveBinaryOperator(DiagnosticPosition pos,
  2400                                  JCTree.Tag optag,
  2401                                  Env<AttrContext> env,
  2402                                  Type left,
  2403                                  Type right) {
  2404         return resolveOperator(pos, optag, env, List.of(left, right));
  2407     /**
  2408      * Resolution of member references is typically done as a single
  2409      * overload resolution step, where the argument types A are inferred from
  2410      * the target functional descriptor.
  2412      * If the member reference is a method reference with a type qualifier,
  2413      * a two-step lookup process is performed. The first step uses the
  2414      * expected argument list A, while the second step discards the first
  2415      * type from A (which is treated as a receiver type).
  2417      * There are two cases in which inference is performed: (i) if the member
  2418      * reference is a constructor reference and the qualifier type is raw - in
  2419      * which case diamond inference is used to infer a parameterization for the
  2420      * type qualifier; (ii) if the member reference is an unbound reference
  2421      * where the type qualifier is raw - in that case, during the unbound lookup
  2422      * the receiver argument type is used to infer an instantiation for the raw
  2423      * qualifier type.
  2425      * When a multi-step resolution process is exploited, it is an error
  2426      * if two candidates are found (ambiguity).
  2428      * This routine returns a pair (T,S), where S is the member reference symbol,
  2429      * and T is the type of the class in which S is defined. This is necessary as
  2430      * the type T might be dynamically inferred (i.e. if constructor reference
  2431      * has a raw qualifier).
  2432      */
  2433     Pair<Symbol, ReferenceLookupHelper> resolveMemberReference(DiagnosticPosition pos,
  2434                                   Env<AttrContext> env,
  2435                                   JCMemberReference referenceTree,
  2436                                   Type site,
  2437                                   Name name, List<Type> argtypes,
  2438                                   List<Type> typeargtypes,
  2439                                   boolean boxingAllowed) {
  2440         MethodResolutionPhase maxPhase = boxingAllowed ? VARARITY : BASIC;
  2441         //step 1 - bound lookup
  2442         ReferenceLookupHelper boundLookupHelper = name.equals(names.init) ?
  2443                 new ConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase) :
  2444                 new MethodReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
  2445         Env<AttrContext> boundEnv = env.dup(env.tree, env.info.dup());
  2446         Symbol boundSym = lookupMethod(boundEnv, env.tree.pos(), site.tsym, boundLookupHelper);
  2448         //step 2 - unbound lookup
  2449         ReferenceLookupHelper unboundLookupHelper = boundLookupHelper.unboundLookup();
  2450         Env<AttrContext> unboundEnv = env.dup(env.tree, env.info.dup());
  2451         Symbol unboundSym = lookupMethod(unboundEnv, env.tree.pos(), site.tsym, unboundLookupHelper);
  2453         //merge results
  2454         Pair<Symbol, ReferenceLookupHelper> res;
  2455         if (unboundSym.kind != MTH) {
  2456             res = new Pair<Symbol, ReferenceLookupHelper>(boundSym, boundLookupHelper);
  2457             env.info.pendingResolutionPhase = boundEnv.info.pendingResolutionPhase;
  2458         } else if (boundSym.kind == MTH) {
  2459             res = new Pair<Symbol, ReferenceLookupHelper>(ambiguityError(boundSym, unboundSym), boundLookupHelper);
  2460             env.info.pendingResolutionPhase = boundEnv.info.pendingResolutionPhase;
  2461         } else {
  2462             res = new Pair<Symbol, ReferenceLookupHelper>(unboundSym, unboundLookupHelper);
  2463             env.info.pendingResolutionPhase = unboundEnv.info.pendingResolutionPhase;
  2466         return res;
  2469     /**
  2470      * Helper for defining custom method-like lookup logic; a lookup helper
  2471      * provides hooks for (i) the actual lookup logic and (ii) accessing the
  2472      * lookup result (this step might result in compiler diagnostics to be generated)
  2473      */
  2474     abstract class LookupHelper {
  2476         /** name of the symbol to lookup */
  2477         Name name;
  2479         /** location in which the lookup takes place */
  2480         Type site;
  2482         /** actual types used during the lookup */
  2483         List<Type> argtypes;
  2485         /** type arguments used during the lookup */
  2486         List<Type> typeargtypes;
  2488         /** Max overload resolution phase handled by this helper */
  2489         MethodResolutionPhase maxPhase;
  2491         LookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2492             this.name = name;
  2493             this.site = site;
  2494             this.argtypes = argtypes;
  2495             this.typeargtypes = typeargtypes;
  2496             this.maxPhase = maxPhase;
  2499         /**
  2500          * Should lookup stop at given phase with given result
  2501          */
  2502         protected boolean shouldStop(Symbol sym, MethodResolutionPhase phase) {
  2503             return phase.ordinal() > maxPhase.ordinal() ||
  2504                     sym.kind < ERRONEOUS || sym.kind == AMBIGUOUS;
  2507         /**
  2508          * Search for a symbol under a given overload resolution phase - this method
  2509          * is usually called several times, once per each overload resolution phase
  2510          */
  2511         abstract Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase);
  2513         /**
  2514          * Validate the result of the lookup
  2515          */
  2516         abstract Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym);
  2519     abstract class BasicLookupHelper extends LookupHelper {
  2521         BasicLookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes) {
  2522             super(name, site, argtypes, typeargtypes, MethodResolutionPhase.VARARITY);
  2525         @Override
  2526         Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2527             if (sym.kind >= AMBIGUOUS) {
  2528                 //if nothing is found return the 'first' error
  2529                 sym = accessMethod(sym, pos, location, site, name, true, argtypes, typeargtypes);
  2531             return sym;
  2535     /**
  2536      * Helper class for member reference lookup. A reference lookup helper
  2537      * defines the basic logic for member reference lookup; a method gives
  2538      * access to an 'unbound' helper used to perform an unbound member
  2539      * reference lookup.
  2540      */
  2541     abstract class ReferenceLookupHelper extends LookupHelper {
  2543         /** The member reference tree */
  2544         JCMemberReference referenceTree;
  2546         ReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
  2547                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2548             super(name, site, argtypes, typeargtypes, maxPhase);
  2549             this.referenceTree = referenceTree;
  2553         /**
  2554          * Returns an unbound version of this lookup helper. By default, this
  2555          * method returns an dummy lookup helper.
  2556          */
  2557         ReferenceLookupHelper unboundLookup() {
  2558             //dummy loopkup helper that always return 'methodNotFound'
  2559             return new ReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase) {
  2560                 @Override
  2561                 ReferenceLookupHelper unboundLookup() {
  2562                     return this;
  2564                 @Override
  2565                 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2566                     return methodNotFound;
  2568                 @Override
  2569                 ReferenceKind referenceKind(Symbol sym) {
  2570                     Assert.error();
  2571                     return null;
  2573             };
  2576         /**
  2577          * Get the kind of the member reference
  2578          */
  2579         abstract JCMemberReference.ReferenceKind referenceKind(Symbol sym);
  2581         Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2582             //skip error reporting
  2583             return sym;
  2587     /**
  2588      * Helper class for method reference lookup. The lookup logic is based
  2589      * upon Resolve.findMethod; in certain cases, this helper class has a
  2590      * corresponding unbound helper class (see UnboundMethodReferenceLookupHelper).
  2591      * In such cases, non-static lookup results are thrown away.
  2592      */
  2593     class MethodReferenceLookupHelper extends ReferenceLookupHelper {
  2595         MethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
  2596                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2597             super(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
  2600         protected Symbol lookupReferenceInternal(Env<AttrContext> env, MethodResolutionPhase phase) {
  2601             return findMethod(env, site, name, argtypes, typeargtypes,
  2602                     phase.isBoxingRequired(), phase.isVarargsRequired(), syms.operatorNames.contains(name));
  2605         protected Symbol adjustLookupResult(Env<AttrContext> env, Symbol sym) {
  2606             return !TreeInfo.isStaticSelector(referenceTree.expr, names) ||
  2607                         sym.kind != MTH ||
  2608                         sym.isStatic() ? sym : new StaticError(sym);
  2611         @Override
  2612         final Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2613             return adjustLookupResult(env, lookupReferenceInternal(env, phase));
  2616         @Override
  2617         ReferenceLookupHelper unboundLookup() {
  2618             if (TreeInfo.isStaticSelector(referenceTree.expr, names) &&
  2619                     argtypes.nonEmpty() &&
  2620                     types.isSubtypeUnchecked(argtypes.head, site)) {
  2621                 return new UnboundMethodReferenceLookupHelper(referenceTree, name,
  2622                         site, argtypes, typeargtypes, maxPhase);
  2623             } else {
  2624                 return super.unboundLookup();
  2628         @Override
  2629         ReferenceKind referenceKind(Symbol sym) {
  2630             if (sym.isStatic()) {
  2631                 return ReferenceKind.STATIC;
  2632             } else {
  2633                 Name selName = TreeInfo.name(referenceTree.getQualifierExpression());
  2634                 return selName != null && selName == names._super ?
  2635                         ReferenceKind.SUPER :
  2636                         ReferenceKind.BOUND;
  2641     /**
  2642      * Helper class for unbound method reference lookup. Essentially the same
  2643      * as the basic method reference lookup helper; main difference is that static
  2644      * lookup results are thrown away. If qualifier type is raw, an attempt to
  2645      * infer a parameterized type is made using the first actual argument (that
  2646      * would otherwise be ignored during the lookup).
  2647      */
  2648     class UnboundMethodReferenceLookupHelper extends MethodReferenceLookupHelper {
  2650         UnboundMethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
  2651                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2652             super(referenceTree, name,
  2653                     site.isRaw() ? types.asSuper(argtypes.head, site.tsym) : site,
  2654                     argtypes.tail, typeargtypes, maxPhase);
  2657         @Override
  2658         protected Symbol adjustLookupResult(Env<AttrContext> env, Symbol sym) {
  2659             return sym.kind != MTH || !sym.isStatic() ? sym : new StaticError(sym);
  2662         @Override
  2663         ReferenceLookupHelper unboundLookup() {
  2664             return this;
  2667         @Override
  2668         ReferenceKind referenceKind(Symbol sym) {
  2669             return ReferenceKind.UNBOUND;
  2673     /**
  2674      * Helper class for constructor reference lookup. The lookup logic is based
  2675      * upon either Resolve.findMethod or Resolve.findDiamond - depending on
  2676      * whether the constructor reference needs diamond inference (this is the case
  2677      * if the qualifier type is raw). A special erroneous symbol is returned
  2678      * if the lookup returns the constructor of an inner class and there's no
  2679      * enclosing instance in scope.
  2680      */
  2681     class ConstructorReferenceLookupHelper extends ReferenceLookupHelper {
  2683         boolean needsInference;
  2685         ConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
  2686                 List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2687             super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase);
  2688             if (site.isRaw()) {
  2689                 this.site = new ClassType(site.getEnclosingType(), site.tsym.type.getTypeArguments(), site.tsym);
  2690                 needsInference = true;
  2694         @Override
  2695         protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2696             Symbol sym = needsInference ?
  2697                 findDiamond(env, site, argtypes, typeargtypes, phase.isBoxingRequired(), phase.isVarargsRequired()) :
  2698                 findMethod(env, site, name, argtypes, typeargtypes,
  2699                         phase.isBoxingRequired(), phase.isVarargsRequired(), syms.operatorNames.contains(name));
  2700             return sym.kind != MTH ||
  2701                           site.getEnclosingType().hasTag(NONE) ||
  2702                           hasEnclosingInstance(env, site) ?
  2703                           sym : new InvalidSymbolError(Kinds.MISSING_ENCL, sym, null) {
  2704                     @Override
  2705                     JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
  2706                        return diags.create(dkind, log.currentSource(), pos,
  2707                             "cant.access.inner.cls.constr", site.tsym.name, argtypes, site.getEnclosingType());
  2709                 };
  2712         @Override
  2713         ReferenceKind referenceKind(Symbol sym) {
  2714             return site.getEnclosingType().hasTag(NONE) ?
  2715                     ReferenceKind.TOPLEVEL : ReferenceKind.IMPLICIT_INNER;
  2719     /**
  2720      * Main overload resolution routine. On each overload resolution step, a
  2721      * lookup helper class is used to perform the method/constructor lookup;
  2722      * at the end of the lookup, the helper is used to validate the results
  2723      * (this last step might trigger overload resolution diagnostics).
  2724      */
  2725     Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, LookupHelper lookupHelper) {
  2726         return lookupMethod(env, pos, location, new MethodResolutionContext(), lookupHelper);
  2729     Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location,
  2730             MethodResolutionContext resolveContext, LookupHelper lookupHelper) {
  2731         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  2732         try {
  2733             Symbol bestSoFar = methodNotFound;
  2734             currentResolutionContext = resolveContext;
  2735             for (MethodResolutionPhase phase : methodResolutionSteps) {
  2736                 if (!phase.isApplicable(boxingEnabled, varargsEnabled) ||
  2737                         lookupHelper.shouldStop(bestSoFar, phase)) break;
  2738                 MethodResolutionPhase prevPhase = currentResolutionContext.step;
  2739                 Symbol prevBest = bestSoFar;
  2740                 currentResolutionContext.step = phase;
  2741                 bestSoFar = phase.mergeResults(bestSoFar, lookupHelper.lookup(env, phase));
  2742                 env.info.pendingResolutionPhase = (prevBest == bestSoFar) ? prevPhase : phase;
  2744             return lookupHelper.access(env, pos, location, bestSoFar);
  2745         } finally {
  2746             currentResolutionContext = prevResolutionContext;
  2750     /**
  2751      * Resolve `c.name' where name == this or name == super.
  2752      * @param pos           The position to use for error reporting.
  2753      * @param env           The environment current at the expression.
  2754      * @param c             The qualifier.
  2755      * @param name          The identifier's name.
  2756      */
  2757     Symbol resolveSelf(DiagnosticPosition pos,
  2758                        Env<AttrContext> env,
  2759                        TypeSymbol c,
  2760                        Name name) {
  2761         Env<AttrContext> env1 = env;
  2762         boolean staticOnly = false;
  2763         while (env1.outer != null) {
  2764             if (isStatic(env1)) staticOnly = true;
  2765             if (env1.enclClass.sym == c) {
  2766                 Symbol sym = env1.info.scope.lookup(name).sym;
  2767                 if (sym != null) {
  2768                     if (staticOnly) sym = new StaticError(sym);
  2769                     return accessBase(sym, pos, env.enclClass.sym.type,
  2770                                   name, true);
  2773             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  2774             env1 = env1.outer;
  2776         if (allowDefaultMethods && c.isInterface() &&
  2777                 name == names._super && !isStatic(env) &&
  2778                 types.isDirectSuperInterface(c, env.enclClass.sym)) {
  2779             //this might be a default super call if one of the superinterfaces is 'c'
  2780             for (Type t : pruneInterfaces(env.enclClass.type)) {
  2781                 if (t.tsym == c) {
  2782                     env.info.defaultSuperCallSite = t;
  2783                     return new VarSymbol(0, names._super,
  2784                             types.asSuper(env.enclClass.type, c), env.enclClass.sym);
  2787             //find a direct superinterface that is a subtype of 'c'
  2788             for (Type i : types.interfaces(env.enclClass.type)) {
  2789                 if (i.tsym.isSubClass(c, types) && i.tsym != c) {
  2790                     log.error(pos, "illegal.default.super.call", c,
  2791                             diags.fragment("redundant.supertype", c, i));
  2792                     return syms.errSymbol;
  2795             Assert.error();
  2797         log.error(pos, "not.encl.class", c);
  2798         return syms.errSymbol;
  2800     //where
  2801     private List<Type> pruneInterfaces(Type t) {
  2802         ListBuffer<Type> result = ListBuffer.lb();
  2803         for (Type t1 : types.interfaces(t)) {
  2804             boolean shouldAdd = true;
  2805             for (Type t2 : types.interfaces(t)) {
  2806                 if (t1 != t2 && types.isSubtypeNoCapture(t2, t1)) {
  2807                     shouldAdd = false;
  2810             if (shouldAdd) {
  2811                 result.append(t1);
  2814         return result.toList();
  2818     /**
  2819      * Resolve `c.this' for an enclosing class c that contains the
  2820      * named member.
  2821      * @param pos           The position to use for error reporting.
  2822      * @param env           The environment current at the expression.
  2823      * @param member        The member that must be contained in the result.
  2824      */
  2825     Symbol resolveSelfContaining(DiagnosticPosition pos,
  2826                                  Env<AttrContext> env,
  2827                                  Symbol member,
  2828                                  boolean isSuperCall) {
  2829         Symbol sym = resolveSelfContainingInternal(env, member, isSuperCall);
  2830         if (sym == null) {
  2831             log.error(pos, "encl.class.required", member);
  2832             return syms.errSymbol;
  2833         } else {
  2834             return accessBase(sym, pos, env.enclClass.sym.type, sym.name, true);
  2838     boolean hasEnclosingInstance(Env<AttrContext> env, Type type) {
  2839         Symbol encl = resolveSelfContainingInternal(env, type.tsym, false);
  2840         return encl != null && encl.kind < ERRONEOUS;
  2843     private Symbol resolveSelfContainingInternal(Env<AttrContext> env,
  2844                                  Symbol member,
  2845                                  boolean isSuperCall) {
  2846         Name name = names._this;
  2847         Env<AttrContext> env1 = isSuperCall ? env.outer : env;
  2848         boolean staticOnly = false;
  2849         if (env1 != null) {
  2850             while (env1 != null && env1.outer != null) {
  2851                 if (isStatic(env1)) staticOnly = true;
  2852                 if (env1.enclClass.sym.isSubClass(member.owner, types)) {
  2853                     Symbol sym = env1.info.scope.lookup(name).sym;
  2854                     if (sym != null) {
  2855                         if (staticOnly) sym = new StaticError(sym);
  2856                         return sym;
  2859                 if ((env1.enclClass.sym.flags() & STATIC) != 0)
  2860                     staticOnly = true;
  2861                 env1 = env1.outer;
  2864         return null;
  2867     /**
  2868      * Resolve an appropriate implicit this instance for t's container.
  2869      * JLS 8.8.5.1 and 15.9.2
  2870      */
  2871     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
  2872         return resolveImplicitThis(pos, env, t, false);
  2875     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t, boolean isSuperCall) {
  2876         Type thisType = (((t.tsym.owner.kind & (MTH|VAR)) != 0)
  2877                          ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
  2878                          : resolveSelfContaining(pos, env, t.tsym, isSuperCall)).type;
  2879         if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
  2880             log.error(pos, "cant.ref.before.ctor.called", "this");
  2881         return thisType;
  2884 /* ***************************************************************************
  2885  *  ResolveError classes, indicating error situations when accessing symbols
  2886  ****************************************************************************/
  2888     //used by TransTypes when checking target type of synthetic cast
  2889     public void logAccessErrorInternal(Env<AttrContext> env, JCTree tree, Type type) {
  2890         AccessError error = new AccessError(env, env.enclClass.type, type.tsym);
  2891         logResolveError(error, tree.pos(), env.enclClass.sym, env.enclClass.type, null, null, null);
  2893     //where
  2894     private void logResolveError(ResolveError error,
  2895             DiagnosticPosition pos,
  2896             Symbol location,
  2897             Type site,
  2898             Name name,
  2899             List<Type> argtypes,
  2900             List<Type> typeargtypes) {
  2901         JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
  2902                 pos, location, site, name, argtypes, typeargtypes);
  2903         if (d != null) {
  2904             d.setFlag(DiagnosticFlag.RESOLVE_ERROR);
  2905             log.report(d);
  2909     private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
  2911     public Object methodArguments(List<Type> argtypes) {
  2912         if (argtypes == null || argtypes.isEmpty()) {
  2913             return noArgs;
  2914         } else {
  2915             ListBuffer<Object> diagArgs = ListBuffer.lb();
  2916             for (Type t : argtypes) {
  2917                 if (t.hasTag(DEFERRED)) {
  2918                     diagArgs.append(((DeferredAttr.DeferredType)t).tree);
  2919                 } else {
  2920                     diagArgs.append(t);
  2923             return diagArgs;
  2927     /**
  2928      * Root class for resolution errors. Subclass of ResolveError
  2929      * represent a different kinds of resolution error - as such they must
  2930      * specify how they map into concrete compiler diagnostics.
  2931      */
  2932     abstract class ResolveError extends Symbol {
  2934         /** The name of the kind of error, for debugging only. */
  2935         final String debugName;
  2937         ResolveError(int kind, String debugName) {
  2938             super(kind, 0, null, null, null);
  2939             this.debugName = debugName;
  2942         @Override
  2943         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
  2944             throw new AssertionError();
  2947         @Override
  2948         public String toString() {
  2949             return debugName;
  2952         @Override
  2953         public boolean exists() {
  2954             return false;
  2957         /**
  2958          * Create an external representation for this erroneous symbol to be
  2959          * used during attribution - by default this returns the symbol of a
  2960          * brand new error type which stores the original type found
  2961          * during resolution.
  2963          * @param name     the name used during resolution
  2964          * @param location the location from which the symbol is accessed
  2965          */
  2966         protected Symbol access(Name name, TypeSymbol location) {
  2967             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  2970         /**
  2971          * Create a diagnostic representing this resolution error.
  2973          * @param dkind     The kind of the diagnostic to be created (e.g error).
  2974          * @param pos       The position to be used for error reporting.
  2975          * @param site      The original type from where the selection took place.
  2976          * @param name      The name of the symbol to be resolved.
  2977          * @param argtypes  The invocation's value arguments,
  2978          *                  if we looked for a method.
  2979          * @param typeargtypes  The invocation's type arguments,
  2980          *                      if we looked for a method.
  2981          */
  2982         abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2983                 DiagnosticPosition pos,
  2984                 Symbol location,
  2985                 Type site,
  2986                 Name name,
  2987                 List<Type> argtypes,
  2988                 List<Type> typeargtypes);
  2991     /**
  2992      * This class is the root class of all resolution errors caused by
  2993      * an invalid symbol being found during resolution.
  2994      */
  2995     abstract class InvalidSymbolError extends ResolveError {
  2997         /** The invalid symbol found during resolution */
  2998         Symbol sym;
  3000         InvalidSymbolError(int kind, Symbol sym, String debugName) {
  3001             super(kind, debugName);
  3002             this.sym = sym;
  3005         @Override
  3006         public boolean exists() {
  3007             return true;
  3010         @Override
  3011         public String toString() {
  3012              return super.toString() + " wrongSym=" + sym;
  3015         @Override
  3016         public Symbol access(Name name, TypeSymbol location) {
  3017             if (sym.kind >= AMBIGUOUS)
  3018                 return ((ResolveError)sym).access(name, location);
  3019             else if ((sym.kind & ERRONEOUS) == 0 && (sym.kind & TYP) != 0)
  3020                 return types.createErrorType(name, location, sym.type).tsym;
  3021             else
  3022                 return sym;
  3026     /**
  3027      * InvalidSymbolError error class indicating that a symbol matching a
  3028      * given name does not exists in a given site.
  3029      */
  3030     class SymbolNotFoundError extends ResolveError {
  3032         SymbolNotFoundError(int kind) {
  3033             super(kind, "symbol not found error");
  3036         @Override
  3037         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3038                 DiagnosticPosition pos,
  3039                 Symbol location,
  3040                 Type site,
  3041                 Name name,
  3042                 List<Type> argtypes,
  3043                 List<Type> typeargtypes) {
  3044             argtypes = argtypes == null ? List.<Type>nil() : argtypes;
  3045             typeargtypes = typeargtypes == null ? List.<Type>nil() : typeargtypes;
  3046             if (name == names.error)
  3047                 return null;
  3049             if (syms.operatorNames.contains(name)) {
  3050                 boolean isUnaryOp = argtypes.size() == 1;
  3051                 String key = argtypes.size() == 1 ?
  3052                     "operator.cant.be.applied" :
  3053                     "operator.cant.be.applied.1";
  3054                 Type first = argtypes.head;
  3055                 Type second = !isUnaryOp ? argtypes.tail.head : null;
  3056                 return diags.create(dkind, log.currentSource(), pos,
  3057                         key, name, first, second);
  3059             boolean hasLocation = false;
  3060             if (location == null) {
  3061                 location = site.tsym;
  3063             if (!location.name.isEmpty()) {
  3064                 if (location.kind == PCK && !site.tsym.exists()) {
  3065                     return diags.create(dkind, log.currentSource(), pos,
  3066                         "doesnt.exist", location);
  3068                 hasLocation = !location.name.equals(names._this) &&
  3069                         !location.name.equals(names._super);
  3071             boolean isConstructor = kind == ABSENT_MTH && name == names.init;
  3072             KindName kindname = isConstructor ? KindName.CONSTRUCTOR : absentKind(kind);
  3073             Name idname = isConstructor ? site.tsym.name : name;
  3074             String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation);
  3075             if (hasLocation) {
  3076                 return diags.create(dkind, log.currentSource(), pos,
  3077                         errKey, kindname, idname, //symbol kindname, name
  3078                         typeargtypes, args(argtypes), //type parameters and arguments (if any)
  3079                         getLocationDiag(location, site)); //location kindname, type
  3081             else {
  3082                 return diags.create(dkind, log.currentSource(), pos,
  3083                         errKey, kindname, idname, //symbol kindname, name
  3084                         typeargtypes, args(argtypes)); //type parameters and arguments (if any)
  3087         //where
  3088         private Object args(List<Type> args) {
  3089             return args.isEmpty() ? args : methodArguments(args);
  3092         private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) {
  3093             String key = "cant.resolve";
  3094             String suffix = hasLocation ? ".location" : "";
  3095             switch (kindname) {
  3096                 case METHOD:
  3097                 case CONSTRUCTOR: {
  3098                     suffix += ".args";
  3099                     suffix += hasTypeArgs ? ".params" : "";
  3102             return key + suffix;
  3104         private JCDiagnostic getLocationDiag(Symbol location, Type site) {
  3105             if (location.kind == VAR) {
  3106                 return diags.fragment("location.1",
  3107                     kindName(location),
  3108                     location,
  3109                     location.type);
  3110             } else {
  3111                 return diags.fragment("location",
  3112                     typeKindName(site),
  3113                     site,
  3114                     null);
  3119     /**
  3120      * InvalidSymbolError error class indicating that a given symbol
  3121      * (either a method, a constructor or an operand) is not applicable
  3122      * given an actual arguments/type argument list.
  3123      */
  3124     class InapplicableSymbolError extends ResolveError {
  3126         protected MethodResolutionContext resolveContext;
  3128         InapplicableSymbolError(MethodResolutionContext context) {
  3129             this(WRONG_MTH, "inapplicable symbol error", context);
  3132         protected InapplicableSymbolError(int kind, String debugName, MethodResolutionContext context) {
  3133             super(kind, debugName);
  3134             this.resolveContext = context;
  3137         @Override
  3138         public String toString() {
  3139             return super.toString();
  3142         @Override
  3143         public boolean exists() {
  3144             return true;
  3147         @Override
  3148         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3149                 DiagnosticPosition pos,
  3150                 Symbol location,
  3151                 Type site,
  3152                 Name name,
  3153                 List<Type> argtypes,
  3154                 List<Type> typeargtypes) {
  3155             if (name == names.error)
  3156                 return null;
  3158             if (syms.operatorNames.contains(name)) {
  3159                 boolean isUnaryOp = argtypes.size() == 1;
  3160                 String key = argtypes.size() == 1 ?
  3161                     "operator.cant.be.applied" :
  3162                     "operator.cant.be.applied.1";
  3163                 Type first = argtypes.head;
  3164                 Type second = !isUnaryOp ? argtypes.tail.head : null;
  3165                 return diags.create(dkind, log.currentSource(), pos,
  3166                         key, name, first, second);
  3168             else {
  3169                 Candidate c = errCandidate();
  3170                 Symbol ws = c.sym.asMemberOf(site, types);
  3171                 return diags.create(dkind, log.currentSource(), pos,
  3172                           "cant.apply.symbol",
  3173                           kindName(ws),
  3174                           ws.name == names.init ? ws.owner.name : ws.name,
  3175                           methodArguments(ws.type.getParameterTypes()),
  3176                           methodArguments(argtypes),
  3177                           kindName(ws.owner),
  3178                           ws.owner.type,
  3179                           c.details);
  3183         @Override
  3184         public Symbol access(Name name, TypeSymbol location) {
  3185             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  3188         private Candidate errCandidate() {
  3189             Candidate bestSoFar = null;
  3190             for (Candidate c : resolveContext.candidates) {
  3191                 if (c.isApplicable()) continue;
  3192                 bestSoFar = c;
  3194             Assert.checkNonNull(bestSoFar);
  3195             return bestSoFar;
  3199     /**
  3200      * ResolveError error class indicating that a set of symbols
  3201      * (either methods, constructors or operands) is not applicable
  3202      * given an actual arguments/type argument list.
  3203      */
  3204     class InapplicableSymbolsError extends InapplicableSymbolError {
  3206         InapplicableSymbolsError(MethodResolutionContext context) {
  3207             super(WRONG_MTHS, "inapplicable symbols", context);
  3210         @Override
  3211         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3212                 DiagnosticPosition pos,
  3213                 Symbol location,
  3214                 Type site,
  3215                 Name name,
  3216                 List<Type> argtypes,
  3217                 List<Type> typeargtypes) {
  3218             if (!resolveContext.candidates.isEmpty()) {
  3219                 JCDiagnostic err = diags.create(dkind,
  3220                         log.currentSource(),
  3221                         pos,
  3222                         "cant.apply.symbols",
  3223                         name == names.init ? KindName.CONSTRUCTOR : absentKind(kind),
  3224                         name == names.init ? site.tsym.name : name,
  3225                         methodArguments(argtypes));
  3226                 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(site));
  3227             } else {
  3228                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
  3229                     location, site, name, argtypes, typeargtypes);
  3233         //where
  3234         List<JCDiagnostic> candidateDetails(Type site) {
  3235             Map<Symbol, JCDiagnostic> details = new LinkedHashMap<Symbol, JCDiagnostic>();
  3236             for (Candidate c : resolveContext.candidates) {
  3237                 if (c.isApplicable()) continue;
  3238                 JCDiagnostic detailDiag = diags.fragment("inapplicable.method",
  3239                         Kinds.kindName(c.sym),
  3240                         c.sym.location(site, types),
  3241                         c.sym.asMemberOf(site, types),
  3242                         c.details);
  3243                 details.put(c.sym, detailDiag);
  3245             return List.from(details.values());
  3249     /**
  3250      * An InvalidSymbolError error class indicating that a symbol is not
  3251      * accessible from a given site
  3252      */
  3253     class AccessError extends InvalidSymbolError {
  3255         private Env<AttrContext> env;
  3256         private Type site;
  3258         AccessError(Symbol sym) {
  3259             this(null, null, sym);
  3262         AccessError(Env<AttrContext> env, Type site, Symbol sym) {
  3263             super(HIDDEN, sym, "access error");
  3264             this.env = env;
  3265             this.site = site;
  3266             if (debugResolve)
  3267                 log.error("proc.messager", sym + " @ " + site + " is inaccessible.");
  3270         @Override
  3271         public boolean exists() {
  3272             return false;
  3275         @Override
  3276         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3277                 DiagnosticPosition pos,
  3278                 Symbol location,
  3279                 Type site,
  3280                 Name name,
  3281                 List<Type> argtypes,
  3282                 List<Type> typeargtypes) {
  3283             if (sym.owner.type.hasTag(ERROR))
  3284                 return null;
  3286             if (sym.name == names.init && sym.owner != site.tsym) {
  3287                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
  3288                         pos, location, site, name, argtypes, typeargtypes);
  3290             else if ((sym.flags() & PUBLIC) != 0
  3291                 || (env != null && this.site != null
  3292                     && !isAccessible(env, this.site))) {
  3293                 return diags.create(dkind, log.currentSource(),
  3294                         pos, "not.def.access.class.intf.cant.access",
  3295                     sym, sym.location());
  3297             else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) {
  3298                 return diags.create(dkind, log.currentSource(),
  3299                         pos, "report.access", sym,
  3300                         asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
  3301                         sym.location());
  3303             else {
  3304                 return diags.create(dkind, log.currentSource(),
  3305                         pos, "not.def.public.cant.access", sym, sym.location());
  3310     /**
  3311      * InvalidSymbolError error class indicating that an instance member
  3312      * has erroneously been accessed from a static context.
  3313      */
  3314     class StaticError extends InvalidSymbolError {
  3316         StaticError(Symbol sym) {
  3317             super(STATICERR, sym, "static error");
  3320         @Override
  3321         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3322                 DiagnosticPosition pos,
  3323                 Symbol location,
  3324                 Type site,
  3325                 Name name,
  3326                 List<Type> argtypes,
  3327                 List<Type> typeargtypes) {
  3328             Symbol errSym = ((sym.kind == TYP && sym.type.hasTag(CLASS))
  3329                 ? types.erasure(sym.type).tsym
  3330                 : sym);
  3331             return diags.create(dkind, log.currentSource(), pos,
  3332                     "non-static.cant.be.ref", kindName(sym), errSym);
  3336     /**
  3337      * InvalidSymbolError error class indicating that a pair of symbols
  3338      * (either methods, constructors or operands) are ambiguous
  3339      * given an actual arguments/type argument list.
  3340      */
  3341     class AmbiguityError extends InvalidSymbolError {
  3343         /** The other maximally specific symbol */
  3344         Symbol sym2;
  3346         AmbiguityError(Symbol sym1, Symbol sym2) {
  3347             super(AMBIGUOUS, sym1, "ambiguity error");
  3348             this.sym2 = sym2;
  3351         @Override
  3352         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3353                 DiagnosticPosition pos,
  3354                 Symbol location,
  3355                 Type site,
  3356                 Name name,
  3357                 List<Type> argtypes,
  3358                 List<Type> typeargtypes) {
  3359             AmbiguityError pair = this;
  3360             while (true) {
  3361                 if (pair.sym.kind == AMBIGUOUS)
  3362                     pair = (AmbiguityError)pair.sym;
  3363                 else if (pair.sym2.kind == AMBIGUOUS)
  3364                     pair = (AmbiguityError)pair.sym2;
  3365                 else break;
  3367             Name sname = pair.sym.name;
  3368             if (sname == names.init) sname = pair.sym.owner.name;
  3369             return diags.create(dkind, log.currentSource(),
  3370                       pos, "ref.ambiguous", sname,
  3371                       kindName(pair.sym),
  3372                       pair.sym,
  3373                       pair.sym.location(site, types),
  3374                       kindName(pair.sym2),
  3375                       pair.sym2,
  3376                       pair.sym2.location(site, types));
  3380     enum MethodResolutionPhase {
  3381         BASIC(false, false),
  3382         BOX(true, false),
  3383         VARARITY(true, true) {
  3384             @Override
  3385             public Symbol mergeResults(Symbol bestSoFar, Symbol sym) {
  3386                 switch (sym.kind) {
  3387                     case WRONG_MTH:
  3388                         return (bestSoFar.kind == WRONG_MTH || bestSoFar.kind == WRONG_MTHS) ?
  3389                             bestSoFar :
  3390                             sym;
  3391                     case ABSENT_MTH:
  3392                         return bestSoFar;
  3393                     default:
  3394                         return sym;
  3397         };
  3399         final boolean isBoxingRequired;
  3400         final boolean isVarargsRequired;
  3402         MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) {
  3403            this.isBoxingRequired = isBoxingRequired;
  3404            this.isVarargsRequired = isVarargsRequired;
  3407         public boolean isBoxingRequired() {
  3408             return isBoxingRequired;
  3411         public boolean isVarargsRequired() {
  3412             return isVarargsRequired;
  3415         public boolean isApplicable(boolean boxingEnabled, boolean varargsEnabled) {
  3416             return (varargsEnabled || !isVarargsRequired) &&
  3417                    (boxingEnabled || !isBoxingRequired);
  3420         public Symbol mergeResults(Symbol prev, Symbol sym) {
  3421             return sym;
  3425     final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
  3427     /**
  3428      * A resolution context is used to keep track of intermediate results of
  3429      * overload resolution, such as list of method that are not applicable
  3430      * (used to generate more precise diagnostics) and so on. Resolution contexts
  3431      * can be nested - this means that when each overload resolution routine should
  3432      * work within the resolution context it created.
  3433      */
  3434     class MethodResolutionContext {
  3436         private List<Candidate> candidates = List.nil();
  3438         MethodResolutionPhase step = null;
  3440         private boolean internalResolution = false;
  3441         private DeferredAttr.AttrMode attrMode = DeferredAttr.AttrMode.SPECULATIVE;
  3443         void addInapplicableCandidate(Symbol sym, JCDiagnostic details) {
  3444             Candidate c = new Candidate(currentResolutionContext.step, sym, details, null);
  3445             candidates = candidates.append(c);
  3448         void addApplicableCandidate(Symbol sym, Type mtype) {
  3449             Candidate c = new Candidate(currentResolutionContext.step, sym, null, mtype);
  3450             candidates = candidates.append(c);
  3453         /**
  3454          * This class represents an overload resolution candidate. There are two
  3455          * kinds of candidates: applicable methods and inapplicable methods;
  3456          * applicable methods have a pointer to the instantiated method type,
  3457          * while inapplicable candidates contain further details about the
  3458          * reason why the method has been considered inapplicable.
  3459          */
  3460         class Candidate {
  3462             final MethodResolutionPhase step;
  3463             final Symbol sym;
  3464             final JCDiagnostic details;
  3465             final Type mtype;
  3467             private Candidate(MethodResolutionPhase step, Symbol sym, JCDiagnostic details, Type mtype) {
  3468                 this.step = step;
  3469                 this.sym = sym;
  3470                 this.details = details;
  3471                 this.mtype = mtype;
  3474             @Override
  3475             public boolean equals(Object o) {
  3476                 if (o instanceof Candidate) {
  3477                     Symbol s1 = this.sym;
  3478                     Symbol s2 = ((Candidate)o).sym;
  3479                     if  ((s1 != s2 &&
  3480                             (s1.overrides(s2, s1.owner.type.tsym, types, false) ||
  3481                             (s2.overrides(s1, s2.owner.type.tsym, types, false)))) ||
  3482                             ((s1.isConstructor() || s2.isConstructor()) && s1.owner != s2.owner))
  3483                         return true;
  3485                 return false;
  3488             boolean isApplicable() {
  3489                 return mtype != null;
  3493         DeferredAttr.AttrMode attrMode() {
  3494             return attrMode;
  3497         boolean internal() {
  3498             return internalResolution;
  3502     MethodResolutionContext currentResolutionContext = null;

mercurial