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

Tue, 06 Nov 2012 14:45:27 +0000

author
mcimadamore
date
Tue, 06 Nov 2012 14:45:27 +0000
changeset 1396
9b85813d2262
parent 1394
dbc94b8363dd
child 1409
33abf479f202
permissions
-rw-r--r--

8002286: Regression: Fix for 8000931 causes a JCK test failure
Summary: Wrong type used as 'site' in Resolve.resolveMethod
Reviewed-by: jjg

     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         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     /** Try to instantiate the type of a method so that it fits
   431      *  given type arguments and argument types. If succesful, return
   432      *  the method's instantiated type, else return null.
   433      *  The instantiation will take into account an additional leading
   434      *  formal parameter if the method is an instance method seen as a member
   435      *  of un underdetermined site In this case, we treat site as an additional
   436      *  parameter and the parameters of the class containing the method as
   437      *  additional type variables that get instantiated.
   438      *
   439      *  @param env         The current environment
   440      *  @param site        The type of which the method is a member.
   441      *  @param m           The method symbol.
   442      *  @param argtypes    The invocation's given value arguments.
   443      *  @param typeargtypes    The invocation's given type arguments.
   444      *  @param allowBoxing Allow boxing conversions of arguments.
   445      *  @param useVarargs Box trailing arguments into an array for varargs.
   446      */
   447     Type rawInstantiate(Env<AttrContext> env,
   448                         Type site,
   449                         Symbol m,
   450                         ResultInfo resultInfo,
   451                         List<Type> argtypes,
   452                         List<Type> typeargtypes,
   453                         boolean allowBoxing,
   454                         boolean useVarargs,
   455                         Warner warn) throws Infer.InferenceException {
   457         Type mt = types.memberType(site, m);
   458         // tvars is the list of formal type variables for which type arguments
   459         // need to inferred.
   460         List<Type> tvars = List.nil();
   461         if (typeargtypes == null) typeargtypes = List.nil();
   462         if (!mt.hasTag(FORALL) && typeargtypes.nonEmpty()) {
   463             // This is not a polymorphic method, but typeargs are supplied
   464             // which is fine, see JLS 15.12.2.1
   465         } else if (mt.hasTag(FORALL) && typeargtypes.nonEmpty()) {
   466             ForAll pmt = (ForAll) mt;
   467             if (typeargtypes.length() != pmt.tvars.length())
   468                 throw inapplicableMethodException.setMessage("arg.length.mismatch"); // not enough args
   469             // Check type arguments are within bounds
   470             List<Type> formals = pmt.tvars;
   471             List<Type> actuals = typeargtypes;
   472             while (formals.nonEmpty() && actuals.nonEmpty()) {
   473                 List<Type> bounds = types.subst(types.getBounds((TypeVar)formals.head),
   474                                                 pmt.tvars, typeargtypes);
   475                 for (; bounds.nonEmpty(); bounds = bounds.tail)
   476                     if (!types.isSubtypeUnchecked(actuals.head, bounds.head, warn))
   477                         throw inapplicableMethodException.setMessage("explicit.param.do.not.conform.to.bounds",actuals.head, bounds);
   478                 formals = formals.tail;
   479                 actuals = actuals.tail;
   480             }
   481             mt = types.subst(pmt.qtype, pmt.tvars, typeargtypes);
   482         } else if (mt.hasTag(FORALL)) {
   483             ForAll pmt = (ForAll) mt;
   484             List<Type> tvars1 = types.newInstances(pmt.tvars);
   485             tvars = tvars.appendList(tvars1);
   486             mt = types.subst(pmt.qtype, pmt.tvars, tvars1);
   487         }
   489         // find out whether we need to go the slow route via infer
   490         boolean instNeeded = tvars.tail != null; /*inlined: tvars.nonEmpty()*/
   491         for (List<Type> l = argtypes;
   492              l.tail != null/*inlined: l.nonEmpty()*/ && !instNeeded;
   493              l = l.tail) {
   494             if (l.head.hasTag(FORALL)) instNeeded = true;
   495         }
   497         if (instNeeded)
   498             return infer.instantiateMethod(env,
   499                                     tvars,
   500                                     (MethodType)mt,
   501                                     resultInfo,
   502                                     m,
   503                                     argtypes,
   504                                     allowBoxing,
   505                                     useVarargs,
   506                                     currentResolutionContext,
   507                                     warn);
   509         checkRawArgumentsAcceptable(env, m, argtypes, mt.getParameterTypes(),
   510                                 allowBoxing, useVarargs, warn);
   511         return mt;
   512     }
   514     Type checkMethod(Env<AttrContext> env,
   515                      Type site,
   516                      Symbol m,
   517                      ResultInfo resultInfo,
   518                      List<Type> argtypes,
   519                      List<Type> typeargtypes,
   520                      Warner warn) {
   521         MethodResolutionContext prevContext = currentResolutionContext;
   522         try {
   523             currentResolutionContext = new MethodResolutionContext();
   524             currentResolutionContext.attrMode = DeferredAttr.AttrMode.CHECK;
   525             MethodResolutionPhase step = currentResolutionContext.step = env.info.pendingResolutionPhase;
   526             return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
   527                     step.isBoxingRequired(), step.isVarargsRequired(), warn);
   528         }
   529         finally {
   530             currentResolutionContext = prevContext;
   531         }
   532     }
   534     /** Same but returns null instead throwing a NoInstanceException
   535      */
   536     Type instantiate(Env<AttrContext> env,
   537                      Type site,
   538                      Symbol m,
   539                      ResultInfo resultInfo,
   540                      List<Type> argtypes,
   541                      List<Type> typeargtypes,
   542                      boolean allowBoxing,
   543                      boolean useVarargs,
   544                      Warner warn) {
   545         try {
   546             return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
   547                                   allowBoxing, useVarargs, warn);
   548         } catch (InapplicableMethodException ex) {
   549             return null;
   550         }
   551     }
   553     /** Check if a parameter list accepts a list of args.
   554      */
   555     boolean argumentsAcceptable(Env<AttrContext> env,
   556                                 Symbol msym,
   557                                 List<Type> argtypes,
   558                                 List<Type> formals,
   559                                 boolean allowBoxing,
   560                                 boolean useVarargs,
   561                                 Warner warn) {
   562         try {
   563             checkRawArgumentsAcceptable(env, msym, argtypes, formals, allowBoxing, useVarargs, warn);
   564             return true;
   565         } catch (InapplicableMethodException ex) {
   566             return false;
   567         }
   568     }
   569     /**
   570      * A check handler is used by the main method applicability routine in order
   571      * to handle specific method applicability failures. It is assumed that a class
   572      * implementing this interface should throw exceptions that are a subtype of
   573      * InapplicableMethodException (see below). Such exception will terminate the
   574      * method applicability check and propagate important info outwards (for the
   575      * purpose of generating better diagnostics).
   576      */
   577     interface MethodCheckHandler {
   578         /* The number of actuals and formals differ */
   579         InapplicableMethodException arityMismatch();
   580         /* An actual argument type does not conform to the corresponding formal type */
   581         InapplicableMethodException argumentMismatch(boolean varargs, JCDiagnostic details);
   582         /* The element type of a varargs is not accessible in the current context */
   583         InapplicableMethodException inaccessibleVarargs(Symbol location, Type expected);
   584     }
   586     /**
   587      * Basic method check handler used within Resolve - all methods end up
   588      * throwing InapplicableMethodException; a diagnostic fragment that describes
   589      * the cause as to why the method is not applicable is set on the exception
   590      * before it is thrown.
   591      */
   592     MethodCheckHandler resolveHandler = new MethodCheckHandler() {
   593             public InapplicableMethodException arityMismatch() {
   594                 return inapplicableMethodException.setMessage("arg.length.mismatch");
   595             }
   596             public InapplicableMethodException argumentMismatch(boolean varargs, JCDiagnostic details) {
   597                 String key = varargs ?
   598                         "varargs.argument.mismatch" :
   599                         "no.conforming.assignment.exists";
   600                 return inapplicableMethodException.setMessage(key,
   601                         details);
   602             }
   603             public InapplicableMethodException inaccessibleVarargs(Symbol location, Type expected) {
   604                 return inapplicableMethodException.setMessage("inaccessible.varargs.type",
   605                         expected, Kinds.kindName(location), location);
   606             }
   607     };
   609     void checkRawArgumentsAcceptable(Env<AttrContext> env,
   610                                 Symbol msym,
   611                                 List<Type> argtypes,
   612                                 List<Type> formals,
   613                                 boolean allowBoxing,
   614                                 boolean useVarargs,
   615                                 Warner warn) {
   616         checkRawArgumentsAcceptable(env, msym, currentResolutionContext.attrMode(), infer.emptyContext, argtypes, formals,
   617                 allowBoxing, useVarargs, warn, resolveHandler);
   618     }
   620     /**
   621      * Main method applicability routine. Given a list of actual types A,
   622      * a list of formal types F, determines whether the types in A are
   623      * compatible (by method invocation conversion) with the types in F.
   624      *
   625      * Since this routine is shared between overload resolution and method
   626      * type-inference, a (possibly empty) inference context is used to convert
   627      * formal types to the corresponding 'undet' form ahead of a compatibility
   628      * check so that constraints can be propagated and collected.
   629      *
   630      * Moreover, if one or more types in A is a deferred type, this routine uses
   631      * DeferredAttr in order to perform deferred attribution. If one or more actual
   632      * deferred types are stuck, they are placed in a queue and revisited later
   633      * after the remainder of the arguments have been seen. If this is not sufficient
   634      * to 'unstuck' the argument, a cyclic inference error is called out.
   635      *
   636      * A method check handler (see above) is used in order to report errors.
   637      */
   638     void checkRawArgumentsAcceptable(final Env<AttrContext> env,
   639                                 Symbol msym,
   640                                 DeferredAttr.AttrMode mode,
   641                                 final Infer.InferenceContext inferenceContext,
   642                                 List<Type> argtypes,
   643                                 List<Type> formals,
   644                                 boolean allowBoxing,
   645                                 boolean useVarargs,
   646                                 Warner warn,
   647                                 final MethodCheckHandler handler) {
   648         Type varargsFormal = useVarargs ? formals.last() : null;
   650         if (varargsFormal == null &&
   651                 argtypes.size() != formals.size()) {
   652             throw handler.arityMismatch(); // not enough args
   653         }
   655         DeferredAttr.DeferredAttrContext deferredAttrContext =
   656                 deferredAttr.new DeferredAttrContext(mode, msym, currentResolutionContext.step, inferenceContext);
   658         while (argtypes.nonEmpty() && formals.head != varargsFormal) {
   659             ResultInfo mresult = methodCheckResult(formals.head, allowBoxing, false, inferenceContext, deferredAttrContext, handler, warn);
   660             mresult.check(null, argtypes.head);
   661             argtypes = argtypes.tail;
   662             formals = formals.tail;
   663         }
   665         if (formals.head != varargsFormal) {
   666             throw handler.arityMismatch(); // not enough args
   667         }
   669         if (useVarargs) {
   670             //note: if applicability check is triggered by most specific test,
   671             //the last argument of a varargs is _not_ an array type (see JLS 15.12.2.5)
   672             final Type elt = types.elemtype(varargsFormal);
   673             ResultInfo mresult = methodCheckResult(elt, allowBoxing, true, inferenceContext, deferredAttrContext, handler, warn);
   674             while (argtypes.nonEmpty()) {
   675                 mresult.check(null, argtypes.head);
   676                 argtypes = argtypes.tail;
   677             }
   678             //check varargs element type accessibility
   679             varargsAccessible(env, elt, handler, inferenceContext);
   680         }
   682         deferredAttrContext.complete();
   683     }
   685     void varargsAccessible(final Env<AttrContext> env, final Type t, final Resolve.MethodCheckHandler handler, final InferenceContext inferenceContext) {
   686         if (inferenceContext.free(t)) {
   687             inferenceContext.addFreeTypeListener(List.of(t), new FreeTypeListener() {
   688                 @Override
   689                 public void typesInferred(InferenceContext inferenceContext) {
   690                     varargsAccessible(env, inferenceContext.asInstType(t, types), handler, inferenceContext);
   691                 }
   692             });
   693         } else {
   694             if (!isAccessible(env, t)) {
   695                 Symbol location = env.enclClass.sym;
   696                 throw handler.inaccessibleVarargs(location, t);
   697             }
   698         }
   699     }
   701     /**
   702      * Check context to be used during method applicability checks. A method check
   703      * context might contain inference variables.
   704      */
   705     abstract class MethodCheckContext implements CheckContext {
   707         MethodCheckHandler handler;
   708         boolean useVarargs;
   709         Infer.InferenceContext inferenceContext;
   710         DeferredAttrContext deferredAttrContext;
   711         Warner rsWarner;
   713         public MethodCheckContext(MethodCheckHandler handler, boolean useVarargs,
   714                 Infer.InferenceContext inferenceContext, DeferredAttrContext deferredAttrContext, Warner rsWarner) {
   715             this.handler = handler;
   716             this.useVarargs = useVarargs;
   717             this.inferenceContext = inferenceContext;
   718             this.deferredAttrContext = deferredAttrContext;
   719             this.rsWarner = rsWarner;
   720         }
   722         public void report(DiagnosticPosition pos, JCDiagnostic details) {
   723             throw handler.argumentMismatch(useVarargs, details);
   724         }
   726         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
   727             return rsWarner;
   728         }
   730         public InferenceContext inferenceContext() {
   731             return inferenceContext;
   732         }
   734         public DeferredAttrContext deferredAttrContext() {
   735             return deferredAttrContext;
   736         }
   737     }
   739     /**
   740      * Subclass of method check context class that implements strict method conversion.
   741      * Strict method conversion checks compatibility between types using subtyping tests.
   742      */
   743     class StrictMethodContext extends MethodCheckContext {
   745         public StrictMethodContext(MethodCheckHandler handler, boolean useVarargs,
   746                 Infer.InferenceContext inferenceContext, DeferredAttrContext deferredAttrContext, Warner rsWarner) {
   747             super(handler, useVarargs, inferenceContext, deferredAttrContext, rsWarner);
   748         }
   750         public boolean compatible(Type found, Type req, Warner warn) {
   751             return types.isSubtypeUnchecked(found, inferenceContext.asFree(req, types), warn);
   752         }
   754         public boolean allowBoxing() {
   755             return false;
   756         }
   757     }
   759     /**
   760      * Subclass of method check context class that implements loose method conversion.
   761      * Loose method conversion checks compatibility between types using method conversion tests.
   762      */
   763     class LooseMethodContext extends MethodCheckContext {
   765         public LooseMethodContext(MethodCheckHandler handler, boolean useVarargs,
   766                 Infer.InferenceContext inferenceContext, DeferredAttrContext deferredAttrContext, Warner rsWarner) {
   767             super(handler, useVarargs, inferenceContext, deferredAttrContext, rsWarner);
   768         }
   770         public boolean compatible(Type found, Type req, Warner warn) {
   771             return types.isConvertible(found, inferenceContext.asFree(req, types), warn);
   772         }
   774         public boolean allowBoxing() {
   775             return true;
   776         }
   777     }
   779     /**
   780      * Create a method check context to be used during method applicability check
   781      */
   782     ResultInfo methodCheckResult(Type to, boolean allowBoxing, boolean useVarargs,
   783             Infer.InferenceContext inferenceContext, DeferredAttr.DeferredAttrContext deferredAttrContext,
   784             MethodCheckHandler methodHandler, Warner rsWarner) {
   785         MethodCheckContext checkContext = allowBoxing ?
   786                 new LooseMethodContext(methodHandler, useVarargs, inferenceContext, deferredAttrContext, rsWarner) :
   787                 new StrictMethodContext(methodHandler, useVarargs, inferenceContext, deferredAttrContext, rsWarner);
   788         return new MethodResultInfo(to, checkContext, deferredAttrContext);
   789     }
   791     class MethodResultInfo extends ResultInfo {
   793         DeferredAttr.DeferredAttrContext deferredAttrContext;
   795         public MethodResultInfo(Type pt, MethodCheckContext checkContext, DeferredAttr.DeferredAttrContext deferredAttrContext) {
   796             attr.super(VAL, pt, checkContext);
   797             this.deferredAttrContext = deferredAttrContext;
   798         }
   800         @Override
   801         protected Type check(DiagnosticPosition pos, Type found) {
   802             if (found.hasTag(DEFERRED)) {
   803                 DeferredType dt = (DeferredType)found;
   804                 return dt.check(this);
   805             } else {
   806                 return super.check(pos, chk.checkNonVoid(pos, types.capture(types.upperBound(found.baseType()))));
   807             }
   808         }
   810         @Override
   811         protected MethodResultInfo dup(Type newPt) {
   812             return new MethodResultInfo(newPt, (MethodCheckContext)checkContext, deferredAttrContext);
   813         }
   814     }
   816     public static class InapplicableMethodException extends RuntimeException {
   817         private static final long serialVersionUID = 0;
   819         JCDiagnostic diagnostic;
   820         JCDiagnostic.Factory diags;
   822         InapplicableMethodException(JCDiagnostic.Factory diags) {
   823             this.diagnostic = null;
   824             this.diags = diags;
   825         }
   826         InapplicableMethodException setMessage() {
   827             return setMessage((JCDiagnostic)null);
   828         }
   829         InapplicableMethodException setMessage(String key) {
   830             return setMessage(key != null ? diags.fragment(key) : null);
   831         }
   832         InapplicableMethodException setMessage(String key, Object... args) {
   833             return setMessage(key != null ? diags.fragment(key, args) : null);
   834         }
   835         InapplicableMethodException setMessage(JCDiagnostic diag) {
   836             this.diagnostic = diag;
   837             return this;
   838         }
   840         public JCDiagnostic getDiagnostic() {
   841             return diagnostic;
   842         }
   843     }
   844     private final InapplicableMethodException inapplicableMethodException;
   846 /* ***************************************************************************
   847  *  Symbol lookup
   848  *  the following naming conventions for arguments are used
   849  *
   850  *       env      is the environment where the symbol was mentioned
   851  *       site     is the type of which the symbol is a member
   852  *       name     is the symbol's name
   853  *                if no arguments are given
   854  *       argtypes are the value arguments, if we search for a method
   855  *
   856  *  If no symbol was found, a ResolveError detailing the problem is returned.
   857  ****************************************************************************/
   859     /** Find field. Synthetic fields are always skipped.
   860      *  @param env     The current environment.
   861      *  @param site    The original type from where the selection takes place.
   862      *  @param name    The name of the field.
   863      *  @param c       The class to search for the field. This is always
   864      *                 a superclass or implemented interface of site's class.
   865      */
   866     Symbol findField(Env<AttrContext> env,
   867                      Type site,
   868                      Name name,
   869                      TypeSymbol c) {
   870         while (c.type.hasTag(TYPEVAR))
   871             c = c.type.getUpperBound().tsym;
   872         Symbol bestSoFar = varNotFound;
   873         Symbol sym;
   874         Scope.Entry e = c.members().lookup(name);
   875         while (e.scope != null) {
   876             if (e.sym.kind == VAR && (e.sym.flags_field & SYNTHETIC) == 0) {
   877                 return isAccessible(env, site, e.sym)
   878                     ? e.sym : new AccessError(env, site, e.sym);
   879             }
   880             e = e.next();
   881         }
   882         Type st = types.supertype(c.type);
   883         if (st != null && (st.hasTag(CLASS) || st.hasTag(TYPEVAR))) {
   884             sym = findField(env, site, name, st.tsym);
   885             if (sym.kind < bestSoFar.kind) bestSoFar = sym;
   886         }
   887         for (List<Type> l = types.interfaces(c.type);
   888              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
   889              l = l.tail) {
   890             sym = findField(env, site, name, l.head.tsym);
   891             if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
   892                 sym.owner != bestSoFar.owner)
   893                 bestSoFar = new AmbiguityError(bestSoFar, sym);
   894             else if (sym.kind < bestSoFar.kind)
   895                 bestSoFar = sym;
   896         }
   897         return bestSoFar;
   898     }
   900     /** Resolve a field identifier, throw a fatal error if not found.
   901      *  @param pos       The position to use for error reporting.
   902      *  @param env       The environment current at the method invocation.
   903      *  @param site      The type of the qualifying expression, in which
   904      *                   identifier is searched.
   905      *  @param name      The identifier's name.
   906      */
   907     public VarSymbol resolveInternalField(DiagnosticPosition pos, Env<AttrContext> env,
   908                                           Type site, Name name) {
   909         Symbol sym = findField(env, site, name, site.tsym);
   910         if (sym.kind == VAR) return (VarSymbol)sym;
   911         else throw new FatalError(
   912                  diags.fragment("fatal.err.cant.locate.field",
   913                                 name));
   914     }
   916     /** Find unqualified variable or field with given name.
   917      *  Synthetic fields always skipped.
   918      *  @param env     The current environment.
   919      *  @param name    The name of the variable or field.
   920      */
   921     Symbol findVar(Env<AttrContext> env, Name name) {
   922         Symbol bestSoFar = varNotFound;
   923         Symbol sym;
   924         Env<AttrContext> env1 = env;
   925         boolean staticOnly = false;
   926         while (env1.outer != null) {
   927             if (isStatic(env1)) staticOnly = true;
   928             Scope.Entry e = env1.info.scope.lookup(name);
   929             while (e.scope != null &&
   930                    (e.sym.kind != VAR ||
   931                     (e.sym.flags_field & SYNTHETIC) != 0))
   932                 e = e.next();
   933             sym = (e.scope != null)
   934                 ? e.sym
   935                 : findField(
   936                     env1, env1.enclClass.sym.type, name, env1.enclClass.sym);
   937             if (sym.exists()) {
   938                 if (staticOnly &&
   939                     sym.kind == VAR &&
   940                     sym.owner.kind == TYP &&
   941                     (sym.flags() & STATIC) == 0)
   942                     return new StaticError(sym);
   943                 else
   944                     return sym;
   945             } else if (sym.kind < bestSoFar.kind) {
   946                 bestSoFar = sym;
   947             }
   949             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
   950             env1 = env1.outer;
   951         }
   953         sym = findField(env, syms.predefClass.type, name, syms.predefClass);
   954         if (sym.exists())
   955             return sym;
   956         if (bestSoFar.exists())
   957             return bestSoFar;
   959         Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
   960         for (; e.scope != null; e = e.next()) {
   961             sym = e.sym;
   962             Type origin = e.getOrigin().owner.type;
   963             if (sym.kind == VAR) {
   964                 if (e.sym.owner.type != origin)
   965                     sym = sym.clone(e.getOrigin().owner);
   966                 return isAccessible(env, origin, sym)
   967                     ? sym : new AccessError(env, origin, sym);
   968             }
   969         }
   971         Symbol origin = null;
   972         e = env.toplevel.starImportScope.lookup(name);
   973         for (; e.scope != null; e = e.next()) {
   974             sym = e.sym;
   975             if (sym.kind != VAR)
   976                 continue;
   977             // invariant: sym.kind == VAR
   978             if (bestSoFar.kind < AMBIGUOUS && sym.owner != bestSoFar.owner)
   979                 return new AmbiguityError(bestSoFar, sym);
   980             else if (bestSoFar.kind >= VAR) {
   981                 origin = e.getOrigin().owner;
   982                 bestSoFar = isAccessible(env, origin.type, sym)
   983                     ? sym : new AccessError(env, origin.type, sym);
   984             }
   985         }
   986         if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type)
   987             return bestSoFar.clone(origin);
   988         else
   989             return bestSoFar;
   990     }
   992     Warner noteWarner = new Warner();
   994     /** Select the best method for a call site among two choices.
   995      *  @param env              The current environment.
   996      *  @param site             The original type from where the
   997      *                          selection takes place.
   998      *  @param argtypes         The invocation's value arguments,
   999      *  @param typeargtypes     The invocation's type arguments,
  1000      *  @param sym              Proposed new best match.
  1001      *  @param bestSoFar        Previously found best match.
  1002      *  @param allowBoxing Allow boxing conversions of arguments.
  1003      *  @param useVarargs Box trailing arguments into an array for varargs.
  1004      */
  1005     @SuppressWarnings("fallthrough")
  1006     Symbol selectBest(Env<AttrContext> env,
  1007                       Type site,
  1008                       List<Type> argtypes,
  1009                       List<Type> typeargtypes,
  1010                       Symbol sym,
  1011                       Symbol bestSoFar,
  1012                       boolean allowBoxing,
  1013                       boolean useVarargs,
  1014                       boolean operator) {
  1015         if (sym.kind == ERR ||
  1016                 !sym.isInheritedIn(site.tsym, types) ||
  1017                 (useVarargs && (sym.flags() & VARARGS) == 0)) {
  1018             return bestSoFar;
  1020         Assert.check(sym.kind < AMBIGUOUS);
  1021         try {
  1022             Type mt = rawInstantiate(env, site, sym, null, argtypes, typeargtypes,
  1023                                allowBoxing, useVarargs, Warner.noWarnings);
  1024             if (!operator)
  1025                 currentResolutionContext.addApplicableCandidate(sym, mt);
  1026         } catch (InapplicableMethodException ex) {
  1027             if (!operator)
  1028                 currentResolutionContext.addInapplicableCandidate(sym, ex.getDiagnostic());
  1029             switch (bestSoFar.kind) {
  1030                 case ABSENT_MTH:
  1031                     return new InapplicableSymbolError(currentResolutionContext);
  1032                 case WRONG_MTH:
  1033                     if (operator) return bestSoFar;
  1034                     bestSoFar = new InapplicableSymbolsError(currentResolutionContext);
  1035                 default:
  1036                     return bestSoFar;
  1039         if (!isAccessible(env, site, sym)) {
  1040             return (bestSoFar.kind == ABSENT_MTH)
  1041                 ? new AccessError(env, site, sym)
  1042                 : bestSoFar;
  1044         return (bestSoFar.kind > AMBIGUOUS)
  1045             ? sym
  1046             : mostSpecific(argtypes, sym, bestSoFar, env, site,
  1047                            allowBoxing && operator, useVarargs);
  1050     /* Return the most specific of the two methods for a call,
  1051      *  given that both are accessible and applicable.
  1052      *  @param m1               A new candidate for most specific.
  1053      *  @param m2               The previous most specific candidate.
  1054      *  @param env              The current environment.
  1055      *  @param site             The original type from where the selection
  1056      *                          takes place.
  1057      *  @param allowBoxing Allow boxing conversions of arguments.
  1058      *  @param useVarargs Box trailing arguments into an array for varargs.
  1059      */
  1060     Symbol mostSpecific(List<Type> argtypes, Symbol m1,
  1061                         Symbol m2,
  1062                         Env<AttrContext> env,
  1063                         final Type site,
  1064                         boolean allowBoxing,
  1065                         boolean useVarargs) {
  1066         switch (m2.kind) {
  1067         case MTH:
  1068             if (m1 == m2) return m1;
  1069             boolean m1SignatureMoreSpecific =
  1070                     signatureMoreSpecific(argtypes, env, site, m1, m2, allowBoxing, useVarargs);
  1071             boolean m2SignatureMoreSpecific =
  1072                     signatureMoreSpecific(argtypes, env, site, m2, m1, allowBoxing, useVarargs);
  1073             if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) {
  1074                 Type mt1 = types.memberType(site, m1);
  1075                 Type mt2 = types.memberType(site, m2);
  1076                 if (!types.overrideEquivalent(mt1, mt2))
  1077                     return ambiguityError(m1, m2);
  1079                 // same signature; select (a) the non-bridge method, or
  1080                 // (b) the one that overrides the other, or (c) the concrete
  1081                 // one, or (d) merge both abstract signatures
  1082                 if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE))
  1083                     return ((m1.flags() & BRIDGE) != 0) ? m2 : m1;
  1085                 // if one overrides or hides the other, use it
  1086                 TypeSymbol m1Owner = (TypeSymbol)m1.owner;
  1087                 TypeSymbol m2Owner = (TypeSymbol)m2.owner;
  1088                 if (types.asSuper(m1Owner.type, m2Owner) != null &&
  1089                     ((m1.owner.flags_field & INTERFACE) == 0 ||
  1090                      (m2.owner.flags_field & INTERFACE) != 0) &&
  1091                     m1.overrides(m2, m1Owner, types, false))
  1092                     return m1;
  1093                 if (types.asSuper(m2Owner.type, m1Owner) != null &&
  1094                     ((m2.owner.flags_field & INTERFACE) == 0 ||
  1095                      (m1.owner.flags_field & INTERFACE) != 0) &&
  1096                     m2.overrides(m1, m2Owner, types, false))
  1097                     return m2;
  1098                 boolean m1Abstract = (m1.flags() & ABSTRACT) != 0;
  1099                 boolean m2Abstract = (m2.flags() & ABSTRACT) != 0;
  1100                 if (m1Abstract && !m2Abstract) return m2;
  1101                 if (m2Abstract && !m1Abstract) return m1;
  1102                 // both abstract or both concrete
  1103                 if (!m1Abstract && !m2Abstract)
  1104                     return ambiguityError(m1, m2);
  1105                 // check that both signatures have the same erasure
  1106                 if (!types.isSameTypes(m1.erasure(types).getParameterTypes(),
  1107                                        m2.erasure(types).getParameterTypes()))
  1108                     return ambiguityError(m1, m2);
  1109                 // both abstract, neither overridden; merge throws clause and result type
  1110                 Type mst = mostSpecificReturnType(mt1, mt2);
  1111                 if (mst == null) {
  1112                     // Theoretically, this can't happen, but it is possible
  1113                     // due to error recovery or mixing incompatible class files
  1114                     return ambiguityError(m1, m2);
  1116                 Symbol mostSpecific = mst == mt1 ? m1 : m2;
  1117                 List<Type> allThrown = chk.intersect(mt1.getThrownTypes(), mt2.getThrownTypes());
  1118                 Type newSig = types.createMethodTypeWithThrown(mostSpecific.type, allThrown);
  1119                 MethodSymbol result = new MethodSymbol(
  1120                         mostSpecific.flags(),
  1121                         mostSpecific.name,
  1122                         newSig,
  1123                         mostSpecific.owner) {
  1124                     @Override
  1125                     public MethodSymbol implementation(TypeSymbol origin, Types types, boolean checkResult) {
  1126                         if (origin == site.tsym)
  1127                             return this;
  1128                         else
  1129                             return super.implementation(origin, types, checkResult);
  1131                     };
  1132                 return result;
  1134             if (m1SignatureMoreSpecific) return m1;
  1135             if (m2SignatureMoreSpecific) return m2;
  1136             return ambiguityError(m1, m2);
  1137         case AMBIGUOUS:
  1138             AmbiguityError e = (AmbiguityError)m2;
  1139             Symbol err1 = mostSpecific(argtypes, m1, e.sym, env, site, allowBoxing, useVarargs);
  1140             Symbol err2 = mostSpecific(argtypes, m1, e.sym2, env, site, allowBoxing, useVarargs);
  1141             if (err1 == err2) return err1;
  1142             if (err1 == e.sym && err2 == e.sym2) return m2;
  1143             if (err1 instanceof AmbiguityError &&
  1144                 err2 instanceof AmbiguityError &&
  1145                 ((AmbiguityError)err1).sym == ((AmbiguityError)err2).sym)
  1146                 return ambiguityError(m1, m2);
  1147             else
  1148                 return ambiguityError(err1, err2);
  1149         default:
  1150             throw new AssertionError();
  1153     //where
  1154     private boolean signatureMoreSpecific(List<Type> actuals, Env<AttrContext> env, Type site, Symbol m1, Symbol m2, boolean allowBoxing, boolean useVarargs) {
  1155         Symbol m12 = adjustVarargs(m1, m2, useVarargs);
  1156         Symbol m22 = adjustVarargs(m2, m1, useVarargs);
  1157         Type mtype1 = types.memberType(site, m12);
  1158         Type mtype2 = types.memberType(site, m22);
  1160         //check if invocation is more specific
  1161         if (invocationMoreSpecific(env, site, m22, mtype1.getParameterTypes(), allowBoxing, useVarargs)) {
  1162             return true;
  1165         //perform structural check
  1167         List<Type> formals1 = mtype1.getParameterTypes();
  1168         Type lastFormal1 = formals1.last();
  1169         List<Type> formals2 = mtype2.getParameterTypes();
  1170         Type lastFormal2 = formals2.last();
  1171         ListBuffer<Type> newFormals = ListBuffer.lb();
  1173         boolean hasStructuralPoly = false;
  1174         for (Type actual : actuals) {
  1175             //perform formal argument adaptation in case actuals > formals (varargs)
  1176             Type f1 = formals1.isEmpty() ?
  1177                     lastFormal1 : formals1.head;
  1178             Type f2 = formals2.isEmpty() ?
  1179                     lastFormal2 : formals2.head;
  1181             //is this a structural actual argument?
  1182             boolean isStructuralPoly = actual.hasTag(DEFERRED) &&
  1183                     (((DeferredType)actual).tree.hasTag(LAMBDA) ||
  1184                     ((DeferredType)actual).tree.hasTag(REFERENCE));
  1186             Type newFormal = f1;
  1188             if (isStructuralPoly) {
  1189                 //for structural arguments only - check that corresponding formals
  1190                 //are related - if so replace formal with <null>
  1191                 hasStructuralPoly = true;
  1192                 DeferredType dt = (DeferredType)actual;
  1193                 Type t1 = deferredAttr.new DeferredTypeMap(AttrMode.SPECULATIVE, m1, currentResolutionContext.step).apply(dt);
  1194                 Type t2 = deferredAttr.new DeferredTypeMap(AttrMode.SPECULATIVE, m2, currentResolutionContext.step).apply(dt);
  1195                 if (t1.isErroneous() || t2.isErroneous() || !isStructuralSubtype(t1, t2)) {
  1196                     //not structural subtypes - simply fail
  1197                     return false;
  1198                 } else {
  1199                     newFormal = syms.botType;
  1203             newFormals.append(newFormal);
  1204             if (newFormals.length() > mtype2.getParameterTypes().length()) {
  1205                 //expand m2's type so as to fit the new formal arity (varargs)
  1206                 m22.type = types.createMethodTypeWithParameters(m22.type, m22.type.getParameterTypes().append(f2));
  1209             formals1 = formals1.isEmpty() ? formals1 : formals1.tail;
  1210             formals2 = formals2.isEmpty() ? formals2 : formals2.tail;
  1213         if (!hasStructuralPoly) {
  1214             //if no structural actual was found, we're done
  1215             return false;
  1217         //perform additional adaptation if actuals < formals (varargs)
  1218         for (Type t : formals1) {
  1219             newFormals.append(t);
  1221         //check if invocation (with tweaked args) is more specific
  1222         return invocationMoreSpecific(env, site, m22, newFormals.toList(), allowBoxing, useVarargs);
  1224     //where
  1225     private boolean invocationMoreSpecific(Env<AttrContext> env, Type site, Symbol m2, List<Type> argtypes1, boolean allowBoxing, boolean useVarargs) {
  1226         noteWarner.clear();
  1227         Type mst = instantiate(env, site, m2, null,
  1228                 types.lowerBounds(argtypes1), null,
  1229                 allowBoxing, false, noteWarner);
  1230         return mst != null &&
  1231                 !noteWarner.hasLint(Lint.LintCategory.UNCHECKED);
  1233     //where
  1234     private Symbol adjustVarargs(Symbol to, Symbol from, boolean useVarargs) {
  1235         List<Type> fromArgs = from.type.getParameterTypes();
  1236         List<Type> toArgs = to.type.getParameterTypes();
  1237         if (useVarargs &&
  1238                 (from.flags() & VARARGS) != 0 &&
  1239                 (to.flags() & VARARGS) != 0) {
  1240             Type varargsTypeFrom = fromArgs.last();
  1241             Type varargsTypeTo = toArgs.last();
  1242             ListBuffer<Type> args = ListBuffer.lb();
  1243             if (toArgs.length() < fromArgs.length()) {
  1244                 //if we are checking a varargs method 'from' against another varargs
  1245                 //method 'to' (where arity of 'to' < arity of 'from') then expand signature
  1246                 //of 'to' to 'fit' arity of 'from' (this means adding fake formals to 'to'
  1247                 //until 'to' signature has the same arity as 'from')
  1248                 while (fromArgs.head != varargsTypeFrom) {
  1249                     args.append(toArgs.head == varargsTypeTo ? types.elemtype(varargsTypeTo) : toArgs.head);
  1250                     fromArgs = fromArgs.tail;
  1251                     toArgs = toArgs.head == varargsTypeTo ?
  1252                         toArgs :
  1253                         toArgs.tail;
  1255             } else {
  1256                 //formal argument list is same as original list where last
  1257                 //argument (array type) is removed
  1258                 args.appendList(toArgs.reverse().tail.reverse());
  1260             //append varargs element type as last synthetic formal
  1261             args.append(types.elemtype(varargsTypeTo));
  1262             Type mtype = types.createMethodTypeWithParameters(to.type, args.toList());
  1263             return new MethodSymbol(to.flags_field & ~VARARGS, to.name, mtype, to.owner);
  1264         } else {
  1265             return to;
  1268     //where
  1269     boolean isStructuralSubtype(Type s, Type t) {
  1271         Type ret_s = types.findDescriptorType(s).getReturnType();
  1272         Type ret_t = types.findDescriptorType(t).getReturnType();
  1274         //covariant most specific check for function descriptor return type
  1275         if (!types.isSubtype(ret_s, ret_t)) {
  1276             return false;
  1279         List<Type> args_s = types.findDescriptorType(s).getParameterTypes();
  1280         List<Type> args_t = types.findDescriptorType(t).getParameterTypes();
  1282         //arity must be identical
  1283         if (args_s.length() != args_t.length()) {
  1284             return false;
  1287         //invariant most specific check for function descriptor parameter types
  1288         if (!types.isSameTypes(args_t, args_s)) {
  1289             return false;
  1292         return true;
  1294     //where
  1295     Type mostSpecificReturnType(Type mt1, Type mt2) {
  1296         Type rt1 = mt1.getReturnType();
  1297         Type rt2 = mt2.getReturnType();
  1299         if (mt1.hasTag(FORALL) && mt2.hasTag(FORALL)) {
  1300             //if both are generic methods, adjust return type ahead of subtyping check
  1301             rt1 = types.subst(rt1, mt1.getTypeArguments(), mt2.getTypeArguments());
  1303         //first use subtyping, then return type substitutability
  1304         if (types.isSubtype(rt1, rt2)) {
  1305             return mt1;
  1306         } else if (types.isSubtype(rt2, rt1)) {
  1307             return mt2;
  1308         } else if (types.returnTypeSubstitutable(mt1, mt2)) {
  1309             return mt1;
  1310         } else if (types.returnTypeSubstitutable(mt2, mt1)) {
  1311             return mt2;
  1312         } else {
  1313             return null;
  1316     //where
  1317     Symbol ambiguityError(Symbol m1, Symbol m2) {
  1318         if (((m1.flags() | m2.flags()) & CLASH) != 0) {
  1319             return (m1.flags() & CLASH) == 0 ? m1 : m2;
  1320         } else {
  1321             return new AmbiguityError(m1, m2);
  1325     Symbol findMethodInScope(Env<AttrContext> env,
  1326             Type site,
  1327             Name name,
  1328             List<Type> argtypes,
  1329             List<Type> typeargtypes,
  1330             Scope sc,
  1331             Symbol bestSoFar,
  1332             boolean allowBoxing,
  1333             boolean useVarargs,
  1334             boolean operator,
  1335             boolean abstractok) {
  1336         for (Symbol s : sc.getElementsByName(name, new LookupFilter(abstractok))) {
  1337             bestSoFar = selectBest(env, site, argtypes, typeargtypes, s,
  1338                     bestSoFar, allowBoxing, useVarargs, operator);
  1340         return bestSoFar;
  1342     //where
  1343         class LookupFilter implements Filter<Symbol> {
  1345             boolean abstractOk;
  1347             LookupFilter(boolean abstractOk) {
  1348                 this.abstractOk = abstractOk;
  1351             public boolean accepts(Symbol s) {
  1352                 long flags = s.flags();
  1353                 return s.kind == MTH &&
  1354                         (flags & SYNTHETIC) == 0 &&
  1355                         (abstractOk ||
  1356                         (flags & DEFAULT) != 0 ||
  1357                         (flags & ABSTRACT) == 0);
  1359         };
  1361     /** Find best qualified method matching given name, type and value
  1362      *  arguments.
  1363      *  @param env       The current environment.
  1364      *  @param site      The original type from where the selection
  1365      *                   takes place.
  1366      *  @param name      The method's name.
  1367      *  @param argtypes  The method's value arguments.
  1368      *  @param typeargtypes The method's type arguments
  1369      *  @param allowBoxing Allow boxing conversions of arguments.
  1370      *  @param useVarargs Box trailing arguments into an array for varargs.
  1371      */
  1372     Symbol findMethod(Env<AttrContext> env,
  1373                       Type site,
  1374                       Name name,
  1375                       List<Type> argtypes,
  1376                       List<Type> typeargtypes,
  1377                       boolean allowBoxing,
  1378                       boolean useVarargs,
  1379                       boolean operator) {
  1380         Symbol bestSoFar = methodNotFound;
  1381         bestSoFar = findMethod(env,
  1382                           site,
  1383                           name,
  1384                           argtypes,
  1385                           typeargtypes,
  1386                           site.tsym.type,
  1387                           bestSoFar,
  1388                           allowBoxing,
  1389                           useVarargs,
  1390                           operator);
  1391         reportVerboseResolutionDiagnostic(env.tree.pos(), name, site, argtypes, typeargtypes, bestSoFar);
  1392         return bestSoFar;
  1394     // where
  1395     private Symbol findMethod(Env<AttrContext> env,
  1396                               Type site,
  1397                               Name name,
  1398                               List<Type> argtypes,
  1399                               List<Type> typeargtypes,
  1400                               Type intype,
  1401                               Symbol bestSoFar,
  1402                               boolean allowBoxing,
  1403                               boolean useVarargs,
  1404                               boolean operator) {
  1405         @SuppressWarnings({"unchecked","rawtypes"})
  1406         List<Type>[] itypes = (List<Type>[])new List[] { List.<Type>nil(), List.<Type>nil() };
  1407         InterfaceLookupPhase iphase = InterfaceLookupPhase.ABSTRACT_OK;
  1408         for (TypeSymbol s : superclasses(intype)) {
  1409             bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
  1410                     s.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
  1411             if (name == names.init) return bestSoFar;
  1412             iphase = (iphase == null) ? null : iphase.update(s, this);
  1413             if (iphase != null) {
  1414                 for (Type itype : types.interfaces(s.type)) {
  1415                     itypes[iphase.ordinal()] = types.union(types.closure(itype), itypes[iphase.ordinal()]);
  1420         Symbol concrete = bestSoFar.kind < ERR &&
  1421                 (bestSoFar.flags() & ABSTRACT) == 0 ?
  1422                 bestSoFar : methodNotFound;
  1424         for (InterfaceLookupPhase iphase2 : InterfaceLookupPhase.values()) {
  1425             if (iphase2 == InterfaceLookupPhase.DEFAULT_OK && !allowDefaultMethods) break;
  1426             //keep searching for abstract methods
  1427             for (Type itype : itypes[iphase2.ordinal()]) {
  1428                 if (!itype.isInterface()) continue; //skip j.l.Object (included by Types.closure())
  1429                 if (iphase2 == InterfaceLookupPhase.DEFAULT_OK &&
  1430                         (itype.tsym.flags() & DEFAULT) == 0) continue;
  1431                 bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
  1432                         itype.tsym.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
  1433                 if (concrete != bestSoFar &&
  1434                         concrete.kind < ERR  && bestSoFar.kind < ERR &&
  1435                         types.isSubSignature(concrete.type, bestSoFar.type)) {
  1436                     //this is an hack - as javac does not do full membership checks
  1437                     //most specific ends up comparing abstract methods that might have
  1438                     //been implemented by some concrete method in a subclass and,
  1439                     //because of raw override, it is possible for an abstract method
  1440                     //to be more specific than the concrete method - so we need
  1441                     //to explicitly call that out (see CR 6178365)
  1442                     bestSoFar = concrete;
  1446         return bestSoFar;
  1449     enum InterfaceLookupPhase {
  1450         ABSTRACT_OK() {
  1451             @Override
  1452             InterfaceLookupPhase update(Symbol s, Resolve rs) {
  1453                 //We should not look for abstract methods if receiver is a concrete class
  1454                 //(as concrete classes are expected to implement all abstracts coming
  1455                 //from superinterfaces)
  1456                 if ((s.flags() & (ABSTRACT | INTERFACE | ENUM)) != 0) {
  1457                     return this;
  1458                 } else if (rs.allowDefaultMethods) {
  1459                     return DEFAULT_OK;
  1460                 } else {
  1461                     return null;
  1464         },
  1465         DEFAULT_OK() {
  1466             @Override
  1467             InterfaceLookupPhase update(Symbol s, Resolve rs) {
  1468                 return this;
  1470         };
  1472         abstract InterfaceLookupPhase update(Symbol s, Resolve rs);
  1475     /**
  1476      * Return an Iterable object to scan the superclasses of a given type.
  1477      * It's crucial that the scan is done lazily, as we don't want to accidentally
  1478      * access more supertypes than strictly needed (as this could trigger completion
  1479      * errors if some of the not-needed supertypes are missing/ill-formed).
  1480      */
  1481     Iterable<TypeSymbol> superclasses(final Type intype) {
  1482         return new Iterable<TypeSymbol>() {
  1483             public Iterator<TypeSymbol> iterator() {
  1484                 return new Iterator<TypeSymbol>() {
  1486                     List<TypeSymbol> seen = List.nil();
  1487                     TypeSymbol currentSym = symbolFor(intype);
  1488                     TypeSymbol prevSym = null;
  1490                     public boolean hasNext() {
  1491                         if (currentSym == syms.noSymbol) {
  1492                             currentSym = symbolFor(types.supertype(prevSym.type));
  1494                         return currentSym != null;
  1497                     public TypeSymbol next() {
  1498                         prevSym = currentSym;
  1499                         currentSym = syms.noSymbol;
  1500                         Assert.check(prevSym != null || prevSym != syms.noSymbol);
  1501                         return prevSym;
  1504                     public void remove() {
  1505                         throw new UnsupportedOperationException();
  1508                     TypeSymbol symbolFor(Type t) {
  1509                         if (!t.hasTag(CLASS) &&
  1510                                 !t.hasTag(TYPEVAR)) {
  1511                             return null;
  1513                         while (t.hasTag(TYPEVAR))
  1514                             t = t.getUpperBound();
  1515                         if (seen.contains(t.tsym)) {
  1516                             //degenerate case in which we have a circular
  1517                             //class hierarchy - because of ill-formed classfiles
  1518                             return null;
  1520                         seen = seen.prepend(t.tsym);
  1521                         return t.tsym;
  1523                 };
  1525         };
  1528     /** Find unqualified method matching given name, type and value arguments.
  1529      *  @param env       The current environment.
  1530      *  @param name      The method's name.
  1531      *  @param argtypes  The method's value arguments.
  1532      *  @param typeargtypes  The method's type arguments.
  1533      *  @param allowBoxing Allow boxing conversions of arguments.
  1534      *  @param useVarargs Box trailing arguments into an array for varargs.
  1535      */
  1536     Symbol findFun(Env<AttrContext> env, Name name,
  1537                    List<Type> argtypes, List<Type> typeargtypes,
  1538                    boolean allowBoxing, boolean useVarargs) {
  1539         Symbol bestSoFar = methodNotFound;
  1540         Symbol sym;
  1541         Env<AttrContext> env1 = env;
  1542         boolean staticOnly = false;
  1543         while (env1.outer != null) {
  1544             if (isStatic(env1)) staticOnly = true;
  1545             sym = findMethod(
  1546                 env1, env1.enclClass.sym.type, name, argtypes, typeargtypes,
  1547                 allowBoxing, useVarargs, false);
  1548             if (sym.exists()) {
  1549                 if (staticOnly &&
  1550                     sym.kind == MTH &&
  1551                     sym.owner.kind == TYP &&
  1552                     (sym.flags() & STATIC) == 0) return new StaticError(sym);
  1553                 else return sym;
  1554             } else if (sym.kind < bestSoFar.kind) {
  1555                 bestSoFar = sym;
  1557             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  1558             env1 = env1.outer;
  1561         sym = findMethod(env, syms.predefClass.type, name, argtypes,
  1562                          typeargtypes, allowBoxing, useVarargs, false);
  1563         if (sym.exists())
  1564             return sym;
  1566         Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
  1567         for (; e.scope != null; e = e.next()) {
  1568             sym = e.sym;
  1569             Type origin = e.getOrigin().owner.type;
  1570             if (sym.kind == MTH) {
  1571                 if (e.sym.owner.type != origin)
  1572                     sym = sym.clone(e.getOrigin().owner);
  1573                 if (!isAccessible(env, origin, sym))
  1574                     sym = new AccessError(env, origin, sym);
  1575                 bestSoFar = selectBest(env, origin,
  1576                                        argtypes, typeargtypes,
  1577                                        sym, bestSoFar,
  1578                                        allowBoxing, useVarargs, false);
  1581         if (bestSoFar.exists())
  1582             return bestSoFar;
  1584         e = env.toplevel.starImportScope.lookup(name);
  1585         for (; e.scope != null; e = e.next()) {
  1586             sym = e.sym;
  1587             Type origin = e.getOrigin().owner.type;
  1588             if (sym.kind == MTH) {
  1589                 if (e.sym.owner.type != origin)
  1590                     sym = sym.clone(e.getOrigin().owner);
  1591                 if (!isAccessible(env, origin, sym))
  1592                     sym = new AccessError(env, origin, sym);
  1593                 bestSoFar = selectBest(env, origin,
  1594                                        argtypes, typeargtypes,
  1595                                        sym, bestSoFar,
  1596                                        allowBoxing, useVarargs, false);
  1599         return bestSoFar;
  1602     /** Load toplevel or member class with given fully qualified name and
  1603      *  verify that it is accessible.
  1604      *  @param env       The current environment.
  1605      *  @param name      The fully qualified name of the class to be loaded.
  1606      */
  1607     Symbol loadClass(Env<AttrContext> env, Name name) {
  1608         try {
  1609             ClassSymbol c = reader.loadClass(name);
  1610             return isAccessible(env, c) ? c : new AccessError(c);
  1611         } catch (ClassReader.BadClassFile err) {
  1612             throw err;
  1613         } catch (CompletionFailure ex) {
  1614             return typeNotFound;
  1618     /** Find qualified member type.
  1619      *  @param env       The current environment.
  1620      *  @param site      The original type from where the selection takes
  1621      *                   place.
  1622      *  @param name      The type's name.
  1623      *  @param c         The class to search for the member type. This is
  1624      *                   always a superclass or implemented interface of
  1625      *                   site's class.
  1626      */
  1627     Symbol findMemberType(Env<AttrContext> env,
  1628                           Type site,
  1629                           Name name,
  1630                           TypeSymbol c) {
  1631         Symbol bestSoFar = typeNotFound;
  1632         Symbol sym;
  1633         Scope.Entry e = c.members().lookup(name);
  1634         while (e.scope != null) {
  1635             if (e.sym.kind == TYP) {
  1636                 return isAccessible(env, site, e.sym)
  1637                     ? e.sym
  1638                     : new AccessError(env, site, e.sym);
  1640             e = e.next();
  1642         Type st = types.supertype(c.type);
  1643         if (st != null && st.hasTag(CLASS)) {
  1644             sym = findMemberType(env, site, name, st.tsym);
  1645             if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1647         for (List<Type> l = types.interfaces(c.type);
  1648              bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
  1649              l = l.tail) {
  1650             sym = findMemberType(env, site, name, l.head.tsym);
  1651             if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
  1652                 sym.owner != bestSoFar.owner)
  1653                 bestSoFar = new AmbiguityError(bestSoFar, sym);
  1654             else if (sym.kind < bestSoFar.kind)
  1655                 bestSoFar = sym;
  1657         return bestSoFar;
  1660     /** Find a global type in given scope and load corresponding class.
  1661      *  @param env       The current environment.
  1662      *  @param scope     The scope in which to look for the type.
  1663      *  @param name      The type's name.
  1664      */
  1665     Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name) {
  1666         Symbol bestSoFar = typeNotFound;
  1667         for (Scope.Entry e = scope.lookup(name); e.scope != null; e = e.next()) {
  1668             Symbol sym = loadClass(env, e.sym.flatName());
  1669             if (bestSoFar.kind == TYP && sym.kind == TYP &&
  1670                 bestSoFar != sym)
  1671                 return new AmbiguityError(bestSoFar, sym);
  1672             else if (sym.kind < bestSoFar.kind)
  1673                 bestSoFar = sym;
  1675         return bestSoFar;
  1678     /** Find an unqualified type symbol.
  1679      *  @param env       The current environment.
  1680      *  @param name      The type's name.
  1681      */
  1682     Symbol findType(Env<AttrContext> env, Name name) {
  1683         Symbol bestSoFar = typeNotFound;
  1684         Symbol sym;
  1685         boolean staticOnly = false;
  1686         for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
  1687             if (isStatic(env1)) staticOnly = true;
  1688             for (Scope.Entry e = env1.info.scope.lookup(name);
  1689                  e.scope != null;
  1690                  e = e.next()) {
  1691                 if (e.sym.kind == TYP) {
  1692                     if (staticOnly &&
  1693                         e.sym.type.hasTag(TYPEVAR) &&
  1694                         e.sym.owner.kind == TYP) return new StaticError(e.sym);
  1695                     return e.sym;
  1699             sym = findMemberType(env1, env1.enclClass.sym.type, name,
  1700                                  env1.enclClass.sym);
  1701             if (staticOnly && sym.kind == TYP &&
  1702                 sym.type.hasTag(CLASS) &&
  1703                 sym.type.getEnclosingType().hasTag(CLASS) &&
  1704                 env1.enclClass.sym.type.isParameterized() &&
  1705                 sym.type.getEnclosingType().isParameterized())
  1706                 return new StaticError(sym);
  1707             else if (sym.exists()) return sym;
  1708             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1710             JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass;
  1711             if ((encl.sym.flags() & STATIC) != 0)
  1712                 staticOnly = true;
  1715         if (!env.tree.hasTag(IMPORT)) {
  1716             sym = findGlobalType(env, env.toplevel.namedImportScope, name);
  1717             if (sym.exists()) return sym;
  1718             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1720             sym = findGlobalType(env, env.toplevel.packge.members(), name);
  1721             if (sym.exists()) return sym;
  1722             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1724             sym = findGlobalType(env, env.toplevel.starImportScope, name);
  1725             if (sym.exists()) return sym;
  1726             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1729         return bestSoFar;
  1732     /** Find an unqualified identifier which matches a specified kind set.
  1733      *  @param env       The current environment.
  1734      *  @param name      The indentifier's name.
  1735      *  @param kind      Indicates the possible symbol kinds
  1736      *                   (a subset of VAL, TYP, PCK).
  1737      */
  1738     Symbol findIdent(Env<AttrContext> env, Name name, int kind) {
  1739         Symbol bestSoFar = typeNotFound;
  1740         Symbol sym;
  1742         if ((kind & VAR) != 0) {
  1743             sym = findVar(env, name);
  1744             if (sym.exists()) return sym;
  1745             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1748         if ((kind & TYP) != 0) {
  1749             sym = findType(env, name);
  1750             if (sym.exists()) return sym;
  1751             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1754         if ((kind & PCK) != 0) return reader.enterPackage(name);
  1755         else return bestSoFar;
  1758     /** Find an identifier in a package which matches a specified kind set.
  1759      *  @param env       The current environment.
  1760      *  @param name      The identifier's name.
  1761      *  @param kind      Indicates the possible symbol kinds
  1762      *                   (a nonempty subset of TYP, PCK).
  1763      */
  1764     Symbol findIdentInPackage(Env<AttrContext> env, TypeSymbol pck,
  1765                               Name name, int kind) {
  1766         Name fullname = TypeSymbol.formFullName(name, pck);
  1767         Symbol bestSoFar = typeNotFound;
  1768         PackageSymbol pack = null;
  1769         if ((kind & PCK) != 0) {
  1770             pack = reader.enterPackage(fullname);
  1771             if (pack.exists()) return pack;
  1773         if ((kind & TYP) != 0) {
  1774             Symbol sym = loadClass(env, fullname);
  1775             if (sym.exists()) {
  1776                 // don't allow programs to use flatnames
  1777                 if (name == sym.name) return sym;
  1779             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1781         return (pack != null) ? pack : bestSoFar;
  1784     /** Find an identifier among the members of a given type `site'.
  1785      *  @param env       The current environment.
  1786      *  @param site      The type containing the symbol to be found.
  1787      *  @param name      The identifier's name.
  1788      *  @param kind      Indicates the possible symbol kinds
  1789      *                   (a subset of VAL, TYP).
  1790      */
  1791     Symbol findIdentInType(Env<AttrContext> env, Type site,
  1792                            Name name, int kind) {
  1793         Symbol bestSoFar = typeNotFound;
  1794         Symbol sym;
  1795         if ((kind & VAR) != 0) {
  1796             sym = findField(env, site, name, site.tsym);
  1797             if (sym.exists()) return sym;
  1798             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1801         if ((kind & TYP) != 0) {
  1802             sym = findMemberType(env, site, name, site.tsym);
  1803             if (sym.exists()) return sym;
  1804             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
  1806         return bestSoFar;
  1809 /* ***************************************************************************
  1810  *  Access checking
  1811  *  The following methods convert ResolveErrors to ErrorSymbols, issuing
  1812  *  an error message in the process
  1813  ****************************************************************************/
  1815     /** If `sym' is a bad symbol: report error and return errSymbol
  1816      *  else pass through unchanged,
  1817      *  additional arguments duplicate what has been used in trying to find the
  1818      *  symbol {@literal (--> flyweight pattern)}. This improves performance since we
  1819      *  expect misses to happen frequently.
  1821      *  @param sym       The symbol that was found, or a ResolveError.
  1822      *  @param pos       The position to use for error reporting.
  1823      *  @param location  The symbol the served as a context for this lookup
  1824      *  @param site      The original type from where the selection took place.
  1825      *  @param name      The symbol's name.
  1826      *  @param qualified Did we get here through a qualified expression resolution?
  1827      *  @param argtypes  The invocation's value arguments,
  1828      *                   if we looked for a method.
  1829      *  @param typeargtypes  The invocation's type arguments,
  1830      *                   if we looked for a method.
  1831      *  @param logResolveHelper helper class used to log resolve errors
  1832      */
  1833     Symbol accessInternal(Symbol sym,
  1834                   DiagnosticPosition pos,
  1835                   Symbol location,
  1836                   Type site,
  1837                   Name name,
  1838                   boolean qualified,
  1839                   List<Type> argtypes,
  1840                   List<Type> typeargtypes,
  1841                   LogResolveHelper logResolveHelper) {
  1842         if (sym.kind >= AMBIGUOUS) {
  1843             ResolveError errSym = (ResolveError)sym;
  1844             sym = errSym.access(name, qualified ? site.tsym : syms.noSymbol);
  1845             argtypes = logResolveHelper.getArgumentTypes(errSym, sym, name, argtypes);
  1846             if (logResolveHelper.resolveDiagnosticNeeded(site, argtypes, typeargtypes)) {
  1847                 logResolveError(errSym, pos, location, site, name, argtypes, typeargtypes);
  1850         return sym;
  1853     /**
  1854      * Variant of the generalized access routine, to be used for generating method
  1855      * resolution diagnostics
  1856      */
  1857     Symbol accessMethod(Symbol sym,
  1858                   DiagnosticPosition pos,
  1859                   Symbol location,
  1860                   Type site,
  1861                   Name name,
  1862                   boolean qualified,
  1863                   List<Type> argtypes,
  1864                   List<Type> typeargtypes) {
  1865         return accessInternal(sym, pos, location, site, name, qualified, argtypes, typeargtypes, methodLogResolveHelper);
  1868     /** Same as original accessMethod(), but without location.
  1869      */
  1870     Symbol accessMethod(Symbol sym,
  1871                   DiagnosticPosition pos,
  1872                   Type site,
  1873                   Name name,
  1874                   boolean qualified,
  1875                   List<Type> argtypes,
  1876                   List<Type> typeargtypes) {
  1877         return accessMethod(sym, pos, site.tsym, site, name, qualified, argtypes, typeargtypes);
  1880     /**
  1881      * Variant of the generalized access routine, to be used for generating variable,
  1882      * type resolution diagnostics
  1883      */
  1884     Symbol accessBase(Symbol sym,
  1885                   DiagnosticPosition pos,
  1886                   Symbol location,
  1887                   Type site,
  1888                   Name name,
  1889                   boolean qualified) {
  1890         return accessInternal(sym, pos, location, site, name, qualified, List.<Type>nil(), null, basicLogResolveHelper);
  1893     /** Same as original accessBase(), but without location.
  1894      */
  1895     Symbol accessBase(Symbol sym,
  1896                   DiagnosticPosition pos,
  1897                   Type site,
  1898                   Name name,
  1899                   boolean qualified) {
  1900         return accessBase(sym, pos, site.tsym, site, name, qualified);
  1903     interface LogResolveHelper {
  1904         boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes);
  1905         List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes);
  1908     LogResolveHelper basicLogResolveHelper = new LogResolveHelper() {
  1909         public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
  1910             return !site.isErroneous();
  1912         public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
  1913             return argtypes;
  1915     };
  1917     LogResolveHelper methodLogResolveHelper = new LogResolveHelper() {
  1918         public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
  1919             return !site.isErroneous() &&
  1920                         !Type.isErroneous(argtypes) &&
  1921                         (typeargtypes == null || !Type.isErroneous(typeargtypes));
  1923         public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
  1924             if (syms.operatorNames.contains(name)) {
  1925                 return argtypes;
  1926             } else {
  1927                 Symbol msym = errSym.kind == WRONG_MTH ?
  1928                         ((InapplicableSymbolError)errSym).errCandidate().sym : accessedSym;
  1930                 List<Type> argtypes2 = Type.map(argtypes,
  1931                         deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, msym, currentResolutionContext.step));
  1933                 if (msym != accessedSym) {
  1934                     //fixup deferred type caches - this 'hack' is required because the symbol
  1935                     //returned by InapplicableSymbolError.access() will hide the candidate
  1936                     //method symbol that can be used for lookups in the speculative cache,
  1937                     //causing problems in Attr.checkId()
  1938                     for (Type t : argtypes) {
  1939                         if (t.hasTag(DEFERRED)) {
  1940                             DeferredType dt = (DeferredType)t;
  1941                             dt.speculativeCache.dupAllTo(msym, accessedSym);
  1945                 return argtypes2;
  1948     };
  1950     /** Check that sym is not an abstract method.
  1951      */
  1952     void checkNonAbstract(DiagnosticPosition pos, Symbol sym) {
  1953         if ((sym.flags() & ABSTRACT) != 0 && (sym.flags() & DEFAULT) == 0)
  1954             log.error(pos, "abstract.cant.be.accessed.directly",
  1955                       kindName(sym), sym, sym.location());
  1958 /* ***************************************************************************
  1959  *  Debugging
  1960  ****************************************************************************/
  1962     /** print all scopes starting with scope s and proceeding outwards.
  1963      *  used for debugging.
  1964      */
  1965     public void printscopes(Scope s) {
  1966         while (s != null) {
  1967             if (s.owner != null)
  1968                 System.err.print(s.owner + ": ");
  1969             for (Scope.Entry e = s.elems; e != null; e = e.sibling) {
  1970                 if ((e.sym.flags() & ABSTRACT) != 0)
  1971                     System.err.print("abstract ");
  1972                 System.err.print(e.sym + " ");
  1974             System.err.println();
  1975             s = s.next;
  1979     void printscopes(Env<AttrContext> env) {
  1980         while (env.outer != null) {
  1981             System.err.println("------------------------------");
  1982             printscopes(env.info.scope);
  1983             env = env.outer;
  1987     public void printscopes(Type t) {
  1988         while (t.hasTag(CLASS)) {
  1989             printscopes(t.tsym.members());
  1990             t = types.supertype(t);
  1994 /* ***************************************************************************
  1995  *  Name resolution
  1996  *  Naming conventions are as for symbol lookup
  1997  *  Unlike the find... methods these methods will report access errors
  1998  ****************************************************************************/
  2000     /** Resolve an unqualified (non-method) identifier.
  2001      *  @param pos       The position to use for error reporting.
  2002      *  @param env       The environment current at the identifier use.
  2003      *  @param name      The identifier's name.
  2004      *  @param kind      The set of admissible symbol kinds for the identifier.
  2005      */
  2006     Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env,
  2007                         Name name, int kind) {
  2008         return accessBase(
  2009             findIdent(env, name, kind),
  2010             pos, env.enclClass.sym.type, name, false);
  2013     /** Resolve an unqualified method identifier.
  2014      *  @param pos       The position to use for error reporting.
  2015      *  @param env       The environment current at the method invocation.
  2016      *  @param name      The identifier's name.
  2017      *  @param argtypes  The types of the invocation's value arguments.
  2018      *  @param typeargtypes  The types of the invocation's type arguments.
  2019      */
  2020     Symbol resolveMethod(DiagnosticPosition pos,
  2021                          Env<AttrContext> env,
  2022                          Name name,
  2023                          List<Type> argtypes,
  2024                          List<Type> typeargtypes) {
  2025         return lookupMethod(env, pos, env.enclClass.sym, new BasicLookupHelper(name, env.enclClass.sym.type, argtypes, typeargtypes) {
  2026             @Override
  2027             Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2028                 return findFun(env, name, argtypes, typeargtypes,
  2029                         phase.isBoxingRequired(),
  2030                         phase.isVarargsRequired());
  2032         });
  2035     /** Resolve a qualified method identifier
  2036      *  @param pos       The position to use for error reporting.
  2037      *  @param env       The environment current at the method invocation.
  2038      *  @param site      The type of the qualifying expression, in which
  2039      *                   identifier is searched.
  2040      *  @param name      The identifier's name.
  2041      *  @param argtypes  The types of the invocation's value arguments.
  2042      *  @param typeargtypes  The types of the invocation's type arguments.
  2043      */
  2044     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
  2045                                   Type site, Name name, List<Type> argtypes,
  2046                                   List<Type> typeargtypes) {
  2047         return resolveQualifiedMethod(pos, env, site.tsym, site, name, argtypes, typeargtypes);
  2049     Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
  2050                                   Symbol location, Type site, Name name, List<Type> argtypes,
  2051                                   List<Type> typeargtypes) {
  2052         return resolveQualifiedMethod(new MethodResolutionContext(), pos, env, location, site, name, argtypes, typeargtypes);
  2054     private Symbol resolveQualifiedMethod(MethodResolutionContext resolveContext,
  2055                                   DiagnosticPosition pos, Env<AttrContext> env,
  2056                                   Symbol location, Type site, Name name, List<Type> argtypes,
  2057                                   List<Type> typeargtypes) {
  2058         return lookupMethod(env, pos, location, resolveContext, new BasicLookupHelper(name, site, argtypes, typeargtypes) {
  2059             @Override
  2060             Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2061                 return findMethod(env, site, name, argtypes, typeargtypes,
  2062                         phase.isBoxingRequired(),
  2063                         phase.isVarargsRequired(), false);
  2065             @Override
  2066             Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2067                 if (sym.kind >= AMBIGUOUS) {
  2068                     sym = super.access(env, pos, location, sym);
  2069                 } else if (allowMethodHandles) {
  2070                     MethodSymbol msym = (MethodSymbol)sym;
  2071                     if (msym.isSignaturePolymorphic(types)) {
  2072                         env.info.pendingResolutionPhase = BASIC;
  2073                         return findPolymorphicSignatureInstance(env, sym, argtypes);
  2076                 return sym;
  2078         });
  2081     /** Find or create an implicit method of exactly the given type (after erasure).
  2082      *  Searches in a side table, not the main scope of the site.
  2083      *  This emulates the lookup process required by JSR 292 in JVM.
  2084      *  @param env       Attribution environment
  2085      *  @param spMethod  signature polymorphic method - i.e. MH.invokeExact
  2086      *  @param argtypes  The required argument types
  2087      */
  2088     Symbol findPolymorphicSignatureInstance(Env<AttrContext> env,
  2089                                             Symbol spMethod,
  2090                                             List<Type> argtypes) {
  2091         Type mtype = infer.instantiatePolymorphicSignatureInstance(env,
  2092                 (MethodSymbol)spMethod, currentResolutionContext, argtypes);
  2093         for (Symbol sym : polymorphicSignatureScope.getElementsByName(spMethod.name)) {
  2094             if (types.isSameType(mtype, sym.type)) {
  2095                return sym;
  2099         // create the desired method
  2100         long flags = ABSTRACT | HYPOTHETICAL | spMethod.flags() & Flags.AccessFlags;
  2101         Symbol msym = new MethodSymbol(flags, spMethod.name, mtype, spMethod.owner);
  2102         polymorphicSignatureScope.enter(msym);
  2103         return msym;
  2106     /** Resolve a qualified method identifier, throw a fatal error if not
  2107      *  found.
  2108      *  @param pos       The position to use for error reporting.
  2109      *  @param env       The environment current at the method invocation.
  2110      *  @param site      The type of the qualifying expression, in which
  2111      *                   identifier is searched.
  2112      *  @param name      The identifier's name.
  2113      *  @param argtypes  The types of the invocation's value arguments.
  2114      *  @param typeargtypes  The types of the invocation's type arguments.
  2115      */
  2116     public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env,
  2117                                         Type site, Name name,
  2118                                         List<Type> argtypes,
  2119                                         List<Type> typeargtypes) {
  2120         MethodResolutionContext resolveContext = new MethodResolutionContext();
  2121         resolveContext.internalResolution = true;
  2122         Symbol sym = resolveQualifiedMethod(resolveContext, pos, env, site.tsym,
  2123                 site, name, argtypes, typeargtypes);
  2124         if (sym.kind == MTH) return (MethodSymbol)sym;
  2125         else throw new FatalError(
  2126                  diags.fragment("fatal.err.cant.locate.meth",
  2127                                 name));
  2130     /** Resolve constructor.
  2131      *  @param pos       The position to use for error reporting.
  2132      *  @param env       The environment current at the constructor invocation.
  2133      *  @param site      The type of class for which a constructor is searched.
  2134      *  @param argtypes  The types of the constructor invocation's value
  2135      *                   arguments.
  2136      *  @param typeargtypes  The types of the constructor invocation's type
  2137      *                   arguments.
  2138      */
  2139     Symbol resolveConstructor(DiagnosticPosition pos,
  2140                               Env<AttrContext> env,
  2141                               Type site,
  2142                               List<Type> argtypes,
  2143                               List<Type> typeargtypes) {
  2144         return resolveConstructor(new MethodResolutionContext(), pos, env, site, argtypes, typeargtypes);
  2147     private Symbol resolveConstructor(MethodResolutionContext resolveContext,
  2148                               final DiagnosticPosition pos,
  2149                               Env<AttrContext> env,
  2150                               Type site,
  2151                               List<Type> argtypes,
  2152                               List<Type> typeargtypes) {
  2153         return lookupMethod(env, pos, site.tsym, resolveContext, new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
  2154             @Override
  2155             Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2156                 return findConstructor(pos, env, site, argtypes, typeargtypes,
  2157                         phase.isBoxingRequired(),
  2158                         phase.isVarargsRequired());
  2160         });
  2163     /** Resolve a constructor, throw a fatal error if not found.
  2164      *  @param pos       The position to use for error reporting.
  2165      *  @param env       The environment current at the method invocation.
  2166      *  @param site      The type to be constructed.
  2167      *  @param argtypes  The types of the invocation's value arguments.
  2168      *  @param typeargtypes  The types of the invocation's type arguments.
  2169      */
  2170     public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  2171                                         Type site,
  2172                                         List<Type> argtypes,
  2173                                         List<Type> typeargtypes) {
  2174         MethodResolutionContext resolveContext = new MethodResolutionContext();
  2175         resolveContext.internalResolution = true;
  2176         Symbol sym = resolveConstructor(resolveContext, pos, env, site, argtypes, typeargtypes);
  2177         if (sym.kind == MTH) return (MethodSymbol)sym;
  2178         else throw new FatalError(
  2179                  diags.fragment("fatal.err.cant.locate.ctor", site));
  2182     Symbol findConstructor(DiagnosticPosition pos, Env<AttrContext> env,
  2183                               Type site, List<Type> argtypes,
  2184                               List<Type> typeargtypes,
  2185                               boolean allowBoxing,
  2186                               boolean useVarargs) {
  2187         Symbol sym = findMethod(env, site,
  2188                                     names.init, argtypes,
  2189                                     typeargtypes, allowBoxing,
  2190                                     useVarargs, false);
  2191         chk.checkDeprecated(pos, env.info.scope.owner, sym);
  2192         return sym;
  2195     /** Resolve constructor using diamond inference.
  2196      *  @param pos       The position to use for error reporting.
  2197      *  @param env       The environment current at the constructor invocation.
  2198      *  @param site      The type of class for which a constructor is searched.
  2199      *                   The scope of this class has been touched in attribution.
  2200      *  @param argtypes  The types of the constructor invocation's value
  2201      *                   arguments.
  2202      *  @param typeargtypes  The types of the constructor invocation's type
  2203      *                   arguments.
  2204      */
  2205     Symbol resolveDiamond(DiagnosticPosition pos,
  2206                               Env<AttrContext> env,
  2207                               Type site,
  2208                               List<Type> argtypes,
  2209                               List<Type> typeargtypes) {
  2210         return lookupMethod(env, pos, site.tsym, new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
  2211             @Override
  2212             Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2213                 return findDiamond(env, site, argtypes, typeargtypes,
  2214                         phase.isBoxingRequired(),
  2215                         phase.isVarargsRequired());
  2217             @Override
  2218             Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2219                 if (sym.kind >= AMBIGUOUS) {
  2220                     final JCDiagnostic details = sym.kind == WRONG_MTH ?
  2221                                     ((InapplicableSymbolError)sym).errCandidate().details :
  2222                                     null;
  2223                     sym = new InapplicableSymbolError(sym.kind, "diamondError", currentResolutionContext) {
  2224                         @Override
  2225                         JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos,
  2226                                 Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
  2227                             String key = details == null ?
  2228                                 "cant.apply.diamond" :
  2229                                 "cant.apply.diamond.1";
  2230                             return diags.create(dkind, log.currentSource(), pos, key,
  2231                                     diags.fragment("diamond", site.tsym), details);
  2233                     };
  2234                     sym = accessMethod(sym, pos, site, names.init, true, argtypes, typeargtypes);
  2235                     env.info.pendingResolutionPhase = currentResolutionContext.step;
  2237                 return sym;
  2239         });
  2242     /** This method scans all the constructor symbol in a given class scope -
  2243      *  assuming that the original scope contains a constructor of the kind:
  2244      *  {@code Foo(X x, Y y)}, where X,Y are class type-variables declared in Foo,
  2245      *  a method check is executed against the modified constructor type:
  2246      *  {@code <X,Y>Foo<X,Y>(X x, Y y)}. This is crucial in order to enable diamond
  2247      *  inference. The inferred return type of the synthetic constructor IS
  2248      *  the inferred type for the diamond operator.
  2249      */
  2250     private Symbol findDiamond(Env<AttrContext> env,
  2251                               Type site,
  2252                               List<Type> argtypes,
  2253                               List<Type> typeargtypes,
  2254                               boolean allowBoxing,
  2255                               boolean useVarargs) {
  2256         Symbol bestSoFar = methodNotFound;
  2257         for (Scope.Entry e = site.tsym.members().lookup(names.init);
  2258              e.scope != null;
  2259              e = e.next()) {
  2260             final Symbol sym = e.sym;
  2261             //- System.out.println(" e " + e.sym);
  2262             if (sym.kind == MTH &&
  2263                 (sym.flags_field & SYNTHETIC) == 0) {
  2264                     List<Type> oldParams = e.sym.type.hasTag(FORALL) ?
  2265                             ((ForAll)sym.type).tvars :
  2266                             List.<Type>nil();
  2267                     Type constrType = new ForAll(site.tsym.type.getTypeArguments().appendList(oldParams),
  2268                             types.createMethodTypeWithReturn(sym.type.asMethodType(), site));
  2269                     MethodSymbol newConstr = new MethodSymbol(sym.flags(), names.init, constrType, site.tsym) {
  2270                         @Override
  2271                         public Symbol baseSymbol() {
  2272                             return sym;
  2274                     };
  2275                     bestSoFar = selectBest(env, site, argtypes, typeargtypes,
  2276                             newConstr,
  2277                             bestSoFar,
  2278                             allowBoxing,
  2279                             useVarargs,
  2280                             false);
  2283         return bestSoFar;
  2288     /** Resolve operator.
  2289      *  @param pos       The position to use for error reporting.
  2290      *  @param optag     The tag of the operation tree.
  2291      *  @param env       The environment current at the operation.
  2292      *  @param argtypes  The types of the operands.
  2293      */
  2294     Symbol resolveOperator(DiagnosticPosition pos, JCTree.Tag optag,
  2295                            Env<AttrContext> env, List<Type> argtypes) {
  2296         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  2297         try {
  2298             currentResolutionContext = new MethodResolutionContext();
  2299             Name name = treeinfo.operatorName(optag);
  2300             Symbol sym = findMethod(env, syms.predefClass.type, name, argtypes,
  2301                                     null, false, false, true);
  2302             if (boxingEnabled && sym.kind >= WRONG_MTHS)
  2303                 sym = findMethod(env, syms.predefClass.type, name, argtypes,
  2304                                  null, true, false, true);
  2305             return accessMethod(sym, pos, env.enclClass.sym.type, name,
  2306                           false, argtypes, null);
  2308         finally {
  2309             currentResolutionContext = prevResolutionContext;
  2313     /** Resolve operator.
  2314      *  @param pos       The position to use for error reporting.
  2315      *  @param optag     The tag of the operation tree.
  2316      *  @param env       The environment current at the operation.
  2317      *  @param arg       The type of the operand.
  2318      */
  2319     Symbol resolveUnaryOperator(DiagnosticPosition pos, JCTree.Tag optag, Env<AttrContext> env, Type arg) {
  2320         return resolveOperator(pos, optag, env, List.of(arg));
  2323     /** Resolve binary operator.
  2324      *  @param pos       The position to use for error reporting.
  2325      *  @param optag     The tag of the operation tree.
  2326      *  @param env       The environment current at the operation.
  2327      *  @param left      The types of the left operand.
  2328      *  @param right     The types of the right operand.
  2329      */
  2330     Symbol resolveBinaryOperator(DiagnosticPosition pos,
  2331                                  JCTree.Tag optag,
  2332                                  Env<AttrContext> env,
  2333                                  Type left,
  2334                                  Type right) {
  2335         return resolveOperator(pos, optag, env, List.of(left, right));
  2338     /**
  2339      * Resolution of member references is typically done as a single
  2340      * overload resolution step, where the argument types A are inferred from
  2341      * the target functional descriptor.
  2343      * If the member reference is a method reference with a type qualifier,
  2344      * a two-step lookup process is performed. The first step uses the
  2345      * expected argument list A, while the second step discards the first
  2346      * type from A (which is treated as a receiver type).
  2348      * There are two cases in which inference is performed: (i) if the member
  2349      * reference is a constructor reference and the qualifier type is raw - in
  2350      * which case diamond inference is used to infer a parameterization for the
  2351      * type qualifier; (ii) if the member reference is an unbound reference
  2352      * where the type qualifier is raw - in that case, during the unbound lookup
  2353      * the receiver argument type is used to infer an instantiation for the raw
  2354      * qualifier type.
  2356      * When a multi-step resolution process is exploited, it is an error
  2357      * if two candidates are found (ambiguity).
  2359      * This routine returns a pair (T,S), where S is the member reference symbol,
  2360      * and T is the type of the class in which S is defined. This is necessary as
  2361      * the type T might be dynamically inferred (i.e. if constructor reference
  2362      * has a raw qualifier).
  2363      */
  2364     Pair<Symbol, ReferenceLookupHelper> resolveMemberReference(DiagnosticPosition pos,
  2365                                   Env<AttrContext> env,
  2366                                   JCMemberReference referenceTree,
  2367                                   Type site,
  2368                                   Name name, List<Type> argtypes,
  2369                                   List<Type> typeargtypes,
  2370                                   boolean boxingAllowed) {
  2371         MethodResolutionPhase maxPhase = boxingAllowed ? VARARITY : BASIC;
  2372         //step 1 - bound lookup
  2373         ReferenceLookupHelper boundLookupHelper = name.equals(names.init) ?
  2374                 new ConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase) :
  2375                 new MethodReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
  2376         Env<AttrContext> boundEnv = env.dup(env.tree, env.info.dup());
  2377         Symbol boundSym = lookupMethod(boundEnv, env.tree.pos(), site.tsym, boundLookupHelper);
  2379         //step 2 - unbound lookup
  2380         ReferenceLookupHelper unboundLookupHelper = boundLookupHelper.unboundLookup();
  2381         Env<AttrContext> unboundEnv = env.dup(env.tree, env.info.dup());
  2382         Symbol unboundSym = lookupMethod(unboundEnv, env.tree.pos(), site.tsym, unboundLookupHelper);
  2384         //merge results
  2385         Pair<Symbol, ReferenceLookupHelper> res;
  2386         if (unboundSym.kind != MTH) {
  2387             res = new Pair<Symbol, ReferenceLookupHelper>(boundSym, boundLookupHelper);
  2388             env.info.pendingResolutionPhase = boundEnv.info.pendingResolutionPhase;
  2389         } else if (boundSym.kind == MTH) {
  2390             res = new Pair<Symbol, ReferenceLookupHelper>(ambiguityError(boundSym, unboundSym), boundLookupHelper);
  2391             env.info.pendingResolutionPhase = boundEnv.info.pendingResolutionPhase;
  2392         } else {
  2393             res = new Pair<Symbol, ReferenceLookupHelper>(unboundSym, unboundLookupHelper);
  2394             env.info.pendingResolutionPhase = unboundEnv.info.pendingResolutionPhase;
  2397         return res;
  2400     /**
  2401      * Helper for defining custom method-like lookup logic; a lookup helper
  2402      * provides hooks for (i) the actual lookup logic and (ii) accessing the
  2403      * lookup result (this step might result in compiler diagnostics to be generated)
  2404      */
  2405     abstract class LookupHelper {
  2407         /** name of the symbol to lookup */
  2408         Name name;
  2410         /** location in which the lookup takes place */
  2411         Type site;
  2413         /** actual types used during the lookup */
  2414         List<Type> argtypes;
  2416         /** type arguments used during the lookup */
  2417         List<Type> typeargtypes;
  2419         /** Max overload resolution phase handled by this helper */
  2420         MethodResolutionPhase maxPhase;
  2422         LookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2423             this.name = name;
  2424             this.site = site;
  2425             this.argtypes = argtypes;
  2426             this.typeargtypes = typeargtypes;
  2427             this.maxPhase = maxPhase;
  2430         /**
  2431          * Should lookup stop at given phase with given result
  2432          */
  2433         protected boolean shouldStop(Symbol sym, MethodResolutionPhase phase) {
  2434             return phase.ordinal() > maxPhase.ordinal() ||
  2435                     sym.kind < ERRONEOUS || sym.kind == AMBIGUOUS;
  2438         /**
  2439          * Search for a symbol under a given overload resolution phase - this method
  2440          * is usually called several times, once per each overload resolution phase
  2441          */
  2442         abstract Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase);
  2444         /**
  2445          * Validate the result of the lookup
  2446          */
  2447         abstract Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym);
  2450     abstract class BasicLookupHelper extends LookupHelper {
  2452         BasicLookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes) {
  2453             super(name, site, argtypes, typeargtypes, MethodResolutionPhase.VARARITY);
  2456         @Override
  2457         Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2458             if (sym.kind >= AMBIGUOUS) {
  2459                 //if nothing is found return the 'first' error
  2460                 sym = accessMethod(sym, pos, location, site, name, true, argtypes, typeargtypes);
  2462             return sym;
  2466     /**
  2467      * Helper class for member reference lookup. A reference lookup helper
  2468      * defines the basic logic for member reference lookup; a method gives
  2469      * access to an 'unbound' helper used to perform an unbound member
  2470      * reference lookup.
  2471      */
  2472     abstract class ReferenceLookupHelper extends LookupHelper {
  2474         /** The member reference tree */
  2475         JCMemberReference referenceTree;
  2477         ReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
  2478                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2479             super(name, site, argtypes, typeargtypes, maxPhase);
  2480             this.referenceTree = referenceTree;
  2484         /**
  2485          * Returns an unbound version of this lookup helper. By default, this
  2486          * method returns an dummy lookup helper.
  2487          */
  2488         ReferenceLookupHelper unboundLookup() {
  2489             //dummy loopkup helper that always return 'methodNotFound'
  2490             return new ReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase) {
  2491                 @Override
  2492                 ReferenceLookupHelper unboundLookup() {
  2493                     return this;
  2495                 @Override
  2496                 Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2497                     return methodNotFound;
  2499                 @Override
  2500                 ReferenceKind referenceKind(Symbol sym) {
  2501                     Assert.error();
  2502                     return null;
  2504             };
  2507         /**
  2508          * Get the kind of the member reference
  2509          */
  2510         abstract JCMemberReference.ReferenceKind referenceKind(Symbol sym);
  2512         Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
  2513             //skip error reporting
  2514             return sym;
  2518     /**
  2519      * Helper class for method reference lookup. The lookup logic is based
  2520      * upon Resolve.findMethod; in certain cases, this helper class has a
  2521      * corresponding unbound helper class (see UnboundMethodReferenceLookupHelper).
  2522      * In such cases, non-static lookup results are thrown away.
  2523      */
  2524     class MethodReferenceLookupHelper extends ReferenceLookupHelper {
  2526         MethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
  2527                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2528             super(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
  2531         protected Symbol lookupReferenceInternal(Env<AttrContext> env, MethodResolutionPhase phase) {
  2532             return findMethod(env, site, name, argtypes, typeargtypes,
  2533                     phase.isBoxingRequired(), phase.isVarargsRequired(), syms.operatorNames.contains(name));
  2536         protected Symbol adjustLookupResult(Env<AttrContext> env, Symbol sym) {
  2537             return !TreeInfo.isStaticSelector(referenceTree.expr, names) ||
  2538                         sym.kind != MTH ||
  2539                         sym.isStatic() ? sym : new StaticError(sym);
  2542         @Override
  2543         final Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2544             return adjustLookupResult(env, lookupReferenceInternal(env, phase));
  2547         @Override
  2548         ReferenceLookupHelper unboundLookup() {
  2549             if (TreeInfo.isStaticSelector(referenceTree.expr, names) &&
  2550                     argtypes.nonEmpty() &&
  2551                     types.isSubtypeUnchecked(argtypes.head, site)) {
  2552                 return new UnboundMethodReferenceLookupHelper(referenceTree, name,
  2553                         site, argtypes, typeargtypes, maxPhase);
  2554             } else {
  2555                 return super.unboundLookup();
  2559         @Override
  2560         ReferenceKind referenceKind(Symbol sym) {
  2561             if (sym.isStatic()) {
  2562                 return TreeInfo.isStaticSelector(referenceTree.expr, names) ?
  2563                         ReferenceKind.STATIC : ReferenceKind.STATIC_EVAL;
  2564             } else {
  2565                 Name selName = TreeInfo.name(referenceTree.getQualifierExpression());
  2566                 return selName != null && selName == names._super ?
  2567                         ReferenceKind.SUPER :
  2568                         ReferenceKind.BOUND;
  2573     /**
  2574      * Helper class for unbound method reference lookup. Essentially the same
  2575      * as the basic method reference lookup helper; main difference is that static
  2576      * lookup results are thrown away. If qualifier type is raw, an attempt to
  2577      * infer a parameterized type is made using the first actual argument (that
  2578      * would otherwise be ignored during the lookup).
  2579      */
  2580     class UnboundMethodReferenceLookupHelper extends MethodReferenceLookupHelper {
  2582         UnboundMethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
  2583                 List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2584             super(referenceTree, name,
  2585                     site.isRaw() ? types.asSuper(argtypes.head, site.tsym) : site,
  2586                     argtypes.tail, typeargtypes, maxPhase);
  2589         @Override
  2590         protected Symbol adjustLookupResult(Env<AttrContext> env, Symbol sym) {
  2591             return sym.kind != MTH || !sym.isStatic() ? sym : new StaticError(sym);
  2594         @Override
  2595         ReferenceLookupHelper unboundLookup() {
  2596             return this;
  2599         @Override
  2600         ReferenceKind referenceKind(Symbol sym) {
  2601             return ReferenceKind.UNBOUND;
  2605     /**
  2606      * Helper class for constructor reference lookup. The lookup logic is based
  2607      * upon either Resolve.findMethod or Resolve.findDiamond - depending on
  2608      * whether the constructor reference needs diamond inference (this is the case
  2609      * if the qualifier type is raw). A special erroneous symbol is returned
  2610      * if the lookup returns the constructor of an inner class and there's no
  2611      * enclosing instance in scope.
  2612      */
  2613     class ConstructorReferenceLookupHelper extends ReferenceLookupHelper {
  2615         boolean needsInference;
  2617         ConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
  2618                 List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
  2619             super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase);
  2620             if (site.isRaw()) {
  2621                 this.site = new ClassType(site.getEnclosingType(), site.tsym.type.getTypeArguments(), site.tsym);
  2622                 needsInference = true;
  2626         @Override
  2627         protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
  2628             Symbol sym = needsInference ?
  2629                 findDiamond(env, site, argtypes, typeargtypes, phase.isBoxingRequired(), phase.isVarargsRequired()) :
  2630                 findMethod(env, site, name, argtypes, typeargtypes,
  2631                         phase.isBoxingRequired(), phase.isVarargsRequired(), syms.operatorNames.contains(name));
  2632             return sym.kind != MTH ||
  2633                           site.getEnclosingType().hasTag(NONE) ||
  2634                           hasEnclosingInstance(env, site) ?
  2635                           sym : new InvalidSymbolError(Kinds.MISSING_ENCL, sym, null) {
  2636                     @Override
  2637                     JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
  2638                        return diags.create(dkind, log.currentSource(), pos,
  2639                             "cant.access.inner.cls.constr", site.tsym.name, argtypes, site.getEnclosingType());
  2641                 };
  2644         @Override
  2645         ReferenceKind referenceKind(Symbol sym) {
  2646             return site.getEnclosingType().hasTag(NONE) ?
  2647                     ReferenceKind.TOPLEVEL : ReferenceKind.IMPLICIT_INNER;
  2651     /**
  2652      * Main overload resolution routine. On each overload resolution step, a
  2653      * lookup helper class is used to perform the method/constructor lookup;
  2654      * at the end of the lookup, the helper is used to validate the results
  2655      * (this last step might trigger overload resolution diagnostics).
  2656      */
  2657     Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, LookupHelper lookupHelper) {
  2658         return lookupMethod(env, pos, location, new MethodResolutionContext(), lookupHelper);
  2661     Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location,
  2662             MethodResolutionContext resolveContext, LookupHelper lookupHelper) {
  2663         MethodResolutionContext prevResolutionContext = currentResolutionContext;
  2664         try {
  2665             Symbol bestSoFar = methodNotFound;
  2666             currentResolutionContext = resolveContext;
  2667             for (MethodResolutionPhase phase : methodResolutionSteps) {
  2668                 if (!phase.isApplicable(boxingEnabled, varargsEnabled) ||
  2669                         lookupHelper.shouldStop(bestSoFar, phase)) break;
  2670                 MethodResolutionPhase prevPhase = currentResolutionContext.step;
  2671                 Symbol prevBest = bestSoFar;
  2672                 currentResolutionContext.step = phase;
  2673                 bestSoFar = phase.mergeResults(bestSoFar, lookupHelper.lookup(env, phase));
  2674                 env.info.pendingResolutionPhase = (prevBest == bestSoFar) ? prevPhase : phase;
  2676             return lookupHelper.access(env, pos, location, bestSoFar);
  2677         } finally {
  2678             currentResolutionContext = prevResolutionContext;
  2682     /**
  2683      * Resolve `c.name' where name == this or name == super.
  2684      * @param pos           The position to use for error reporting.
  2685      * @param env           The environment current at the expression.
  2686      * @param c             The qualifier.
  2687      * @param name          The identifier's name.
  2688      */
  2689     Symbol resolveSelf(DiagnosticPosition pos,
  2690                        Env<AttrContext> env,
  2691                        TypeSymbol c,
  2692                        Name name) {
  2693         Env<AttrContext> env1 = env;
  2694         boolean staticOnly = false;
  2695         while (env1.outer != null) {
  2696             if (isStatic(env1)) staticOnly = true;
  2697             if (env1.enclClass.sym == c) {
  2698                 Symbol sym = env1.info.scope.lookup(name).sym;
  2699                 if (sym != null) {
  2700                     if (staticOnly) sym = new StaticError(sym);
  2701                     return accessBase(sym, pos, env.enclClass.sym.type,
  2702                                   name, true);
  2705             if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
  2706             env1 = env1.outer;
  2708         if (allowDefaultMethods && c.isInterface() &&
  2709                 name == names._super && !isStatic(env) &&
  2710                 types.isDirectSuperInterface(c.type, env.enclClass.sym)) {
  2711             //this might be a default super call if one of the superinterfaces is 'c'
  2712             for (Type t : pruneInterfaces(env.enclClass.type)) {
  2713                 if (t.tsym == c) {
  2714                     env.info.defaultSuperCallSite = t;
  2715                     return new VarSymbol(0, names._super,
  2716                             types.asSuper(env.enclClass.type, c), env.enclClass.sym);
  2719             //find a direct superinterface that is a subtype of 'c'
  2720             for (Type i : types.interfaces(env.enclClass.type)) {
  2721                 if (i.tsym.isSubClass(c, types) && i.tsym != c) {
  2722                     log.error(pos, "illegal.default.super.call", c,
  2723                             diags.fragment("redundant.supertype", c, i));
  2724                     return syms.errSymbol;
  2727             Assert.error();
  2729         log.error(pos, "not.encl.class", c);
  2730         return syms.errSymbol;
  2732     //where
  2733     private List<Type> pruneInterfaces(Type t) {
  2734         ListBuffer<Type> result = ListBuffer.lb();
  2735         for (Type t1 : types.interfaces(t)) {
  2736             boolean shouldAdd = true;
  2737             for (Type t2 : types.interfaces(t)) {
  2738                 if (t1 != t2 && types.isSubtypeNoCapture(t2, t1)) {
  2739                     shouldAdd = false;
  2742             if (shouldAdd) {
  2743                 result.append(t1);
  2746         return result.toList();
  2750     /**
  2751      * Resolve `c.this' for an enclosing class c that contains the
  2752      * named member.
  2753      * @param pos           The position to use for error reporting.
  2754      * @param env           The environment current at the expression.
  2755      * @param member        The member that must be contained in the result.
  2756      */
  2757     Symbol resolveSelfContaining(DiagnosticPosition pos,
  2758                                  Env<AttrContext> env,
  2759                                  Symbol member,
  2760                                  boolean isSuperCall) {
  2761         Symbol sym = resolveSelfContainingInternal(env, member, isSuperCall);
  2762         if (sym == null) {
  2763             log.error(pos, "encl.class.required", member);
  2764             return syms.errSymbol;
  2765         } else {
  2766             return accessBase(sym, pos, env.enclClass.sym.type, sym.name, true);
  2770     boolean hasEnclosingInstance(Env<AttrContext> env, Type type) {
  2771         Symbol encl = resolveSelfContainingInternal(env, type.tsym, false);
  2772         return encl != null && encl.kind < ERRONEOUS;
  2775     private Symbol resolveSelfContainingInternal(Env<AttrContext> env,
  2776                                  Symbol member,
  2777                                  boolean isSuperCall) {
  2778         Name name = names._this;
  2779         Env<AttrContext> env1 = isSuperCall ? env.outer : env;
  2780         boolean staticOnly = false;
  2781         if (env1 != null) {
  2782             while (env1 != null && env1.outer != null) {
  2783                 if (isStatic(env1)) staticOnly = true;
  2784                 if (env1.enclClass.sym.isSubClass(member.owner, types)) {
  2785                     Symbol sym = env1.info.scope.lookup(name).sym;
  2786                     if (sym != null) {
  2787                         if (staticOnly) sym = new StaticError(sym);
  2788                         return sym;
  2791                 if ((env1.enclClass.sym.flags() & STATIC) != 0)
  2792                     staticOnly = true;
  2793                 env1 = env1.outer;
  2796         return null;
  2799     /**
  2800      * Resolve an appropriate implicit this instance for t's container.
  2801      * JLS 8.8.5.1 and 15.9.2
  2802      */
  2803     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
  2804         return resolveImplicitThis(pos, env, t, false);
  2807     Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t, boolean isSuperCall) {
  2808         Type thisType = (((t.tsym.owner.kind & (MTH|VAR)) != 0)
  2809                          ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
  2810                          : resolveSelfContaining(pos, env, t.tsym, isSuperCall)).type;
  2811         if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
  2812             log.error(pos, "cant.ref.before.ctor.called", "this");
  2813         return thisType;
  2816 /* ***************************************************************************
  2817  *  ResolveError classes, indicating error situations when accessing symbols
  2818  ****************************************************************************/
  2820     //used by TransTypes when checking target type of synthetic cast
  2821     public void logAccessErrorInternal(Env<AttrContext> env, JCTree tree, Type type) {
  2822         AccessError error = new AccessError(env, env.enclClass.type, type.tsym);
  2823         logResolveError(error, tree.pos(), env.enclClass.sym, env.enclClass.type, null, null, null);
  2825     //where
  2826     private void logResolveError(ResolveError error,
  2827             DiagnosticPosition pos,
  2828             Symbol location,
  2829             Type site,
  2830             Name name,
  2831             List<Type> argtypes,
  2832             List<Type> typeargtypes) {
  2833         JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
  2834                 pos, location, site, name, argtypes, typeargtypes);
  2835         if (d != null) {
  2836             d.setFlag(DiagnosticFlag.RESOLVE_ERROR);
  2837             log.report(d);
  2841     private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
  2843     public Object methodArguments(List<Type> argtypes) {
  2844         if (argtypes == null || argtypes.isEmpty()) {
  2845             return noArgs;
  2846         } else {
  2847             ListBuffer<Object> diagArgs = ListBuffer.lb();
  2848             for (Type t : argtypes) {
  2849                 if (t.hasTag(DEFERRED)) {
  2850                     diagArgs.append(((DeferredAttr.DeferredType)t).tree);
  2851                 } else {
  2852                     diagArgs.append(t);
  2855             return diagArgs;
  2859     /**
  2860      * Root class for resolution errors. Subclass of ResolveError
  2861      * represent a different kinds of resolution error - as such they must
  2862      * specify how they map into concrete compiler diagnostics.
  2863      */
  2864     abstract class ResolveError extends Symbol {
  2866         /** The name of the kind of error, for debugging only. */
  2867         final String debugName;
  2869         ResolveError(int kind, String debugName) {
  2870             super(kind, 0, null, null, null);
  2871             this.debugName = debugName;
  2874         @Override
  2875         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
  2876             throw new AssertionError();
  2879         @Override
  2880         public String toString() {
  2881             return debugName;
  2884         @Override
  2885         public boolean exists() {
  2886             return false;
  2889         /**
  2890          * Create an external representation for this erroneous symbol to be
  2891          * used during attribution - by default this returns the symbol of a
  2892          * brand new error type which stores the original type found
  2893          * during resolution.
  2895          * @param name     the name used during resolution
  2896          * @param location the location from which the symbol is accessed
  2897          */
  2898         protected Symbol access(Name name, TypeSymbol location) {
  2899             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  2902         /**
  2903          * Create a diagnostic representing this resolution error.
  2905          * @param dkind     The kind of the diagnostic to be created (e.g error).
  2906          * @param pos       The position to be used for error reporting.
  2907          * @param site      The original type from where the selection took place.
  2908          * @param name      The name of the symbol to be resolved.
  2909          * @param argtypes  The invocation's value arguments,
  2910          *                  if we looked for a method.
  2911          * @param typeargtypes  The invocation's type arguments,
  2912          *                      if we looked for a method.
  2913          */
  2914         abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2915                 DiagnosticPosition pos,
  2916                 Symbol location,
  2917                 Type site,
  2918                 Name name,
  2919                 List<Type> argtypes,
  2920                 List<Type> typeargtypes);
  2923     /**
  2924      * This class is the root class of all resolution errors caused by
  2925      * an invalid symbol being found during resolution.
  2926      */
  2927     abstract class InvalidSymbolError extends ResolveError {
  2929         /** The invalid symbol found during resolution */
  2930         Symbol sym;
  2932         InvalidSymbolError(int kind, Symbol sym, String debugName) {
  2933             super(kind, debugName);
  2934             this.sym = sym;
  2937         @Override
  2938         public boolean exists() {
  2939             return true;
  2942         @Override
  2943         public String toString() {
  2944              return super.toString() + " wrongSym=" + sym;
  2947         @Override
  2948         public Symbol access(Name name, TypeSymbol location) {
  2949             if (sym.kind >= AMBIGUOUS)
  2950                 return ((ResolveError)sym).access(name, location);
  2951             else if ((sym.kind & ERRONEOUS) == 0 && (sym.kind & TYP) != 0)
  2952                 return types.createErrorType(name, location, sym.type).tsym;
  2953             else
  2954                 return sym;
  2958     /**
  2959      * InvalidSymbolError error class indicating that a symbol matching a
  2960      * given name does not exists in a given site.
  2961      */
  2962     class SymbolNotFoundError extends ResolveError {
  2964         SymbolNotFoundError(int kind) {
  2965             super(kind, "symbol not found error");
  2968         @Override
  2969         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  2970                 DiagnosticPosition pos,
  2971                 Symbol location,
  2972                 Type site,
  2973                 Name name,
  2974                 List<Type> argtypes,
  2975                 List<Type> typeargtypes) {
  2976             argtypes = argtypes == null ? List.<Type>nil() : argtypes;
  2977             typeargtypes = typeargtypes == null ? List.<Type>nil() : typeargtypes;
  2978             if (name == names.error)
  2979                 return null;
  2981             if (syms.operatorNames.contains(name)) {
  2982                 boolean isUnaryOp = argtypes.size() == 1;
  2983                 String key = argtypes.size() == 1 ?
  2984                     "operator.cant.be.applied" :
  2985                     "operator.cant.be.applied.1";
  2986                 Type first = argtypes.head;
  2987                 Type second = !isUnaryOp ? argtypes.tail.head : null;
  2988                 return diags.create(dkind, log.currentSource(), pos,
  2989                         key, name, first, second);
  2991             boolean hasLocation = false;
  2992             if (location == null) {
  2993                 location = site.tsym;
  2995             if (!location.name.isEmpty()) {
  2996                 if (location.kind == PCK && !site.tsym.exists()) {
  2997                     return diags.create(dkind, log.currentSource(), pos,
  2998                         "doesnt.exist", location);
  3000                 hasLocation = !location.name.equals(names._this) &&
  3001                         !location.name.equals(names._super);
  3003             boolean isConstructor = kind == ABSENT_MTH && name == names.init;
  3004             KindName kindname = isConstructor ? KindName.CONSTRUCTOR : absentKind(kind);
  3005             Name idname = isConstructor ? site.tsym.name : name;
  3006             String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation);
  3007             if (hasLocation) {
  3008                 return diags.create(dkind, log.currentSource(), pos,
  3009                         errKey, kindname, idname, //symbol kindname, name
  3010                         typeargtypes, argtypes, //type parameters and arguments (if any)
  3011                         getLocationDiag(location, site)); //location kindname, type
  3013             else {
  3014                 return diags.create(dkind, log.currentSource(), pos,
  3015                         errKey, kindname, idname, //symbol kindname, name
  3016                         typeargtypes, argtypes); //type parameters and arguments (if any)
  3019         //where
  3020         private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) {
  3021             String key = "cant.resolve";
  3022             String suffix = hasLocation ? ".location" : "";
  3023             switch (kindname) {
  3024                 case METHOD:
  3025                 case CONSTRUCTOR: {
  3026                     suffix += ".args";
  3027                     suffix += hasTypeArgs ? ".params" : "";
  3030             return key + suffix;
  3032         private JCDiagnostic getLocationDiag(Symbol location, Type site) {
  3033             if (location.kind == VAR) {
  3034                 return diags.fragment("location.1",
  3035                     kindName(location),
  3036                     location,
  3037                     location.type);
  3038             } else {
  3039                 return diags.fragment("location",
  3040                     typeKindName(site),
  3041                     site,
  3042                     null);
  3047     /**
  3048      * InvalidSymbolError error class indicating that a given symbol
  3049      * (either a method, a constructor or an operand) is not applicable
  3050      * given an actual arguments/type argument list.
  3051      */
  3052     class InapplicableSymbolError extends ResolveError {
  3054         protected MethodResolutionContext resolveContext;
  3056         InapplicableSymbolError(MethodResolutionContext context) {
  3057             this(WRONG_MTH, "inapplicable symbol error", context);
  3060         protected InapplicableSymbolError(int kind, String debugName, MethodResolutionContext context) {
  3061             super(kind, debugName);
  3062             this.resolveContext = context;
  3065         @Override
  3066         public String toString() {
  3067             return super.toString();
  3070         @Override
  3071         public boolean exists() {
  3072             return true;
  3075         @Override
  3076         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3077                 DiagnosticPosition pos,
  3078                 Symbol location,
  3079                 Type site,
  3080                 Name name,
  3081                 List<Type> argtypes,
  3082                 List<Type> typeargtypes) {
  3083             if (name == names.error)
  3084                 return null;
  3086             if (syms.operatorNames.contains(name)) {
  3087                 boolean isUnaryOp = argtypes.size() == 1;
  3088                 String key = argtypes.size() == 1 ?
  3089                     "operator.cant.be.applied" :
  3090                     "operator.cant.be.applied.1";
  3091                 Type first = argtypes.head;
  3092                 Type second = !isUnaryOp ? argtypes.tail.head : null;
  3093                 return diags.create(dkind, log.currentSource(), pos,
  3094                         key, name, first, second);
  3096             else {
  3097                 Candidate c = errCandidate();
  3098                 Symbol ws = c.sym.asMemberOf(site, types);
  3099                 return diags.create(dkind, log.currentSource(), pos,
  3100                           "cant.apply.symbol",
  3101                           kindName(ws),
  3102                           ws.name == names.init ? ws.owner.name : ws.name,
  3103                           methodArguments(ws.type.getParameterTypes()),
  3104                           methodArguments(argtypes),
  3105                           kindName(ws.owner),
  3106                           ws.owner.type,
  3107                           c.details);
  3111         @Override
  3112         public Symbol access(Name name, TypeSymbol location) {
  3113             return types.createErrorType(name, location, syms.errSymbol.type).tsym;
  3116         private Candidate errCandidate() {
  3117             Candidate bestSoFar = null;
  3118             for (Candidate c : resolveContext.candidates) {
  3119                 if (c.isApplicable()) continue;
  3120                 bestSoFar = c;
  3122             Assert.checkNonNull(bestSoFar);
  3123             return bestSoFar;
  3127     /**
  3128      * ResolveError error class indicating that a set of symbols
  3129      * (either methods, constructors or operands) is not applicable
  3130      * given an actual arguments/type argument list.
  3131      */
  3132     class InapplicableSymbolsError extends InapplicableSymbolError {
  3134         InapplicableSymbolsError(MethodResolutionContext context) {
  3135             super(WRONG_MTHS, "inapplicable symbols", context);
  3138         @Override
  3139         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3140                 DiagnosticPosition pos,
  3141                 Symbol location,
  3142                 Type site,
  3143                 Name name,
  3144                 List<Type> argtypes,
  3145                 List<Type> typeargtypes) {
  3146             if (!resolveContext.candidates.isEmpty()) {
  3147                 JCDiagnostic err = diags.create(dkind,
  3148                         log.currentSource(),
  3149                         pos,
  3150                         "cant.apply.symbols",
  3151                         name == names.init ? KindName.CONSTRUCTOR : absentKind(kind),
  3152                         name == names.init ? site.tsym.name : name,
  3153                         argtypes);
  3154                 return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(site));
  3155             } else {
  3156                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
  3157                     location, site, name, argtypes, typeargtypes);
  3161         //where
  3162         List<JCDiagnostic> candidateDetails(Type site) {
  3163             Map<Symbol, JCDiagnostic> details = new LinkedHashMap<Symbol, JCDiagnostic>();
  3164             for (Candidate c : resolveContext.candidates) {
  3165                 if (c.isApplicable()) continue;
  3166                 JCDiagnostic detailDiag = diags.fragment("inapplicable.method",
  3167                         Kinds.kindName(c.sym),
  3168                         c.sym.location(site, types),
  3169                         c.sym.asMemberOf(site, types),
  3170                         c.details);
  3171                 details.put(c.sym, detailDiag);
  3173             return List.from(details.values());
  3177     /**
  3178      * An InvalidSymbolError error class indicating that a symbol is not
  3179      * accessible from a given site
  3180      */
  3181     class AccessError extends InvalidSymbolError {
  3183         private Env<AttrContext> env;
  3184         private Type site;
  3186         AccessError(Symbol sym) {
  3187             this(null, null, sym);
  3190         AccessError(Env<AttrContext> env, Type site, Symbol sym) {
  3191             super(HIDDEN, sym, "access error");
  3192             this.env = env;
  3193             this.site = site;
  3194             if (debugResolve)
  3195                 log.error("proc.messager", sym + " @ " + site + " is inaccessible.");
  3198         @Override
  3199         public boolean exists() {
  3200             return false;
  3203         @Override
  3204         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3205                 DiagnosticPosition pos,
  3206                 Symbol location,
  3207                 Type site,
  3208                 Name name,
  3209                 List<Type> argtypes,
  3210                 List<Type> typeargtypes) {
  3211             if (sym.owner.type.hasTag(ERROR))
  3212                 return null;
  3214             if (sym.name == names.init && sym.owner != site.tsym) {
  3215                 return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
  3216                         pos, location, site, name, argtypes, typeargtypes);
  3218             else if ((sym.flags() & PUBLIC) != 0
  3219                 || (env != null && this.site != null
  3220                     && !isAccessible(env, this.site))) {
  3221                 return diags.create(dkind, log.currentSource(),
  3222                         pos, "not.def.access.class.intf.cant.access",
  3223                     sym, sym.location());
  3225             else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) {
  3226                 return diags.create(dkind, log.currentSource(),
  3227                         pos, "report.access", sym,
  3228                         asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
  3229                         sym.location());
  3231             else {
  3232                 return diags.create(dkind, log.currentSource(),
  3233                         pos, "not.def.public.cant.access", sym, sym.location());
  3238     /**
  3239      * InvalidSymbolError error class indicating that an instance member
  3240      * has erroneously been accessed from a static context.
  3241      */
  3242     class StaticError extends InvalidSymbolError {
  3244         StaticError(Symbol sym) {
  3245             super(STATICERR, sym, "static error");
  3248         @Override
  3249         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3250                 DiagnosticPosition pos,
  3251                 Symbol location,
  3252                 Type site,
  3253                 Name name,
  3254                 List<Type> argtypes,
  3255                 List<Type> typeargtypes) {
  3256             Symbol errSym = ((sym.kind == TYP && sym.type.hasTag(CLASS))
  3257                 ? types.erasure(sym.type).tsym
  3258                 : sym);
  3259             return diags.create(dkind, log.currentSource(), pos,
  3260                     "non-static.cant.be.ref", kindName(sym), errSym);
  3264     /**
  3265      * InvalidSymbolError error class indicating that a pair of symbols
  3266      * (either methods, constructors or operands) are ambiguous
  3267      * given an actual arguments/type argument list.
  3268      */
  3269     class AmbiguityError extends InvalidSymbolError {
  3271         /** The other maximally specific symbol */
  3272         Symbol sym2;
  3274         AmbiguityError(Symbol sym1, Symbol sym2) {
  3275             super(AMBIGUOUS, sym1, "ambiguity error");
  3276             this.sym2 = sym2;
  3279         @Override
  3280         JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
  3281                 DiagnosticPosition pos,
  3282                 Symbol location,
  3283                 Type site,
  3284                 Name name,
  3285                 List<Type> argtypes,
  3286                 List<Type> typeargtypes) {
  3287             AmbiguityError pair = this;
  3288             while (true) {
  3289                 if (pair.sym.kind == AMBIGUOUS)
  3290                     pair = (AmbiguityError)pair.sym;
  3291                 else if (pair.sym2.kind == AMBIGUOUS)
  3292                     pair = (AmbiguityError)pair.sym2;
  3293                 else break;
  3295             Name sname = pair.sym.name;
  3296             if (sname == names.init) sname = pair.sym.owner.name;
  3297             return diags.create(dkind, log.currentSource(),
  3298                       pos, "ref.ambiguous", sname,
  3299                       kindName(pair.sym),
  3300                       pair.sym,
  3301                       pair.sym.location(site, types),
  3302                       kindName(pair.sym2),
  3303                       pair.sym2,
  3304                       pair.sym2.location(site, types));
  3308     enum MethodResolutionPhase {
  3309         BASIC(false, false),
  3310         BOX(true, false),
  3311         VARARITY(true, true) {
  3312             @Override
  3313             public Symbol mergeResults(Symbol bestSoFar, Symbol sym) {
  3314                 switch (sym.kind) {
  3315                     case WRONG_MTH:
  3316                         return (bestSoFar.kind == WRONG_MTH || bestSoFar.kind == WRONG_MTHS) ?
  3317                             bestSoFar :
  3318                             sym;
  3319                     case ABSENT_MTH:
  3320                         return bestSoFar;
  3321                     default:
  3322                         return sym;
  3325         };
  3327         boolean isBoxingRequired;
  3328         boolean isVarargsRequired;
  3330         MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) {
  3331            this.isBoxingRequired = isBoxingRequired;
  3332            this.isVarargsRequired = isVarargsRequired;
  3335         public boolean isBoxingRequired() {
  3336             return isBoxingRequired;
  3339         public boolean isVarargsRequired() {
  3340             return isVarargsRequired;
  3343         public boolean isApplicable(boolean boxingEnabled, boolean varargsEnabled) {
  3344             return (varargsEnabled || !isVarargsRequired) &&
  3345                    (boxingEnabled || !isBoxingRequired);
  3348         public Symbol mergeResults(Symbol prev, Symbol sym) {
  3349             return sym;
  3353     final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
  3355     /**
  3356      * A resolution context is used to keep track of intermediate results of
  3357      * overload resolution, such as list of method that are not applicable
  3358      * (used to generate more precise diagnostics) and so on. Resolution contexts
  3359      * can be nested - this means that when each overload resolution routine should
  3360      * work within the resolution context it created.
  3361      */
  3362     class MethodResolutionContext {
  3364         private List<Candidate> candidates = List.nil();
  3366         MethodResolutionPhase step = null;
  3368         private boolean internalResolution = false;
  3369         private DeferredAttr.AttrMode attrMode = DeferredAttr.AttrMode.SPECULATIVE;
  3371         void addInapplicableCandidate(Symbol sym, JCDiagnostic details) {
  3372             Candidate c = new Candidate(currentResolutionContext.step, sym, details, null);
  3373             candidates = candidates.append(c);
  3376         void addApplicableCandidate(Symbol sym, Type mtype) {
  3377             Candidate c = new Candidate(currentResolutionContext.step, sym, null, mtype);
  3378             candidates = candidates.append(c);
  3381         /**
  3382          * This class represents an overload resolution candidate. There are two
  3383          * kinds of candidates: applicable methods and inapplicable methods;
  3384          * applicable methods have a pointer to the instantiated method type,
  3385          * while inapplicable candidates contain further details about the
  3386          * reason why the method has been considered inapplicable.
  3387          */
  3388         class Candidate {
  3390             final MethodResolutionPhase step;
  3391             final Symbol sym;
  3392             final JCDiagnostic details;
  3393             final Type mtype;
  3395             private Candidate(MethodResolutionPhase step, Symbol sym, JCDiagnostic details, Type mtype) {
  3396                 this.step = step;
  3397                 this.sym = sym;
  3398                 this.details = details;
  3399                 this.mtype = mtype;
  3402             @Override
  3403             public boolean equals(Object o) {
  3404                 if (o instanceof Candidate) {
  3405                     Symbol s1 = this.sym;
  3406                     Symbol s2 = ((Candidate)o).sym;
  3407                     if  ((s1 != s2 &&
  3408                             (s1.overrides(s2, s1.owner.type.tsym, types, false) ||
  3409                             (s2.overrides(s1, s2.owner.type.tsym, types, false)))) ||
  3410                             ((s1.isConstructor() || s2.isConstructor()) && s1.owner != s2.owner))
  3411                         return true;
  3413                 return false;
  3416             boolean isApplicable() {
  3417                 return mtype != null;
  3421         DeferredAttr.AttrMode attrMode() {
  3422             return attrMode;
  3425         boolean internal() {
  3426             return internalResolution;
  3430     MethodResolutionContext currentResolutionContext = null;

mercurial