Resolve.java revision 2773:92ee16cb8a0c
1/*
2 * Copyright (c) 1999, 2014, 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 */
25
26package com.sun.tools.javac.comp;
27
28import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
29import com.sun.tools.javac.api.Formattable.LocalizedString;
30import com.sun.tools.javac.code.*;
31import com.sun.tools.javac.code.Scope.WriteableScope;
32import com.sun.tools.javac.code.Symbol.*;
33import com.sun.tools.javac.code.Type.*;
34import com.sun.tools.javac.comp.Attr.ResultInfo;
35import com.sun.tools.javac.comp.Check.CheckContext;
36import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
37import com.sun.tools.javac.comp.DeferredAttr.DeferredAttrContext;
38import com.sun.tools.javac.comp.DeferredAttr.DeferredType;
39import com.sun.tools.javac.comp.Infer.InferenceContext;
40import com.sun.tools.javac.comp.Infer.FreeTypeListener;
41import com.sun.tools.javac.comp.Resolve.MethodResolutionContext.Candidate;
42import com.sun.tools.javac.comp.Resolve.MethodResolutionDiagHelper.Template;
43import com.sun.tools.javac.jvm.*;
44import com.sun.tools.javac.main.Option;
45import com.sun.tools.javac.tree.*;
46import com.sun.tools.javac.tree.JCTree.*;
47import com.sun.tools.javac.tree.JCTree.JCMemberReference.ReferenceKind;
48import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
49import com.sun.tools.javac.util.*;
50import com.sun.tools.javac.util.DefinedBy.Api;
51import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
52import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
53import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType;
54
55import java.util.Arrays;
56import java.util.Collection;
57import java.util.EnumSet;
58import java.util.Iterator;
59import java.util.LinkedHashMap;
60import java.util.Map;
61import java.util.function.BiPredicate;
62import java.util.stream.Stream;
63
64import javax.lang.model.element.ElementVisitor;
65
66import static com.sun.tools.javac.code.Flags.*;
67import static com.sun.tools.javac.code.Flags.BLOCK;
68import static com.sun.tools.javac.code.Kinds.*;
69import static com.sun.tools.javac.code.Kinds.Kind.*;
70import static com.sun.tools.javac.code.TypeTag.*;
71import static com.sun.tools.javac.comp.Resolve.MethodResolutionPhase.*;
72import static com.sun.tools.javac.tree.JCTree.Tag.*;
73
74/** Helper class for name resolution, used mostly by the attribution phase.
75 *
76 *  <p><b>This is NOT part of any supported API.
77 *  If you write code that depends on this, you do so at your own risk.
78 *  This code and its internal interfaces are subject to change or
79 *  deletion without notice.</b>
80 */
81public class Resolve {
82    protected static final Context.Key<Resolve> resolveKey = new Context.Key<>();
83
84    Names names;
85    Log log;
86    Symtab syms;
87    Attr attr;
88    DeferredAttr deferredAttr;
89    Check chk;
90    Infer infer;
91    ClassFinder finder;
92    TreeInfo treeinfo;
93    Types types;
94    JCDiagnostic.Factory diags;
95    public final boolean allowMethodHandles;
96    public final boolean allowFunctionalInterfaceMostSpecific;
97    public final boolean checkVarargsAccessAfterResolution;
98    private final boolean debugResolve;
99    private final boolean compactMethodDiags;
100    final EnumSet<VerboseResolutionMode> verboseResolutionMode;
101
102    WriteableScope polymorphicSignatureScope;
103
104    protected Resolve(Context context) {
105        context.put(resolveKey, this);
106        syms = Symtab.instance(context);
107
108        varNotFound = new
109            SymbolNotFoundError(ABSENT_VAR);
110        methodNotFound = new
111            SymbolNotFoundError(ABSENT_MTH);
112        methodWithCorrectStaticnessNotFound = new
113            SymbolNotFoundError(WRONG_STATICNESS,
114                "method found has incorrect staticness");
115        typeNotFound = new
116            SymbolNotFoundError(ABSENT_TYP);
117
118        names = Names.instance(context);
119        log = Log.instance(context);
120        attr = Attr.instance(context);
121        deferredAttr = DeferredAttr.instance(context);
122        chk = Check.instance(context);
123        infer = Infer.instance(context);
124        finder = ClassFinder.instance(context);
125        treeinfo = TreeInfo.instance(context);
126        types = Types.instance(context);
127        diags = JCDiagnostic.Factory.instance(context);
128        Source source = Source.instance(context);
129        Options options = Options.instance(context);
130        debugResolve = options.isSet("debugresolve");
131        compactMethodDiags = options.isSet(Option.XDIAGS, "compact") ||
132                options.isUnset(Option.XDIAGS) && options.isUnset("rawDiagnostics");
133        verboseResolutionMode = VerboseResolutionMode.getVerboseResolutionMode(options);
134        Target target = Target.instance(context);
135        allowMethodHandles = target.hasMethodHandles();
136        allowFunctionalInterfaceMostSpecific = source.allowFunctionalInterfaceMostSpecific();
137        checkVarargsAccessAfterResolution =
138                source.allowPostApplicabilityVarargsAccessCheck();
139        polymorphicSignatureScope = WriteableScope.create(syms.noSymbol);
140
141        inapplicableMethodException = new InapplicableMethodException(diags);
142    }
143
144    /** error symbols, which are returned when resolution fails
145     */
146    private final SymbolNotFoundError varNotFound;
147    private final SymbolNotFoundError methodNotFound;
148    private final SymbolNotFoundError methodWithCorrectStaticnessNotFound;
149    private final SymbolNotFoundError typeNotFound;
150
151    public static Resolve instance(Context context) {
152        Resolve instance = context.get(resolveKey);
153        if (instance == null)
154            instance = new Resolve(context);
155        return instance;
156    }
157
158    private static Symbol bestOf(Symbol s1,
159                                 Symbol s2) {
160        return s1.kind.betterThan(s2.kind) ? s1 : s2;
161    }
162
163    // <editor-fold defaultstate="collapsed" desc="Verbose resolution diagnostics support">
164    enum VerboseResolutionMode {
165        SUCCESS("success"),
166        FAILURE("failure"),
167        APPLICABLE("applicable"),
168        INAPPLICABLE("inapplicable"),
169        DEFERRED_INST("deferred-inference"),
170        PREDEF("predef"),
171        OBJECT_INIT("object-init"),
172        INTERNAL("internal");
173
174        final String opt;
175
176        private VerboseResolutionMode(String opt) {
177            this.opt = opt;
178        }
179
180        static EnumSet<VerboseResolutionMode> getVerboseResolutionMode(Options opts) {
181            String s = opts.get("verboseResolution");
182            EnumSet<VerboseResolutionMode> res = EnumSet.noneOf(VerboseResolutionMode.class);
183            if (s == null) return res;
184            if (s.contains("all")) {
185                res = EnumSet.allOf(VerboseResolutionMode.class);
186            }
187            Collection<String> args = Arrays.asList(s.split(","));
188            for (VerboseResolutionMode mode : values()) {
189                if (args.contains(mode.opt)) {
190                    res.add(mode);
191                } else if (args.contains("-" + mode.opt)) {
192                    res.remove(mode);
193                }
194            }
195            return res;
196        }
197    }
198
199    void reportVerboseResolutionDiagnostic(DiagnosticPosition dpos, Name name, Type site,
200            List<Type> argtypes, List<Type> typeargtypes, Symbol bestSoFar) {
201        boolean success = !bestSoFar.kind.isOverloadError();
202
203        if (success && !verboseResolutionMode.contains(VerboseResolutionMode.SUCCESS)) {
204            return;
205        } else if (!success && !verboseResolutionMode.contains(VerboseResolutionMode.FAILURE)) {
206            return;
207        }
208
209        if (bestSoFar.name == names.init &&
210                bestSoFar.owner == syms.objectType.tsym &&
211                !verboseResolutionMode.contains(VerboseResolutionMode.OBJECT_INIT)) {
212            return; //skip diags for Object constructor resolution
213        } else if (site == syms.predefClass.type &&
214                !verboseResolutionMode.contains(VerboseResolutionMode.PREDEF)) {
215            return; //skip spurious diags for predef symbols (i.e. operators)
216        } else if (currentResolutionContext.internalResolution &&
217                !verboseResolutionMode.contains(VerboseResolutionMode.INTERNAL)) {
218            return;
219        }
220
221        int pos = 0;
222        int mostSpecificPos = -1;
223        ListBuffer<JCDiagnostic> subDiags = new ListBuffer<>();
224        for (Candidate c : currentResolutionContext.candidates) {
225            if (currentResolutionContext.step != c.step ||
226                    (c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.APPLICABLE)) ||
227                    (!c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.INAPPLICABLE))) {
228                continue;
229            } else {
230                subDiags.append(c.isApplicable() ?
231                        getVerboseApplicableCandidateDiag(pos, c.sym, c.mtype) :
232                        getVerboseInapplicableCandidateDiag(pos, c.sym, c.details));
233                if (c.sym == bestSoFar)
234                    mostSpecificPos = pos;
235                pos++;
236            }
237        }
238        String key = success ? "verbose.resolve.multi" : "verbose.resolve.multi.1";
239        List<Type> argtypes2 = Type.map(argtypes,
240                    deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, bestSoFar, currentResolutionContext.step));
241        JCDiagnostic main = diags.note(log.currentSource(), dpos, key, name,
242                site.tsym, mostSpecificPos, currentResolutionContext.step,
243                methodArguments(argtypes2),
244                methodArguments(typeargtypes));
245        JCDiagnostic d = new JCDiagnostic.MultilineDiagnostic(main, subDiags.toList());
246        log.report(d);
247    }
248
249    JCDiagnostic getVerboseApplicableCandidateDiag(int pos, Symbol sym, Type inst) {
250        JCDiagnostic subDiag = null;
251        if (sym.type.hasTag(FORALL)) {
252            subDiag = diags.fragment("partial.inst.sig", inst);
253        }
254
255        String key = subDiag == null ?
256                "applicable.method.found" :
257                "applicable.method.found.1";
258
259        return diags.fragment(key, pos, sym, subDiag);
260    }
261
262    JCDiagnostic getVerboseInapplicableCandidateDiag(int pos, Symbol sym, JCDiagnostic subDiag) {
263        return diags.fragment("not.applicable.method.found", pos, sym, subDiag);
264    }
265    // </editor-fold>
266
267/* ************************************************************************
268 * Identifier resolution
269 *************************************************************************/
270
271    /** An environment is "static" if its static level is greater than
272     *  the one of its outer environment
273     */
274    protected static boolean isStatic(Env<AttrContext> env) {
275        return env.outer != null && env.info.staticLevel > env.outer.info.staticLevel;
276    }
277
278    /** An environment is an "initializer" if it is a constructor or
279     *  an instance initializer.
280     */
281    static boolean isInitializer(Env<AttrContext> env) {
282        Symbol owner = env.info.scope.owner;
283        return owner.isConstructor() ||
284            owner.owner.kind == TYP &&
285            (owner.kind == VAR ||
286             owner.kind == MTH && (owner.flags() & BLOCK) != 0) &&
287            (owner.flags() & STATIC) == 0;
288    }
289
290    /** Is class accessible in given evironment?
291     *  @param env    The current environment.
292     *  @param c      The class whose accessibility is checked.
293     */
294    public boolean isAccessible(Env<AttrContext> env, TypeSymbol c) {
295        return isAccessible(env, c, false);
296    }
297
298    public boolean isAccessible(Env<AttrContext> env, TypeSymbol c, boolean checkInner) {
299        boolean isAccessible = false;
300        switch ((short)(c.flags() & AccessFlags)) {
301            case PRIVATE:
302                isAccessible =
303                    env.enclClass.sym.outermostClass() ==
304                    c.owner.outermostClass();
305                break;
306            case 0:
307                isAccessible =
308                    env.toplevel.packge == c.owner // fast special case
309                    ||
310                    env.toplevel.packge == c.packge()
311                    ||
312                    // Hack: this case is added since synthesized default constructors
313                    // of anonymous classes should be allowed to access
314                    // classes which would be inaccessible otherwise.
315                    env.enclMethod != null &&
316                    (env.enclMethod.mods.flags & ANONCONSTR) != 0;
317                break;
318            default: // error recovery
319            case PUBLIC:
320                isAccessible = true;
321                break;
322            case PROTECTED:
323                isAccessible =
324                    env.toplevel.packge == c.owner // fast special case
325                    ||
326                    env.toplevel.packge == c.packge()
327                    ||
328                    isInnerSubClass(env.enclClass.sym, c.owner);
329                break;
330        }
331        return (checkInner == false || c.type.getEnclosingType() == Type.noType) ?
332            isAccessible :
333            isAccessible && isAccessible(env, c.type.getEnclosingType(), checkInner);
334    }
335    //where
336        /** Is given class a subclass of given base class, or an inner class
337         *  of a subclass?
338         *  Return null if no such class exists.
339         *  @param c     The class which is the subclass or is contained in it.
340         *  @param base  The base class
341         */
342        private boolean isInnerSubClass(ClassSymbol c, Symbol base) {
343            while (c != null && !c.isSubClass(base, types)) {
344                c = c.owner.enclClass();
345            }
346            return c != null;
347        }
348
349    boolean isAccessible(Env<AttrContext> env, Type t) {
350        return isAccessible(env, t, false);
351    }
352
353    boolean isAccessible(Env<AttrContext> env, Type t, boolean checkInner) {
354        return (t.hasTag(ARRAY))
355            ? isAccessible(env, types.cvarUpperBound(types.elemtype(t)))
356            : isAccessible(env, t.tsym, checkInner);
357    }
358
359    /** Is symbol accessible as a member of given type in given environment?
360     *  @param env    The current environment.
361     *  @param site   The type of which the tested symbol is regarded
362     *                as a member.
363     *  @param sym    The symbol.
364     */
365    public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym) {
366        return isAccessible(env, site, sym, false);
367    }
368    public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym, boolean checkInner) {
369        if (sym.name == names.init && sym.owner != site.tsym) return false;
370        switch ((short)(sym.flags() & AccessFlags)) {
371        case PRIVATE:
372            return
373                (env.enclClass.sym == sym.owner // fast special case
374                 ||
375                 env.enclClass.sym.outermostClass() ==
376                 sym.owner.outermostClass())
377                &&
378                sym.isInheritedIn(site.tsym, types);
379        case 0:
380            return
381                (env.toplevel.packge == sym.owner.owner // fast special case
382                 ||
383                 env.toplevel.packge == sym.packge())
384                &&
385                isAccessible(env, site, checkInner)
386                &&
387                sym.isInheritedIn(site.tsym, types)
388                &&
389                notOverriddenIn(site, sym);
390        case PROTECTED:
391            return
392                (env.toplevel.packge == sym.owner.owner // fast special case
393                 ||
394                 env.toplevel.packge == sym.packge()
395                 ||
396                 isProtectedAccessible(sym, env.enclClass.sym, site)
397                 ||
398                 // OK to select instance method or field from 'super' or type name
399                 // (but type names should be disallowed elsewhere!)
400                 env.info.selectSuper && (sym.flags() & STATIC) == 0 && sym.kind != TYP)
401                &&
402                isAccessible(env, site, checkInner)
403                &&
404                notOverriddenIn(site, sym);
405        default: // this case includes erroneous combinations as well
406            return isAccessible(env, site, checkInner) && notOverriddenIn(site, sym);
407        }
408    }
409    //where
410    /* `sym' is accessible only if not overridden by
411     * another symbol which is a member of `site'
412     * (because, if it is overridden, `sym' is not strictly
413     * speaking a member of `site'). A polymorphic signature method
414     * cannot be overridden (e.g. MH.invokeExact(Object[])).
415     */
416    private boolean notOverriddenIn(Type site, Symbol sym) {
417        if (sym.kind != MTH || sym.isConstructor() || sym.isStatic())
418            return true;
419        else {
420            Symbol s2 = ((MethodSymbol)sym).implementation(site.tsym, types, true);
421            return (s2 == null || s2 == sym || sym.owner == s2.owner ||
422                    !types.isSubSignature(types.memberType(site, s2), types.memberType(site, sym)));
423        }
424    }
425    //where
426        /** Is given protected symbol accessible if it is selected from given site
427         *  and the selection takes place in given class?
428         *  @param sym     The symbol with protected access
429         *  @param c       The class where the access takes place
430         *  @site          The type of the qualifier
431         */
432        private
433        boolean isProtectedAccessible(Symbol sym, ClassSymbol c, Type site) {
434            Type newSite = site.hasTag(TYPEVAR) ? site.getUpperBound() : site;
435            while (c != null &&
436                   !(c.isSubClass(sym.owner, types) &&
437                     (c.flags() & INTERFACE) == 0 &&
438                     // In JLS 2e 6.6.2.1, the subclass restriction applies
439                     // only to instance fields and methods -- types are excluded
440                     // regardless of whether they are declared 'static' or not.
441                     ((sym.flags() & STATIC) != 0 || sym.kind == TYP || newSite.tsym.isSubClass(c, types))))
442                c = c.owner.enclClass();
443            return c != null;
444        }
445
446    /**
447     * Performs a recursive scan of a type looking for accessibility problems
448     * from current attribution environment
449     */
450    void checkAccessibleType(Env<AttrContext> env, Type t) {
451        accessibilityChecker.visit(t, env);
452    }
453
454    /**
455     * Accessibility type-visitor
456     */
457    Types.SimpleVisitor<Void, Env<AttrContext>> accessibilityChecker =
458            new Types.SimpleVisitor<Void, Env<AttrContext>>() {
459
460        void visit(List<Type> ts, Env<AttrContext> env) {
461            for (Type t : ts) {
462                visit(t, env);
463            }
464        }
465
466        public Void visitType(Type t, Env<AttrContext> env) {
467            return null;
468        }
469
470        @Override
471        public Void visitArrayType(ArrayType t, Env<AttrContext> env) {
472            visit(t.elemtype, env);
473            return null;
474        }
475
476        @Override
477        public Void visitClassType(ClassType t, Env<AttrContext> env) {
478            visit(t.getTypeArguments(), env);
479            if (!isAccessible(env, t, true)) {
480                accessBase(new AccessError(t.tsym), env.tree.pos(), env.enclClass.sym, t, t.tsym.name, true);
481            }
482            return null;
483        }
484
485        @Override
486        public Void visitWildcardType(WildcardType t, Env<AttrContext> env) {
487            visit(t.type, env);
488            return null;
489        }
490
491        @Override
492        public Void visitMethodType(MethodType t, Env<AttrContext> env) {
493            visit(t.getParameterTypes(), env);
494            visit(t.getReturnType(), env);
495            visit(t.getThrownTypes(), env);
496            return null;
497        }
498    };
499
500    /** Try to instantiate the type of a method so that it fits
501     *  given type arguments and argument types. If successful, return
502     *  the method's instantiated type, else return null.
503     *  The instantiation will take into account an additional leading
504     *  formal parameter if the method is an instance method seen as a member
505     *  of an under determined site. In this case, we treat site as an additional
506     *  parameter and the parameters of the class containing the method as
507     *  additional type variables that get instantiated.
508     *
509     *  @param env         The current environment
510     *  @param site        The type of which the method is a member.
511     *  @param m           The method symbol.
512     *  @param argtypes    The invocation's given value arguments.
513     *  @param typeargtypes    The invocation's given type arguments.
514     *  @param allowBoxing Allow boxing conversions of arguments.
515     *  @param useVarargs Box trailing arguments into an array for varargs.
516     */
517    Type rawInstantiate(Env<AttrContext> env,
518                        Type site,
519                        Symbol m,
520                        ResultInfo resultInfo,
521                        List<Type> argtypes,
522                        List<Type> typeargtypes,
523                        boolean allowBoxing,
524                        boolean useVarargs,
525                        Warner warn) throws Infer.InferenceException {
526        Type mt = types.memberType(site, m);
527        // tvars is the list of formal type variables for which type arguments
528        // need to inferred.
529        List<Type> tvars = List.nil();
530        if (typeargtypes == null) typeargtypes = List.nil();
531        if (!mt.hasTag(FORALL) && typeargtypes.nonEmpty()) {
532            // This is not a polymorphic method, but typeargs are supplied
533            // which is fine, see JLS 15.12.2.1
534        } else if (mt.hasTag(FORALL) && typeargtypes.nonEmpty()) {
535            ForAll pmt = (ForAll) mt;
536            if (typeargtypes.length() != pmt.tvars.length())
537                throw inapplicableMethodException.setMessage("arg.length.mismatch"); // not enough args
538            // Check type arguments are within bounds
539            List<Type> formals = pmt.tvars;
540            List<Type> actuals = typeargtypes;
541            while (formals.nonEmpty() && actuals.nonEmpty()) {
542                List<Type> bounds = types.subst(types.getBounds((TypeVar)formals.head),
543                                                pmt.tvars, typeargtypes);
544                for (; bounds.nonEmpty(); bounds = bounds.tail) {
545                    if (!types.isSubtypeUnchecked(actuals.head, bounds.head, warn))
546                        throw inapplicableMethodException.setMessage("explicit.param.do.not.conform.to.bounds",actuals.head, bounds);
547                }
548                formals = formals.tail;
549                actuals = actuals.tail;
550            }
551            mt = types.subst(pmt.qtype, pmt.tvars, typeargtypes);
552        } else if (mt.hasTag(FORALL)) {
553            ForAll pmt = (ForAll) mt;
554            List<Type> tvars1 = types.newInstances(pmt.tvars);
555            tvars = tvars.appendList(tvars1);
556            mt = types.subst(pmt.qtype, pmt.tvars, tvars1);
557        }
558
559        // find out whether we need to go the slow route via infer
560        boolean instNeeded = tvars.tail != null; /*inlined: tvars.nonEmpty()*/
561        for (List<Type> l = argtypes;
562             l.tail != null/*inlined: l.nonEmpty()*/ && !instNeeded;
563             l = l.tail) {
564            if (l.head.hasTag(FORALL)) instNeeded = true;
565        }
566
567        if (instNeeded) {
568            return infer.instantiateMethod(env,
569                                    tvars,
570                                    (MethodType)mt,
571                                    resultInfo,
572                                    (MethodSymbol)m,
573                                    argtypes,
574                                    allowBoxing,
575                                    useVarargs,
576                                    currentResolutionContext,
577                                    warn);
578        }
579
580        DeferredAttr.DeferredAttrContext dc = currentResolutionContext.deferredAttrContext(m, infer.emptyContext, resultInfo, warn);
581        currentResolutionContext.methodCheck.argumentsAcceptable(env, dc,
582                                argtypes, mt.getParameterTypes(), warn);
583        dc.complete();
584        return mt;
585    }
586
587    Type checkMethod(Env<AttrContext> env,
588                     Type site,
589                     Symbol m,
590                     ResultInfo resultInfo,
591                     List<Type> argtypes,
592                     List<Type> typeargtypes,
593                     Warner warn) {
594        MethodResolutionContext prevContext = currentResolutionContext;
595        try {
596            currentResolutionContext = new MethodResolutionContext();
597            currentResolutionContext.attrMode = DeferredAttr.AttrMode.CHECK;
598            if (env.tree.hasTag(JCTree.Tag.REFERENCE)) {
599                //method/constructor references need special check class
600                //to handle inference variables in 'argtypes' (might happen
601                //during an unsticking round)
602                currentResolutionContext.methodCheck =
603                        new MethodReferenceCheck(resultInfo.checkContext.inferenceContext());
604            }
605            MethodResolutionPhase step = currentResolutionContext.step = env.info.pendingResolutionPhase;
606            return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
607                    step.isBoxingRequired(), step.isVarargsRequired(), warn);
608        }
609        finally {
610            currentResolutionContext = prevContext;
611        }
612    }
613
614    /** Same but returns null instead throwing a NoInstanceException
615     */
616    Type instantiate(Env<AttrContext> env,
617                     Type site,
618                     Symbol m,
619                     ResultInfo resultInfo,
620                     List<Type> argtypes,
621                     List<Type> typeargtypes,
622                     boolean allowBoxing,
623                     boolean useVarargs,
624                     Warner warn) {
625        try {
626            return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
627                                  allowBoxing, useVarargs, warn);
628        } catch (InapplicableMethodException ex) {
629            return null;
630        }
631    }
632
633    /**
634     * This interface defines an entry point that should be used to perform a
635     * method check. A method check usually consist in determining as to whether
636     * a set of types (actuals) is compatible with another set of types (formals).
637     * Since the notion of compatibility can vary depending on the circumstances,
638     * this interfaces allows to easily add new pluggable method check routines.
639     */
640    interface MethodCheck {
641        /**
642         * Main method check routine. A method check usually consist in determining
643         * as to whether a set of types (actuals) is compatible with another set of
644         * types (formals). If an incompatibility is found, an unchecked exception
645         * is assumed to be thrown.
646         */
647        void argumentsAcceptable(Env<AttrContext> env,
648                                DeferredAttrContext deferredAttrContext,
649                                List<Type> argtypes,
650                                List<Type> formals,
651                                Warner warn);
652
653        /**
654         * Retrieve the method check object that will be used during a
655         * most specific check.
656         */
657        MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict);
658    }
659
660    /**
661     * Helper enum defining all method check diagnostics (used by resolveMethodCheck).
662     */
663    enum MethodCheckDiag {
664        /**
665         * Actuals and formals differs in length.
666         */
667        ARITY_MISMATCH("arg.length.mismatch", "infer.arg.length.mismatch"),
668        /**
669         * An actual is incompatible with a formal.
670         */
671        ARG_MISMATCH("no.conforming.assignment.exists", "infer.no.conforming.assignment.exists"),
672        /**
673         * An actual is incompatible with the varargs element type.
674         */
675        VARARG_MISMATCH("varargs.argument.mismatch", "infer.varargs.argument.mismatch"),
676        /**
677         * The varargs element type is inaccessible.
678         */
679        INACCESSIBLE_VARARGS("inaccessible.varargs.type", "inaccessible.varargs.type");
680
681        final String basicKey;
682        final String inferKey;
683
684        MethodCheckDiag(String basicKey, String inferKey) {
685            this.basicKey = basicKey;
686            this.inferKey = inferKey;
687        }
688
689        String regex() {
690            return String.format("([a-z]*\\.)*(%s|%s)", basicKey, inferKey);
691        }
692    }
693
694    /**
695     * Dummy method check object. All methods are deemed applicable, regardless
696     * of their formal parameter types.
697     */
698    MethodCheck nilMethodCheck = new MethodCheck() {
699        public void argumentsAcceptable(Env<AttrContext> env, DeferredAttrContext deferredAttrContext, List<Type> argtypes, List<Type> formals, Warner warn) {
700            //do nothing - method always applicable regardless of actuals
701        }
702
703        public MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict) {
704            return this;
705        }
706    };
707
708    /**
709     * Base class for 'real' method checks. The class defines the logic for
710     * iterating through formals and actuals and provides and entry point
711     * that can be used by subclasses in order to define the actual check logic.
712     */
713    abstract class AbstractMethodCheck implements MethodCheck {
714        @Override
715        public void argumentsAcceptable(final Env<AttrContext> env,
716                                    DeferredAttrContext deferredAttrContext,
717                                    List<Type> argtypes,
718                                    List<Type> formals,
719                                    Warner warn) {
720            //should we expand formals?
721            boolean useVarargs = deferredAttrContext.phase.isVarargsRequired();
722            List<JCExpression> trees = TreeInfo.args(env.tree);
723
724            //inference context used during this method check
725            InferenceContext inferenceContext = deferredAttrContext.inferenceContext;
726
727            Type varargsFormal = useVarargs ? formals.last() : null;
728
729            if (varargsFormal == null &&
730                    argtypes.size() != formals.size()) {
731                reportMC(env.tree, MethodCheckDiag.ARITY_MISMATCH, inferenceContext); // not enough args
732            }
733
734            while (argtypes.nonEmpty() && formals.head != varargsFormal) {
735                DiagnosticPosition pos = trees != null ? trees.head : null;
736                checkArg(pos, false, argtypes.head, formals.head, deferredAttrContext, warn);
737                argtypes = argtypes.tail;
738                formals = formals.tail;
739                trees = trees != null ? trees.tail : trees;
740            }
741
742            if (formals.head != varargsFormal) {
743                reportMC(env.tree, MethodCheckDiag.ARITY_MISMATCH, inferenceContext); // not enough args
744            }
745
746            if (useVarargs) {
747                //note: if applicability check is triggered by most specific test,
748                //the last argument of a varargs is _not_ an array type (see JLS 15.12.2.5)
749                final Type elt = types.elemtype(varargsFormal);
750                while (argtypes.nonEmpty()) {
751                    DiagnosticPosition pos = trees != null ? trees.head : null;
752                    checkArg(pos, true, argtypes.head, elt, deferredAttrContext, warn);
753                    argtypes = argtypes.tail;
754                    trees = trees != null ? trees.tail : trees;
755                }
756            }
757        }
758
759        /**
760         * Does the actual argument conforms to the corresponding formal?
761         */
762        abstract void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn);
763
764        protected void reportMC(DiagnosticPosition pos, MethodCheckDiag diag, InferenceContext inferenceContext, Object... args) {
765            boolean inferDiag = inferenceContext != infer.emptyContext;
766            InapplicableMethodException ex = inferDiag ?
767                    infer.inferenceException : inapplicableMethodException;
768            if (inferDiag && (!diag.inferKey.equals(diag.basicKey))) {
769                Object[] args2 = new Object[args.length + 1];
770                System.arraycopy(args, 0, args2, 1, args.length);
771                args2[0] = inferenceContext.inferenceVars();
772                args = args2;
773            }
774            String key = inferDiag ? diag.inferKey : diag.basicKey;
775            throw ex.setMessage(diags.create(DiagnosticType.FRAGMENT, log.currentSource(), pos, key, args));
776        }
777
778        public MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict) {
779            return nilMethodCheck;
780        }
781
782    }
783
784    /**
785     * Arity-based method check. A method is applicable if the number of actuals
786     * supplied conforms to the method signature.
787     */
788    MethodCheck arityMethodCheck = new AbstractMethodCheck() {
789        @Override
790        void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn) {
791            //do nothing - actual always compatible to formals
792        }
793
794        @Override
795        public String toString() {
796            return "arityMethodCheck";
797        }
798    };
799
800    List<Type> dummyArgs(int length) {
801        ListBuffer<Type> buf = new ListBuffer<>();
802        for (int i = 0 ; i < length ; i++) {
803            buf.append(Type.noType);
804        }
805        return buf.toList();
806    }
807
808    /**
809     * Main method applicability routine. Given a list of actual types A,
810     * a list of formal types F, determines whether the types in A are
811     * compatible (by method invocation conversion) with the types in F.
812     *
813     * Since this routine is shared between overload resolution and method
814     * type-inference, a (possibly empty) inference context is used to convert
815     * formal types to the corresponding 'undet' form ahead of a compatibility
816     * check so that constraints can be propagated and collected.
817     *
818     * Moreover, if one or more types in A is a deferred type, this routine uses
819     * DeferredAttr in order to perform deferred attribution. If one or more actual
820     * deferred types are stuck, they are placed in a queue and revisited later
821     * after the remainder of the arguments have been seen. If this is not sufficient
822     * to 'unstuck' the argument, a cyclic inference error is called out.
823     *
824     * A method check handler (see above) is used in order to report errors.
825     */
826    MethodCheck resolveMethodCheck = new AbstractMethodCheck() {
827
828        @Override
829        void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn) {
830            ResultInfo mresult = methodCheckResult(varargs, formal, deferredAttrContext, warn);
831            mresult.check(pos, actual);
832        }
833
834        @Override
835        public void argumentsAcceptable(final Env<AttrContext> env,
836                                    DeferredAttrContext deferredAttrContext,
837                                    List<Type> argtypes,
838                                    List<Type> formals,
839                                    Warner warn) {
840            super.argumentsAcceptable(env, deferredAttrContext, argtypes, formals, warn);
841            //should we expand formals?
842            if (deferredAttrContext.phase.isVarargsRequired()) {
843                Type typeToCheck = null;
844                if (!checkVarargsAccessAfterResolution) {
845                    typeToCheck = types.elemtype(formals.last());
846                } else if (deferredAttrContext.mode == AttrMode.CHECK) {
847                    typeToCheck = types.erasure(types.elemtype(formals.last()));
848                }
849                if (typeToCheck != null) {
850                    varargsAccessible(env, typeToCheck, deferredAttrContext.inferenceContext);
851                }
852            }
853        }
854
855        private void varargsAccessible(final Env<AttrContext> env, final Type t, final InferenceContext inferenceContext) {
856            if (inferenceContext.free(t)) {
857                inferenceContext.addFreeTypeListener(List.of(t), new FreeTypeListener() {
858                    @Override
859                    public void typesInferred(InferenceContext inferenceContext) {
860                        varargsAccessible(env, inferenceContext.asInstType(t), inferenceContext);
861                    }
862                });
863            } else {
864                if (!isAccessible(env, t)) {
865                    Symbol location = env.enclClass.sym;
866                    reportMC(env.tree, MethodCheckDiag.INACCESSIBLE_VARARGS, inferenceContext, t, Kinds.kindName(location), location);
867                }
868            }
869        }
870
871        private ResultInfo methodCheckResult(final boolean varargsCheck, Type to,
872                final DeferredAttr.DeferredAttrContext deferredAttrContext, Warner rsWarner) {
873            CheckContext checkContext = new MethodCheckContext(!deferredAttrContext.phase.isBoxingRequired(), deferredAttrContext, rsWarner) {
874                MethodCheckDiag methodDiag = varargsCheck ?
875                                 MethodCheckDiag.VARARG_MISMATCH : MethodCheckDiag.ARG_MISMATCH;
876
877                @Override
878                public void report(DiagnosticPosition pos, JCDiagnostic details) {
879                    reportMC(pos, methodDiag, deferredAttrContext.inferenceContext, details);
880                }
881            };
882            return new MethodResultInfo(to, checkContext);
883        }
884
885        @Override
886        public MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict) {
887            return new MostSpecificCheck(strict, actuals);
888        }
889
890        @Override
891        public String toString() {
892            return "resolveMethodCheck";
893        }
894    };
895
896    /**
897     * This class handles method reference applicability checks; since during
898     * these checks it's sometime possible to have inference variables on
899     * the actual argument types list, the method applicability check must be
900     * extended so that inference variables are 'opened' as needed.
901     */
902    class MethodReferenceCheck extends AbstractMethodCheck {
903
904        InferenceContext pendingInferenceContext;
905
906        MethodReferenceCheck(InferenceContext pendingInferenceContext) {
907            this.pendingInferenceContext = pendingInferenceContext;
908        }
909
910        @Override
911        void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn) {
912            ResultInfo mresult = methodCheckResult(varargs, formal, deferredAttrContext, warn);
913            mresult.check(pos, actual);
914        }
915
916        private ResultInfo methodCheckResult(final boolean varargsCheck, Type to,
917                final DeferredAttr.DeferredAttrContext deferredAttrContext, Warner rsWarner) {
918            CheckContext checkContext = new MethodCheckContext(!deferredAttrContext.phase.isBoxingRequired(), deferredAttrContext, rsWarner) {
919                MethodCheckDiag methodDiag = varargsCheck ?
920                                 MethodCheckDiag.VARARG_MISMATCH : MethodCheckDiag.ARG_MISMATCH;
921
922                @Override
923                public boolean compatible(Type found, Type req, Warner warn) {
924                    found = pendingInferenceContext.asUndetVar(found);
925                    if (found.hasTag(UNDETVAR) && req.isPrimitive()) {
926                        req = types.boxedClass(req).type;
927                    }
928                    return super.compatible(found, req, warn);
929                }
930
931                @Override
932                public void report(DiagnosticPosition pos, JCDiagnostic details) {
933                    reportMC(pos, methodDiag, deferredAttrContext.inferenceContext, details);
934                }
935            };
936            return new MethodResultInfo(to, checkContext);
937        }
938
939        @Override
940        public MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict) {
941            return new MostSpecificCheck(strict, actuals);
942        }
943
944        @Override
945        public String toString() {
946            return "MethodReferenceCheck";
947        }
948    }
949
950    /**
951     * Check context to be used during method applicability checks. A method check
952     * context might contain inference variables.
953     */
954    abstract class MethodCheckContext implements CheckContext {
955
956        boolean strict;
957        DeferredAttrContext deferredAttrContext;
958        Warner rsWarner;
959
960        public MethodCheckContext(boolean strict, DeferredAttrContext deferredAttrContext, Warner rsWarner) {
961           this.strict = strict;
962           this.deferredAttrContext = deferredAttrContext;
963           this.rsWarner = rsWarner;
964        }
965
966        public boolean compatible(Type found, Type req, Warner warn) {
967            InferenceContext inferenceContext = deferredAttrContext.inferenceContext;
968            return strict ?
969                    types.isSubtypeUnchecked(inferenceContext.asUndetVar(found), inferenceContext.asUndetVar(req), warn) :
970                    types.isConvertible(inferenceContext.asUndetVar(found), inferenceContext.asUndetVar(req), warn);
971        }
972
973        public void report(DiagnosticPosition pos, JCDiagnostic details) {
974            throw inapplicableMethodException.setMessage(details);
975        }
976
977        public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
978            return rsWarner;
979        }
980
981        public InferenceContext inferenceContext() {
982            return deferredAttrContext.inferenceContext;
983        }
984
985        public DeferredAttrContext deferredAttrContext() {
986            return deferredAttrContext;
987        }
988
989        @Override
990        public String toString() {
991            return "MethodCheckContext";
992        }
993    }
994
995    /**
996     * ResultInfo class to be used during method applicability checks. Check
997     * for deferred types goes through special path.
998     */
999    class MethodResultInfo extends ResultInfo {
1000
1001        public MethodResultInfo(Type pt, CheckContext checkContext) {
1002            attr.super(KindSelector.VAL, pt, checkContext);
1003        }
1004
1005        @Override
1006        protected Type check(DiagnosticPosition pos, Type found) {
1007            if (found.hasTag(DEFERRED)) {
1008                DeferredType dt = (DeferredType)found;
1009                return dt.check(this);
1010            } else {
1011                Type uResult = U(found.baseType());
1012                Type capturedType = pos == null || pos.getTree() == null ?
1013                        types.capture(uResult) :
1014                        checkContext.inferenceContext()
1015                            .cachedCapture(pos.getTree(), uResult, true);
1016                return super.check(pos, chk.checkNonVoid(pos, capturedType));
1017            }
1018        }
1019
1020        /**
1021         * javac has a long-standing 'simplification' (see 6391995):
1022         * given an actual argument type, the method check is performed
1023         * on its upper bound. This leads to inconsistencies when an
1024         * argument type is checked against itself. For example, given
1025         * a type-variable T, it is not true that {@code U(T) <: T},
1026         * so we need to guard against that.
1027         */
1028        private Type U(Type found) {
1029            return found == pt ?
1030                    found : types.cvarUpperBound(found);
1031        }
1032
1033        @Override
1034        protected MethodResultInfo dup(Type newPt) {
1035            return new MethodResultInfo(newPt, checkContext);
1036        }
1037
1038        @Override
1039        protected ResultInfo dup(CheckContext newContext) {
1040            return new MethodResultInfo(pt, newContext);
1041        }
1042    }
1043
1044    /**
1045     * Most specific method applicability routine. Given a list of actual types A,
1046     * a list of formal types F1, and a list of formal types F2, the routine determines
1047     * as to whether the types in F1 can be considered more specific than those in F2 w.r.t.
1048     * argument types A.
1049     */
1050    class MostSpecificCheck implements MethodCheck {
1051
1052        boolean strict;
1053        List<Type> actuals;
1054
1055        MostSpecificCheck(boolean strict, List<Type> actuals) {
1056            this.strict = strict;
1057            this.actuals = actuals;
1058        }
1059
1060        @Override
1061        public void argumentsAcceptable(final Env<AttrContext> env,
1062                                    DeferredAttrContext deferredAttrContext,
1063                                    List<Type> formals1,
1064                                    List<Type> formals2,
1065                                    Warner warn) {
1066            formals2 = adjustArgs(formals2, deferredAttrContext.msym, formals1.length(), deferredAttrContext.phase.isVarargsRequired());
1067            while (formals2.nonEmpty()) {
1068                ResultInfo mresult = methodCheckResult(formals2.head, deferredAttrContext, warn, actuals.head);
1069                mresult.check(null, formals1.head);
1070                formals1 = formals1.tail;
1071                formals2 = formals2.tail;
1072                actuals = actuals.isEmpty() ? actuals : actuals.tail;
1073            }
1074        }
1075
1076       /**
1077        * Create a method check context to be used during the most specific applicability check
1078        */
1079        ResultInfo methodCheckResult(Type to, DeferredAttr.DeferredAttrContext deferredAttrContext,
1080               Warner rsWarner, Type actual) {
1081            return attr.new ResultInfo(KindSelector.VAL, to,
1082                   new MostSpecificCheckContext(strict, deferredAttrContext, rsWarner, actual));
1083        }
1084
1085        /**
1086         * Subclass of method check context class that implements most specific
1087         * method conversion. If the actual type under analysis is a deferred type
1088         * a full blown structural analysis is carried out.
1089         */
1090        class MostSpecificCheckContext extends MethodCheckContext {
1091
1092            Type actual;
1093
1094            public MostSpecificCheckContext(boolean strict, DeferredAttrContext deferredAttrContext, Warner rsWarner, Type actual) {
1095                super(strict, deferredAttrContext, rsWarner);
1096                this.actual = actual;
1097            }
1098
1099            public boolean compatible(Type found, Type req, Warner warn) {
1100                if (allowFunctionalInterfaceMostSpecific &&
1101                        unrelatedFunctionalInterfaces(found, req) &&
1102                        (actual != null && actual.getTag() == DEFERRED)) {
1103                    DeferredType dt = (DeferredType) actual;
1104                    DeferredType.SpeculativeCache.Entry e =
1105                            dt.speculativeCache.get(deferredAttrContext.msym, deferredAttrContext.phase);
1106                    if (e != null && e.speculativeTree != deferredAttr.stuckTree) {
1107                        return functionalInterfaceMostSpecific(found, req, e.speculativeTree, warn);
1108                    }
1109                }
1110                return super.compatible(found, req, warn);
1111            }
1112
1113            /** Whether {@code t} and {@code s} are unrelated functional interface types. */
1114            private boolean unrelatedFunctionalInterfaces(Type t, Type s) {
1115                return types.isFunctionalInterface(t.tsym) &&
1116                       types.isFunctionalInterface(s.tsym) &&
1117                       types.asSuper(t, s.tsym) == null &&
1118                       types.asSuper(s, t.tsym) == null;
1119            }
1120
1121            /** Parameters {@code t} and {@code s} are unrelated functional interface types. */
1122            private boolean functionalInterfaceMostSpecific(Type t, Type s, JCTree tree, Warner warn) {
1123                FunctionalInterfaceMostSpecificChecker msc = new FunctionalInterfaceMostSpecificChecker(t, s, warn);
1124                msc.scan(tree);
1125                return msc.result;
1126            }
1127
1128            /**
1129             * Tests whether one functional interface type can be considered more specific
1130             * than another unrelated functional interface type for the scanned expression.
1131             */
1132            class FunctionalInterfaceMostSpecificChecker extends DeferredAttr.PolyScanner {
1133
1134                final Type t;
1135                final Type s;
1136                final Warner warn;
1137                boolean result;
1138
1139                /** Parameters {@code t} and {@code s} are unrelated functional interface types. */
1140                FunctionalInterfaceMostSpecificChecker(Type t, Type s, Warner warn) {
1141                    this.t = t;
1142                    this.s = s;
1143                    this.warn = warn;
1144                    result = true;
1145                }
1146
1147                @Override
1148                void skip(JCTree tree) {
1149                    result &= false;
1150                }
1151
1152                @Override
1153                public void visitConditional(JCConditional tree) {
1154                    scan(tree.truepart);
1155                    scan(tree.falsepart);
1156                }
1157
1158                @Override
1159                public void visitReference(JCMemberReference tree) {
1160                    Type desc_t = types.findDescriptorType(t);
1161                    Type desc_s = types.findDescriptorType(s);
1162                    // use inference variables here for more-specific inference (18.5.4)
1163                    if (!types.isSameTypes(desc_t.getParameterTypes(),
1164                            inferenceContext().asUndetVars(desc_s.getParameterTypes()))) {
1165                        result &= false;
1166                    } else {
1167                        // compare return types
1168                        Type ret_t = desc_t.getReturnType();
1169                        Type ret_s = desc_s.getReturnType();
1170                        if (ret_s.hasTag(VOID)) {
1171                            result &= true;
1172                        } else if (ret_t.hasTag(VOID)) {
1173                            result &= false;
1174                        } else if (ret_t.isPrimitive() != ret_s.isPrimitive()) {
1175                            boolean retValIsPrimitive =
1176                                    tree.refPolyKind == PolyKind.STANDALONE &&
1177                                    tree.sym.type.getReturnType().isPrimitive();
1178                            result &= (retValIsPrimitive == ret_t.isPrimitive()) &&
1179                                      (retValIsPrimitive != ret_s.isPrimitive());
1180                        } else {
1181                            result &= MostSpecificCheckContext.super.compatible(ret_t, ret_s, warn);
1182                        }
1183                    }
1184                }
1185
1186                @Override
1187                public void visitLambda(JCLambda tree) {
1188                    Type desc_t = types.findDescriptorType(t);
1189                    Type desc_s = types.findDescriptorType(s);
1190                    // use inference variables here for more-specific inference (18.5.4)
1191                    if (!types.isSameTypes(desc_t.getParameterTypes(),
1192                            inferenceContext().asUndetVars(desc_s.getParameterTypes()))) {
1193                        result &= false;
1194                    } else {
1195                        // compare return types
1196                        Type ret_t = desc_t.getReturnType();
1197                        Type ret_s = desc_s.getReturnType();
1198                        if (ret_s.hasTag(VOID)) {
1199                            result &= true;
1200                        } else if (ret_t.hasTag(VOID)) {
1201                            result &= false;
1202                        } else if (unrelatedFunctionalInterfaces(ret_t, ret_s)) {
1203                            for (JCExpression expr : lambdaResults(tree)) {
1204                                result &= functionalInterfaceMostSpecific(ret_t, ret_s, expr, warn);
1205                            }
1206                        } else if (ret_t.isPrimitive() != ret_s.isPrimitive()) {
1207                            for (JCExpression expr : lambdaResults(tree)) {
1208                                boolean retValIsPrimitive = expr.isStandalone() && expr.type.isPrimitive();
1209                                result &= (retValIsPrimitive == ret_t.isPrimitive()) &&
1210                                          (retValIsPrimitive != ret_s.isPrimitive());
1211                            }
1212                        } else {
1213                            result &= MostSpecificCheckContext.super.compatible(ret_t, ret_s, warn);
1214                        }
1215                    }
1216                }
1217                //where
1218
1219                private List<JCExpression> lambdaResults(JCLambda lambda) {
1220                    if (lambda.getBodyKind() == JCTree.JCLambda.BodyKind.EXPRESSION) {
1221                        return List.of((JCExpression) lambda.body);
1222                    } else {
1223                        final ListBuffer<JCExpression> buffer = new ListBuffer<>();
1224                        DeferredAttr.LambdaReturnScanner lambdaScanner =
1225                                new DeferredAttr.LambdaReturnScanner() {
1226                                    @Override
1227                                    public void visitReturn(JCReturn tree) {
1228                                        if (tree.expr != null) {
1229                                            buffer.append(tree.expr);
1230                                        }
1231                                    }
1232                                };
1233                        lambdaScanner.scan(lambda.body);
1234                        return buffer.toList();
1235                    }
1236                }
1237            }
1238
1239        }
1240
1241        public MethodCheck mostSpecificCheck(List<Type> actuals, boolean strict) {
1242            Assert.error("Cannot get here!");
1243            return null;
1244        }
1245    }
1246
1247    public static class InapplicableMethodException extends RuntimeException {
1248        private static final long serialVersionUID = 0;
1249
1250        JCDiagnostic diagnostic;
1251        JCDiagnostic.Factory diags;
1252
1253        InapplicableMethodException(JCDiagnostic.Factory diags) {
1254            this.diagnostic = null;
1255            this.diags = diags;
1256        }
1257        InapplicableMethodException setMessage() {
1258            return setMessage((JCDiagnostic)null);
1259        }
1260        InapplicableMethodException setMessage(String key) {
1261            return setMessage(key != null ? diags.fragment(key) : null);
1262        }
1263        InapplicableMethodException setMessage(String key, Object... args) {
1264            return setMessage(key != null ? diags.fragment(key, args) : null);
1265        }
1266        InapplicableMethodException setMessage(JCDiagnostic diag) {
1267            this.diagnostic = diag;
1268            return this;
1269        }
1270
1271        public JCDiagnostic getDiagnostic() {
1272            return diagnostic;
1273        }
1274    }
1275    private final InapplicableMethodException inapplicableMethodException;
1276
1277/* ***************************************************************************
1278 *  Symbol lookup
1279 *  the following naming conventions for arguments are used
1280 *
1281 *       env      is the environment where the symbol was mentioned
1282 *       site     is the type of which the symbol is a member
1283 *       name     is the symbol's name
1284 *                if no arguments are given
1285 *       argtypes are the value arguments, if we search for a method
1286 *
1287 *  If no symbol was found, a ResolveError detailing the problem is returned.
1288 ****************************************************************************/
1289
1290    /** Find field. Synthetic fields are always skipped.
1291     *  @param env     The current environment.
1292     *  @param site    The original type from where the selection takes place.
1293     *  @param name    The name of the field.
1294     *  @param c       The class to search for the field. This is always
1295     *                 a superclass or implemented interface of site's class.
1296     */
1297    Symbol findField(Env<AttrContext> env,
1298                     Type site,
1299                     Name name,
1300                     TypeSymbol c) {
1301        while (c.type.hasTag(TYPEVAR))
1302            c = c.type.getUpperBound().tsym;
1303        Symbol bestSoFar = varNotFound;
1304        Symbol sym;
1305        for (Symbol s : c.members().getSymbolsByName(name)) {
1306            if (s.kind == VAR && (s.flags_field & SYNTHETIC) == 0) {
1307                return isAccessible(env, site, s)
1308                    ? s : new AccessError(env, site, s);
1309            }
1310        }
1311        Type st = types.supertype(c.type);
1312        if (st != null && (st.hasTag(CLASS) || st.hasTag(TYPEVAR))) {
1313            sym = findField(env, site, name, st.tsym);
1314            bestSoFar = bestOf(bestSoFar, sym);
1315        }
1316        for (List<Type> l = types.interfaces(c.type);
1317             bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
1318             l = l.tail) {
1319            sym = findField(env, site, name, l.head.tsym);
1320            if (bestSoFar.exists() && sym.exists() &&
1321                sym.owner != bestSoFar.owner)
1322                bestSoFar = new AmbiguityError(bestSoFar, sym);
1323            else
1324                bestSoFar = bestOf(bestSoFar, sym);
1325        }
1326        return bestSoFar;
1327    }
1328
1329    /** Resolve a field identifier, throw a fatal error if not found.
1330     *  @param pos       The position to use for error reporting.
1331     *  @param env       The environment current at the method invocation.
1332     *  @param site      The type of the qualifying expression, in which
1333     *                   identifier is searched.
1334     *  @param name      The identifier's name.
1335     */
1336    public VarSymbol resolveInternalField(DiagnosticPosition pos, Env<AttrContext> env,
1337                                          Type site, Name name) {
1338        Symbol sym = findField(env, site, name, site.tsym);
1339        if (sym.kind == VAR) return (VarSymbol)sym;
1340        else throw new FatalError(
1341                 diags.fragment("fatal.err.cant.locate.field",
1342                                name));
1343    }
1344
1345    /** Find unqualified variable or field with given name.
1346     *  Synthetic fields always skipped.
1347     *  @param env     The current environment.
1348     *  @param name    The name of the variable or field.
1349     */
1350    Symbol findVar(Env<AttrContext> env, Name name) {
1351        Symbol bestSoFar = varNotFound;
1352        Env<AttrContext> env1 = env;
1353        boolean staticOnly = false;
1354        while (env1.outer != null) {
1355            Symbol sym = null;
1356            if (isStatic(env1)) staticOnly = true;
1357            for (Symbol s : env1.info.scope.getSymbolsByName(name)) {
1358                if (s.kind == VAR && (s.flags_field & SYNTHETIC) == 0) {
1359                    sym = s;
1360                    break;
1361                }
1362            }
1363            if (sym == null) {
1364                sym = findField(env1, env1.enclClass.sym.type, name, env1.enclClass.sym);
1365            }
1366            if (sym.exists()) {
1367                if (staticOnly &&
1368                    sym.kind == VAR &&
1369                    sym.owner.kind == TYP &&
1370                    (sym.flags() & STATIC) == 0)
1371                    return new StaticError(sym);
1372                else
1373                    return sym;
1374            } else {
1375                bestSoFar = bestOf(bestSoFar, sym);
1376            }
1377
1378            if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
1379            env1 = env1.outer;
1380        }
1381
1382        Symbol sym = findField(env, syms.predefClass.type, name, syms.predefClass);
1383        if (sym.exists())
1384            return sym;
1385        if (bestSoFar.exists())
1386            return bestSoFar;
1387
1388        Symbol origin = null;
1389        for (Scope sc : new Scope[] { env.toplevel.namedImportScope, env.toplevel.starImportScope }) {
1390            for (Symbol currentSymbol : sc.getSymbolsByName(name)) {
1391                if (currentSymbol.kind != VAR)
1392                    continue;
1393                // invariant: sym.kind == Symbol.Kind.VAR
1394                if (!bestSoFar.kind.isOverloadError() &&
1395                    currentSymbol.owner != bestSoFar.owner)
1396                    return new AmbiguityError(bestSoFar, currentSymbol);
1397                else if (!bestSoFar.kind.betterThan(VAR)) {
1398                    origin = sc.getOrigin(currentSymbol).owner;
1399                    bestSoFar = isAccessible(env, origin.type, currentSymbol)
1400                        ? currentSymbol : new AccessError(env, origin.type, currentSymbol);
1401                }
1402            }
1403            if (bestSoFar.exists()) break;
1404        }
1405        if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type)
1406            return bestSoFar.clone(origin);
1407        else
1408            return bestSoFar;
1409    }
1410
1411    Warner noteWarner = new Warner();
1412
1413    /** Select the best method for a call site among two choices.
1414     *  @param env              The current environment.
1415     *  @param site             The original type from where the
1416     *                          selection takes place.
1417     *  @param argtypes         The invocation's value arguments,
1418     *  @param typeargtypes     The invocation's type arguments,
1419     *  @param sym              Proposed new best match.
1420     *  @param bestSoFar        Previously found best match.
1421     *  @param allowBoxing Allow boxing conversions of arguments.
1422     *  @param useVarargs Box trailing arguments into an array for varargs.
1423     */
1424    @SuppressWarnings("fallthrough")
1425    Symbol selectBest(Env<AttrContext> env,
1426                      Type site,
1427                      List<Type> argtypes,
1428                      List<Type> typeargtypes,
1429                      Symbol sym,
1430                      Symbol bestSoFar,
1431                      boolean allowBoxing,
1432                      boolean useVarargs,
1433                      boolean operator) {
1434        if (sym.kind == ERR ||
1435                !sym.isInheritedIn(site.tsym, types)) {
1436            return bestSoFar;
1437        } else if (useVarargs && (sym.flags() & VARARGS) == 0) {
1438            return bestSoFar.kind.isOverloadError() ?
1439                    new BadVarargsMethod((ResolveError)bestSoFar.baseSymbol()) :
1440                    bestSoFar;
1441        }
1442        Assert.check(!sym.kind.isOverloadError());
1443        try {
1444            Type mt = rawInstantiate(env, site, sym, null, argtypes, typeargtypes,
1445                               allowBoxing, useVarargs, types.noWarnings);
1446            if (!operator || verboseResolutionMode.contains(VerboseResolutionMode.PREDEF))
1447                currentResolutionContext.addApplicableCandidate(sym, mt);
1448        } catch (InapplicableMethodException ex) {
1449            if (!operator)
1450                currentResolutionContext.addInapplicableCandidate(sym, ex.getDiagnostic());
1451            switch (bestSoFar.kind) {
1452                case ABSENT_MTH:
1453                    return new InapplicableSymbolError(currentResolutionContext);
1454                case WRONG_MTH:
1455                    if (operator) return bestSoFar;
1456                    bestSoFar = new InapplicableSymbolsError(currentResolutionContext);
1457                default:
1458                    return bestSoFar;
1459            }
1460        }
1461        if (!isAccessible(env, site, sym)) {
1462            return (bestSoFar.kind == ABSENT_MTH)
1463                ? new AccessError(env, site, sym)
1464                : bestSoFar;
1465        }
1466        return (bestSoFar.kind.isOverloadError() && bestSoFar.kind != AMBIGUOUS)
1467            ? sym
1468            : mostSpecific(argtypes, sym, bestSoFar, env, site,
1469                           allowBoxing && operator, useVarargs);
1470    }
1471
1472    /* Return the most specific of the two methods for a call,
1473     *  given that both are accessible and applicable.
1474     *  @param m1               A new candidate for most specific.
1475     *  @param m2               The previous most specific candidate.
1476     *  @param env              The current environment.
1477     *  @param site             The original type from where the selection
1478     *                          takes place.
1479     *  @param allowBoxing Allow boxing conversions of arguments.
1480     *  @param useVarargs Box trailing arguments into an array for varargs.
1481     */
1482    Symbol mostSpecific(List<Type> argtypes, Symbol m1,
1483                        Symbol m2,
1484                        Env<AttrContext> env,
1485                        final Type site,
1486                        boolean allowBoxing,
1487                        boolean useVarargs) {
1488        switch (m2.kind) {
1489        case MTH:
1490            if (m1 == m2) return m1;
1491            boolean m1SignatureMoreSpecific =
1492                    signatureMoreSpecific(argtypes, env, site, m1, m2, allowBoxing, useVarargs);
1493            boolean m2SignatureMoreSpecific =
1494                    signatureMoreSpecific(argtypes, env, site, m2, m1, allowBoxing, useVarargs);
1495            if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) {
1496                Type mt1 = types.memberType(site, m1);
1497                Type mt2 = types.memberType(site, m2);
1498                if (!types.overrideEquivalent(mt1, mt2))
1499                    return ambiguityError(m1, m2);
1500
1501                // same signature; select (a) the non-bridge method, or
1502                // (b) the one that overrides the other, or (c) the concrete
1503                // one, or (d) merge both abstract signatures
1504                if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE))
1505                    return ((m1.flags() & BRIDGE) != 0) ? m2 : m1;
1506
1507                // if one overrides or hides the other, use it
1508                TypeSymbol m1Owner = (TypeSymbol)m1.owner;
1509                TypeSymbol m2Owner = (TypeSymbol)m2.owner;
1510                if (types.asSuper(m1Owner.type, m2Owner) != null &&
1511                    ((m1.owner.flags_field & INTERFACE) == 0 ||
1512                     (m2.owner.flags_field & INTERFACE) != 0) &&
1513                    m1.overrides(m2, m1Owner, types, false))
1514                    return m1;
1515                if (types.asSuper(m2Owner.type, m1Owner) != null &&
1516                    ((m2.owner.flags_field & INTERFACE) == 0 ||
1517                     (m1.owner.flags_field & INTERFACE) != 0) &&
1518                    m2.overrides(m1, m2Owner, types, false))
1519                    return m2;
1520                boolean m1Abstract = (m1.flags() & ABSTRACT) != 0;
1521                boolean m2Abstract = (m2.flags() & ABSTRACT) != 0;
1522                if (m1Abstract && !m2Abstract) return m2;
1523                if (m2Abstract && !m1Abstract) return m1;
1524                // both abstract or both concrete
1525                return ambiguityError(m1, m2);
1526            }
1527            if (m1SignatureMoreSpecific) return m1;
1528            if (m2SignatureMoreSpecific) return m2;
1529            return ambiguityError(m1, m2);
1530        case AMBIGUOUS:
1531            //compare m1 to ambiguous methods in m2
1532            AmbiguityError e = (AmbiguityError)m2.baseSymbol();
1533            boolean m1MoreSpecificThanAnyAmbiguous = true;
1534            boolean allAmbiguousMoreSpecificThanM1 = true;
1535            for (Symbol s : e.ambiguousSyms) {
1536                Symbol moreSpecific = mostSpecific(argtypes, m1, s, env, site, allowBoxing, useVarargs);
1537                m1MoreSpecificThanAnyAmbiguous &= moreSpecific == m1;
1538                allAmbiguousMoreSpecificThanM1 &= moreSpecific == s;
1539            }
1540            if (m1MoreSpecificThanAnyAmbiguous)
1541                return m1;
1542            //if m1 is more specific than some ambiguous methods, but other ambiguous methods are
1543            //more specific than m1, add it as a new ambiguous method:
1544            if (!allAmbiguousMoreSpecificThanM1)
1545                e.addAmbiguousSymbol(m1);
1546            return e;
1547        default:
1548            throw new AssertionError();
1549        }
1550    }
1551    //where
1552    private boolean signatureMoreSpecific(List<Type> actuals, Env<AttrContext> env, Type site, Symbol m1, Symbol m2, boolean allowBoxing, boolean useVarargs) {
1553        noteWarner.clear();
1554        int maxLength = Math.max(
1555                            Math.max(m1.type.getParameterTypes().length(), actuals.length()),
1556                            m2.type.getParameterTypes().length());
1557        MethodResolutionContext prevResolutionContext = currentResolutionContext;
1558        try {
1559            currentResolutionContext = new MethodResolutionContext();
1560            currentResolutionContext.step = prevResolutionContext.step;
1561            currentResolutionContext.methodCheck =
1562                    prevResolutionContext.methodCheck.mostSpecificCheck(actuals, !allowBoxing);
1563            Type mst = instantiate(env, site, m2, null,
1564                    adjustArgs(types.cvarLowerBounds(types.memberType(site, m1).getParameterTypes()), m1, maxLength, useVarargs), null,
1565                    allowBoxing, useVarargs, noteWarner);
1566            return mst != null &&
1567                    !noteWarner.hasLint(Lint.LintCategory.UNCHECKED);
1568        } finally {
1569            currentResolutionContext = prevResolutionContext;
1570        }
1571    }
1572
1573    List<Type> adjustArgs(List<Type> args, Symbol msym, int length, boolean allowVarargs) {
1574        if ((msym.flags() & VARARGS) != 0 && allowVarargs) {
1575            Type varargsElem = types.elemtype(args.last());
1576            if (varargsElem == null) {
1577                Assert.error("Bad varargs = " + args.last() + " " + msym);
1578            }
1579            List<Type> newArgs = args.reverse().tail.prepend(varargsElem).reverse();
1580            while (newArgs.length() < length) {
1581                newArgs = newArgs.append(newArgs.last());
1582            }
1583            return newArgs;
1584        } else {
1585            return args;
1586        }
1587    }
1588    //where
1589    Type mostSpecificReturnType(Type mt1, Type mt2) {
1590        Type rt1 = mt1.getReturnType();
1591        Type rt2 = mt2.getReturnType();
1592
1593        if (mt1.hasTag(FORALL) && mt2.hasTag(FORALL)) {
1594            //if both are generic methods, adjust return type ahead of subtyping check
1595            rt1 = types.subst(rt1, mt1.getTypeArguments(), mt2.getTypeArguments());
1596        }
1597        //first use subtyping, then return type substitutability
1598        if (types.isSubtype(rt1, rt2)) {
1599            return mt1;
1600        } else if (types.isSubtype(rt2, rt1)) {
1601            return mt2;
1602        } else if (types.returnTypeSubstitutable(mt1, mt2)) {
1603            return mt1;
1604        } else if (types.returnTypeSubstitutable(mt2, mt1)) {
1605            return mt2;
1606        } else {
1607            return null;
1608        }
1609    }
1610    //where
1611    Symbol ambiguityError(Symbol m1, Symbol m2) {
1612        if (((m1.flags() | m2.flags()) & CLASH) != 0) {
1613            return (m1.flags() & CLASH) == 0 ? m1 : m2;
1614        } else {
1615            return new AmbiguityError(m1, m2);
1616        }
1617    }
1618
1619    Symbol findMethodInScope(Env<AttrContext> env,
1620            Type site,
1621            Name name,
1622            List<Type> argtypes,
1623            List<Type> typeargtypes,
1624            Scope sc,
1625            Symbol bestSoFar,
1626            boolean allowBoxing,
1627            boolean useVarargs,
1628            boolean operator,
1629            boolean abstractok) {
1630        for (Symbol s : sc.getSymbolsByName(name, new LookupFilter(abstractok))) {
1631            bestSoFar = selectBest(env, site, argtypes, typeargtypes, s,
1632                    bestSoFar, allowBoxing, useVarargs, operator);
1633        }
1634        return bestSoFar;
1635    }
1636    //where
1637        class LookupFilter implements Filter<Symbol> {
1638
1639            boolean abstractOk;
1640
1641            LookupFilter(boolean abstractOk) {
1642                this.abstractOk = abstractOk;
1643            }
1644
1645            public boolean accepts(Symbol s) {
1646                long flags = s.flags();
1647                return s.kind == MTH &&
1648                        (flags & SYNTHETIC) == 0 &&
1649                        (abstractOk ||
1650                        (flags & DEFAULT) != 0 ||
1651                        (flags & ABSTRACT) == 0);
1652            }
1653        }
1654
1655    /** Find best qualified method matching given name, type and value
1656     *  arguments.
1657     *  @param env       The current environment.
1658     *  @param site      The original type from where the selection
1659     *                   takes place.
1660     *  @param name      The method's name.
1661     *  @param argtypes  The method's value arguments.
1662     *  @param typeargtypes The method's type arguments
1663     *  @param allowBoxing Allow boxing conversions of arguments.
1664     *  @param useVarargs Box trailing arguments into an array for varargs.
1665     */
1666    Symbol findMethod(Env<AttrContext> env,
1667                      Type site,
1668                      Name name,
1669                      List<Type> argtypes,
1670                      List<Type> typeargtypes,
1671                      boolean allowBoxing,
1672                      boolean useVarargs,
1673                      boolean operator) {
1674        Symbol bestSoFar = methodNotFound;
1675        bestSoFar = findMethod(env,
1676                          site,
1677                          name,
1678                          argtypes,
1679                          typeargtypes,
1680                          site.tsym.type,
1681                          bestSoFar,
1682                          allowBoxing,
1683                          useVarargs,
1684                          operator);
1685        return bestSoFar;
1686    }
1687    // where
1688    private Symbol findMethod(Env<AttrContext> env,
1689                              Type site,
1690                              Name name,
1691                              List<Type> argtypes,
1692                              List<Type> typeargtypes,
1693                              Type intype,
1694                              Symbol bestSoFar,
1695                              boolean allowBoxing,
1696                              boolean useVarargs,
1697                              boolean operator) {
1698        @SuppressWarnings({"unchecked","rawtypes"})
1699        List<Type>[] itypes = (List<Type>[])new List[] { List.<Type>nil(), List.<Type>nil() };
1700
1701        InterfaceLookupPhase iphase = InterfaceLookupPhase.ABSTRACT_OK;
1702        for (TypeSymbol s : superclasses(intype)) {
1703            bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
1704                    s.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
1705            if (name == names.init) return bestSoFar;
1706            iphase = (iphase == null) ? null : iphase.update(s, this);
1707            if (iphase != null) {
1708                for (Type itype : types.interfaces(s.type)) {
1709                    itypes[iphase.ordinal()] = types.union(types.closure(itype), itypes[iphase.ordinal()]);
1710                }
1711            }
1712        }
1713
1714        Symbol concrete = bestSoFar.kind.isValid() &&
1715                (bestSoFar.flags() & ABSTRACT) == 0 ?
1716                bestSoFar : methodNotFound;
1717
1718        for (InterfaceLookupPhase iphase2 : InterfaceLookupPhase.values()) {
1719            //keep searching for abstract methods
1720            for (Type itype : itypes[iphase2.ordinal()]) {
1721                if (!itype.isInterface()) continue; //skip j.l.Object (included by Types.closure())
1722                if (iphase2 == InterfaceLookupPhase.DEFAULT_OK &&
1723                        (itype.tsym.flags() & DEFAULT) == 0) continue;
1724                bestSoFar = findMethodInScope(env, site, name, argtypes, typeargtypes,
1725                        itype.tsym.members(), bestSoFar, allowBoxing, useVarargs, operator, true);
1726                if (concrete != bestSoFar &&
1727                    concrete.kind.isValid() &&
1728                    bestSoFar.kind.isValid() &&
1729                        types.isSubSignature(concrete.type, bestSoFar.type)) {
1730                    //this is an hack - as javac does not do full membership checks
1731                    //most specific ends up comparing abstract methods that might have
1732                    //been implemented by some concrete method in a subclass and,
1733                    //because of raw override, it is possible for an abstract method
1734                    //to be more specific than the concrete method - so we need
1735                    //to explicitly call that out (see CR 6178365)
1736                    bestSoFar = concrete;
1737                }
1738            }
1739        }
1740        return bestSoFar;
1741    }
1742
1743    enum InterfaceLookupPhase {
1744        ABSTRACT_OK() {
1745            @Override
1746            InterfaceLookupPhase update(Symbol s, Resolve rs) {
1747                //We should not look for abstract methods if receiver is a concrete class
1748                //(as concrete classes are expected to implement all abstracts coming
1749                //from superinterfaces)
1750                if ((s.flags() & (ABSTRACT | INTERFACE | ENUM)) != 0) {
1751                    return this;
1752                } else {
1753                    return DEFAULT_OK;
1754                }
1755            }
1756        },
1757        DEFAULT_OK() {
1758            @Override
1759            InterfaceLookupPhase update(Symbol s, Resolve rs) {
1760                return this;
1761            }
1762        };
1763
1764        abstract InterfaceLookupPhase update(Symbol s, Resolve rs);
1765    }
1766
1767    /**
1768     * Return an Iterable object to scan the superclasses of a given type.
1769     * It's crucial that the scan is done lazily, as we don't want to accidentally
1770     * access more supertypes than strictly needed (as this could trigger completion
1771     * errors if some of the not-needed supertypes are missing/ill-formed).
1772     */
1773    Iterable<TypeSymbol> superclasses(final Type intype) {
1774        return new Iterable<TypeSymbol>() {
1775            public Iterator<TypeSymbol> iterator() {
1776                return new Iterator<TypeSymbol>() {
1777
1778                    List<TypeSymbol> seen = List.nil();
1779                    TypeSymbol currentSym = symbolFor(intype);
1780                    TypeSymbol prevSym = null;
1781
1782                    public boolean hasNext() {
1783                        if (currentSym == syms.noSymbol) {
1784                            currentSym = symbolFor(types.supertype(prevSym.type));
1785                        }
1786                        return currentSym != null;
1787                    }
1788
1789                    public TypeSymbol next() {
1790                        prevSym = currentSym;
1791                        currentSym = syms.noSymbol;
1792                        Assert.check(prevSym != null || prevSym != syms.noSymbol);
1793                        return prevSym;
1794                    }
1795
1796                    public void remove() {
1797                        throw new UnsupportedOperationException();
1798                    }
1799
1800                    TypeSymbol symbolFor(Type t) {
1801                        if (!t.hasTag(CLASS) &&
1802                                !t.hasTag(TYPEVAR)) {
1803                            return null;
1804                        }
1805                        while (t.hasTag(TYPEVAR))
1806                            t = t.getUpperBound();
1807                        if (seen.contains(t.tsym)) {
1808                            //degenerate case in which we have a circular
1809                            //class hierarchy - because of ill-formed classfiles
1810                            return null;
1811                        }
1812                        seen = seen.prepend(t.tsym);
1813                        return t.tsym;
1814                    }
1815                };
1816            }
1817        };
1818    }
1819
1820    /** Find unqualified method matching given name, type and value arguments.
1821     *  @param env       The current environment.
1822     *  @param name      The method's name.
1823     *  @param argtypes  The method's value arguments.
1824     *  @param typeargtypes  The method's type arguments.
1825     *  @param allowBoxing Allow boxing conversions of arguments.
1826     *  @param useVarargs Box trailing arguments into an array for varargs.
1827     */
1828    Symbol findFun(Env<AttrContext> env, Name name,
1829                   List<Type> argtypes, List<Type> typeargtypes,
1830                   boolean allowBoxing, boolean useVarargs) {
1831        Symbol bestSoFar = methodNotFound;
1832        Env<AttrContext> env1 = env;
1833        boolean staticOnly = false;
1834        while (env1.outer != null) {
1835            if (isStatic(env1)) staticOnly = true;
1836            Symbol sym = findMethod(
1837                env1, env1.enclClass.sym.type, name, argtypes, typeargtypes,
1838                allowBoxing, useVarargs, false);
1839            if (sym.exists()) {
1840                if (staticOnly &&
1841                    sym.kind == MTH &&
1842                    sym.owner.kind == TYP &&
1843                    (sym.flags() & STATIC) == 0) return new StaticError(sym);
1844                else return sym;
1845            } else {
1846                bestSoFar = bestOf(bestSoFar, sym);
1847            }
1848            if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
1849            env1 = env1.outer;
1850        }
1851
1852        Symbol sym = findMethod(env, syms.predefClass.type, name, argtypes,
1853                                typeargtypes, allowBoxing, useVarargs, false);
1854        if (sym.exists())
1855            return sym;
1856
1857        for (Symbol currentSym : env.toplevel.namedImportScope.getSymbolsByName(name)) {
1858            Symbol origin = env.toplevel.namedImportScope.getOrigin(currentSym).owner;
1859            if (currentSym.kind == MTH) {
1860                if (currentSym.owner.type != origin.type)
1861                    currentSym = currentSym.clone(origin);
1862                if (!isAccessible(env, origin.type, currentSym))
1863                    currentSym = new AccessError(env, origin.type, currentSym);
1864                bestSoFar = selectBest(env, origin.type,
1865                                       argtypes, typeargtypes,
1866                                       currentSym, bestSoFar,
1867                                       allowBoxing, useVarargs, false);
1868            }
1869        }
1870        if (bestSoFar.exists())
1871            return bestSoFar;
1872
1873        for (Symbol currentSym : env.toplevel.starImportScope.getSymbolsByName(name)) {
1874            Symbol origin = env.toplevel.starImportScope.getOrigin(currentSym).owner;
1875            if (currentSym.kind == MTH) {
1876                if (currentSym.owner.type != origin.type)
1877                    currentSym = currentSym.clone(origin);
1878                if (!isAccessible(env, origin.type, currentSym))
1879                    currentSym = new AccessError(env, origin.type, currentSym);
1880                bestSoFar = selectBest(env, origin.type,
1881                                       argtypes, typeargtypes,
1882                                       currentSym, bestSoFar,
1883                                       allowBoxing, useVarargs, false);
1884            }
1885        }
1886        return bestSoFar;
1887    }
1888
1889    /** Load toplevel or member class with given fully qualified name and
1890     *  verify that it is accessible.
1891     *  @param env       The current environment.
1892     *  @param name      The fully qualified name of the class to be loaded.
1893     */
1894    Symbol loadClass(Env<AttrContext> env, Name name) {
1895        try {
1896            ClassSymbol c = finder.loadClass(name);
1897            return isAccessible(env, c) ? c : new AccessError(c);
1898        } catch (ClassFinder.BadClassFile err) {
1899            throw err;
1900        } catch (CompletionFailure ex) {
1901            return typeNotFound;
1902        }
1903    }
1904
1905
1906    /**
1907     * Find a type declared in a scope (not inherited).  Return null
1908     * if none is found.
1909     *  @param env       The current environment.
1910     *  @param site      The original type from where the selection takes
1911     *                   place.
1912     *  @param name      The type's name.
1913     *  @param c         The class to search for the member type. This is
1914     *                   always a superclass or implemented interface of
1915     *                   site's class.
1916     */
1917    Symbol findImmediateMemberType(Env<AttrContext> env,
1918                                   Type site,
1919                                   Name name,
1920                                   TypeSymbol c) {
1921        for (Symbol sym : c.members().getSymbolsByName(name)) {
1922            if (sym.kind == TYP) {
1923                return isAccessible(env, site, sym)
1924                    ? sym
1925                    : new AccessError(env, site, sym);
1926            }
1927        }
1928        return typeNotFound;
1929    }
1930
1931    /** Find a member type inherited from a superclass or interface.
1932     *  @param env       The current environment.
1933     *  @param site      The original type from where the selection takes
1934     *                   place.
1935     *  @param name      The type's name.
1936     *  @param c         The class to search for the member type. This is
1937     *                   always a superclass or implemented interface of
1938     *                   site's class.
1939     */
1940    Symbol findInheritedMemberType(Env<AttrContext> env,
1941                                   Type site,
1942                                   Name name,
1943                                   TypeSymbol c) {
1944        Symbol bestSoFar = typeNotFound;
1945        Symbol sym;
1946        Type st = types.supertype(c.type);
1947        if (st != null && st.hasTag(CLASS)) {
1948            sym = findMemberType(env, site, name, st.tsym);
1949            bestSoFar = bestOf(bestSoFar, sym);
1950        }
1951        for (List<Type> l = types.interfaces(c.type);
1952             bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
1953             l = l.tail) {
1954            sym = findMemberType(env, site, name, l.head.tsym);
1955            if (!bestSoFar.kind.isOverloadError() &&
1956                !sym.kind.isOverloadError() &&
1957                sym.owner != bestSoFar.owner)
1958                bestSoFar = new AmbiguityError(bestSoFar, sym);
1959            else
1960                bestSoFar = bestOf(bestSoFar, sym);
1961        }
1962        return bestSoFar;
1963    }
1964
1965    /** Find qualified member type.
1966     *  @param env       The current environment.
1967     *  @param site      The original type from where the selection takes
1968     *                   place.
1969     *  @param name      The type's name.
1970     *  @param c         The class to search for the member type. This is
1971     *                   always a superclass or implemented interface of
1972     *                   site's class.
1973     */
1974    Symbol findMemberType(Env<AttrContext> env,
1975                          Type site,
1976                          Name name,
1977                          TypeSymbol c) {
1978        Symbol sym = findImmediateMemberType(env, site, name, c);
1979
1980        if (sym != typeNotFound)
1981            return sym;
1982
1983        return findInheritedMemberType(env, site, name, c);
1984
1985    }
1986
1987    /** Find a global type in given scope and load corresponding class.
1988     *  @param env       The current environment.
1989     *  @param scope     The scope in which to look for the type.
1990     *  @param name      The type's name.
1991     */
1992    Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name) {
1993        Symbol bestSoFar = typeNotFound;
1994        for (Symbol s : scope.getSymbolsByName(name)) {
1995            Symbol sym = loadClass(env, s.flatName());
1996            if (bestSoFar.kind == TYP && sym.kind == TYP &&
1997                bestSoFar != sym)
1998                return new AmbiguityError(bestSoFar, sym);
1999            else
2000                bestSoFar = bestOf(bestSoFar, sym);
2001        }
2002        return bestSoFar;
2003    }
2004
2005    Symbol findTypeVar(Env<AttrContext> env, Name name, boolean staticOnly) {
2006        for (Symbol sym : env.info.scope.getSymbolsByName(name)) {
2007            if (sym.kind == TYP) {
2008                if (staticOnly &&
2009                    sym.type.hasTag(TYPEVAR) &&
2010                    sym.owner.kind == TYP)
2011                    return new StaticError(sym);
2012                return sym;
2013            }
2014        }
2015        return typeNotFound;
2016    }
2017
2018    /** Find an unqualified type symbol.
2019     *  @param env       The current environment.
2020     *  @param name      The type's name.
2021     */
2022    Symbol findType(Env<AttrContext> env, Name name) {
2023        Symbol bestSoFar = typeNotFound;
2024        Symbol sym;
2025        boolean staticOnly = false;
2026        for (Env<AttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
2027            if (isStatic(env1)) staticOnly = true;
2028            // First, look for a type variable and the first member type
2029            final Symbol tyvar = findTypeVar(env1, name, staticOnly);
2030            sym = findImmediateMemberType(env1, env1.enclClass.sym.type,
2031                                          name, env1.enclClass.sym);
2032
2033            // Return the type variable if we have it, and have no
2034            // immediate member, OR the type variable is for a method.
2035            if (tyvar != typeNotFound) {
2036                if (env.baseClause || sym == typeNotFound ||
2037                    (tyvar.kind == TYP && tyvar.exists() &&
2038                     tyvar.owner.kind == MTH)) {
2039                    return tyvar;
2040                }
2041            }
2042
2043            // If the environment is a class def, finish up,
2044            // otherwise, do the entire findMemberType
2045            if (sym == typeNotFound)
2046                sym = findInheritedMemberType(env1, env1.enclClass.sym.type,
2047                                              name, env1.enclClass.sym);
2048
2049            if (staticOnly && sym.kind == TYP &&
2050                sym.type.hasTag(CLASS) &&
2051                sym.type.getEnclosingType().hasTag(CLASS) &&
2052                env1.enclClass.sym.type.isParameterized() &&
2053                sym.type.getEnclosingType().isParameterized())
2054                return new StaticError(sym);
2055            else if (sym.exists()) return sym;
2056            else bestSoFar = bestOf(bestSoFar, sym);
2057
2058            JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass;
2059            if ((encl.sym.flags() & STATIC) != 0)
2060                staticOnly = true;
2061        }
2062
2063        if (!env.tree.hasTag(IMPORT)) {
2064            sym = findGlobalType(env, env.toplevel.namedImportScope, name);
2065            if (sym.exists()) return sym;
2066            else bestSoFar = bestOf(bestSoFar, sym);
2067
2068            sym = findGlobalType(env, env.toplevel.packge.members(), name);
2069            if (sym.exists()) return sym;
2070            else bestSoFar = bestOf(bestSoFar, sym);
2071
2072            sym = findGlobalType(env, env.toplevel.starImportScope, name);
2073            if (sym.exists()) return sym;
2074            else bestSoFar = bestOf(bestSoFar, sym);
2075        }
2076
2077        return bestSoFar;
2078    }
2079
2080    /** Find an unqualified identifier which matches a specified kind set.
2081     *  @param env       The current environment.
2082     *  @param name      The identifier's name.
2083     *  @param kind      Indicates the possible symbol kinds
2084     *                   (a subset of VAL, TYP, PCK).
2085     */
2086    Symbol findIdent(Env<AttrContext> env, Name name, KindSelector kind) {
2087        Symbol bestSoFar = typeNotFound;
2088        Symbol sym;
2089
2090        if (kind.contains(KindSelector.VAL)) {
2091            sym = findVar(env, name);
2092            if (sym.exists()) return sym;
2093            else bestSoFar = bestOf(bestSoFar, sym);
2094        }
2095
2096        if (kind.contains(KindSelector.TYP)) {
2097            sym = findType(env, name);
2098
2099            if (sym.exists()) return sym;
2100            else bestSoFar = bestOf(bestSoFar, sym);
2101        }
2102
2103        if (kind.contains(KindSelector.PCK))
2104            return syms.enterPackage(name);
2105        else return bestSoFar;
2106    }
2107
2108    /** Find an identifier in a package which matches a specified kind set.
2109     *  @param env       The current environment.
2110     *  @param name      The identifier's name.
2111     *  @param kind      Indicates the possible symbol kinds
2112     *                   (a nonempty subset of TYP, PCK).
2113     */
2114    Symbol findIdentInPackage(Env<AttrContext> env, TypeSymbol pck,
2115                              Name name, KindSelector kind) {
2116        Name fullname = TypeSymbol.formFullName(name, pck);
2117        Symbol bestSoFar = typeNotFound;
2118        PackageSymbol pack = null;
2119        if (kind.contains(KindSelector.PCK)) {
2120            pack = syms.enterPackage(fullname);
2121            if (pack.exists()) return pack;
2122        }
2123        if (kind.contains(KindSelector.TYP)) {
2124            Symbol sym = loadClass(env, fullname);
2125            if (sym.exists()) {
2126                // don't allow programs to use flatnames
2127                if (name == sym.name) return sym;
2128            }
2129            else bestSoFar = bestOf(bestSoFar, sym);
2130        }
2131        return (pack != null) ? pack : bestSoFar;
2132    }
2133
2134    /** Find an identifier among the members of a given type `site'.
2135     *  @param env       The current environment.
2136     *  @param site      The type containing the symbol to be found.
2137     *  @param name      The identifier's name.
2138     *  @param kind      Indicates the possible symbol kinds
2139     *                   (a subset of VAL, TYP).
2140     */
2141    Symbol findIdentInType(Env<AttrContext> env, Type site,
2142                           Name name, KindSelector kind) {
2143        Symbol bestSoFar = typeNotFound;
2144        Symbol sym;
2145        if (kind.contains(KindSelector.VAL)) {
2146            sym = findField(env, site, name, site.tsym);
2147            if (sym.exists()) return sym;
2148            else bestSoFar = bestOf(bestSoFar, sym);
2149        }
2150
2151        if (kind.contains(KindSelector.TYP)) {
2152            sym = findMemberType(env, site, name, site.tsym);
2153            if (sym.exists()) return sym;
2154            else bestSoFar = bestOf(bestSoFar, sym);
2155        }
2156        return bestSoFar;
2157    }
2158
2159/* ***************************************************************************
2160 *  Access checking
2161 *  The following methods convert ResolveErrors to ErrorSymbols, issuing
2162 *  an error message in the process
2163 ****************************************************************************/
2164
2165    /** If `sym' is a bad symbol: report error and return errSymbol
2166     *  else pass through unchanged,
2167     *  additional arguments duplicate what has been used in trying to find the
2168     *  symbol {@literal (--> flyweight pattern)}. This improves performance since we
2169     *  expect misses to happen frequently.
2170     *
2171     *  @param sym       The symbol that was found, or a ResolveError.
2172     *  @param pos       The position to use for error reporting.
2173     *  @param location  The symbol the served as a context for this lookup
2174     *  @param site      The original type from where the selection took place.
2175     *  @param name      The symbol's name.
2176     *  @param qualified Did we get here through a qualified expression resolution?
2177     *  @param argtypes  The invocation's value arguments,
2178     *                   if we looked for a method.
2179     *  @param typeargtypes  The invocation's type arguments,
2180     *                   if we looked for a method.
2181     *  @param logResolveHelper helper class used to log resolve errors
2182     */
2183    Symbol accessInternal(Symbol sym,
2184                  DiagnosticPosition pos,
2185                  Symbol location,
2186                  Type site,
2187                  Name name,
2188                  boolean qualified,
2189                  List<Type> argtypes,
2190                  List<Type> typeargtypes,
2191                  LogResolveHelper logResolveHelper) {
2192        if (sym.kind.isOverloadError()) {
2193            ResolveError errSym = (ResolveError)sym.baseSymbol();
2194            sym = errSym.access(name, qualified ? site.tsym : syms.noSymbol);
2195            argtypes = logResolveHelper.getArgumentTypes(errSym, sym, name, argtypes);
2196            if (logResolveHelper.resolveDiagnosticNeeded(site, argtypes, typeargtypes)) {
2197                logResolveError(errSym, pos, location, site, name, argtypes, typeargtypes);
2198            }
2199        }
2200        return sym;
2201    }
2202
2203    /**
2204     * Variant of the generalized access routine, to be used for generating method
2205     * resolution diagnostics
2206     */
2207    Symbol accessMethod(Symbol sym,
2208                  DiagnosticPosition pos,
2209                  Symbol location,
2210                  Type site,
2211                  Name name,
2212                  boolean qualified,
2213                  List<Type> argtypes,
2214                  List<Type> typeargtypes) {
2215        return accessInternal(sym, pos, location, site, name, qualified, argtypes, typeargtypes, methodLogResolveHelper);
2216    }
2217
2218    /** Same as original accessMethod(), but without location.
2219     */
2220    Symbol accessMethod(Symbol sym,
2221                  DiagnosticPosition pos,
2222                  Type site,
2223                  Name name,
2224                  boolean qualified,
2225                  List<Type> argtypes,
2226                  List<Type> typeargtypes) {
2227        return accessMethod(sym, pos, site.tsym, site, name, qualified, argtypes, typeargtypes);
2228    }
2229
2230    /**
2231     * Variant of the generalized access routine, to be used for generating variable,
2232     * type resolution diagnostics
2233     */
2234    Symbol accessBase(Symbol sym,
2235                  DiagnosticPosition pos,
2236                  Symbol location,
2237                  Type site,
2238                  Name name,
2239                  boolean qualified) {
2240        return accessInternal(sym, pos, location, site, name, qualified, List.<Type>nil(), null, basicLogResolveHelper);
2241    }
2242
2243    /** Same as original accessBase(), but without location.
2244     */
2245    Symbol accessBase(Symbol sym,
2246                  DiagnosticPosition pos,
2247                  Type site,
2248                  Name name,
2249                  boolean qualified) {
2250        return accessBase(sym, pos, site.tsym, site, name, qualified);
2251    }
2252
2253    interface LogResolveHelper {
2254        boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes);
2255        List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes);
2256    }
2257
2258    LogResolveHelper basicLogResolveHelper = new LogResolveHelper() {
2259        public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
2260            return !site.isErroneous();
2261        }
2262        public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
2263            return argtypes;
2264        }
2265    };
2266
2267    LogResolveHelper methodLogResolveHelper = new LogResolveHelper() {
2268        public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
2269            return !site.isErroneous() &&
2270                        !Type.isErroneous(argtypes) &&
2271                        (typeargtypes == null || !Type.isErroneous(typeargtypes));
2272        }
2273        public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
2274            return (syms.operatorNames.contains(name)) ?
2275                    argtypes :
2276                    Type.map(argtypes, new ResolveDeferredRecoveryMap(AttrMode.SPECULATIVE, accessedSym, currentResolutionContext.step));
2277        }
2278    };
2279
2280    class ResolveDeferredRecoveryMap extends DeferredAttr.RecoveryDeferredTypeMap {
2281
2282        public ResolveDeferredRecoveryMap(AttrMode mode, Symbol msym, MethodResolutionPhase step) {
2283            deferredAttr.super(mode, msym, step);
2284        }
2285
2286        @Override
2287        protected Type typeOf(DeferredType dt) {
2288            Type res = super.typeOf(dt);
2289            if (!res.isErroneous()) {
2290                switch (TreeInfo.skipParens(dt.tree).getTag()) {
2291                    case LAMBDA:
2292                    case REFERENCE:
2293                        return dt;
2294                    case CONDEXPR:
2295                        return res == Type.recoveryType ?
2296                                dt : res;
2297                }
2298            }
2299            return res;
2300        }
2301    }
2302
2303    /** Check that sym is not an abstract method.
2304     */
2305    void checkNonAbstract(DiagnosticPosition pos, Symbol sym) {
2306        if ((sym.flags() & ABSTRACT) != 0 && (sym.flags() & DEFAULT) == 0)
2307            log.error(pos, "abstract.cant.be.accessed.directly",
2308                      kindName(sym), sym, sym.location());
2309    }
2310
2311/* ***************************************************************************
2312 *  Name resolution
2313 *  Naming conventions are as for symbol lookup
2314 *  Unlike the find... methods these methods will report access errors
2315 ****************************************************************************/
2316
2317    /** Resolve an unqualified (non-method) identifier.
2318     *  @param pos       The position to use for error reporting.
2319     *  @param env       The environment current at the identifier use.
2320     *  @param name      The identifier's name.
2321     *  @param kind      The set of admissible symbol kinds for the identifier.
2322     */
2323    Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env,
2324                        Name name, KindSelector kind) {
2325        return accessBase(
2326            findIdent(env, name, kind),
2327            pos, env.enclClass.sym.type, name, false);
2328    }
2329
2330    /** Resolve an unqualified method identifier.
2331     *  @param pos       The position to use for error reporting.
2332     *  @param env       The environment current at the method invocation.
2333     *  @param name      The identifier's name.
2334     *  @param argtypes  The types of the invocation's value arguments.
2335     *  @param typeargtypes  The types of the invocation's type arguments.
2336     */
2337    Symbol resolveMethod(DiagnosticPosition pos,
2338                         Env<AttrContext> env,
2339                         Name name,
2340                         List<Type> argtypes,
2341                         List<Type> typeargtypes) {
2342        return lookupMethod(env, pos, env.enclClass.sym, resolveMethodCheck,
2343                new BasicLookupHelper(name, env.enclClass.sym.type, argtypes, typeargtypes) {
2344                    @Override
2345                    Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2346                        return findFun(env, name, argtypes, typeargtypes,
2347                                phase.isBoxingRequired(),
2348                                phase.isVarargsRequired());
2349                    }});
2350    }
2351
2352    /** Resolve a qualified method identifier
2353     *  @param pos       The position to use for error reporting.
2354     *  @param env       The environment current at the method invocation.
2355     *  @param site      The type of the qualifying expression, in which
2356     *                   identifier is searched.
2357     *  @param name      The identifier's name.
2358     *  @param argtypes  The types of the invocation's value arguments.
2359     *  @param typeargtypes  The types of the invocation's type arguments.
2360     */
2361    Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
2362                                  Type site, Name name, List<Type> argtypes,
2363                                  List<Type> typeargtypes) {
2364        return resolveQualifiedMethod(pos, env, site.tsym, site, name, argtypes, typeargtypes);
2365    }
2366    Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
2367                                  Symbol location, Type site, Name name, List<Type> argtypes,
2368                                  List<Type> typeargtypes) {
2369        return resolveQualifiedMethod(new MethodResolutionContext(), pos, env, location, site, name, argtypes, typeargtypes);
2370    }
2371    private Symbol resolveQualifiedMethod(MethodResolutionContext resolveContext,
2372                                  DiagnosticPosition pos, Env<AttrContext> env,
2373                                  Symbol location, Type site, Name name, List<Type> argtypes,
2374                                  List<Type> typeargtypes) {
2375        return lookupMethod(env, pos, location, resolveContext, new BasicLookupHelper(name, site, argtypes, typeargtypes) {
2376            @Override
2377            Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2378                return findMethod(env, site, name, argtypes, typeargtypes,
2379                        phase.isBoxingRequired(),
2380                        phase.isVarargsRequired(), false);
2381            }
2382            @Override
2383            Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
2384                if (sym.kind.isOverloadError()) {
2385                    sym = super.access(env, pos, location, sym);
2386                } else if (allowMethodHandles) {
2387                    MethodSymbol msym = (MethodSymbol)sym;
2388                    if ((msym.flags() & SIGNATURE_POLYMORPHIC) != 0) {
2389                        return findPolymorphicSignatureInstance(env, sym, argtypes);
2390                    }
2391                }
2392                return sym;
2393            }
2394        });
2395    }
2396
2397    /** Find or create an implicit method of exactly the given type (after erasure).
2398     *  Searches in a side table, not the main scope of the site.
2399     *  This emulates the lookup process required by JSR 292 in JVM.
2400     *  @param env       Attribution environment
2401     *  @param spMethod  signature polymorphic method - i.e. MH.invokeExact
2402     *  @param argtypes  The required argument types
2403     */
2404    Symbol findPolymorphicSignatureInstance(Env<AttrContext> env,
2405                                            final Symbol spMethod,
2406                                            List<Type> argtypes) {
2407        Type mtype = infer.instantiatePolymorphicSignatureInstance(env,
2408                (MethodSymbol)spMethod, currentResolutionContext, argtypes);
2409        for (Symbol sym : polymorphicSignatureScope.getSymbolsByName(spMethod.name)) {
2410            if (types.isSameType(mtype, sym.type)) {
2411               return sym;
2412            }
2413        }
2414
2415        // create the desired method
2416        long flags = ABSTRACT | HYPOTHETICAL | spMethod.flags() & Flags.AccessFlags;
2417        Symbol msym = new MethodSymbol(flags, spMethod.name, mtype, spMethod.owner) {
2418            @Override
2419            public Symbol baseSymbol() {
2420                return spMethod;
2421            }
2422        };
2423        polymorphicSignatureScope.enter(msym);
2424        return msym;
2425    }
2426
2427    /** Resolve a qualified method identifier, throw a fatal error if not
2428     *  found.
2429     *  @param pos       The position to use for error reporting.
2430     *  @param env       The environment current at the method invocation.
2431     *  @param site      The type of the qualifying expression, in which
2432     *                   identifier is searched.
2433     *  @param name      The identifier's name.
2434     *  @param argtypes  The types of the invocation's value arguments.
2435     *  @param typeargtypes  The types of the invocation's type arguments.
2436     */
2437    public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env,
2438                                        Type site, Name name,
2439                                        List<Type> argtypes,
2440                                        List<Type> typeargtypes) {
2441        MethodResolutionContext resolveContext = new MethodResolutionContext();
2442        resolveContext.internalResolution = true;
2443        Symbol sym = resolveQualifiedMethod(resolveContext, pos, env, site.tsym,
2444                site, name, argtypes, typeargtypes);
2445        if (sym.kind == MTH) return (MethodSymbol)sym;
2446        else throw new FatalError(
2447                 diags.fragment("fatal.err.cant.locate.meth",
2448                                name));
2449    }
2450
2451    /** Resolve constructor.
2452     *  @param pos       The position to use for error reporting.
2453     *  @param env       The environment current at the constructor invocation.
2454     *  @param site      The type of class for which a constructor is searched.
2455     *  @param argtypes  The types of the constructor invocation's value
2456     *                   arguments.
2457     *  @param typeargtypes  The types of the constructor invocation's type
2458     *                   arguments.
2459     */
2460    Symbol resolveConstructor(DiagnosticPosition pos,
2461                              Env<AttrContext> env,
2462                              Type site,
2463                              List<Type> argtypes,
2464                              List<Type> typeargtypes) {
2465        return resolveConstructor(new MethodResolutionContext(), pos, env, site, argtypes, typeargtypes);
2466    }
2467
2468    private Symbol resolveConstructor(MethodResolutionContext resolveContext,
2469                              final DiagnosticPosition pos,
2470                              Env<AttrContext> env,
2471                              Type site,
2472                              List<Type> argtypes,
2473                              List<Type> typeargtypes) {
2474        return lookupMethod(env, pos, site.tsym, resolveContext, new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
2475            @Override
2476            Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2477                return findConstructor(pos, env, site, argtypes, typeargtypes,
2478                        phase.isBoxingRequired(),
2479                        phase.isVarargsRequired());
2480            }
2481        });
2482    }
2483
2484    /** Resolve a constructor, throw a fatal error if not found.
2485     *  @param pos       The position to use for error reporting.
2486     *  @param env       The environment current at the method invocation.
2487     *  @param site      The type to be constructed.
2488     *  @param argtypes  The types of the invocation's value arguments.
2489     *  @param typeargtypes  The types of the invocation's type arguments.
2490     */
2491    public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
2492                                        Type site,
2493                                        List<Type> argtypes,
2494                                        List<Type> typeargtypes) {
2495        MethodResolutionContext resolveContext = new MethodResolutionContext();
2496        resolveContext.internalResolution = true;
2497        Symbol sym = resolveConstructor(resolveContext, pos, env, site, argtypes, typeargtypes);
2498        if (sym.kind == MTH) return (MethodSymbol)sym;
2499        else throw new FatalError(
2500                 diags.fragment("fatal.err.cant.locate.ctor", site));
2501    }
2502
2503    Symbol findConstructor(DiagnosticPosition pos, Env<AttrContext> env,
2504                              Type site, List<Type> argtypes,
2505                              List<Type> typeargtypes,
2506                              boolean allowBoxing,
2507                              boolean useVarargs) {
2508        Symbol sym = findMethod(env, site,
2509                                    names.init, argtypes,
2510                                    typeargtypes, allowBoxing,
2511                                    useVarargs, false);
2512        chk.checkDeprecated(pos, env.info.scope.owner, sym);
2513        return sym;
2514    }
2515
2516    /** Resolve constructor using diamond inference.
2517     *  @param pos       The position to use for error reporting.
2518     *  @param env       The environment current at the constructor invocation.
2519     *  @param site      The type of class for which a constructor is searched.
2520     *                   The scope of this class has been touched in attribution.
2521     *  @param argtypes  The types of the constructor invocation's value
2522     *                   arguments.
2523     *  @param typeargtypes  The types of the constructor invocation's type
2524     *                   arguments.
2525     */
2526    Symbol resolveDiamond(DiagnosticPosition pos,
2527                              Env<AttrContext> env,
2528                              Type site,
2529                              List<Type> argtypes,
2530                              List<Type> typeargtypes) {
2531        return lookupMethod(env, pos, site.tsym, resolveMethodCheck,
2532                new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
2533                    @Override
2534                    Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2535                        return findDiamond(env, site, argtypes, typeargtypes,
2536                                phase.isBoxingRequired(),
2537                                phase.isVarargsRequired());
2538                    }
2539                    @Override
2540                    Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
2541                        if (sym.kind.isOverloadError()) {
2542                            if (sym.kind != WRONG_MTH &&
2543                                sym.kind != WRONG_MTHS) {
2544                                sym = super.access(env, pos, location, sym);
2545                            } else {
2546                                final JCDiagnostic details = sym.kind == WRONG_MTH ?
2547                                                ((InapplicableSymbolError)sym.baseSymbol()).errCandidate().snd :
2548                                                null;
2549                                sym = new DiamondError(sym, currentResolutionContext);
2550                                sym = accessMethod(sym, pos, site, names.init, true, argtypes, typeargtypes);
2551                                env.info.pendingResolutionPhase = currentResolutionContext.step;
2552                            }
2553                        }
2554                        return sym;
2555                    }});
2556    }
2557
2558    /** This method scans all the constructor symbol in a given class scope -
2559     *  assuming that the original scope contains a constructor of the kind:
2560     *  {@code Foo(X x, Y y)}, where X,Y are class type-variables declared in Foo,
2561     *  a method check is executed against the modified constructor type:
2562     *  {@code <X,Y>Foo<X,Y>(X x, Y y)}. This is crucial in order to enable diamond
2563     *  inference. The inferred return type of the synthetic constructor IS
2564     *  the inferred type for the diamond operator.
2565     */
2566    private Symbol findDiamond(Env<AttrContext> env,
2567                              Type site,
2568                              List<Type> argtypes,
2569                              List<Type> typeargtypes,
2570                              boolean allowBoxing,
2571                              boolean useVarargs) {
2572        Symbol bestSoFar = methodNotFound;
2573        for (final Symbol sym : site.tsym.members().getSymbolsByName(names.init)) {
2574            //- System.out.println(" e " + e.sym);
2575            if (sym.kind == MTH &&
2576                (sym.flags_field & SYNTHETIC) == 0) {
2577                    List<Type> oldParams = sym.type.hasTag(FORALL) ?
2578                            ((ForAll)sym.type).tvars :
2579                            List.<Type>nil();
2580                    Type constrType = new ForAll(site.tsym.type.getTypeArguments().appendList(oldParams),
2581                                                 types.createMethodTypeWithReturn(sym.type.asMethodType(), site));
2582                    MethodSymbol newConstr = new MethodSymbol(sym.flags(), names.init, constrType, site.tsym) {
2583                        @Override
2584                        public Symbol baseSymbol() {
2585                            return sym;
2586                        }
2587                    };
2588                    bestSoFar = selectBest(env, site, argtypes, typeargtypes,
2589                            newConstr,
2590                            bestSoFar,
2591                            allowBoxing,
2592                            useVarargs,
2593                            false);
2594            }
2595        }
2596        return bestSoFar;
2597    }
2598
2599
2600
2601    /** Resolve operator.
2602     *  @param pos       The position to use for error reporting.
2603     *  @param optag     The tag of the operation tree.
2604     *  @param env       The environment current at the operation.
2605     *  @param argtypes  The types of the operands.
2606     */
2607    Symbol resolveOperator(DiagnosticPosition pos, JCTree.Tag optag,
2608                           Env<AttrContext> env, List<Type> argtypes) {
2609        MethodResolutionContext prevResolutionContext = currentResolutionContext;
2610        try {
2611            currentResolutionContext = new MethodResolutionContext();
2612            Name name = treeinfo.operatorName(optag);
2613            return lookupMethod(env, pos, syms.predefClass, currentResolutionContext,
2614                    new BasicLookupHelper(name, syms.predefClass.type, argtypes, null, BOX) {
2615                @Override
2616                Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2617                    return findMethod(env, site, name, argtypes, typeargtypes,
2618                            phase.isBoxingRequired(),
2619                            phase.isVarargsRequired(), true);
2620                }
2621                @Override
2622                Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
2623                    return accessMethod(sym, pos, env.enclClass.sym.type, name,
2624                          false, argtypes, null);
2625                }
2626            });
2627        } finally {
2628            currentResolutionContext = prevResolutionContext;
2629        }
2630    }
2631
2632    /** Resolve operator.
2633     *  @param pos       The position to use for error reporting.
2634     *  @param optag     The tag of the operation tree.
2635     *  @param env       The environment current at the operation.
2636     *  @param arg       The type of the operand.
2637     */
2638    Symbol resolveUnaryOperator(DiagnosticPosition pos, JCTree.Tag optag, Env<AttrContext> env, Type arg) {
2639        return resolveOperator(pos, optag, env, List.of(arg));
2640    }
2641
2642    /** Resolve binary operator.
2643     *  @param pos       The position to use for error reporting.
2644     *  @param optag     The tag of the operation tree.
2645     *  @param env       The environment current at the operation.
2646     *  @param left      The types of the left operand.
2647     *  @param right     The types of the right operand.
2648     */
2649    Symbol resolveBinaryOperator(DiagnosticPosition pos,
2650                                 JCTree.Tag optag,
2651                                 Env<AttrContext> env,
2652                                 Type left,
2653                                 Type right) {
2654        return resolveOperator(pos, optag, env, List.of(left, right));
2655    }
2656
2657    Symbol getMemberReference(DiagnosticPosition pos,
2658            Env<AttrContext> env,
2659            JCMemberReference referenceTree,
2660            Type site,
2661            Name name) {
2662
2663        site = types.capture(site);
2664
2665        ReferenceLookupHelper lookupHelper = makeReferenceLookupHelper(
2666                referenceTree, site, name, List.<Type>nil(), null, VARARITY);
2667
2668        Env<AttrContext> newEnv = env.dup(env.tree, env.info.dup());
2669        Symbol sym = lookupMethod(newEnv, env.tree.pos(), site.tsym,
2670                nilMethodCheck, lookupHelper);
2671
2672        env.info.pendingResolutionPhase = newEnv.info.pendingResolutionPhase;
2673
2674        return sym;
2675    }
2676
2677    ReferenceLookupHelper makeReferenceLookupHelper(JCMemberReference referenceTree,
2678                                  Type site,
2679                                  Name name,
2680                                  List<Type> argtypes,
2681                                  List<Type> typeargtypes,
2682                                  MethodResolutionPhase maxPhase) {
2683        ReferenceLookupHelper result;
2684        if (!name.equals(names.init)) {
2685            //method reference
2686            result =
2687                    new MethodReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
2688        } else {
2689            if (site.hasTag(ARRAY)) {
2690                //array constructor reference
2691                result =
2692                        new ArrayConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase);
2693            } else {
2694                //class constructor reference
2695                result =
2696                        new ConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase);
2697            }
2698        }
2699        return result;
2700    }
2701
2702    Symbol resolveMemberReferenceByArity(Env<AttrContext> env,
2703                                  JCMemberReference referenceTree,
2704                                  Type site,
2705                                  Name name,
2706                                  List<Type> argtypes,
2707                                  InferenceContext inferenceContext) {
2708
2709        boolean isStaticSelector = TreeInfo.isStaticSelector(referenceTree.expr, names);
2710        site = types.capture(site);
2711
2712        ReferenceLookupHelper boundLookupHelper = makeReferenceLookupHelper(
2713                referenceTree, site, name, argtypes, null, VARARITY);
2714        //step 1 - bound lookup
2715        Env<AttrContext> boundEnv = env.dup(env.tree, env.info.dup());
2716        Symbol boundSym = lookupMethod(boundEnv, env.tree.pos(), site.tsym,
2717                arityMethodCheck, boundLookupHelper);
2718        if (isStaticSelector &&
2719            !name.equals(names.init) &&
2720            !boundSym.isStatic() &&
2721            !boundSym.kind.isOverloadError()) {
2722            boundSym = methodNotFound;
2723        }
2724
2725        //step 2 - unbound lookup
2726        Symbol unboundSym = methodNotFound;
2727        ReferenceLookupHelper unboundLookupHelper = null;
2728        Env<AttrContext> unboundEnv = env.dup(env.tree, env.info.dup());
2729        if (isStaticSelector) {
2730            unboundLookupHelper = boundLookupHelper.unboundLookup(inferenceContext);
2731            unboundSym = lookupMethod(unboundEnv, env.tree.pos(), site.tsym,
2732                    arityMethodCheck, unboundLookupHelper);
2733            if (unboundSym.isStatic() &&
2734                !unboundSym.kind.isOverloadError()) {
2735                unboundSym = methodNotFound;
2736            }
2737        }
2738
2739        //merge results
2740        Symbol bestSym = choose(boundSym, unboundSym);
2741        env.info.pendingResolutionPhase = bestSym == unboundSym ?
2742                unboundEnv.info.pendingResolutionPhase :
2743                boundEnv.info.pendingResolutionPhase;
2744
2745        return bestSym;
2746    }
2747
2748    /**
2749     * Resolution of member references is typically done as a single
2750     * overload resolution step, where the argument types A are inferred from
2751     * the target functional descriptor.
2752     *
2753     * If the member reference is a method reference with a type qualifier,
2754     * a two-step lookup process is performed. The first step uses the
2755     * expected argument list A, while the second step discards the first
2756     * type from A (which is treated as a receiver type).
2757     *
2758     * There are two cases in which inference is performed: (i) if the member
2759     * reference is a constructor reference and the qualifier type is raw - in
2760     * which case diamond inference is used to infer a parameterization for the
2761     * type qualifier; (ii) if the member reference is an unbound reference
2762     * where the type qualifier is raw - in that case, during the unbound lookup
2763     * the receiver argument type is used to infer an instantiation for the raw
2764     * qualifier type.
2765     *
2766     * When a multi-step resolution process is exploited, it is an error
2767     * if two candidates are found (ambiguity).
2768     *
2769     * This routine returns a pair (T,S), where S is the member reference symbol,
2770     * and T is the type of the class in which S is defined. This is necessary as
2771     * the type T might be dynamically inferred (i.e. if constructor reference
2772     * has a raw qualifier).
2773     */
2774    Pair<Symbol, ReferenceLookupHelper> resolveMemberReference(Env<AttrContext> env,
2775                                  JCMemberReference referenceTree,
2776                                  Type site,
2777                                  Name name,
2778                                  List<Type> argtypes,
2779                                  List<Type> typeargtypes,
2780                                  MethodCheck methodCheck,
2781                                  InferenceContext inferenceContext,
2782                                  AttrMode mode) {
2783
2784        site = types.capture(site);
2785        ReferenceLookupHelper boundLookupHelper = makeReferenceLookupHelper(
2786                referenceTree, site, name, argtypes, typeargtypes, VARARITY);
2787
2788        //step 1 - bound lookup
2789        Env<AttrContext> boundEnv = env.dup(env.tree, env.info.dup());
2790        Symbol origBoundSym;
2791        boolean staticErrorForBound = false;
2792        MethodResolutionContext boundSearchResolveContext = new MethodResolutionContext();
2793        boundSearchResolveContext.methodCheck = methodCheck;
2794        Symbol boundSym = origBoundSym = lookupMethod(boundEnv, env.tree.pos(),
2795                site.tsym, boundSearchResolveContext, boundLookupHelper);
2796        SearchResultKind boundSearchResultKind = SearchResultKind.NOT_APPLICABLE_MATCH;
2797        boolean isStaticSelector = TreeInfo.isStaticSelector(referenceTree.expr, names);
2798        boolean shouldCheckForStaticness = isStaticSelector &&
2799                referenceTree.getMode() == ReferenceMode.INVOKE;
2800        if (boundSym.kind != WRONG_MTHS && boundSym.kind != WRONG_MTH) {
2801            if (shouldCheckForStaticness) {
2802                if (!boundSym.isStatic()) {
2803                    staticErrorForBound = true;
2804                    if (hasAnotherApplicableMethod(
2805                            boundSearchResolveContext, boundSym, true)) {
2806                        boundSearchResultKind = SearchResultKind.BAD_MATCH_MORE_SPECIFIC;
2807                    } else {
2808                        boundSearchResultKind = SearchResultKind.BAD_MATCH;
2809                        if (!boundSym.kind.isOverloadError()) {
2810                            boundSym = methodWithCorrectStaticnessNotFound;
2811                        }
2812                    }
2813                } else if (!boundSym.kind.isOverloadError()) {
2814                    boundSearchResultKind = SearchResultKind.GOOD_MATCH;
2815                }
2816            }
2817        }
2818
2819        //step 2 - unbound lookup
2820        Symbol origUnboundSym = null;
2821        Symbol unboundSym = methodNotFound;
2822        ReferenceLookupHelper unboundLookupHelper = null;
2823        Env<AttrContext> unboundEnv = env.dup(env.tree, env.info.dup());
2824        SearchResultKind unboundSearchResultKind = SearchResultKind.NOT_APPLICABLE_MATCH;
2825        boolean staticErrorForUnbound = false;
2826        if (isStaticSelector) {
2827            unboundLookupHelper = boundLookupHelper.unboundLookup(inferenceContext);
2828            MethodResolutionContext unboundSearchResolveContext =
2829                    new MethodResolutionContext();
2830            unboundSearchResolveContext.methodCheck = methodCheck;
2831            unboundSym = origUnboundSym = lookupMethod(unboundEnv, env.tree.pos(),
2832                    site.tsym, unboundSearchResolveContext, unboundLookupHelper);
2833
2834            if (unboundSym.kind != WRONG_MTH && unboundSym.kind != WRONG_MTHS) {
2835                if (shouldCheckForStaticness) {
2836                    if (unboundSym.isStatic()) {
2837                        staticErrorForUnbound = true;
2838                        if (hasAnotherApplicableMethod(
2839                                unboundSearchResolveContext, unboundSym, false)) {
2840                            unboundSearchResultKind = SearchResultKind.BAD_MATCH_MORE_SPECIFIC;
2841                        } else {
2842                            unboundSearchResultKind = SearchResultKind.BAD_MATCH;
2843                            if (!unboundSym.kind.isOverloadError()) {
2844                                unboundSym = methodWithCorrectStaticnessNotFound;
2845                            }
2846                        }
2847                    } else if (!unboundSym.kind.isOverloadError()) {
2848                        unboundSearchResultKind = SearchResultKind.GOOD_MATCH;
2849                    }
2850                }
2851            }
2852        }
2853
2854        //merge results
2855        Pair<Symbol, ReferenceLookupHelper> res;
2856        Symbol bestSym = choose(boundSym, unboundSym);
2857        if (!bestSym.kind.isOverloadError() &&
2858            (staticErrorForBound || staticErrorForUnbound)) {
2859            if (staticErrorForBound) {
2860                boundSym = methodWithCorrectStaticnessNotFound;
2861            }
2862            if (staticErrorForUnbound) {
2863                unboundSym = methodWithCorrectStaticnessNotFound;
2864            }
2865            bestSym = choose(boundSym, unboundSym);
2866        }
2867        if (bestSym == methodWithCorrectStaticnessNotFound && mode == AttrMode.CHECK) {
2868            Symbol symToPrint = origBoundSym;
2869            String errorFragmentToPrint = "non-static.cant.be.ref";
2870            if (staticErrorForBound && staticErrorForUnbound) {
2871                if (unboundSearchResultKind == SearchResultKind.BAD_MATCH_MORE_SPECIFIC) {
2872                    symToPrint = origUnboundSym;
2873                    errorFragmentToPrint = "static.method.in.unbound.lookup";
2874                }
2875            } else {
2876                if (!staticErrorForBound) {
2877                    symToPrint = origUnboundSym;
2878                    errorFragmentToPrint = "static.method.in.unbound.lookup";
2879                }
2880            }
2881            log.error(referenceTree.expr.pos(), "invalid.mref",
2882                Kinds.kindName(referenceTree.getMode()),
2883                diags.fragment(errorFragmentToPrint,
2884                Kinds.kindName(symToPrint), symToPrint));
2885        }
2886        res = new Pair<>(bestSym,
2887                bestSym == unboundSym ? unboundLookupHelper : boundLookupHelper);
2888        env.info.pendingResolutionPhase = bestSym == unboundSym ?
2889                unboundEnv.info.pendingResolutionPhase :
2890                boundEnv.info.pendingResolutionPhase;
2891
2892        return res;
2893    }
2894
2895    enum SearchResultKind {
2896        GOOD_MATCH,                 //type I
2897        BAD_MATCH_MORE_SPECIFIC,    //type II
2898        BAD_MATCH,                  //type III
2899        NOT_APPLICABLE_MATCH        //type IV
2900    }
2901
2902    boolean hasAnotherApplicableMethod(MethodResolutionContext resolutionContext,
2903            Symbol bestSoFar, boolean staticMth) {
2904        for (Candidate c : resolutionContext.candidates) {
2905            if (resolutionContext.step != c.step ||
2906                !c.isApplicable() ||
2907                c.sym == bestSoFar) {
2908                continue;
2909            } else {
2910                if (c.sym.isStatic() == staticMth) {
2911                    return true;
2912                }
2913            }
2914        }
2915        return false;
2916    }
2917
2918    //where
2919        private Symbol choose(Symbol boundSym, Symbol unboundSym) {
2920            if (lookupSuccess(boundSym) && lookupSuccess(unboundSym)) {
2921                return ambiguityError(boundSym, unboundSym);
2922            } else if (lookupSuccess(boundSym) ||
2923                    (canIgnore(unboundSym) && !canIgnore(boundSym))) {
2924                return boundSym;
2925            } else if (lookupSuccess(unboundSym) ||
2926                    (canIgnore(boundSym) && !canIgnore(unboundSym))) {
2927                return unboundSym;
2928            } else {
2929                return boundSym;
2930            }
2931        }
2932
2933        private boolean lookupSuccess(Symbol s) {
2934            return s.kind == MTH || s.kind == AMBIGUOUS;
2935        }
2936
2937        private boolean canIgnore(Symbol s) {
2938            switch (s.kind) {
2939                case ABSENT_MTH:
2940                    return true;
2941                case WRONG_MTH:
2942                    InapplicableSymbolError errSym =
2943                            (InapplicableSymbolError)s.baseSymbol();
2944                    return new Template(MethodCheckDiag.ARITY_MISMATCH.regex())
2945                            .matches(errSym.errCandidate().snd);
2946                case WRONG_MTHS:
2947                    InapplicableSymbolsError errSyms =
2948                            (InapplicableSymbolsError)s.baseSymbol();
2949                    return errSyms.filterCandidates(errSyms.mapCandidates()).isEmpty();
2950                case WRONG_STATICNESS:
2951                    return false;
2952                default:
2953                    return false;
2954            }
2955        }
2956
2957    /**
2958     * Helper for defining custom method-like lookup logic; a lookup helper
2959     * provides hooks for (i) the actual lookup logic and (ii) accessing the
2960     * lookup result (this step might result in compiler diagnostics to be generated)
2961     */
2962    abstract class LookupHelper {
2963
2964        /** name of the symbol to lookup */
2965        Name name;
2966
2967        /** location in which the lookup takes place */
2968        Type site;
2969
2970        /** actual types used during the lookup */
2971        List<Type> argtypes;
2972
2973        /** type arguments used during the lookup */
2974        List<Type> typeargtypes;
2975
2976        /** Max overload resolution phase handled by this helper */
2977        MethodResolutionPhase maxPhase;
2978
2979        LookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
2980            this.name = name;
2981            this.site = site;
2982            this.argtypes = argtypes;
2983            this.typeargtypes = typeargtypes;
2984            this.maxPhase = maxPhase;
2985        }
2986
2987        /**
2988         * Should lookup stop at given phase with given result
2989         */
2990        final boolean shouldStop(Symbol sym, MethodResolutionPhase phase) {
2991            return phase.ordinal() > maxPhase.ordinal() ||
2992                !sym.kind.isOverloadError() || sym.kind == AMBIGUOUS;
2993        }
2994
2995        /**
2996         * Search for a symbol under a given overload resolution phase - this method
2997         * is usually called several times, once per each overload resolution phase
2998         */
2999        abstract Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase);
3000
3001        /**
3002         * Dump overload resolution info
3003         */
3004        void debug(DiagnosticPosition pos, Symbol sym) {
3005            //do nothing
3006        }
3007
3008        /**
3009         * Validate the result of the lookup
3010         */
3011        abstract Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym);
3012    }
3013
3014    abstract class BasicLookupHelper extends LookupHelper {
3015
3016        BasicLookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes) {
3017            this(name, site, argtypes, typeargtypes, MethodResolutionPhase.VARARITY);
3018        }
3019
3020        BasicLookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
3021            super(name, site, argtypes, typeargtypes, maxPhase);
3022        }
3023
3024        @Override
3025        final Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
3026            Symbol sym = doLookup(env, phase);
3027            if (sym.kind == AMBIGUOUS) {
3028                AmbiguityError a_err = (AmbiguityError)sym.baseSymbol();
3029                sym = a_err.mergeAbstracts(site);
3030            }
3031            return sym;
3032        }
3033
3034        abstract Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase);
3035
3036        @Override
3037        Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
3038            if (sym.kind.isOverloadError()) {
3039                //if nothing is found return the 'first' error
3040                sym = accessMethod(sym, pos, location, site, name, true, argtypes, typeargtypes);
3041            }
3042            return sym;
3043        }
3044
3045        @Override
3046        void debug(DiagnosticPosition pos, Symbol sym) {
3047            reportVerboseResolutionDiagnostic(pos, name, site, argtypes, typeargtypes, sym);
3048        }
3049    }
3050
3051    /**
3052     * Helper class for member reference lookup. A reference lookup helper
3053     * defines the basic logic for member reference lookup; a method gives
3054     * access to an 'unbound' helper used to perform an unbound member
3055     * reference lookup.
3056     */
3057    abstract class ReferenceLookupHelper extends LookupHelper {
3058
3059        /** The member reference tree */
3060        JCMemberReference referenceTree;
3061
3062        ReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
3063                List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
3064            super(name, site, argtypes, typeargtypes, maxPhase);
3065            this.referenceTree = referenceTree;
3066        }
3067
3068        /**
3069         * Returns an unbound version of this lookup helper. By default, this
3070         * method returns an dummy lookup helper.
3071         */
3072        ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
3073            //dummy loopkup helper that always return 'methodNotFound'
3074            return new ReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase) {
3075                @Override
3076                ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
3077                    return this;
3078                }
3079                @Override
3080                Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
3081                    return methodNotFound;
3082                }
3083                @Override
3084                ReferenceKind referenceKind(Symbol sym) {
3085                    Assert.error();
3086                    return null;
3087                }
3088            };
3089        }
3090
3091        /**
3092         * Get the kind of the member reference
3093         */
3094        abstract JCMemberReference.ReferenceKind referenceKind(Symbol sym);
3095
3096        Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
3097            if (sym.kind == AMBIGUOUS) {
3098                AmbiguityError a_err = (AmbiguityError)sym.baseSymbol();
3099                sym = a_err.mergeAbstracts(site);
3100            }
3101            //skip error reporting
3102            return sym;
3103        }
3104    }
3105
3106    /**
3107     * Helper class for method reference lookup. The lookup logic is based
3108     * upon Resolve.findMethod; in certain cases, this helper class has a
3109     * corresponding unbound helper class (see UnboundMethodReferenceLookupHelper).
3110     * In such cases, non-static lookup results are thrown away.
3111     */
3112    class MethodReferenceLookupHelper extends ReferenceLookupHelper {
3113
3114        MethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
3115                List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
3116            super(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
3117        }
3118
3119        @Override
3120        final Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
3121            return findMethod(env, site, name, argtypes, typeargtypes,
3122                    phase.isBoxingRequired(), phase.isVarargsRequired(), syms.operatorNames.contains(name));
3123        }
3124
3125        @Override
3126        ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
3127            if (TreeInfo.isStaticSelector(referenceTree.expr, names) &&
3128                    argtypes.nonEmpty() &&
3129                    (argtypes.head.hasTag(NONE) ||
3130                    types.isSubtypeUnchecked(inferenceContext.asUndetVar(argtypes.head), site))) {
3131                return new UnboundMethodReferenceLookupHelper(referenceTree, name,
3132                        site, argtypes, typeargtypes, maxPhase);
3133            } else {
3134                return super.unboundLookup(inferenceContext);
3135            }
3136        }
3137
3138        @Override
3139        ReferenceKind referenceKind(Symbol sym) {
3140            if (sym.isStatic()) {
3141                return ReferenceKind.STATIC;
3142            } else {
3143                Name selName = TreeInfo.name(referenceTree.getQualifierExpression());
3144                return selName != null && selName == names._super ?
3145                        ReferenceKind.SUPER :
3146                        ReferenceKind.BOUND;
3147            }
3148        }
3149    }
3150
3151    /**
3152     * Helper class for unbound method reference lookup. Essentially the same
3153     * as the basic method reference lookup helper; main difference is that static
3154     * lookup results are thrown away. If qualifier type is raw, an attempt to
3155     * infer a parameterized type is made using the first actual argument (that
3156     * would otherwise be ignored during the lookup).
3157     */
3158    class UnboundMethodReferenceLookupHelper extends MethodReferenceLookupHelper {
3159
3160        UnboundMethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
3161                List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
3162            super(referenceTree, name, site, argtypes.tail, typeargtypes, maxPhase);
3163            if (site.isRaw() && !argtypes.head.hasTag(NONE)) {
3164                Type asSuperSite = types.asSuper(argtypes.head, site.tsym);
3165                this.site = types.capture(asSuperSite);
3166            }
3167        }
3168
3169        @Override
3170        ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
3171            return this;
3172        }
3173
3174        @Override
3175        ReferenceKind referenceKind(Symbol sym) {
3176            return ReferenceKind.UNBOUND;
3177        }
3178    }
3179
3180    /**
3181     * Helper class for array constructor lookup; an array constructor lookup
3182     * is simulated by looking up a method that returns the array type specified
3183     * as qualifier, and that accepts a single int parameter (size of the array).
3184     */
3185    class ArrayConstructorReferenceLookupHelper extends ReferenceLookupHelper {
3186
3187        ArrayConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
3188                List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
3189            super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase);
3190        }
3191
3192        @Override
3193        protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
3194            WriteableScope sc = WriteableScope.create(syms.arrayClass);
3195            MethodSymbol arrayConstr = new MethodSymbol(PUBLIC, name, null, site.tsym);
3196            arrayConstr.type = new MethodType(List.<Type>of(syms.intType), site, List.<Type>nil(), syms.methodClass);
3197            sc.enter(arrayConstr);
3198            return findMethodInScope(env, site, name, argtypes, typeargtypes, sc, methodNotFound, phase.isBoxingRequired(), phase.isVarargsRequired(), false, false);
3199        }
3200
3201        @Override
3202        ReferenceKind referenceKind(Symbol sym) {
3203            return ReferenceKind.ARRAY_CTOR;
3204        }
3205    }
3206
3207    /**
3208     * Helper class for constructor reference lookup. The lookup logic is based
3209     * upon either Resolve.findMethod or Resolve.findDiamond - depending on
3210     * whether the constructor reference needs diamond inference (this is the case
3211     * if the qualifier type is raw). A special erroneous symbol is returned
3212     * if the lookup returns the constructor of an inner class and there's no
3213     * enclosing instance in scope.
3214     */
3215    class ConstructorReferenceLookupHelper extends ReferenceLookupHelper {
3216
3217        boolean needsInference;
3218
3219        ConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
3220                List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
3221            super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase);
3222            if (site.isRaw()) {
3223                this.site = new ClassType(site.getEnclosingType(), site.tsym.type.getTypeArguments(), site.tsym, site.getMetadata());
3224                needsInference = true;
3225            }
3226        }
3227
3228        @Override
3229        protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
3230            Symbol sym = needsInference ?
3231                findDiamond(env, site, argtypes, typeargtypes, phase.isBoxingRequired(), phase.isVarargsRequired()) :
3232                findMethod(env, site, name, argtypes, typeargtypes,
3233                        phase.isBoxingRequired(), phase.isVarargsRequired(), syms.operatorNames.contains(name));
3234            return sym.kind != MTH ||
3235                          site.getEnclosingType().hasTag(NONE) ||
3236                          hasEnclosingInstance(env, site) ?
3237                          sym : new InvalidSymbolError(MISSING_ENCL, sym, null) {
3238                    @Override
3239                    JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
3240                       return diags.create(dkind, log.currentSource(), pos,
3241                            "cant.access.inner.cls.constr", site.tsym.name, argtypes, site.getEnclosingType());
3242                    }
3243                };
3244        }
3245
3246        @Override
3247        ReferenceKind referenceKind(Symbol sym) {
3248            return site.getEnclosingType().hasTag(NONE) ?
3249                    ReferenceKind.TOPLEVEL : ReferenceKind.IMPLICIT_INNER;
3250        }
3251    }
3252
3253    /**
3254     * Main overload resolution routine. On each overload resolution step, a
3255     * lookup helper class is used to perform the method/constructor lookup;
3256     * at the end of the lookup, the helper is used to validate the results
3257     * (this last step might trigger overload resolution diagnostics).
3258     */
3259    Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, MethodCheck methodCheck, LookupHelper lookupHelper) {
3260        MethodResolutionContext resolveContext = new MethodResolutionContext();
3261        resolveContext.methodCheck = methodCheck;
3262        return lookupMethod(env, pos, location, resolveContext, lookupHelper);
3263    }
3264
3265    Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location,
3266            MethodResolutionContext resolveContext, LookupHelper lookupHelper) {
3267        MethodResolutionContext prevResolutionContext = currentResolutionContext;
3268        try {
3269            Symbol bestSoFar = methodNotFound;
3270            currentResolutionContext = resolveContext;
3271            for (MethodResolutionPhase phase : methodResolutionSteps) {
3272                if (lookupHelper.shouldStop(bestSoFar, phase))
3273                    break;
3274                MethodResolutionPhase prevPhase = currentResolutionContext.step;
3275                Symbol prevBest = bestSoFar;
3276                currentResolutionContext.step = phase;
3277                Symbol sym = lookupHelper.lookup(env, phase);
3278                lookupHelper.debug(pos, sym);
3279                bestSoFar = phase.mergeResults(bestSoFar, sym);
3280                env.info.pendingResolutionPhase = (prevBest == bestSoFar) ? prevPhase : phase;
3281            }
3282            return lookupHelper.access(env, pos, location, bestSoFar);
3283        } finally {
3284            currentResolutionContext = prevResolutionContext;
3285        }
3286    }
3287
3288    /**
3289     * Resolve `c.name' where name == this or name == super.
3290     * @param pos           The position to use for error reporting.
3291     * @param env           The environment current at the expression.
3292     * @param c             The qualifier.
3293     * @param name          The identifier's name.
3294     */
3295    Symbol resolveSelf(DiagnosticPosition pos,
3296                       Env<AttrContext> env,
3297                       TypeSymbol c,
3298                       Name name) {
3299        Env<AttrContext> env1 = env;
3300        boolean staticOnly = false;
3301        while (env1.outer != null) {
3302            if (isStatic(env1)) staticOnly = true;
3303            if (env1.enclClass.sym == c) {
3304                Symbol sym = env1.info.scope.findFirst(name);
3305                if (sym != null) {
3306                    if (staticOnly) sym = new StaticError(sym);
3307                    return accessBase(sym, pos, env.enclClass.sym.type,
3308                                  name, true);
3309                }
3310            }
3311            if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
3312            env1 = env1.outer;
3313        }
3314        if (c.isInterface() &&
3315            name == names._super && !isStatic(env) &&
3316            types.isDirectSuperInterface(c, env.enclClass.sym)) {
3317            //this might be a default super call if one of the superinterfaces is 'c'
3318            for (Type t : pruneInterfaces(env.enclClass.type)) {
3319                if (t.tsym == c) {
3320                    env.info.defaultSuperCallSite = t;
3321                    return new VarSymbol(0, names._super,
3322                            types.asSuper(env.enclClass.type, c), env.enclClass.sym);
3323                }
3324            }
3325            //find a direct superinterface that is a subtype of 'c'
3326            for (Type i : types.interfaces(env.enclClass.type)) {
3327                if (i.tsym.isSubClass(c, types) && i.tsym != c) {
3328                    log.error(pos, "illegal.default.super.call", c,
3329                            diags.fragment("redundant.supertype", c, i));
3330                    return syms.errSymbol;
3331                }
3332            }
3333            Assert.error();
3334        }
3335        log.error(pos, "not.encl.class", c);
3336        return syms.errSymbol;
3337    }
3338    //where
3339    private List<Type> pruneInterfaces(Type t) {
3340        ListBuffer<Type> result = new ListBuffer<>();
3341        for (Type t1 : types.interfaces(t)) {
3342            boolean shouldAdd = true;
3343            for (Type t2 : types.interfaces(t)) {
3344                if (t1 != t2 && types.isSubtypeNoCapture(t2, t1)) {
3345                    shouldAdd = false;
3346                }
3347            }
3348            if (shouldAdd) {
3349                result.append(t1);
3350            }
3351        }
3352        return result.toList();
3353    }
3354
3355
3356    /**
3357     * Resolve `c.this' for an enclosing class c that contains the
3358     * named member.
3359     * @param pos           The position to use for error reporting.
3360     * @param env           The environment current at the expression.
3361     * @param member        The member that must be contained in the result.
3362     */
3363    Symbol resolveSelfContaining(DiagnosticPosition pos,
3364                                 Env<AttrContext> env,
3365                                 Symbol member,
3366                                 boolean isSuperCall) {
3367        Symbol sym = resolveSelfContainingInternal(env, member, isSuperCall);
3368        if (sym == null) {
3369            log.error(pos, "encl.class.required", member);
3370            return syms.errSymbol;
3371        } else {
3372            return accessBase(sym, pos, env.enclClass.sym.type, sym.name, true);
3373        }
3374    }
3375
3376    boolean hasEnclosingInstance(Env<AttrContext> env, Type type) {
3377        Symbol encl = resolveSelfContainingInternal(env, type.tsym, false);
3378        return encl != null && !encl.kind.isOverloadError();
3379    }
3380
3381    private Symbol resolveSelfContainingInternal(Env<AttrContext> env,
3382                                 Symbol member,
3383                                 boolean isSuperCall) {
3384        Name name = names._this;
3385        Env<AttrContext> env1 = isSuperCall ? env.outer : env;
3386        boolean staticOnly = false;
3387        if (env1 != null) {
3388            while (env1 != null && env1.outer != null) {
3389                if (isStatic(env1)) staticOnly = true;
3390                if (env1.enclClass.sym.isSubClass(member.owner, types)) {
3391                    Symbol sym = env1.info.scope.findFirst(name);
3392                    if (sym != null) {
3393                        if (staticOnly) sym = new StaticError(sym);
3394                        return sym;
3395                    }
3396                }
3397                if ((env1.enclClass.sym.flags() & STATIC) != 0)
3398                    staticOnly = true;
3399                env1 = env1.outer;
3400            }
3401        }
3402        return null;
3403    }
3404
3405    /**
3406     * Resolve an appropriate implicit this instance for t's container.
3407     * JLS 8.8.5.1 and 15.9.2
3408     */
3409    Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
3410        return resolveImplicitThis(pos, env, t, false);
3411    }
3412
3413    Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t, boolean isSuperCall) {
3414        Type thisType = (t.tsym.owner.kind.matches(KindSelector.VAL_MTH)
3415                         ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
3416                         : resolveSelfContaining(pos, env, t.tsym, isSuperCall)).type;
3417        if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
3418            log.error(pos, "cant.ref.before.ctor.called", "this");
3419        return thisType;
3420    }
3421
3422/* ***************************************************************************
3423 *  ResolveError classes, indicating error situations when accessing symbols
3424 ****************************************************************************/
3425
3426    //used by TransTypes when checking target type of synthetic cast
3427    public void logAccessErrorInternal(Env<AttrContext> env, JCTree tree, Type type) {
3428        AccessError error = new AccessError(env, env.enclClass.type, type.tsym);
3429        logResolveError(error, tree.pos(), env.enclClass.sym, env.enclClass.type, null, null, null);
3430    }
3431    //where
3432    private void logResolveError(ResolveError error,
3433            DiagnosticPosition pos,
3434            Symbol location,
3435            Type site,
3436            Name name,
3437            List<Type> argtypes,
3438            List<Type> typeargtypes) {
3439        JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
3440                pos, location, site, name, argtypes, typeargtypes);
3441        if (d != null) {
3442            d.setFlag(DiagnosticFlag.RESOLVE_ERROR);
3443            log.report(d);
3444        }
3445    }
3446
3447    private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
3448
3449    public Object methodArguments(List<Type> argtypes) {
3450        if (argtypes == null || argtypes.isEmpty()) {
3451            return noArgs;
3452        } else {
3453            ListBuffer<Object> diagArgs = new ListBuffer<>();
3454            for (Type t : argtypes) {
3455                if (t.hasTag(DEFERRED)) {
3456                    diagArgs.append(((DeferredAttr.DeferredType)t).tree);
3457                } else {
3458                    diagArgs.append(t);
3459                }
3460            }
3461            return diagArgs;
3462        }
3463    }
3464
3465    /**
3466     * Root class for resolution errors. Subclass of ResolveError
3467     * represent a different kinds of resolution error - as such they must
3468     * specify how they map into concrete compiler diagnostics.
3469     */
3470    abstract class ResolveError extends Symbol {
3471
3472        /** The name of the kind of error, for debugging only. */
3473        final String debugName;
3474
3475        ResolveError(Kind kind, String debugName) {
3476            super(kind, 0, null, null, null);
3477            this.debugName = debugName;
3478        }
3479
3480        @Override @DefinedBy(Api.LANGUAGE_MODEL)
3481        public <R, P> R accept(ElementVisitor<R, P> v, P p) {
3482            throw new AssertionError();
3483        }
3484
3485        @Override
3486        public String toString() {
3487            return debugName;
3488        }
3489
3490        @Override
3491        public boolean exists() {
3492            return false;
3493        }
3494
3495        @Override
3496        public boolean isStatic() {
3497            return false;
3498        }
3499
3500        /**
3501         * Create an external representation for this erroneous symbol to be
3502         * used during attribution - by default this returns the symbol of a
3503         * brand new error type which stores the original type found
3504         * during resolution.
3505         *
3506         * @param name     the name used during resolution
3507         * @param location the location from which the symbol is accessed
3508         */
3509        protected Symbol access(Name name, TypeSymbol location) {
3510            return types.createErrorType(name, location, syms.errSymbol.type).tsym;
3511        }
3512
3513        /**
3514         * Create a diagnostic representing this resolution error.
3515         *
3516         * @param dkind     The kind of the diagnostic to be created (e.g error).
3517         * @param pos       The position to be used for error reporting.
3518         * @param site      The original type from where the selection took place.
3519         * @param name      The name of the symbol to be resolved.
3520         * @param argtypes  The invocation's value arguments,
3521         *                  if we looked for a method.
3522         * @param typeargtypes  The invocation's type arguments,
3523         *                      if we looked for a method.
3524         */
3525        abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3526                DiagnosticPosition pos,
3527                Symbol location,
3528                Type site,
3529                Name name,
3530                List<Type> argtypes,
3531                List<Type> typeargtypes);
3532    }
3533
3534    /**
3535     * This class is the root class of all resolution errors caused by
3536     * an invalid symbol being found during resolution.
3537     */
3538    abstract class InvalidSymbolError extends ResolveError {
3539
3540        /** The invalid symbol found during resolution */
3541        Symbol sym;
3542
3543        InvalidSymbolError(Kind kind, Symbol sym, String debugName) {
3544            super(kind, debugName);
3545            this.sym = sym;
3546        }
3547
3548        @Override
3549        public boolean exists() {
3550            return true;
3551        }
3552
3553        @Override
3554        public String toString() {
3555             return super.toString() + " wrongSym=" + sym;
3556        }
3557
3558        @Override
3559        public Symbol access(Name name, TypeSymbol location) {
3560            if (!sym.kind.isOverloadError() && sym.kind.matches(KindSelector.TYP))
3561                return types.createErrorType(name, location, sym.type).tsym;
3562            else
3563                return sym;
3564        }
3565    }
3566
3567    /**
3568     * InvalidSymbolError error class indicating that a symbol matching a
3569     * given name does not exists in a given site.
3570     */
3571    class SymbolNotFoundError extends ResolveError {
3572
3573        SymbolNotFoundError(Kind kind) {
3574            this(kind, "symbol not found error");
3575        }
3576
3577        SymbolNotFoundError(Kind kind, String debugName) {
3578            super(kind, debugName);
3579        }
3580
3581        @Override
3582        JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3583                DiagnosticPosition pos,
3584                Symbol location,
3585                Type site,
3586                Name name,
3587                List<Type> argtypes,
3588                List<Type> typeargtypes) {
3589            argtypes = argtypes == null ? List.<Type>nil() : argtypes;
3590            typeargtypes = typeargtypes == null ? List.<Type>nil() : typeargtypes;
3591            if (name == names.error)
3592                return null;
3593
3594            if (syms.operatorNames.contains(name)) {
3595                boolean isUnaryOp = argtypes.size() == 1;
3596                String key = argtypes.size() == 1 ?
3597                    "operator.cant.be.applied" :
3598                    "operator.cant.be.applied.1";
3599                Type first = argtypes.head;
3600                Type second = !isUnaryOp ? argtypes.tail.head : null;
3601                return diags.create(dkind, log.currentSource(), pos,
3602                        key, name, first, second);
3603            }
3604            boolean hasLocation = false;
3605            if (location == null) {
3606                location = site.tsym;
3607            }
3608            if (!location.name.isEmpty()) {
3609                if (location.kind == PCK && !site.tsym.exists()) {
3610                    return diags.create(dkind, log.currentSource(), pos,
3611                        "doesnt.exist", location);
3612                }
3613                hasLocation = !location.name.equals(names._this) &&
3614                        !location.name.equals(names._super);
3615            }
3616            boolean isConstructor = (kind == ABSENT_MTH || kind == WRONG_STATICNESS) &&
3617                    name == names.init;
3618            KindName kindname = isConstructor ? KindName.CONSTRUCTOR : kind.absentKind();
3619            Name idname = isConstructor ? site.tsym.name : name;
3620            String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation);
3621            if (hasLocation) {
3622                return diags.create(dkind, log.currentSource(), pos,
3623                        errKey, kindname, idname, //symbol kindname, name
3624                        typeargtypes, args(argtypes), //type parameters and arguments (if any)
3625                        getLocationDiag(location, site)); //location kindname, type
3626            }
3627            else {
3628                return diags.create(dkind, log.currentSource(), pos,
3629                        errKey, kindname, idname, //symbol kindname, name
3630                        typeargtypes, args(argtypes)); //type parameters and arguments (if any)
3631            }
3632        }
3633        //where
3634        private Object args(List<Type> args) {
3635            return args.isEmpty() ? args : methodArguments(args);
3636        }
3637
3638        private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) {
3639            String key = "cant.resolve";
3640            String suffix = hasLocation ? ".location" : "";
3641            switch (kindname) {
3642                case METHOD:
3643                case CONSTRUCTOR: {
3644                    suffix += ".args";
3645                    suffix += hasTypeArgs ? ".params" : "";
3646                }
3647            }
3648            return key + suffix;
3649        }
3650        private JCDiagnostic getLocationDiag(Symbol location, Type site) {
3651            if (location.kind == VAR) {
3652                return diags.fragment("location.1",
3653                    kindName(location),
3654                    location,
3655                    location.type);
3656            } else {
3657                return diags.fragment("location",
3658                    typeKindName(site),
3659                    site,
3660                    null);
3661            }
3662        }
3663    }
3664
3665    /**
3666     * InvalidSymbolError error class indicating that a given symbol
3667     * (either a method, a constructor or an operand) is not applicable
3668     * given an actual arguments/type argument list.
3669     */
3670    class InapplicableSymbolError extends ResolveError {
3671
3672        protected MethodResolutionContext resolveContext;
3673
3674        InapplicableSymbolError(MethodResolutionContext context) {
3675            this(WRONG_MTH, "inapplicable symbol error", context);
3676        }
3677
3678        protected InapplicableSymbolError(Kind kind, String debugName, MethodResolutionContext context) {
3679            super(kind, debugName);
3680            this.resolveContext = context;
3681        }
3682
3683        @Override
3684        public String toString() {
3685            return super.toString();
3686        }
3687
3688        @Override
3689        public boolean exists() {
3690            return true;
3691        }
3692
3693        @Override
3694        JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3695                DiagnosticPosition pos,
3696                Symbol location,
3697                Type site,
3698                Name name,
3699                List<Type> argtypes,
3700                List<Type> typeargtypes) {
3701            if (name == names.error)
3702                return null;
3703
3704            if (syms.operatorNames.contains(name)) {
3705                boolean isUnaryOp = argtypes.size() == 1;
3706                String key = argtypes.size() == 1 ?
3707                    "operator.cant.be.applied" :
3708                    "operator.cant.be.applied.1";
3709                Type first = argtypes.head;
3710                Type second = !isUnaryOp ? argtypes.tail.head : null;
3711                return diags.create(dkind, log.currentSource(), pos,
3712                        key, name, first, second);
3713            }
3714            else {
3715                Pair<Symbol, JCDiagnostic> c = errCandidate();
3716                if (compactMethodDiags) {
3717                    JCDiagnostic simpleDiag =
3718                        MethodResolutionDiagHelper.rewrite(diags, pos, log.currentSource(), dkind, c.snd);
3719                    if (simpleDiag != null) {
3720                        return simpleDiag;
3721                    }
3722                }
3723                Symbol ws = c.fst.asMemberOf(site, types);
3724                return diags.create(dkind, log.currentSource(), pos,
3725                          "cant.apply.symbol",
3726                          kindName(ws),
3727                          ws.name == names.init ? ws.owner.name : ws.name,
3728                          methodArguments(ws.type.getParameterTypes()),
3729                          methodArguments(argtypes),
3730                          kindName(ws.owner),
3731                          ws.owner.type,
3732                          c.snd);
3733            }
3734        }
3735
3736        @Override
3737        public Symbol access(Name name, TypeSymbol location) {
3738            return types.createErrorType(name, location, syms.errSymbol.type).tsym;
3739        }
3740
3741        protected Pair<Symbol, JCDiagnostic> errCandidate() {
3742            Candidate bestSoFar = null;
3743            for (Candidate c : resolveContext.candidates) {
3744                if (c.isApplicable()) continue;
3745                bestSoFar = c;
3746            }
3747            Assert.checkNonNull(bestSoFar);
3748            return new Pair<>(bestSoFar.sym, bestSoFar.details);
3749        }
3750    }
3751
3752    /**
3753     * ResolveError error class indicating that a symbol (either methods, constructors or operand)
3754     * is not applicable given an actual arguments/type argument list.
3755     */
3756    class InapplicableSymbolsError extends InapplicableSymbolError {
3757
3758        InapplicableSymbolsError(MethodResolutionContext context) {
3759            super(WRONG_MTHS, "inapplicable symbols", context);
3760        }
3761
3762        @Override
3763        JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3764                DiagnosticPosition pos,
3765                Symbol location,
3766                Type site,
3767                Name name,
3768                List<Type> argtypes,
3769                List<Type> typeargtypes) {
3770            Map<Symbol, JCDiagnostic> candidatesMap = mapCandidates();
3771            Map<Symbol, JCDiagnostic> filteredCandidates = compactMethodDiags ?
3772                    filterCandidates(candidatesMap) :
3773                    mapCandidates();
3774            if (filteredCandidates.isEmpty()) {
3775                filteredCandidates = candidatesMap;
3776            }
3777            boolean truncatedDiag = candidatesMap.size() != filteredCandidates.size();
3778            if (filteredCandidates.size() > 1) {
3779                JCDiagnostic err = diags.create(dkind,
3780                        null,
3781                        truncatedDiag ?
3782                            EnumSet.of(DiagnosticFlag.COMPRESSED) :
3783                            EnumSet.noneOf(DiagnosticFlag.class),
3784                        log.currentSource(),
3785                        pos,
3786                        "cant.apply.symbols",
3787                        name == names.init ? KindName.CONSTRUCTOR : kind.absentKind(),
3788                        name == names.init ? site.tsym.name : name,
3789                        methodArguments(argtypes));
3790                return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(filteredCandidates, site));
3791            } else if (filteredCandidates.size() == 1) {
3792                Map.Entry<Symbol, JCDiagnostic> _e =
3793                                filteredCandidates.entrySet().iterator().next();
3794                final Pair<Symbol, JCDiagnostic> p = new Pair<>(_e.getKey(), _e.getValue());
3795                JCDiagnostic d = new InapplicableSymbolError(resolveContext) {
3796                    @Override
3797                    protected Pair<Symbol, JCDiagnostic> errCandidate() {
3798                        return p;
3799                    }
3800                }.getDiagnostic(dkind, pos,
3801                    location, site, name, argtypes, typeargtypes);
3802                if (truncatedDiag) {
3803                    d.setFlag(DiagnosticFlag.COMPRESSED);
3804                }
3805                return d;
3806            } else {
3807                return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
3808                    location, site, name, argtypes, typeargtypes);
3809            }
3810        }
3811        //where
3812            private Map<Symbol, JCDiagnostic> mapCandidates() {
3813                Map<Symbol, JCDiagnostic> candidates = new LinkedHashMap<>();
3814                for (Candidate c : resolveContext.candidates) {
3815                    if (c.isApplicable()) continue;
3816                    candidates.put(c.sym, c.details);
3817                }
3818                return candidates;
3819            }
3820
3821            Map<Symbol, JCDiagnostic> filterCandidates(Map<Symbol, JCDiagnostic> candidatesMap) {
3822                Map<Symbol, JCDiagnostic> candidates = new LinkedHashMap<>();
3823                for (Map.Entry<Symbol, JCDiagnostic> _entry : candidatesMap.entrySet()) {
3824                    JCDiagnostic d = _entry.getValue();
3825                    if (!new Template(MethodCheckDiag.ARITY_MISMATCH.regex()).matches(d)) {
3826                        candidates.put(_entry.getKey(), d);
3827                    }
3828                }
3829                return candidates;
3830            }
3831
3832            private List<JCDiagnostic> candidateDetails(Map<Symbol, JCDiagnostic> candidatesMap, Type site) {
3833                List<JCDiagnostic> details = List.nil();
3834                for (Map.Entry<Symbol, JCDiagnostic> _entry : candidatesMap.entrySet()) {
3835                    Symbol sym = _entry.getKey();
3836                    JCDiagnostic detailDiag = diags.fragment("inapplicable.method",
3837                            Kinds.kindName(sym),
3838                            sym.location(site, types),
3839                            sym.asMemberOf(site, types),
3840                            _entry.getValue());
3841                    details = details.prepend(detailDiag);
3842                }
3843                //typically members are visited in reverse order (see Scope)
3844                //so we need to reverse the candidate list so that candidates
3845                //conform to source order
3846                return details;
3847            }
3848    }
3849
3850    /**
3851     * DiamondError error class indicating that a constructor symbol is not applicable
3852     * given an actual arguments/type argument list using diamond inference.
3853     */
3854    class DiamondError extends InapplicableSymbolError {
3855
3856        Symbol sym;
3857
3858        public DiamondError(Symbol sym, MethodResolutionContext context) {
3859            super(sym.kind, "diamondError", context);
3860            this.sym = sym;
3861        }
3862
3863        JCDiagnostic getDetails() {
3864            return (sym.kind == WRONG_MTH) ?
3865                    ((InapplicableSymbolError)sym.baseSymbol()).errCandidate().snd :
3866                    null;
3867        }
3868
3869        @Override
3870        JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos,
3871                Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
3872            JCDiagnostic details = getDetails();
3873            if (details != null && compactMethodDiags) {
3874                JCDiagnostic simpleDiag =
3875                        MethodResolutionDiagHelper.rewrite(diags, pos, log.currentSource(), dkind, details);
3876                if (simpleDiag != null) {
3877                    return simpleDiag;
3878                }
3879            }
3880            String key = details == null ?
3881                "cant.apply.diamond" :
3882                "cant.apply.diamond.1";
3883            return diags.create(dkind, log.currentSource(), pos, key,
3884                    diags.fragment("diamond", site.tsym), details);
3885        }
3886    }
3887
3888    /**
3889     * An InvalidSymbolError error class indicating that a symbol is not
3890     * accessible from a given site
3891     */
3892    class AccessError extends InvalidSymbolError {
3893
3894        private Env<AttrContext> env;
3895        private Type site;
3896
3897        AccessError(Symbol sym) {
3898            this(null, null, sym);
3899        }
3900
3901        AccessError(Env<AttrContext> env, Type site, Symbol sym) {
3902            super(HIDDEN, sym, "access error");
3903            this.env = env;
3904            this.site = site;
3905            if (debugResolve)
3906                log.error("proc.messager", sym + " @ " + site + " is inaccessible.");
3907        }
3908
3909        @Override
3910        public boolean exists() {
3911            return false;
3912        }
3913
3914        @Override
3915        JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3916                DiagnosticPosition pos,
3917                Symbol location,
3918                Type site,
3919                Name name,
3920                List<Type> argtypes,
3921                List<Type> typeargtypes) {
3922            if (sym.owner.type.hasTag(ERROR))
3923                return null;
3924
3925            if (sym.name == names.init && sym.owner != site.tsym) {
3926                return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
3927                        pos, location, site, name, argtypes, typeargtypes);
3928            }
3929            else if ((sym.flags() & PUBLIC) != 0
3930                || (env != null && this.site != null
3931                    && !isAccessible(env, this.site))) {
3932                return diags.create(dkind, log.currentSource(),
3933                        pos, "not.def.access.class.intf.cant.access",
3934                    sym, sym.location());
3935            }
3936            else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) {
3937                return diags.create(dkind, log.currentSource(),
3938                        pos, "report.access", sym,
3939                        asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
3940                        sym.location());
3941            }
3942            else {
3943                return diags.create(dkind, log.currentSource(),
3944                        pos, "not.def.public.cant.access", sym, sym.location());
3945            }
3946        }
3947    }
3948
3949    /**
3950     * InvalidSymbolError error class indicating that an instance member
3951     * has erroneously been accessed from a static context.
3952     */
3953    class StaticError extends InvalidSymbolError {
3954
3955        StaticError(Symbol sym) {
3956            super(STATICERR, sym, "static error");
3957        }
3958
3959        @Override
3960        JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3961                DiagnosticPosition pos,
3962                Symbol location,
3963                Type site,
3964                Name name,
3965                List<Type> argtypes,
3966                List<Type> typeargtypes) {
3967            Symbol errSym = ((sym.kind == TYP && sym.type.hasTag(CLASS))
3968                ? types.erasure(sym.type).tsym
3969                : sym);
3970            return diags.create(dkind, log.currentSource(), pos,
3971                    "non-static.cant.be.ref", kindName(sym), errSym);
3972        }
3973    }
3974
3975    /**
3976     * InvalidSymbolError error class indicating that a pair of symbols
3977     * (either methods, constructors or operands) are ambiguous
3978     * given an actual arguments/type argument list.
3979     */
3980    class AmbiguityError extends ResolveError {
3981
3982        /** The other maximally specific symbol */
3983        List<Symbol> ambiguousSyms = List.nil();
3984
3985        @Override
3986        public boolean exists() {
3987            return true;
3988        }
3989
3990        AmbiguityError(Symbol sym1, Symbol sym2) {
3991            super(AMBIGUOUS, "ambiguity error");
3992            ambiguousSyms = flatten(sym2).appendList(flatten(sym1));
3993        }
3994
3995        private List<Symbol> flatten(Symbol sym) {
3996            if (sym.kind == AMBIGUOUS) {
3997                return ((AmbiguityError)sym.baseSymbol()).ambiguousSyms;
3998            } else {
3999                return List.of(sym);
4000            }
4001        }
4002
4003        AmbiguityError addAmbiguousSymbol(Symbol s) {
4004            ambiguousSyms = ambiguousSyms.prepend(s);
4005            return this;
4006        }
4007
4008        @Override
4009        JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
4010                DiagnosticPosition pos,
4011                Symbol location,
4012                Type site,
4013                Name name,
4014                List<Type> argtypes,
4015                List<Type> typeargtypes) {
4016            List<Symbol> diagSyms = ambiguousSyms.reverse();
4017            Symbol s1 = diagSyms.head;
4018            Symbol s2 = diagSyms.tail.head;
4019            Name sname = s1.name;
4020            if (sname == names.init) sname = s1.owner.name;
4021            return diags.create(dkind, log.currentSource(),
4022                      pos, "ref.ambiguous", sname,
4023                      kindName(s1),
4024                      s1,
4025                      s1.location(site, types),
4026                      kindName(s2),
4027                      s2,
4028                      s2.location(site, types));
4029        }
4030
4031        /**
4032         * If multiple applicable methods are found during overload and none of them
4033         * is more specific than the others, attempt to merge their signatures.
4034         */
4035        Symbol mergeAbstracts(Type site) {
4036            List<Symbol> ambiguousInOrder = ambiguousSyms.reverse();
4037            for (Symbol s : ambiguousInOrder) {
4038                Type mt = types.memberType(site, s);
4039                boolean found = true;
4040                List<Type> allThrown = mt.getThrownTypes();
4041                for (Symbol s2 : ambiguousInOrder) {
4042                    Type mt2 = types.memberType(site, s2);
4043                    if ((s2.flags() & ABSTRACT) == 0 ||
4044                        !types.overrideEquivalent(mt, mt2) ||
4045                        !types.isSameTypes(s.erasure(types).getParameterTypes(),
4046                                       s2.erasure(types).getParameterTypes())) {
4047                        //ambiguity cannot be resolved
4048                        return this;
4049                    }
4050                    Type mst = mostSpecificReturnType(mt, mt2);
4051                    if (mst == null || mst != mt) {
4052                        found = false;
4053                        break;
4054                    }
4055                    allThrown = chk.intersect(allThrown, mt2.getThrownTypes());
4056                }
4057                if (found) {
4058                    //all ambiguous methods were abstract and one method had
4059                    //most specific return type then others
4060                    return (allThrown == mt.getThrownTypes()) ?
4061                            s : new MethodSymbol(
4062                                s.flags(),
4063                                s.name,
4064                                types.createMethodTypeWithThrown(s.type, allThrown),
4065                                s.owner);
4066                }
4067            }
4068            return this;
4069        }
4070
4071        @Override
4072        protected Symbol access(Name name, TypeSymbol location) {
4073            Symbol firstAmbiguity = ambiguousSyms.last();
4074            return firstAmbiguity.kind == TYP ?
4075                    types.createErrorType(name, location, firstAmbiguity.type).tsym :
4076                    firstAmbiguity;
4077        }
4078    }
4079
4080    class BadVarargsMethod extends ResolveError {
4081
4082        ResolveError delegatedError;
4083
4084        BadVarargsMethod(ResolveError delegatedError) {
4085            super(delegatedError.kind, "badVarargs");
4086            this.delegatedError = delegatedError;
4087        }
4088
4089        @Override
4090        public Symbol baseSymbol() {
4091            return delegatedError.baseSymbol();
4092        }
4093
4094        @Override
4095        protected Symbol access(Name name, TypeSymbol location) {
4096            return delegatedError.access(name, location);
4097        }
4098
4099        @Override
4100        public boolean exists() {
4101            return true;
4102        }
4103
4104        @Override
4105        JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
4106            return delegatedError.getDiagnostic(dkind, pos, location, site, name, argtypes, typeargtypes);
4107        }
4108    }
4109
4110    /**
4111     * Helper class for method resolution diagnostic simplification.
4112     * Certain resolution diagnostic are rewritten as simpler diagnostic
4113     * where the enclosing resolution diagnostic (i.e. 'inapplicable method')
4114     * is stripped away, as it doesn't carry additional info. The logic
4115     * for matching a given diagnostic is given in terms of a template
4116     * hierarchy: a diagnostic template can be specified programmatically,
4117     * so that only certain diagnostics are matched. Each templete is then
4118     * associated with a rewriter object that carries out the task of rewtiting
4119     * the diagnostic to a simpler one.
4120     */
4121    static class MethodResolutionDiagHelper {
4122
4123        /**
4124         * A diagnostic rewriter transforms a method resolution diagnostic
4125         * into a simpler one
4126         */
4127        interface DiagnosticRewriter {
4128            JCDiagnostic rewriteDiagnostic(JCDiagnostic.Factory diags,
4129                    DiagnosticPosition preferedPos, DiagnosticSource preferredSource,
4130                    DiagnosticType preferredKind, JCDiagnostic d);
4131        }
4132
4133        /**
4134         * A diagnostic template is made up of two ingredients: (i) a regular
4135         * expression for matching a diagnostic key and (ii) a list of sub-templates
4136         * for matching diagnostic arguments.
4137         */
4138        static class Template {
4139
4140            /** regex used to match diag key */
4141            String regex;
4142
4143            /** templates used to match diagnostic args */
4144            Template[] subTemplates;
4145
4146            Template(String key, Template... subTemplates) {
4147                this.regex = key;
4148                this.subTemplates = subTemplates;
4149            }
4150
4151            /**
4152             * Returns true if the regex matches the diagnostic key and if
4153             * all diagnostic arguments are matches by corresponding sub-templates.
4154             */
4155            boolean matches(Object o) {
4156                JCDiagnostic d = (JCDiagnostic)o;
4157                Object[] args = d.getArgs();
4158                if (!d.getCode().matches(regex) ||
4159                        subTemplates.length != d.getArgs().length) {
4160                    return false;
4161                }
4162                for (int i = 0; i < args.length ; i++) {
4163                    if (!subTemplates[i].matches(args[i])) {
4164                        return false;
4165                    }
4166                }
4167                return true;
4168            }
4169        }
4170
4171        /**
4172         * Common rewriter for all argument mismatch simplifications.
4173         */
4174        static class ArgMismatchRewriter implements DiagnosticRewriter {
4175
4176            /** the index of the subdiagnostic to be used as primary. */
4177            int causeIndex;
4178
4179            public ArgMismatchRewriter(int causeIndex) {
4180                this.causeIndex = causeIndex;
4181            }
4182
4183            @Override
4184            public JCDiagnostic rewriteDiagnostic(JCDiagnostic.Factory diags,
4185                    DiagnosticPosition preferedPos, DiagnosticSource preferredSource,
4186                    DiagnosticType preferredKind, JCDiagnostic d) {
4187                JCDiagnostic cause = (JCDiagnostic)d.getArgs()[causeIndex];
4188                return diags.create(preferredKind, preferredSource, d.getDiagnosticPosition(),
4189                        "prob.found.req", cause);
4190            }
4191        }
4192
4193        /** a dummy template that match any diagnostic argument */
4194        static final Template skip = new Template("") {
4195            @Override
4196            boolean matches(Object d) {
4197                return true;
4198            }
4199        };
4200
4201        /** template for matching inference-free arguments mismatch failures */
4202        static final Template argMismatchTemplate = new Template(MethodCheckDiag.ARG_MISMATCH.regex(), skip);
4203
4204        /** template for matching inference related arguments mismatch failures */
4205        static final Template inferArgMismatchTemplate = new Template(MethodCheckDiag.ARG_MISMATCH.regex(), skip, skip) {
4206            @Override
4207            boolean matches(Object o) {
4208                if (!super.matches(o)) {
4209                    return false;
4210                }
4211                JCDiagnostic d = (JCDiagnostic)o;
4212                @SuppressWarnings("unchecked")
4213                List<Type> tvars = (List<Type>)d.getArgs()[0];
4214                return !containsAny(d, tvars);
4215            }
4216
4217            BiPredicate<Object, List<Type>> containsPredicate = (o, ts) -> {
4218                if (o instanceof Type) {
4219                    return ((Type)o).containsAny(ts);
4220                } else if (o instanceof JCDiagnostic) {
4221                    return containsAny((JCDiagnostic)o, ts);
4222                } else {
4223                    return false;
4224                }
4225            };
4226
4227            boolean containsAny(JCDiagnostic d, List<Type> ts) {
4228                return Stream.of(d.getArgs())
4229                        .anyMatch(o -> containsPredicate.test(o, ts));
4230            }
4231        };
4232
4233        /** rewriter map used for method resolution simplification */
4234        static final Map<Template, DiagnosticRewriter> rewriters = new LinkedHashMap<>();
4235
4236        static {
4237            rewriters.put(argMismatchTemplate, new ArgMismatchRewriter(0));
4238            rewriters.put(inferArgMismatchTemplate, new ArgMismatchRewriter(1));
4239        }
4240
4241        /**
4242         * Main entry point for diagnostic rewriting - given a diagnostic, see if any templates matches it,
4243         * and rewrite it accordingly.
4244         */
4245        static JCDiagnostic rewrite(JCDiagnostic.Factory diags, DiagnosticPosition pos, DiagnosticSource source,
4246                                    DiagnosticType dkind, JCDiagnostic d) {
4247            for (Map.Entry<Template, DiagnosticRewriter> _entry : rewriters.entrySet()) {
4248                if (_entry.getKey().matches(d)) {
4249                    JCDiagnostic simpleDiag =
4250                            _entry.getValue().rewriteDiagnostic(diags, pos, source, dkind, d);
4251                    simpleDiag.setFlag(DiagnosticFlag.COMPRESSED);
4252                    return simpleDiag;
4253                }
4254            }
4255            return null;
4256        }
4257    }
4258
4259    enum MethodResolutionPhase {
4260        BASIC(false, false),
4261        BOX(true, false),
4262        VARARITY(true, true) {
4263            @Override
4264            public Symbol mergeResults(Symbol bestSoFar, Symbol sym) {
4265                //Check invariants (see {@code LookupHelper.shouldStop})
4266                Assert.check(bestSoFar.kind.isOverloadError() && bestSoFar.kind != AMBIGUOUS);
4267                if (!sym.kind.isOverloadError()) {
4268                    //varargs resolution successful
4269                    return sym;
4270                } else {
4271                    //pick best error
4272                    switch (bestSoFar.kind) {
4273                        case WRONG_MTH:
4274                        case WRONG_MTHS:
4275                            //Override previous errors if they were caused by argument mismatch.
4276                            //This generally means preferring current symbols - but we need to pay
4277                            //attention to the fact that the varargs lookup returns 'less' candidates
4278                            //than the previous rounds, and adjust that accordingly.
4279                            switch (sym.kind) {
4280                                case WRONG_MTH:
4281                                    //if the previous round matched more than one method, return that
4282                                    //result instead
4283                                    return bestSoFar.kind == WRONG_MTHS ?
4284                                            bestSoFar : sym;
4285                                case ABSENT_MTH:
4286                                    //do not override erroneous symbol if the arity lookup did not
4287                                    //match any method
4288                                    return bestSoFar;
4289                                case WRONG_MTHS:
4290                                default:
4291                                    //safe to override
4292                                    return sym;
4293                            }
4294                        default:
4295                            //otherwise, return first error
4296                            return bestSoFar;
4297                    }
4298                }
4299            }
4300        };
4301
4302        final boolean isBoxingRequired;
4303        final boolean isVarargsRequired;
4304
4305        MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) {
4306           this.isBoxingRequired = isBoxingRequired;
4307           this.isVarargsRequired = isVarargsRequired;
4308        }
4309
4310        public boolean isBoxingRequired() {
4311            return isBoxingRequired;
4312        }
4313
4314        public boolean isVarargsRequired() {
4315            return isVarargsRequired;
4316        }
4317
4318        public Symbol mergeResults(Symbol prev, Symbol sym) {
4319            return sym;
4320        }
4321    }
4322
4323    final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
4324
4325    /**
4326     * A resolution context is used to keep track of intermediate results of
4327     * overload resolution, such as list of method that are not applicable
4328     * (used to generate more precise diagnostics) and so on. Resolution contexts
4329     * can be nested - this means that when each overload resolution routine should
4330     * work within the resolution context it created.
4331     */
4332    class MethodResolutionContext {
4333
4334        private List<Candidate> candidates = List.nil();
4335
4336        MethodResolutionPhase step = null;
4337
4338        MethodCheck methodCheck = resolveMethodCheck;
4339
4340        private boolean internalResolution = false;
4341        private DeferredAttr.AttrMode attrMode = DeferredAttr.AttrMode.SPECULATIVE;
4342
4343        void addInapplicableCandidate(Symbol sym, JCDiagnostic details) {
4344            Candidate c = new Candidate(currentResolutionContext.step, sym, details, null);
4345            candidates = candidates.append(c);
4346        }
4347
4348        void addApplicableCandidate(Symbol sym, Type mtype) {
4349            Candidate c = new Candidate(currentResolutionContext.step, sym, null, mtype);
4350            candidates = candidates.append(c);
4351        }
4352
4353        DeferredAttrContext deferredAttrContext(Symbol sym, InferenceContext inferenceContext, ResultInfo pendingResult, Warner warn) {
4354            DeferredAttrContext parent = (pendingResult == null)
4355                ? deferredAttr.emptyDeferredAttrContext
4356                : pendingResult.checkContext.deferredAttrContext();
4357            return deferredAttr.new DeferredAttrContext(attrMode, sym, step,
4358                    inferenceContext, parent, warn);
4359        }
4360
4361        /**
4362         * This class represents an overload resolution candidate. There are two
4363         * kinds of candidates: applicable methods and inapplicable methods;
4364         * applicable methods have a pointer to the instantiated method type,
4365         * while inapplicable candidates contain further details about the
4366         * reason why the method has been considered inapplicable.
4367         */
4368        @SuppressWarnings("overrides")
4369        class Candidate {
4370
4371            final MethodResolutionPhase step;
4372            final Symbol sym;
4373            final JCDiagnostic details;
4374            final Type mtype;
4375
4376            private Candidate(MethodResolutionPhase step, Symbol sym, JCDiagnostic details, Type mtype) {
4377                this.step = step;
4378                this.sym = sym;
4379                this.details = details;
4380                this.mtype = mtype;
4381            }
4382
4383            @Override
4384            public boolean equals(Object o) {
4385                if (o instanceof Candidate) {
4386                    Symbol s1 = this.sym;
4387                    Symbol s2 = ((Candidate)o).sym;
4388                    if  ((s1 != s2 &&
4389                            (s1.overrides(s2, s1.owner.type.tsym, types, false) ||
4390                            (s2.overrides(s1, s2.owner.type.tsym, types, false)))) ||
4391                            ((s1.isConstructor() || s2.isConstructor()) && s1.owner != s2.owner))
4392                        return true;
4393                }
4394                return false;
4395            }
4396
4397            boolean isApplicable() {
4398                return mtype != null;
4399            }
4400        }
4401
4402        DeferredAttr.AttrMode attrMode() {
4403            return attrMode;
4404        }
4405
4406        boolean internal() {
4407            return internalResolution;
4408        }
4409    }
4410
4411    MethodResolutionContext currentResolutionContext = null;
4412}
4413