Resolve.java revision 2673:bf8500822576
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.DiagnosticRewriter;
43import com.sun.tools.javac.comp.Resolve.MethodResolutionDiagHelper.Template;
44import com.sun.tools.javac.jvm.*;
45import com.sun.tools.javac.main.Option;
46import com.sun.tools.javac.tree.*;
47import com.sun.tools.javac.tree.JCTree.*;
48import com.sun.tools.javac.tree.JCTree.JCMemberReference.ReferenceKind;
49import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
50import com.sun.tools.javac.util.*;
51import com.sun.tools.javac.util.DefinedBy.Api;
52import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
53import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
54import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType;
55
56import java.util.Arrays;
57import java.util.Collection;
58import java.util.EnumMap;
59import java.util.EnumSet;
60import java.util.Iterator;
61import java.util.LinkedHashMap;
62import java.util.Map;
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 (sym == typeNotFound ||
2037                    (tyvar.kind == TYP && tyvar.exists() &&
2038                     tyvar.owner.kind == MTH))
2039                    return tyvar;
2040            }
2041
2042            // If the environment is a class def, finish up,
2043            // otherwise, do the entire findMemberType
2044            if (sym == typeNotFound)
2045                sym = findInheritedMemberType(env1, env1.enclClass.sym.type,
2046                                              name, env1.enclClass.sym);
2047
2048            if (staticOnly && sym.kind == TYP &&
2049                sym.type.hasTag(CLASS) &&
2050                sym.type.getEnclosingType().hasTag(CLASS) &&
2051                env1.enclClass.sym.type.isParameterized() &&
2052                sym.type.getEnclosingType().isParameterized())
2053                return new StaticError(sym);
2054            else if (sym.exists()) return sym;
2055            else bestSoFar = bestOf(bestSoFar, sym);
2056
2057            JCClassDecl encl = env1.baseClause ? (JCClassDecl)env1.tree : env1.enclClass;
2058            if ((encl.sym.flags() & STATIC) != 0)
2059                staticOnly = true;
2060        }
2061
2062        if (!env.tree.hasTag(IMPORT)) {
2063            sym = findGlobalType(env, env.toplevel.namedImportScope, name);
2064            if (sym.exists()) return sym;
2065            else bestSoFar = bestOf(bestSoFar, sym);
2066
2067            sym = findGlobalType(env, env.toplevel.packge.members(), name);
2068            if (sym.exists()) return sym;
2069            else bestSoFar = bestOf(bestSoFar, sym);
2070
2071            sym = findGlobalType(env, env.toplevel.starImportScope, name);
2072            if (sym.exists()) return sym;
2073            else bestSoFar = bestOf(bestSoFar, sym);
2074        }
2075
2076        return bestSoFar;
2077    }
2078
2079    /** Find an unqualified identifier which matches a specified kind set.
2080     *  @param env       The current environment.
2081     *  @param name      The identifier's name.
2082     *  @param kind      Indicates the possible symbol kinds
2083     *                   (a subset of VAL, TYP, PCK).
2084     */
2085    Symbol findIdent(Env<AttrContext> env, Name name, KindSelector kind) {
2086        Symbol bestSoFar = typeNotFound;
2087        Symbol sym;
2088
2089        if (kind.contains(KindSelector.VAL)) {
2090            sym = findVar(env, name);
2091            if (sym.exists()) return sym;
2092            else bestSoFar = bestOf(bestSoFar, sym);
2093        }
2094
2095        if (kind.contains(KindSelector.TYP)) {
2096            sym = findType(env, name);
2097
2098            if (sym.exists()) return sym;
2099            else bestSoFar = bestOf(bestSoFar, sym);
2100        }
2101
2102        if (kind.contains(KindSelector.PCK))
2103            return syms.enterPackage(name);
2104        else return bestSoFar;
2105    }
2106
2107    /** Find an identifier in a package which matches a specified kind set.
2108     *  @param env       The current environment.
2109     *  @param name      The identifier's name.
2110     *  @param kind      Indicates the possible symbol kinds
2111     *                   (a nonempty subset of TYP, PCK).
2112     */
2113    Symbol findIdentInPackage(Env<AttrContext> env, TypeSymbol pck,
2114                              Name name, KindSelector kind) {
2115        Name fullname = TypeSymbol.formFullName(name, pck);
2116        Symbol bestSoFar = typeNotFound;
2117        PackageSymbol pack = null;
2118        if (kind.contains(KindSelector.PCK)) {
2119            pack = syms.enterPackage(fullname);
2120            if (pack.exists()) return pack;
2121        }
2122        if (kind.contains(KindSelector.TYP)) {
2123            Symbol sym = loadClass(env, fullname);
2124            if (sym.exists()) {
2125                // don't allow programs to use flatnames
2126                if (name == sym.name) return sym;
2127            }
2128            else bestSoFar = bestOf(bestSoFar, sym);
2129        }
2130        return (pack != null) ? pack : bestSoFar;
2131    }
2132
2133    /** Find an identifier among the members of a given type `site'.
2134     *  @param env       The current environment.
2135     *  @param site      The type containing the symbol to be found.
2136     *  @param name      The identifier's name.
2137     *  @param kind      Indicates the possible symbol kinds
2138     *                   (a subset of VAL, TYP).
2139     */
2140    Symbol findIdentInType(Env<AttrContext> env, Type site,
2141                           Name name, KindSelector kind) {
2142        Symbol bestSoFar = typeNotFound;
2143        Symbol sym;
2144        if (kind.contains(KindSelector.VAL)) {
2145            sym = findField(env, site, name, site.tsym);
2146            if (sym.exists()) return sym;
2147            else bestSoFar = bestOf(bestSoFar, sym);
2148        }
2149
2150        if (kind.contains(KindSelector.TYP)) {
2151            sym = findMemberType(env, site, name, site.tsym);
2152            if (sym.exists()) return sym;
2153            else bestSoFar = bestOf(bestSoFar, sym);
2154        }
2155        return bestSoFar;
2156    }
2157
2158/* ***************************************************************************
2159 *  Access checking
2160 *  The following methods convert ResolveErrors to ErrorSymbols, issuing
2161 *  an error message in the process
2162 ****************************************************************************/
2163
2164    /** If `sym' is a bad symbol: report error and return errSymbol
2165     *  else pass through unchanged,
2166     *  additional arguments duplicate what has been used in trying to find the
2167     *  symbol {@literal (--> flyweight pattern)}. This improves performance since we
2168     *  expect misses to happen frequently.
2169     *
2170     *  @param sym       The symbol that was found, or a ResolveError.
2171     *  @param pos       The position to use for error reporting.
2172     *  @param location  The symbol the served as a context for this lookup
2173     *  @param site      The original type from where the selection took place.
2174     *  @param name      The symbol's name.
2175     *  @param qualified Did we get here through a qualified expression resolution?
2176     *  @param argtypes  The invocation's value arguments,
2177     *                   if we looked for a method.
2178     *  @param typeargtypes  The invocation's type arguments,
2179     *                   if we looked for a method.
2180     *  @param logResolveHelper helper class used to log resolve errors
2181     */
2182    Symbol accessInternal(Symbol sym,
2183                  DiagnosticPosition pos,
2184                  Symbol location,
2185                  Type site,
2186                  Name name,
2187                  boolean qualified,
2188                  List<Type> argtypes,
2189                  List<Type> typeargtypes,
2190                  LogResolveHelper logResolveHelper) {
2191        if (sym.kind.isOverloadError()) {
2192            ResolveError errSym = (ResolveError)sym.baseSymbol();
2193            sym = errSym.access(name, qualified ? site.tsym : syms.noSymbol);
2194            argtypes = logResolveHelper.getArgumentTypes(errSym, sym, name, argtypes);
2195            if (logResolveHelper.resolveDiagnosticNeeded(site, argtypes, typeargtypes)) {
2196                logResolveError(errSym, pos, location, site, name, argtypes, typeargtypes);
2197            }
2198        }
2199        return sym;
2200    }
2201
2202    /**
2203     * Variant of the generalized access routine, to be used for generating method
2204     * resolution diagnostics
2205     */
2206    Symbol accessMethod(Symbol sym,
2207                  DiagnosticPosition pos,
2208                  Symbol location,
2209                  Type site,
2210                  Name name,
2211                  boolean qualified,
2212                  List<Type> argtypes,
2213                  List<Type> typeargtypes) {
2214        return accessInternal(sym, pos, location, site, name, qualified, argtypes, typeargtypes, methodLogResolveHelper);
2215    }
2216
2217    /** Same as original accessMethod(), but without location.
2218     */
2219    Symbol accessMethod(Symbol sym,
2220                  DiagnosticPosition pos,
2221                  Type site,
2222                  Name name,
2223                  boolean qualified,
2224                  List<Type> argtypes,
2225                  List<Type> typeargtypes) {
2226        return accessMethod(sym, pos, site.tsym, site, name, qualified, argtypes, typeargtypes);
2227    }
2228
2229    /**
2230     * Variant of the generalized access routine, to be used for generating variable,
2231     * type resolution diagnostics
2232     */
2233    Symbol accessBase(Symbol sym,
2234                  DiagnosticPosition pos,
2235                  Symbol location,
2236                  Type site,
2237                  Name name,
2238                  boolean qualified) {
2239        return accessInternal(sym, pos, location, site, name, qualified, List.<Type>nil(), null, basicLogResolveHelper);
2240    }
2241
2242    /** Same as original accessBase(), but without location.
2243     */
2244    Symbol accessBase(Symbol sym,
2245                  DiagnosticPosition pos,
2246                  Type site,
2247                  Name name,
2248                  boolean qualified) {
2249        return accessBase(sym, pos, site.tsym, site, name, qualified);
2250    }
2251
2252    interface LogResolveHelper {
2253        boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes);
2254        List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes);
2255    }
2256
2257    LogResolveHelper basicLogResolveHelper = new LogResolveHelper() {
2258        public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
2259            return !site.isErroneous();
2260        }
2261        public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
2262            return argtypes;
2263        }
2264    };
2265
2266    LogResolveHelper methodLogResolveHelper = new LogResolveHelper() {
2267        public boolean resolveDiagnosticNeeded(Type site, List<Type> argtypes, List<Type> typeargtypes) {
2268            return !site.isErroneous() &&
2269                        !Type.isErroneous(argtypes) &&
2270                        (typeargtypes == null || !Type.isErroneous(typeargtypes));
2271        }
2272        public List<Type> getArgumentTypes(ResolveError errSym, Symbol accessedSym, Name name, List<Type> argtypes) {
2273            return (syms.operatorNames.contains(name)) ?
2274                    argtypes :
2275                    Type.map(argtypes, new ResolveDeferredRecoveryMap(AttrMode.SPECULATIVE, accessedSym, currentResolutionContext.step));
2276        }
2277    };
2278
2279    class ResolveDeferredRecoveryMap extends DeferredAttr.RecoveryDeferredTypeMap {
2280
2281        public ResolveDeferredRecoveryMap(AttrMode mode, Symbol msym, MethodResolutionPhase step) {
2282            deferredAttr.super(mode, msym, step);
2283        }
2284
2285        @Override
2286        protected Type typeOf(DeferredType dt) {
2287            Type res = super.typeOf(dt);
2288            if (!res.isErroneous()) {
2289                switch (TreeInfo.skipParens(dt.tree).getTag()) {
2290                    case LAMBDA:
2291                    case REFERENCE:
2292                        return dt;
2293                    case CONDEXPR:
2294                        return res == Type.recoveryType ?
2295                                dt : res;
2296                }
2297            }
2298            return res;
2299        }
2300    }
2301
2302    /** Check that sym is not an abstract method.
2303     */
2304    void checkNonAbstract(DiagnosticPosition pos, Symbol sym) {
2305        if ((sym.flags() & ABSTRACT) != 0 && (sym.flags() & DEFAULT) == 0)
2306            log.error(pos, "abstract.cant.be.accessed.directly",
2307                      kindName(sym), sym, sym.location());
2308    }
2309
2310/* ***************************************************************************
2311 *  Name resolution
2312 *  Naming conventions are as for symbol lookup
2313 *  Unlike the find... methods these methods will report access errors
2314 ****************************************************************************/
2315
2316    /** Resolve an unqualified (non-method) identifier.
2317     *  @param pos       The position to use for error reporting.
2318     *  @param env       The environment current at the identifier use.
2319     *  @param name      The identifier's name.
2320     *  @param kind      The set of admissible symbol kinds for the identifier.
2321     */
2322    Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env,
2323                        Name name, KindSelector kind) {
2324        return accessBase(
2325            findIdent(env, name, kind),
2326            pos, env.enclClass.sym.type, name, false);
2327    }
2328
2329    /** Resolve an unqualified method identifier.
2330     *  @param pos       The position to use for error reporting.
2331     *  @param env       The environment current at the method invocation.
2332     *  @param name      The identifier's name.
2333     *  @param argtypes  The types of the invocation's value arguments.
2334     *  @param typeargtypes  The types of the invocation's type arguments.
2335     */
2336    Symbol resolveMethod(DiagnosticPosition pos,
2337                         Env<AttrContext> env,
2338                         Name name,
2339                         List<Type> argtypes,
2340                         List<Type> typeargtypes) {
2341        return lookupMethod(env, pos, env.enclClass.sym, resolveMethodCheck,
2342                new BasicLookupHelper(name, env.enclClass.sym.type, argtypes, typeargtypes) {
2343                    @Override
2344                    Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2345                        return findFun(env, name, argtypes, typeargtypes,
2346                                phase.isBoxingRequired(),
2347                                phase.isVarargsRequired());
2348                    }});
2349    }
2350
2351    /** Resolve a qualified method identifier
2352     *  @param pos       The position to use for error reporting.
2353     *  @param env       The environment current at the method invocation.
2354     *  @param site      The type of the qualifying expression, in which
2355     *                   identifier is searched.
2356     *  @param name      The identifier's name.
2357     *  @param argtypes  The types of the invocation's value arguments.
2358     *  @param typeargtypes  The types of the invocation's type arguments.
2359     */
2360    Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
2361                                  Type site, Name name, List<Type> argtypes,
2362                                  List<Type> typeargtypes) {
2363        return resolveQualifiedMethod(pos, env, site.tsym, site, name, argtypes, typeargtypes);
2364    }
2365    Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
2366                                  Symbol location, Type site, Name name, List<Type> argtypes,
2367                                  List<Type> typeargtypes) {
2368        return resolveQualifiedMethod(new MethodResolutionContext(), pos, env, location, site, name, argtypes, typeargtypes);
2369    }
2370    private Symbol resolveQualifiedMethod(MethodResolutionContext resolveContext,
2371                                  DiagnosticPosition pos, Env<AttrContext> env,
2372                                  Symbol location, Type site, Name name, List<Type> argtypes,
2373                                  List<Type> typeargtypes) {
2374        return lookupMethod(env, pos, location, resolveContext, new BasicLookupHelper(name, site, argtypes, typeargtypes) {
2375            @Override
2376            Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2377                return findMethod(env, site, name, argtypes, typeargtypes,
2378                        phase.isBoxingRequired(),
2379                        phase.isVarargsRequired(), false);
2380            }
2381            @Override
2382            Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
2383                if (sym.kind.isOverloadError()) {
2384                    sym = super.access(env, pos, location, sym);
2385                } else if (allowMethodHandles) {
2386                    MethodSymbol msym = (MethodSymbol)sym;
2387                    if ((msym.flags() & SIGNATURE_POLYMORPHIC) != 0) {
2388                        return findPolymorphicSignatureInstance(env, sym, argtypes);
2389                    }
2390                }
2391                return sym;
2392            }
2393        });
2394    }
2395
2396    /** Find or create an implicit method of exactly the given type (after erasure).
2397     *  Searches in a side table, not the main scope of the site.
2398     *  This emulates the lookup process required by JSR 292 in JVM.
2399     *  @param env       Attribution environment
2400     *  @param spMethod  signature polymorphic method - i.e. MH.invokeExact
2401     *  @param argtypes  The required argument types
2402     */
2403    Symbol findPolymorphicSignatureInstance(Env<AttrContext> env,
2404                                            final Symbol spMethod,
2405                                            List<Type> argtypes) {
2406        Type mtype = infer.instantiatePolymorphicSignatureInstance(env,
2407                (MethodSymbol)spMethod, currentResolutionContext, argtypes);
2408        for (Symbol sym : polymorphicSignatureScope.getSymbolsByName(spMethod.name)) {
2409            if (types.isSameType(mtype, sym.type)) {
2410               return sym;
2411            }
2412        }
2413
2414        // create the desired method
2415        long flags = ABSTRACT | HYPOTHETICAL | spMethod.flags() & Flags.AccessFlags;
2416        Symbol msym = new MethodSymbol(flags, spMethod.name, mtype, spMethod.owner) {
2417            @Override
2418            public Symbol baseSymbol() {
2419                return spMethod;
2420            }
2421        };
2422        polymorphicSignatureScope.enter(msym);
2423        return msym;
2424    }
2425
2426    /** Resolve a qualified method identifier, throw a fatal error if not
2427     *  found.
2428     *  @param pos       The position to use for error reporting.
2429     *  @param env       The environment current at the method invocation.
2430     *  @param site      The type of the qualifying expression, in which
2431     *                   identifier is searched.
2432     *  @param name      The identifier's name.
2433     *  @param argtypes  The types of the invocation's value arguments.
2434     *  @param typeargtypes  The types of the invocation's type arguments.
2435     */
2436    public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, Env<AttrContext> env,
2437                                        Type site, Name name,
2438                                        List<Type> argtypes,
2439                                        List<Type> typeargtypes) {
2440        MethodResolutionContext resolveContext = new MethodResolutionContext();
2441        resolveContext.internalResolution = true;
2442        Symbol sym = resolveQualifiedMethod(resolveContext, pos, env, site.tsym,
2443                site, name, argtypes, typeargtypes);
2444        if (sym.kind == MTH) return (MethodSymbol)sym;
2445        else throw new FatalError(
2446                 diags.fragment("fatal.err.cant.locate.meth",
2447                                name));
2448    }
2449
2450    /** Resolve constructor.
2451     *  @param pos       The position to use for error reporting.
2452     *  @param env       The environment current at the constructor invocation.
2453     *  @param site      The type of class for which a constructor is searched.
2454     *  @param argtypes  The types of the constructor invocation's value
2455     *                   arguments.
2456     *  @param typeargtypes  The types of the constructor invocation's type
2457     *                   arguments.
2458     */
2459    Symbol resolveConstructor(DiagnosticPosition pos,
2460                              Env<AttrContext> env,
2461                              Type site,
2462                              List<Type> argtypes,
2463                              List<Type> typeargtypes) {
2464        return resolveConstructor(new MethodResolutionContext(), pos, env, site, argtypes, typeargtypes);
2465    }
2466
2467    private Symbol resolveConstructor(MethodResolutionContext resolveContext,
2468                              final DiagnosticPosition pos,
2469                              Env<AttrContext> env,
2470                              Type site,
2471                              List<Type> argtypes,
2472                              List<Type> typeargtypes) {
2473        return lookupMethod(env, pos, site.tsym, resolveContext, new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
2474            @Override
2475            Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2476                return findConstructor(pos, env, site, argtypes, typeargtypes,
2477                        phase.isBoxingRequired(),
2478                        phase.isVarargsRequired());
2479            }
2480        });
2481    }
2482
2483    /** Resolve a constructor, throw a fatal error if not found.
2484     *  @param pos       The position to use for error reporting.
2485     *  @param env       The environment current at the method invocation.
2486     *  @param site      The type to be constructed.
2487     *  @param argtypes  The types of the invocation's value arguments.
2488     *  @param typeargtypes  The types of the invocation's type arguments.
2489     */
2490    public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, Env<AttrContext> env,
2491                                        Type site,
2492                                        List<Type> argtypes,
2493                                        List<Type> typeargtypes) {
2494        MethodResolutionContext resolveContext = new MethodResolutionContext();
2495        resolveContext.internalResolution = true;
2496        Symbol sym = resolveConstructor(resolveContext, pos, env, site, argtypes, typeargtypes);
2497        if (sym.kind == MTH) return (MethodSymbol)sym;
2498        else throw new FatalError(
2499                 diags.fragment("fatal.err.cant.locate.ctor", site));
2500    }
2501
2502    Symbol findConstructor(DiagnosticPosition pos, Env<AttrContext> env,
2503                              Type site, List<Type> argtypes,
2504                              List<Type> typeargtypes,
2505                              boolean allowBoxing,
2506                              boolean useVarargs) {
2507        Symbol sym = findMethod(env, site,
2508                                    names.init, argtypes,
2509                                    typeargtypes, allowBoxing,
2510                                    useVarargs, false);
2511        chk.checkDeprecated(pos, env.info.scope.owner, sym);
2512        return sym;
2513    }
2514
2515    /** Resolve constructor using diamond inference.
2516     *  @param pos       The position to use for error reporting.
2517     *  @param env       The environment current at the constructor invocation.
2518     *  @param site      The type of class for which a constructor is searched.
2519     *                   The scope of this class has been touched in attribution.
2520     *  @param argtypes  The types of the constructor invocation's value
2521     *                   arguments.
2522     *  @param typeargtypes  The types of the constructor invocation's type
2523     *                   arguments.
2524     */
2525    Symbol resolveDiamond(DiagnosticPosition pos,
2526                              Env<AttrContext> env,
2527                              Type site,
2528                              List<Type> argtypes,
2529                              List<Type> typeargtypes) {
2530        return lookupMethod(env, pos, site.tsym, resolveMethodCheck,
2531                new BasicLookupHelper(names.init, site, argtypes, typeargtypes) {
2532                    @Override
2533                    Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2534                        return findDiamond(env, site, argtypes, typeargtypes,
2535                                phase.isBoxingRequired(),
2536                                phase.isVarargsRequired());
2537                    }
2538                    @Override
2539                    Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
2540                        if (sym.kind.isOverloadError()) {
2541                            if (sym.kind != WRONG_MTH &&
2542                                sym.kind != WRONG_MTHS) {
2543                                sym = super.access(env, pos, location, sym);
2544                            } else {
2545                                final JCDiagnostic details = sym.kind == WRONG_MTH ?
2546                                                ((InapplicableSymbolError)sym.baseSymbol()).errCandidate().snd :
2547                                                null;
2548                                sym = new InapplicableSymbolError(sym.kind, "diamondError", currentResolutionContext) {
2549                                    @Override
2550                                    JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos,
2551                                            Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
2552                                        String key = details == null ?
2553                                            "cant.apply.diamond" :
2554                                            "cant.apply.diamond.1";
2555                                        return diags.create(dkind, log.currentSource(), pos, key,
2556                                                diags.fragment("diamond", site.tsym), details);
2557                                    }
2558                                };
2559                                sym = accessMethod(sym, pos, site, names.init, true, argtypes, typeargtypes);
2560                                env.info.pendingResolutionPhase = currentResolutionContext.step;
2561                            }
2562                        }
2563                        return sym;
2564                    }});
2565    }
2566
2567    /** This method scans all the constructor symbol in a given class scope -
2568     *  assuming that the original scope contains a constructor of the kind:
2569     *  {@code Foo(X x, Y y)}, where X,Y are class type-variables declared in Foo,
2570     *  a method check is executed against the modified constructor type:
2571     *  {@code <X,Y>Foo<X,Y>(X x, Y y)}. This is crucial in order to enable diamond
2572     *  inference. The inferred return type of the synthetic constructor IS
2573     *  the inferred type for the diamond operator.
2574     */
2575    private Symbol findDiamond(Env<AttrContext> env,
2576                              Type site,
2577                              List<Type> argtypes,
2578                              List<Type> typeargtypes,
2579                              boolean allowBoxing,
2580                              boolean useVarargs) {
2581        Symbol bestSoFar = methodNotFound;
2582        for (final Symbol sym : site.tsym.members().getSymbolsByName(names.init)) {
2583            //- System.out.println(" e " + e.sym);
2584            if (sym.kind == MTH &&
2585                (sym.flags_field & SYNTHETIC) == 0) {
2586                    List<Type> oldParams = sym.type.hasTag(FORALL) ?
2587                            ((ForAll)sym.type).tvars :
2588                            List.<Type>nil();
2589                    Type constrType = new ForAll(site.tsym.type.getTypeArguments().appendList(oldParams),
2590                                                 types.createMethodTypeWithReturn(sym.type.asMethodType(), site));
2591                    MethodSymbol newConstr = new MethodSymbol(sym.flags(), names.init, constrType, site.tsym) {
2592                        @Override
2593                        public Symbol baseSymbol() {
2594                            return sym;
2595                        }
2596                    };
2597                    bestSoFar = selectBest(env, site, argtypes, typeargtypes,
2598                            newConstr,
2599                            bestSoFar,
2600                            allowBoxing,
2601                            useVarargs,
2602                            false);
2603            }
2604        }
2605        return bestSoFar;
2606    }
2607
2608
2609
2610    /** Resolve operator.
2611     *  @param pos       The position to use for error reporting.
2612     *  @param optag     The tag of the operation tree.
2613     *  @param env       The environment current at the operation.
2614     *  @param argtypes  The types of the operands.
2615     */
2616    Symbol resolveOperator(DiagnosticPosition pos, JCTree.Tag optag,
2617                           Env<AttrContext> env, List<Type> argtypes) {
2618        MethodResolutionContext prevResolutionContext = currentResolutionContext;
2619        try {
2620            currentResolutionContext = new MethodResolutionContext();
2621            Name name = treeinfo.operatorName(optag);
2622            return lookupMethod(env, pos, syms.predefClass, currentResolutionContext,
2623                    new BasicLookupHelper(name, syms.predefClass.type, argtypes, null, BOX) {
2624                @Override
2625                Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) {
2626                    return findMethod(env, site, name, argtypes, typeargtypes,
2627                            phase.isBoxingRequired(),
2628                            phase.isVarargsRequired(), true);
2629                }
2630                @Override
2631                Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
2632                    return accessMethod(sym, pos, env.enclClass.sym.type, name,
2633                          false, argtypes, null);
2634                }
2635            });
2636        } finally {
2637            currentResolutionContext = prevResolutionContext;
2638        }
2639    }
2640
2641    /** Resolve operator.
2642     *  @param pos       The position to use for error reporting.
2643     *  @param optag     The tag of the operation tree.
2644     *  @param env       The environment current at the operation.
2645     *  @param arg       The type of the operand.
2646     */
2647    Symbol resolveUnaryOperator(DiagnosticPosition pos, JCTree.Tag optag, Env<AttrContext> env, Type arg) {
2648        return resolveOperator(pos, optag, env, List.of(arg));
2649    }
2650
2651    /** Resolve binary operator.
2652     *  @param pos       The position to use for error reporting.
2653     *  @param optag     The tag of the operation tree.
2654     *  @param env       The environment current at the operation.
2655     *  @param left      The types of the left operand.
2656     *  @param right     The types of the right operand.
2657     */
2658    Symbol resolveBinaryOperator(DiagnosticPosition pos,
2659                                 JCTree.Tag optag,
2660                                 Env<AttrContext> env,
2661                                 Type left,
2662                                 Type right) {
2663        return resolveOperator(pos, optag, env, List.of(left, right));
2664    }
2665
2666    Symbol getMemberReference(DiagnosticPosition pos,
2667            Env<AttrContext> env,
2668            JCMemberReference referenceTree,
2669            Type site,
2670            Name name) {
2671
2672        site = types.capture(site);
2673
2674        ReferenceLookupHelper lookupHelper = makeReferenceLookupHelper(
2675                referenceTree, site, name, List.<Type>nil(), null, VARARITY);
2676
2677        Env<AttrContext> newEnv = env.dup(env.tree, env.info.dup());
2678        Symbol sym = lookupMethod(newEnv, env.tree.pos(), site.tsym,
2679                nilMethodCheck, lookupHelper);
2680
2681        env.info.pendingResolutionPhase = newEnv.info.pendingResolutionPhase;
2682
2683        return sym;
2684    }
2685
2686    ReferenceLookupHelper makeReferenceLookupHelper(JCMemberReference referenceTree,
2687                                  Type site,
2688                                  Name name,
2689                                  List<Type> argtypes,
2690                                  List<Type> typeargtypes,
2691                                  MethodResolutionPhase maxPhase) {
2692        ReferenceLookupHelper result;
2693        if (!name.equals(names.init)) {
2694            //method reference
2695            result =
2696                    new MethodReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
2697        } else {
2698            if (site.hasTag(ARRAY)) {
2699                //array constructor reference
2700                result =
2701                        new ArrayConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase);
2702            } else {
2703                //class constructor reference
2704                result =
2705                        new ConstructorReferenceLookupHelper(referenceTree, site, argtypes, typeargtypes, maxPhase);
2706            }
2707        }
2708        return result;
2709    }
2710
2711    Symbol resolveMemberReferenceByArity(Env<AttrContext> env,
2712                                  JCMemberReference referenceTree,
2713                                  Type site,
2714                                  Name name,
2715                                  List<Type> argtypes,
2716                                  InferenceContext inferenceContext) {
2717
2718        boolean isStaticSelector = TreeInfo.isStaticSelector(referenceTree.expr, names);
2719        site = types.capture(site);
2720
2721        ReferenceLookupHelper boundLookupHelper = makeReferenceLookupHelper(
2722                referenceTree, site, name, argtypes, null, VARARITY);
2723        //step 1 - bound lookup
2724        Env<AttrContext> boundEnv = env.dup(env.tree, env.info.dup());
2725        Symbol boundSym = lookupMethod(boundEnv, env.tree.pos(), site.tsym,
2726                arityMethodCheck, boundLookupHelper);
2727        if (isStaticSelector &&
2728            !name.equals(names.init) &&
2729            !boundSym.isStatic() &&
2730            !boundSym.kind.isOverloadError()) {
2731            boundSym = methodNotFound;
2732        }
2733
2734        //step 2 - unbound lookup
2735        Symbol unboundSym = methodNotFound;
2736        ReferenceLookupHelper unboundLookupHelper = null;
2737        Env<AttrContext> unboundEnv = env.dup(env.tree, env.info.dup());
2738        if (isStaticSelector) {
2739            unboundLookupHelper = boundLookupHelper.unboundLookup(inferenceContext);
2740            unboundSym = lookupMethod(unboundEnv, env.tree.pos(), site.tsym,
2741                    arityMethodCheck, unboundLookupHelper);
2742            if (unboundSym.isStatic() &&
2743                !unboundSym.kind.isOverloadError()) {
2744                unboundSym = methodNotFound;
2745            }
2746        }
2747
2748        //merge results
2749        Symbol bestSym = choose(boundSym, unboundSym);
2750        env.info.pendingResolutionPhase = bestSym == unboundSym ?
2751                unboundEnv.info.pendingResolutionPhase :
2752                boundEnv.info.pendingResolutionPhase;
2753
2754        return bestSym;
2755    }
2756
2757    /**
2758     * Resolution of member references is typically done as a single
2759     * overload resolution step, where the argument types A are inferred from
2760     * the target functional descriptor.
2761     *
2762     * If the member reference is a method reference with a type qualifier,
2763     * a two-step lookup process is performed. The first step uses the
2764     * expected argument list A, while the second step discards the first
2765     * type from A (which is treated as a receiver type).
2766     *
2767     * There are two cases in which inference is performed: (i) if the member
2768     * reference is a constructor reference and the qualifier type is raw - in
2769     * which case diamond inference is used to infer a parameterization for the
2770     * type qualifier; (ii) if the member reference is an unbound reference
2771     * where the type qualifier is raw - in that case, during the unbound lookup
2772     * the receiver argument type is used to infer an instantiation for the raw
2773     * qualifier type.
2774     *
2775     * When a multi-step resolution process is exploited, it is an error
2776     * if two candidates are found (ambiguity).
2777     *
2778     * This routine returns a pair (T,S), where S is the member reference symbol,
2779     * and T is the type of the class in which S is defined. This is necessary as
2780     * the type T might be dynamically inferred (i.e. if constructor reference
2781     * has a raw qualifier).
2782     */
2783    Pair<Symbol, ReferenceLookupHelper> resolveMemberReference(Env<AttrContext> env,
2784                                  JCMemberReference referenceTree,
2785                                  Type site,
2786                                  Name name,
2787                                  List<Type> argtypes,
2788                                  List<Type> typeargtypes,
2789                                  MethodCheck methodCheck,
2790                                  InferenceContext inferenceContext,
2791                                  AttrMode mode) {
2792
2793        site = types.capture(site);
2794        ReferenceLookupHelper boundLookupHelper = makeReferenceLookupHelper(
2795                referenceTree, site, name, argtypes, typeargtypes, VARARITY);
2796
2797        //step 1 - bound lookup
2798        Env<AttrContext> boundEnv = env.dup(env.tree, env.info.dup());
2799        Symbol origBoundSym;
2800        boolean staticErrorForBound = false;
2801        MethodResolutionContext boundSearchResolveContext = new MethodResolutionContext();
2802        boundSearchResolveContext.methodCheck = methodCheck;
2803        Symbol boundSym = origBoundSym = lookupMethod(boundEnv, env.tree.pos(),
2804                site.tsym, boundSearchResolveContext, boundLookupHelper);
2805        SearchResultKind boundSearchResultKind = SearchResultKind.NOT_APPLICABLE_MATCH;
2806        boolean isStaticSelector = TreeInfo.isStaticSelector(referenceTree.expr, names);
2807        boolean shouldCheckForStaticness = isStaticSelector &&
2808                referenceTree.getMode() == ReferenceMode.INVOKE;
2809        if (boundSym.kind != WRONG_MTHS && boundSym.kind != WRONG_MTH) {
2810            if (shouldCheckForStaticness) {
2811                if (!boundSym.isStatic()) {
2812                    staticErrorForBound = true;
2813                    if (hasAnotherApplicableMethod(
2814                            boundSearchResolveContext, boundSym, true)) {
2815                        boundSearchResultKind = SearchResultKind.BAD_MATCH_MORE_SPECIFIC;
2816                    } else {
2817                        boundSearchResultKind = SearchResultKind.BAD_MATCH;
2818                        if (!boundSym.kind.isOverloadError()) {
2819                            boundSym = methodWithCorrectStaticnessNotFound;
2820                        }
2821                    }
2822                } else if (!boundSym.kind.isOverloadError()) {
2823                    boundSearchResultKind = SearchResultKind.GOOD_MATCH;
2824                }
2825            }
2826        }
2827
2828        //step 2 - unbound lookup
2829        Symbol origUnboundSym = null;
2830        Symbol unboundSym = methodNotFound;
2831        ReferenceLookupHelper unboundLookupHelper = null;
2832        Env<AttrContext> unboundEnv = env.dup(env.tree, env.info.dup());
2833        SearchResultKind unboundSearchResultKind = SearchResultKind.NOT_APPLICABLE_MATCH;
2834        boolean staticErrorForUnbound = false;
2835        if (isStaticSelector) {
2836            unboundLookupHelper = boundLookupHelper.unboundLookup(inferenceContext);
2837            MethodResolutionContext unboundSearchResolveContext =
2838                    new MethodResolutionContext();
2839            unboundSearchResolveContext.methodCheck = methodCheck;
2840            unboundSym = origUnboundSym = lookupMethod(unboundEnv, env.tree.pos(),
2841                    site.tsym, unboundSearchResolveContext, unboundLookupHelper);
2842
2843            if (unboundSym.kind != WRONG_MTH && unboundSym.kind != WRONG_MTHS) {
2844                if (shouldCheckForStaticness) {
2845                    if (unboundSym.isStatic()) {
2846                        staticErrorForUnbound = true;
2847                        if (hasAnotherApplicableMethod(
2848                                unboundSearchResolveContext, unboundSym, false)) {
2849                            unboundSearchResultKind = SearchResultKind.BAD_MATCH_MORE_SPECIFIC;
2850                        } else {
2851                            unboundSearchResultKind = SearchResultKind.BAD_MATCH;
2852                            if (!unboundSym.kind.isOverloadError()) {
2853                                unboundSym = methodWithCorrectStaticnessNotFound;
2854                            }
2855                        }
2856                    } else if (!unboundSym.kind.isOverloadError()) {
2857                        unboundSearchResultKind = SearchResultKind.GOOD_MATCH;
2858                    }
2859                }
2860            }
2861        }
2862
2863        //merge results
2864        Pair<Symbol, ReferenceLookupHelper> res;
2865        Symbol bestSym = choose(boundSym, unboundSym);
2866        if (!bestSym.kind.isOverloadError() &&
2867            (staticErrorForBound || staticErrorForUnbound)) {
2868            if (staticErrorForBound) {
2869                boundSym = methodWithCorrectStaticnessNotFound;
2870            }
2871            if (staticErrorForUnbound) {
2872                unboundSym = methodWithCorrectStaticnessNotFound;
2873            }
2874            bestSym = choose(boundSym, unboundSym);
2875        }
2876        if (bestSym == methodWithCorrectStaticnessNotFound && mode == AttrMode.CHECK) {
2877            Symbol symToPrint = origBoundSym;
2878            String errorFragmentToPrint = "non-static.cant.be.ref";
2879            if (staticErrorForBound && staticErrorForUnbound) {
2880                if (unboundSearchResultKind == SearchResultKind.BAD_MATCH_MORE_SPECIFIC) {
2881                    symToPrint = origUnboundSym;
2882                    errorFragmentToPrint = "static.method.in.unbound.lookup";
2883                }
2884            } else {
2885                if (!staticErrorForBound) {
2886                    symToPrint = origUnboundSym;
2887                    errorFragmentToPrint = "static.method.in.unbound.lookup";
2888                }
2889            }
2890            log.error(referenceTree.expr.pos(), "invalid.mref",
2891                Kinds.kindName(referenceTree.getMode()),
2892                diags.fragment(errorFragmentToPrint,
2893                Kinds.kindName(symToPrint), symToPrint));
2894        }
2895        res = new Pair<>(bestSym,
2896                bestSym == unboundSym ? unboundLookupHelper : boundLookupHelper);
2897        env.info.pendingResolutionPhase = bestSym == unboundSym ?
2898                unboundEnv.info.pendingResolutionPhase :
2899                boundEnv.info.pendingResolutionPhase;
2900
2901        return res;
2902    }
2903
2904    enum SearchResultKind {
2905        GOOD_MATCH,                 //type I
2906        BAD_MATCH_MORE_SPECIFIC,    //type II
2907        BAD_MATCH,                  //type III
2908        NOT_APPLICABLE_MATCH        //type IV
2909    }
2910
2911    boolean hasAnotherApplicableMethod(MethodResolutionContext resolutionContext,
2912            Symbol bestSoFar, boolean staticMth) {
2913        for (Candidate c : resolutionContext.candidates) {
2914            if (resolutionContext.step != c.step ||
2915                !c.isApplicable() ||
2916                c.sym == bestSoFar) {
2917                continue;
2918            } else {
2919                if (c.sym.isStatic() == staticMth) {
2920                    return true;
2921                }
2922            }
2923        }
2924        return false;
2925    }
2926
2927    //where
2928        private Symbol choose(Symbol boundSym, Symbol unboundSym) {
2929            if (lookupSuccess(boundSym) && lookupSuccess(unboundSym)) {
2930                return ambiguityError(boundSym, unboundSym);
2931            } else if (lookupSuccess(boundSym) ||
2932                    (canIgnore(unboundSym) && !canIgnore(boundSym))) {
2933                return boundSym;
2934            } else if (lookupSuccess(unboundSym) ||
2935                    (canIgnore(boundSym) && !canIgnore(unboundSym))) {
2936                return unboundSym;
2937            } else {
2938                return boundSym;
2939            }
2940        }
2941
2942        private boolean lookupSuccess(Symbol s) {
2943            return s.kind == MTH || s.kind == AMBIGUOUS;
2944        }
2945
2946        private boolean canIgnore(Symbol s) {
2947            switch (s.kind) {
2948                case ABSENT_MTH:
2949                    return true;
2950                case WRONG_MTH:
2951                    InapplicableSymbolError errSym =
2952                            (InapplicableSymbolError)s.baseSymbol();
2953                    return new Template(MethodCheckDiag.ARITY_MISMATCH.regex())
2954                            .matches(errSym.errCandidate().snd);
2955                case WRONG_MTHS:
2956                    InapplicableSymbolsError errSyms =
2957                            (InapplicableSymbolsError)s.baseSymbol();
2958                    return errSyms.filterCandidates(errSyms.mapCandidates()).isEmpty();
2959                case WRONG_STATICNESS:
2960                    return false;
2961                default:
2962                    return false;
2963            }
2964        }
2965
2966    /**
2967     * Helper for defining custom method-like lookup logic; a lookup helper
2968     * provides hooks for (i) the actual lookup logic and (ii) accessing the
2969     * lookup result (this step might result in compiler diagnostics to be generated)
2970     */
2971    abstract class LookupHelper {
2972
2973        /** name of the symbol to lookup */
2974        Name name;
2975
2976        /** location in which the lookup takes place */
2977        Type site;
2978
2979        /** actual types used during the lookup */
2980        List<Type> argtypes;
2981
2982        /** type arguments used during the lookup */
2983        List<Type> typeargtypes;
2984
2985        /** Max overload resolution phase handled by this helper */
2986        MethodResolutionPhase maxPhase;
2987
2988        LookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
2989            this.name = name;
2990            this.site = site;
2991            this.argtypes = argtypes;
2992            this.typeargtypes = typeargtypes;
2993            this.maxPhase = maxPhase;
2994        }
2995
2996        /**
2997         * Should lookup stop at given phase with given result
2998         */
2999        final boolean shouldStop(Symbol sym, MethodResolutionPhase phase) {
3000            return phase.ordinal() > maxPhase.ordinal() ||
3001                !sym.kind.isOverloadError() || sym.kind == AMBIGUOUS;
3002        }
3003
3004        /**
3005         * Search for a symbol under a given overload resolution phase - this method
3006         * is usually called several times, once per each overload resolution phase
3007         */
3008        abstract Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase);
3009
3010        /**
3011         * Dump overload resolution info
3012         */
3013        void debug(DiagnosticPosition pos, Symbol sym) {
3014            //do nothing
3015        }
3016
3017        /**
3018         * Validate the result of the lookup
3019         */
3020        abstract Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym);
3021    }
3022
3023    abstract class BasicLookupHelper extends LookupHelper {
3024
3025        BasicLookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes) {
3026            this(name, site, argtypes, typeargtypes, MethodResolutionPhase.VARARITY);
3027        }
3028
3029        BasicLookupHelper(Name name, Type site, List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
3030            super(name, site, argtypes, typeargtypes, maxPhase);
3031        }
3032
3033        @Override
3034        final Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
3035            Symbol sym = doLookup(env, phase);
3036            if (sym.kind == AMBIGUOUS) {
3037                AmbiguityError a_err = (AmbiguityError)sym.baseSymbol();
3038                sym = a_err.mergeAbstracts(site);
3039            }
3040            return sym;
3041        }
3042
3043        abstract Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase);
3044
3045        @Override
3046        Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
3047            if (sym.kind.isOverloadError()) {
3048                //if nothing is found return the 'first' error
3049                sym = accessMethod(sym, pos, location, site, name, true, argtypes, typeargtypes);
3050            }
3051            return sym;
3052        }
3053
3054        @Override
3055        void debug(DiagnosticPosition pos, Symbol sym) {
3056            reportVerboseResolutionDiagnostic(pos, name, site, argtypes, typeargtypes, sym);
3057        }
3058    }
3059
3060    /**
3061     * Helper class for member reference lookup. A reference lookup helper
3062     * defines the basic logic for member reference lookup; a method gives
3063     * access to an 'unbound' helper used to perform an unbound member
3064     * reference lookup.
3065     */
3066    abstract class ReferenceLookupHelper extends LookupHelper {
3067
3068        /** The member reference tree */
3069        JCMemberReference referenceTree;
3070
3071        ReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
3072                List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
3073            super(name, site, argtypes, typeargtypes, maxPhase);
3074            this.referenceTree = referenceTree;
3075        }
3076
3077        /**
3078         * Returns an unbound version of this lookup helper. By default, this
3079         * method returns an dummy lookup helper.
3080         */
3081        ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
3082            //dummy loopkup helper that always return 'methodNotFound'
3083            return new ReferenceLookupHelper(referenceTree, name, site, argtypes, typeargtypes, maxPhase) {
3084                @Override
3085                ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
3086                    return this;
3087                }
3088                @Override
3089                Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
3090                    return methodNotFound;
3091                }
3092                @Override
3093                ReferenceKind referenceKind(Symbol sym) {
3094                    Assert.error();
3095                    return null;
3096                }
3097            };
3098        }
3099
3100        /**
3101         * Get the kind of the member reference
3102         */
3103        abstract JCMemberReference.ReferenceKind referenceKind(Symbol sym);
3104
3105        Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
3106            if (sym.kind == AMBIGUOUS) {
3107                AmbiguityError a_err = (AmbiguityError)sym.baseSymbol();
3108                sym = a_err.mergeAbstracts(site);
3109            }
3110            //skip error reporting
3111            return sym;
3112        }
3113    }
3114
3115    /**
3116     * Helper class for method reference lookup. The lookup logic is based
3117     * upon Resolve.findMethod; in certain cases, this helper class has a
3118     * corresponding unbound helper class (see UnboundMethodReferenceLookupHelper).
3119     * In such cases, non-static lookup results are thrown away.
3120     */
3121    class MethodReferenceLookupHelper extends ReferenceLookupHelper {
3122
3123        MethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
3124                List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
3125            super(referenceTree, name, site, argtypes, typeargtypes, maxPhase);
3126        }
3127
3128        @Override
3129        final Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
3130            return findMethod(env, site, name, argtypes, typeargtypes,
3131                    phase.isBoxingRequired(), phase.isVarargsRequired(), syms.operatorNames.contains(name));
3132        }
3133
3134        @Override
3135        ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
3136            if (TreeInfo.isStaticSelector(referenceTree.expr, names) &&
3137                    argtypes.nonEmpty() &&
3138                    (argtypes.head.hasTag(NONE) ||
3139                    types.isSubtypeUnchecked(inferenceContext.asUndetVar(argtypes.head), site))) {
3140                return new UnboundMethodReferenceLookupHelper(referenceTree, name,
3141                        site, argtypes, typeargtypes, maxPhase);
3142            } else {
3143                return super.unboundLookup(inferenceContext);
3144            }
3145        }
3146
3147        @Override
3148        ReferenceKind referenceKind(Symbol sym) {
3149            if (sym.isStatic()) {
3150                return ReferenceKind.STATIC;
3151            } else {
3152                Name selName = TreeInfo.name(referenceTree.getQualifierExpression());
3153                return selName != null && selName == names._super ?
3154                        ReferenceKind.SUPER :
3155                        ReferenceKind.BOUND;
3156            }
3157        }
3158    }
3159
3160    /**
3161     * Helper class for unbound method reference lookup. Essentially the same
3162     * as the basic method reference lookup helper; main difference is that static
3163     * lookup results are thrown away. If qualifier type is raw, an attempt to
3164     * infer a parameterized type is made using the first actual argument (that
3165     * would otherwise be ignored during the lookup).
3166     */
3167    class UnboundMethodReferenceLookupHelper extends MethodReferenceLookupHelper {
3168
3169        UnboundMethodReferenceLookupHelper(JCMemberReference referenceTree, Name name, Type site,
3170                List<Type> argtypes, List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
3171            super(referenceTree, name, site, argtypes.tail, typeargtypes, maxPhase);
3172            if (site.isRaw() && !argtypes.head.hasTag(NONE)) {
3173                Type asSuperSite = types.asSuper(argtypes.head, site.tsym);
3174                this.site = asSuperSite;
3175            }
3176        }
3177
3178        @Override
3179        ReferenceLookupHelper unboundLookup(InferenceContext inferenceContext) {
3180            return this;
3181        }
3182
3183        @Override
3184        ReferenceKind referenceKind(Symbol sym) {
3185            return ReferenceKind.UNBOUND;
3186        }
3187    }
3188
3189    /**
3190     * Helper class for array constructor lookup; an array constructor lookup
3191     * is simulated by looking up a method that returns the array type specified
3192     * as qualifier, and that accepts a single int parameter (size of the array).
3193     */
3194    class ArrayConstructorReferenceLookupHelper extends ReferenceLookupHelper {
3195
3196        ArrayConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
3197                List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
3198            super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase);
3199        }
3200
3201        @Override
3202        protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
3203            WriteableScope sc = WriteableScope.create(syms.arrayClass);
3204            MethodSymbol arrayConstr = new MethodSymbol(PUBLIC, name, null, site.tsym);
3205            arrayConstr.type = new MethodType(List.<Type>of(syms.intType), site, List.<Type>nil(), syms.methodClass);
3206            sc.enter(arrayConstr);
3207            return findMethodInScope(env, site, name, argtypes, typeargtypes, sc, methodNotFound, phase.isBoxingRequired(), phase.isVarargsRequired(), false, false);
3208        }
3209
3210        @Override
3211        ReferenceKind referenceKind(Symbol sym) {
3212            return ReferenceKind.ARRAY_CTOR;
3213        }
3214    }
3215
3216    /**
3217     * Helper class for constructor reference lookup. The lookup logic is based
3218     * upon either Resolve.findMethod or Resolve.findDiamond - depending on
3219     * whether the constructor reference needs diamond inference (this is the case
3220     * if the qualifier type is raw). A special erroneous symbol is returned
3221     * if the lookup returns the constructor of an inner class and there's no
3222     * enclosing instance in scope.
3223     */
3224    class ConstructorReferenceLookupHelper extends ReferenceLookupHelper {
3225
3226        boolean needsInference;
3227
3228        ConstructorReferenceLookupHelper(JCMemberReference referenceTree, Type site, List<Type> argtypes,
3229                List<Type> typeargtypes, MethodResolutionPhase maxPhase) {
3230            super(referenceTree, names.init, site, argtypes, typeargtypes, maxPhase);
3231            if (site.isRaw()) {
3232                this.site = new ClassType(site.getEnclosingType(), site.tsym.type.getTypeArguments(), site.tsym, site.getMetadata());
3233                needsInference = true;
3234            }
3235        }
3236
3237        @Override
3238        protected Symbol lookup(Env<AttrContext> env, MethodResolutionPhase phase) {
3239            Symbol sym = needsInference ?
3240                findDiamond(env, site, argtypes, typeargtypes, phase.isBoxingRequired(), phase.isVarargsRequired()) :
3241                findMethod(env, site, name, argtypes, typeargtypes,
3242                        phase.isBoxingRequired(), phase.isVarargsRequired(), syms.operatorNames.contains(name));
3243            return sym.kind != MTH ||
3244                          site.getEnclosingType().hasTag(NONE) ||
3245                          hasEnclosingInstance(env, site) ?
3246                          sym : new InvalidSymbolError(MISSING_ENCL, sym, null) {
3247                    @Override
3248                    JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
3249                       return diags.create(dkind, log.currentSource(), pos,
3250                            "cant.access.inner.cls.constr", site.tsym.name, argtypes, site.getEnclosingType());
3251                    }
3252                };
3253        }
3254
3255        @Override
3256        ReferenceKind referenceKind(Symbol sym) {
3257            return site.getEnclosingType().hasTag(NONE) ?
3258                    ReferenceKind.TOPLEVEL : ReferenceKind.IMPLICIT_INNER;
3259        }
3260    }
3261
3262    /**
3263     * Main overload resolution routine. On each overload resolution step, a
3264     * lookup helper class is used to perform the method/constructor lookup;
3265     * at the end of the lookup, the helper is used to validate the results
3266     * (this last step might trigger overload resolution diagnostics).
3267     */
3268    Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, MethodCheck methodCheck, LookupHelper lookupHelper) {
3269        MethodResolutionContext resolveContext = new MethodResolutionContext();
3270        resolveContext.methodCheck = methodCheck;
3271        return lookupMethod(env, pos, location, resolveContext, lookupHelper);
3272    }
3273
3274    Symbol lookupMethod(Env<AttrContext> env, DiagnosticPosition pos, Symbol location,
3275            MethodResolutionContext resolveContext, LookupHelper lookupHelper) {
3276        MethodResolutionContext prevResolutionContext = currentResolutionContext;
3277        try {
3278            Symbol bestSoFar = methodNotFound;
3279            currentResolutionContext = resolveContext;
3280            for (MethodResolutionPhase phase : methodResolutionSteps) {
3281                if (lookupHelper.shouldStop(bestSoFar, phase))
3282                    break;
3283                MethodResolutionPhase prevPhase = currentResolutionContext.step;
3284                Symbol prevBest = bestSoFar;
3285                currentResolutionContext.step = phase;
3286                Symbol sym = lookupHelper.lookup(env, phase);
3287                lookupHelper.debug(pos, sym);
3288                bestSoFar = phase.mergeResults(bestSoFar, sym);
3289                env.info.pendingResolutionPhase = (prevBest == bestSoFar) ? prevPhase : phase;
3290            }
3291            return lookupHelper.access(env, pos, location, bestSoFar);
3292        } finally {
3293            currentResolutionContext = prevResolutionContext;
3294        }
3295    }
3296
3297    /**
3298     * Resolve `c.name' where name == this or name == super.
3299     * @param pos           The position to use for error reporting.
3300     * @param env           The environment current at the expression.
3301     * @param c             The qualifier.
3302     * @param name          The identifier's name.
3303     */
3304    Symbol resolveSelf(DiagnosticPosition pos,
3305                       Env<AttrContext> env,
3306                       TypeSymbol c,
3307                       Name name) {
3308        Env<AttrContext> env1 = env;
3309        boolean staticOnly = false;
3310        while (env1.outer != null) {
3311            if (isStatic(env1)) staticOnly = true;
3312            if (env1.enclClass.sym == c) {
3313                Symbol sym = env1.info.scope.findFirst(name);
3314                if (sym != null) {
3315                    if (staticOnly) sym = new StaticError(sym);
3316                    return accessBase(sym, pos, env.enclClass.sym.type,
3317                                  name, true);
3318                }
3319            }
3320            if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
3321            env1 = env1.outer;
3322        }
3323        if (c.isInterface() &&
3324            name == names._super && !isStatic(env) &&
3325            types.isDirectSuperInterface(c, env.enclClass.sym)) {
3326            //this might be a default super call if one of the superinterfaces is 'c'
3327            for (Type t : pruneInterfaces(env.enclClass.type)) {
3328                if (t.tsym == c) {
3329                    env.info.defaultSuperCallSite = t;
3330                    return new VarSymbol(0, names._super,
3331                            types.asSuper(env.enclClass.type, c), env.enclClass.sym);
3332                }
3333            }
3334            //find a direct superinterface that is a subtype of 'c'
3335            for (Type i : types.interfaces(env.enclClass.type)) {
3336                if (i.tsym.isSubClass(c, types) && i.tsym != c) {
3337                    log.error(pos, "illegal.default.super.call", c,
3338                            diags.fragment("redundant.supertype", c, i));
3339                    return syms.errSymbol;
3340                }
3341            }
3342            Assert.error();
3343        }
3344        log.error(pos, "not.encl.class", c);
3345        return syms.errSymbol;
3346    }
3347    //where
3348    private List<Type> pruneInterfaces(Type t) {
3349        ListBuffer<Type> result = new ListBuffer<>();
3350        for (Type t1 : types.interfaces(t)) {
3351            boolean shouldAdd = true;
3352            for (Type t2 : types.interfaces(t)) {
3353                if (t1 != t2 && types.isSubtypeNoCapture(t2, t1)) {
3354                    shouldAdd = false;
3355                }
3356            }
3357            if (shouldAdd) {
3358                result.append(t1);
3359            }
3360        }
3361        return result.toList();
3362    }
3363
3364
3365    /**
3366     * Resolve `c.this' for an enclosing class c that contains the
3367     * named member.
3368     * @param pos           The position to use for error reporting.
3369     * @param env           The environment current at the expression.
3370     * @param member        The member that must be contained in the result.
3371     */
3372    Symbol resolveSelfContaining(DiagnosticPosition pos,
3373                                 Env<AttrContext> env,
3374                                 Symbol member,
3375                                 boolean isSuperCall) {
3376        Symbol sym = resolveSelfContainingInternal(env, member, isSuperCall);
3377        if (sym == null) {
3378            log.error(pos, "encl.class.required", member);
3379            return syms.errSymbol;
3380        } else {
3381            return accessBase(sym, pos, env.enclClass.sym.type, sym.name, true);
3382        }
3383    }
3384
3385    boolean hasEnclosingInstance(Env<AttrContext> env, Type type) {
3386        Symbol encl = resolveSelfContainingInternal(env, type.tsym, false);
3387        return encl != null && !encl.kind.isOverloadError();
3388    }
3389
3390    private Symbol resolveSelfContainingInternal(Env<AttrContext> env,
3391                                 Symbol member,
3392                                 boolean isSuperCall) {
3393        Name name = names._this;
3394        Env<AttrContext> env1 = isSuperCall ? env.outer : env;
3395        boolean staticOnly = false;
3396        if (env1 != null) {
3397            while (env1 != null && env1.outer != null) {
3398                if (isStatic(env1)) staticOnly = true;
3399                if (env1.enclClass.sym.isSubClass(member.owner, types)) {
3400                    Symbol sym = env1.info.scope.findFirst(name);
3401                    if (sym != null) {
3402                        if (staticOnly) sym = new StaticError(sym);
3403                        return sym;
3404                    }
3405                }
3406                if ((env1.enclClass.sym.flags() & STATIC) != 0)
3407                    staticOnly = true;
3408                env1 = env1.outer;
3409            }
3410        }
3411        return null;
3412    }
3413
3414    /**
3415     * Resolve an appropriate implicit this instance for t's container.
3416     * JLS 8.8.5.1 and 15.9.2
3417     */
3418    Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
3419        return resolveImplicitThis(pos, env, t, false);
3420    }
3421
3422    Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t, boolean isSuperCall) {
3423        Type thisType = (t.tsym.owner.kind.matches(KindSelector.VAL_MTH)
3424                         ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
3425                         : resolveSelfContaining(pos, env, t.tsym, isSuperCall)).type;
3426        if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
3427            log.error(pos, "cant.ref.before.ctor.called", "this");
3428        return thisType;
3429    }
3430
3431/* ***************************************************************************
3432 *  ResolveError classes, indicating error situations when accessing symbols
3433 ****************************************************************************/
3434
3435    //used by TransTypes when checking target type of synthetic cast
3436    public void logAccessErrorInternal(Env<AttrContext> env, JCTree tree, Type type) {
3437        AccessError error = new AccessError(env, env.enclClass.type, type.tsym);
3438        logResolveError(error, tree.pos(), env.enclClass.sym, env.enclClass.type, null, null, null);
3439    }
3440    //where
3441    private void logResolveError(ResolveError error,
3442            DiagnosticPosition pos,
3443            Symbol location,
3444            Type site,
3445            Name name,
3446            List<Type> argtypes,
3447            List<Type> typeargtypes) {
3448        JCDiagnostic d = error.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
3449                pos, location, site, name, argtypes, typeargtypes);
3450        if (d != null) {
3451            d.setFlag(DiagnosticFlag.RESOLVE_ERROR);
3452            log.report(d);
3453        }
3454    }
3455
3456    private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
3457
3458    public Object methodArguments(List<Type> argtypes) {
3459        if (argtypes == null || argtypes.isEmpty()) {
3460            return noArgs;
3461        } else {
3462            ListBuffer<Object> diagArgs = new ListBuffer<>();
3463            for (Type t : argtypes) {
3464                if (t.hasTag(DEFERRED)) {
3465                    diagArgs.append(((DeferredAttr.DeferredType)t).tree);
3466                } else {
3467                    diagArgs.append(t);
3468                }
3469            }
3470            return diagArgs;
3471        }
3472    }
3473
3474    /**
3475     * Root class for resolution errors. Subclass of ResolveError
3476     * represent a different kinds of resolution error - as such they must
3477     * specify how they map into concrete compiler diagnostics.
3478     */
3479    abstract class ResolveError extends Symbol {
3480
3481        /** The name of the kind of error, for debugging only. */
3482        final String debugName;
3483
3484        ResolveError(Kind kind, String debugName) {
3485            super(kind, 0, null, null, null);
3486            this.debugName = debugName;
3487        }
3488
3489        @Override @DefinedBy(Api.LANGUAGE_MODEL)
3490        public <R, P> R accept(ElementVisitor<R, P> v, P p) {
3491            throw new AssertionError();
3492        }
3493
3494        @Override
3495        public String toString() {
3496            return debugName;
3497        }
3498
3499        @Override
3500        public boolean exists() {
3501            return false;
3502        }
3503
3504        @Override
3505        public boolean isStatic() {
3506            return false;
3507        }
3508
3509        /**
3510         * Create an external representation for this erroneous symbol to be
3511         * used during attribution - by default this returns the symbol of a
3512         * brand new error type which stores the original type found
3513         * during resolution.
3514         *
3515         * @param name     the name used during resolution
3516         * @param location the location from which the symbol is accessed
3517         */
3518        protected Symbol access(Name name, TypeSymbol location) {
3519            return types.createErrorType(name, location, syms.errSymbol.type).tsym;
3520        }
3521
3522        /**
3523         * Create a diagnostic representing this resolution error.
3524         *
3525         * @param dkind     The kind of the diagnostic to be created (e.g error).
3526         * @param pos       The position to be used for error reporting.
3527         * @param site      The original type from where the selection took place.
3528         * @param name      The name of the symbol to be resolved.
3529         * @param argtypes  The invocation's value arguments,
3530         *                  if we looked for a method.
3531         * @param typeargtypes  The invocation's type arguments,
3532         *                      if we looked for a method.
3533         */
3534        abstract JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3535                DiagnosticPosition pos,
3536                Symbol location,
3537                Type site,
3538                Name name,
3539                List<Type> argtypes,
3540                List<Type> typeargtypes);
3541    }
3542
3543    /**
3544     * This class is the root class of all resolution errors caused by
3545     * an invalid symbol being found during resolution.
3546     */
3547    abstract class InvalidSymbolError extends ResolveError {
3548
3549        /** The invalid symbol found during resolution */
3550        Symbol sym;
3551
3552        InvalidSymbolError(Kind kind, Symbol sym, String debugName) {
3553            super(kind, debugName);
3554            this.sym = sym;
3555        }
3556
3557        @Override
3558        public boolean exists() {
3559            return true;
3560        }
3561
3562        @Override
3563        public String toString() {
3564             return super.toString() + " wrongSym=" + sym;
3565        }
3566
3567        @Override
3568        public Symbol access(Name name, TypeSymbol location) {
3569            if (!sym.kind.isOverloadError() && sym.kind.matches(KindSelector.TYP))
3570                return types.createErrorType(name, location, sym.type).tsym;
3571            else
3572                return sym;
3573        }
3574    }
3575
3576    /**
3577     * InvalidSymbolError error class indicating that a symbol matching a
3578     * given name does not exists in a given site.
3579     */
3580    class SymbolNotFoundError extends ResolveError {
3581
3582        SymbolNotFoundError(Kind kind) {
3583            this(kind, "symbol not found error");
3584        }
3585
3586        SymbolNotFoundError(Kind kind, String debugName) {
3587            super(kind, debugName);
3588        }
3589
3590        @Override
3591        JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3592                DiagnosticPosition pos,
3593                Symbol location,
3594                Type site,
3595                Name name,
3596                List<Type> argtypes,
3597                List<Type> typeargtypes) {
3598            argtypes = argtypes == null ? List.<Type>nil() : argtypes;
3599            typeargtypes = typeargtypes == null ? List.<Type>nil() : typeargtypes;
3600            if (name == names.error)
3601                return null;
3602
3603            if (syms.operatorNames.contains(name)) {
3604                boolean isUnaryOp = argtypes.size() == 1;
3605                String key = argtypes.size() == 1 ?
3606                    "operator.cant.be.applied" :
3607                    "operator.cant.be.applied.1";
3608                Type first = argtypes.head;
3609                Type second = !isUnaryOp ? argtypes.tail.head : null;
3610                return diags.create(dkind, log.currentSource(), pos,
3611                        key, name, first, second);
3612            }
3613            boolean hasLocation = false;
3614            if (location == null) {
3615                location = site.tsym;
3616            }
3617            if (!location.name.isEmpty()) {
3618                if (location.kind == PCK && !site.tsym.exists()) {
3619                    return diags.create(dkind, log.currentSource(), pos,
3620                        "doesnt.exist", location);
3621                }
3622                hasLocation = !location.name.equals(names._this) &&
3623                        !location.name.equals(names._super);
3624            }
3625            boolean isConstructor = (kind == ABSENT_MTH || kind == WRONG_STATICNESS) &&
3626                    name == names.init;
3627            KindName kindname = isConstructor ? KindName.CONSTRUCTOR : kind.absentKind();
3628            Name idname = isConstructor ? site.tsym.name : name;
3629            String errKey = getErrorKey(kindname, typeargtypes.nonEmpty(), hasLocation);
3630            if (hasLocation) {
3631                return diags.create(dkind, log.currentSource(), pos,
3632                        errKey, kindname, idname, //symbol kindname, name
3633                        typeargtypes, args(argtypes), //type parameters and arguments (if any)
3634                        getLocationDiag(location, site)); //location kindname, type
3635            }
3636            else {
3637                return diags.create(dkind, log.currentSource(), pos,
3638                        errKey, kindname, idname, //symbol kindname, name
3639                        typeargtypes, args(argtypes)); //type parameters and arguments (if any)
3640            }
3641        }
3642        //where
3643        private Object args(List<Type> args) {
3644            return args.isEmpty() ? args : methodArguments(args);
3645        }
3646
3647        private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) {
3648            String key = "cant.resolve";
3649            String suffix = hasLocation ? ".location" : "";
3650            switch (kindname) {
3651                case METHOD:
3652                case CONSTRUCTOR: {
3653                    suffix += ".args";
3654                    suffix += hasTypeArgs ? ".params" : "";
3655                }
3656            }
3657            return key + suffix;
3658        }
3659        private JCDiagnostic getLocationDiag(Symbol location, Type site) {
3660            if (location.kind == VAR) {
3661                return diags.fragment("location.1",
3662                    kindName(location),
3663                    location,
3664                    location.type);
3665            } else {
3666                return diags.fragment("location",
3667                    typeKindName(site),
3668                    site,
3669                    null);
3670            }
3671        }
3672    }
3673
3674    /**
3675     * InvalidSymbolError error class indicating that a given symbol
3676     * (either a method, a constructor or an operand) is not applicable
3677     * given an actual arguments/type argument list.
3678     */
3679    class InapplicableSymbolError extends ResolveError {
3680
3681        protected MethodResolutionContext resolveContext;
3682
3683        InapplicableSymbolError(MethodResolutionContext context) {
3684            this(WRONG_MTH, "inapplicable symbol error", context);
3685        }
3686
3687        protected InapplicableSymbolError(Kind kind, String debugName, MethodResolutionContext context) {
3688            super(kind, debugName);
3689            this.resolveContext = context;
3690        }
3691
3692        @Override
3693        public String toString() {
3694            return super.toString();
3695        }
3696
3697        @Override
3698        public boolean exists() {
3699            return true;
3700        }
3701
3702        @Override
3703        JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3704                DiagnosticPosition pos,
3705                Symbol location,
3706                Type site,
3707                Name name,
3708                List<Type> argtypes,
3709                List<Type> typeargtypes) {
3710            if (name == names.error)
3711                return null;
3712
3713            if (syms.operatorNames.contains(name)) {
3714                boolean isUnaryOp = argtypes.size() == 1;
3715                String key = argtypes.size() == 1 ?
3716                    "operator.cant.be.applied" :
3717                    "operator.cant.be.applied.1";
3718                Type first = argtypes.head;
3719                Type second = !isUnaryOp ? argtypes.tail.head : null;
3720                return diags.create(dkind, log.currentSource(), pos,
3721                        key, name, first, second);
3722            }
3723            else {
3724                Pair<Symbol, JCDiagnostic> c = errCandidate();
3725                if (compactMethodDiags) {
3726                    for (Map.Entry<Template, DiagnosticRewriter> _entry :
3727                            MethodResolutionDiagHelper.rewriters.entrySet()) {
3728                        if (_entry.getKey().matches(c.snd)) {
3729                            JCDiagnostic simpleDiag =
3730                                    _entry.getValue().rewriteDiagnostic(diags, pos,
3731                                        log.currentSource(), dkind, c.snd);
3732                            simpleDiag.setFlag(DiagnosticFlag.COMPRESSED);
3733                            return simpleDiag;
3734                        }
3735                    }
3736                }
3737                Symbol ws = c.fst.asMemberOf(site, types);
3738                return diags.create(dkind, log.currentSource(), pos,
3739                          "cant.apply.symbol",
3740                          kindName(ws),
3741                          ws.name == names.init ? ws.owner.name : ws.name,
3742                          methodArguments(ws.type.getParameterTypes()),
3743                          methodArguments(argtypes),
3744                          kindName(ws.owner),
3745                          ws.owner.type,
3746                          c.snd);
3747            }
3748        }
3749
3750        @Override
3751        public Symbol access(Name name, TypeSymbol location) {
3752            return types.createErrorType(name, location, syms.errSymbol.type).tsym;
3753        }
3754
3755        protected Pair<Symbol, JCDiagnostic> errCandidate() {
3756            Candidate bestSoFar = null;
3757            for (Candidate c : resolveContext.candidates) {
3758                if (c.isApplicable()) continue;
3759                bestSoFar = c;
3760            }
3761            Assert.checkNonNull(bestSoFar);
3762            return new Pair<>(bestSoFar.sym, bestSoFar.details);
3763        }
3764    }
3765
3766    /**
3767     * ResolveError error class indicating that a set of symbols
3768     * (either methods, constructors or operands) is not applicable
3769     * given an actual arguments/type argument list.
3770     */
3771    class InapplicableSymbolsError extends InapplicableSymbolError {
3772
3773        InapplicableSymbolsError(MethodResolutionContext context) {
3774            super(WRONG_MTHS, "inapplicable symbols", context);
3775        }
3776
3777        @Override
3778        JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3779                DiagnosticPosition pos,
3780                Symbol location,
3781                Type site,
3782                Name name,
3783                List<Type> argtypes,
3784                List<Type> typeargtypes) {
3785            Map<Symbol, JCDiagnostic> candidatesMap = mapCandidates();
3786            Map<Symbol, JCDiagnostic> filteredCandidates = compactMethodDiags ?
3787                    filterCandidates(candidatesMap) :
3788                    mapCandidates();
3789            if (filteredCandidates.isEmpty()) {
3790                filteredCandidates = candidatesMap;
3791            }
3792            boolean truncatedDiag = candidatesMap.size() != filteredCandidates.size();
3793            if (filteredCandidates.size() > 1) {
3794                JCDiagnostic err = diags.create(dkind,
3795                        null,
3796                        truncatedDiag ?
3797                            EnumSet.of(DiagnosticFlag.COMPRESSED) :
3798                            EnumSet.noneOf(DiagnosticFlag.class),
3799                        log.currentSource(),
3800                        pos,
3801                        "cant.apply.symbols",
3802                        name == names.init ? KindName.CONSTRUCTOR : kind.absentKind(),
3803                        name == names.init ? site.tsym.name : name,
3804                        methodArguments(argtypes));
3805                return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(filteredCandidates, site));
3806            } else if (filteredCandidates.size() == 1) {
3807                Map.Entry<Symbol, JCDiagnostic> _e =
3808                                filteredCandidates.entrySet().iterator().next();
3809                final Pair<Symbol, JCDiagnostic> p = new Pair<>(_e.getKey(), _e.getValue());
3810                JCDiagnostic d = new InapplicableSymbolError(resolveContext) {
3811                    @Override
3812                    protected Pair<Symbol, JCDiagnostic> errCandidate() {
3813                        return p;
3814                    }
3815                }.getDiagnostic(dkind, pos,
3816                    location, site, name, argtypes, typeargtypes);
3817                if (truncatedDiag) {
3818                    d.setFlag(DiagnosticFlag.COMPRESSED);
3819                }
3820                return d;
3821            } else {
3822                return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
3823                    location, site, name, argtypes, typeargtypes);
3824            }
3825        }
3826        //where
3827            private Map<Symbol, JCDiagnostic> mapCandidates() {
3828                Map<Symbol, JCDiagnostic> candidates = new LinkedHashMap<>();
3829                for (Candidate c : resolveContext.candidates) {
3830                    if (c.isApplicable()) continue;
3831                    candidates.put(c.sym, c.details);
3832                }
3833                return candidates;
3834            }
3835
3836            Map<Symbol, JCDiagnostic> filterCandidates(Map<Symbol, JCDiagnostic> candidatesMap) {
3837                Map<Symbol, JCDiagnostic> candidates = new LinkedHashMap<>();
3838                for (Map.Entry<Symbol, JCDiagnostic> _entry : candidatesMap.entrySet()) {
3839                    JCDiagnostic d = _entry.getValue();
3840                    if (!new Template(MethodCheckDiag.ARITY_MISMATCH.regex()).matches(d)) {
3841                        candidates.put(_entry.getKey(), d);
3842                    }
3843                }
3844                return candidates;
3845            }
3846
3847            private List<JCDiagnostic> candidateDetails(Map<Symbol, JCDiagnostic> candidatesMap, Type site) {
3848                List<JCDiagnostic> details = List.nil();
3849                for (Map.Entry<Symbol, JCDiagnostic> _entry : candidatesMap.entrySet()) {
3850                    Symbol sym = _entry.getKey();
3851                    JCDiagnostic detailDiag = diags.fragment("inapplicable.method",
3852                            Kinds.kindName(sym),
3853                            sym.location(site, types),
3854                            sym.asMemberOf(site, types),
3855                            _entry.getValue());
3856                    details = details.prepend(detailDiag);
3857                }
3858                //typically members are visited in reverse order (see Scope)
3859                //so we need to reverse the candidate list so that candidates
3860                //conform to source order
3861                return details;
3862            }
3863    }
3864
3865    /**
3866     * An InvalidSymbolError error class indicating that a symbol is not
3867     * accessible from a given site
3868     */
3869    class AccessError extends InvalidSymbolError {
3870
3871        private Env<AttrContext> env;
3872        private Type site;
3873
3874        AccessError(Symbol sym) {
3875            this(null, null, sym);
3876        }
3877
3878        AccessError(Env<AttrContext> env, Type site, Symbol sym) {
3879            super(HIDDEN, sym, "access error");
3880            this.env = env;
3881            this.site = site;
3882            if (debugResolve)
3883                log.error("proc.messager", sym + " @ " + site + " is inaccessible.");
3884        }
3885
3886        @Override
3887        public boolean exists() {
3888            return false;
3889        }
3890
3891        @Override
3892        JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3893                DiagnosticPosition pos,
3894                Symbol location,
3895                Type site,
3896                Name name,
3897                List<Type> argtypes,
3898                List<Type> typeargtypes) {
3899            if (sym.owner.type.hasTag(ERROR))
3900                return null;
3901
3902            if (sym.name == names.init && sym.owner != site.tsym) {
3903                return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind,
3904                        pos, location, site, name, argtypes, typeargtypes);
3905            }
3906            else if ((sym.flags() & PUBLIC) != 0
3907                || (env != null && this.site != null
3908                    && !isAccessible(env, this.site))) {
3909                return diags.create(dkind, log.currentSource(),
3910                        pos, "not.def.access.class.intf.cant.access",
3911                    sym, sym.location());
3912            }
3913            else if ((sym.flags() & (PRIVATE | PROTECTED)) != 0) {
3914                return diags.create(dkind, log.currentSource(),
3915                        pos, "report.access", sym,
3916                        asFlagSet(sym.flags() & (PRIVATE | PROTECTED)),
3917                        sym.location());
3918            }
3919            else {
3920                return diags.create(dkind, log.currentSource(),
3921                        pos, "not.def.public.cant.access", sym, sym.location());
3922            }
3923        }
3924    }
3925
3926    /**
3927     * InvalidSymbolError error class indicating that an instance member
3928     * has erroneously been accessed from a static context.
3929     */
3930    class StaticError extends InvalidSymbolError {
3931
3932        StaticError(Symbol sym) {
3933            super(STATICERR, sym, "static error");
3934        }
3935
3936        @Override
3937        JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3938                DiagnosticPosition pos,
3939                Symbol location,
3940                Type site,
3941                Name name,
3942                List<Type> argtypes,
3943                List<Type> typeargtypes) {
3944            Symbol errSym = ((sym.kind == TYP && sym.type.hasTag(CLASS))
3945                ? types.erasure(sym.type).tsym
3946                : sym);
3947            return diags.create(dkind, log.currentSource(), pos,
3948                    "non-static.cant.be.ref", kindName(sym), errSym);
3949        }
3950    }
3951
3952    /**
3953     * InvalidSymbolError error class indicating that a pair of symbols
3954     * (either methods, constructors or operands) are ambiguous
3955     * given an actual arguments/type argument list.
3956     */
3957    class AmbiguityError extends ResolveError {
3958
3959        /** The other maximally specific symbol */
3960        List<Symbol> ambiguousSyms = List.nil();
3961
3962        @Override
3963        public boolean exists() {
3964            return true;
3965        }
3966
3967        AmbiguityError(Symbol sym1, Symbol sym2) {
3968            super(AMBIGUOUS, "ambiguity error");
3969            ambiguousSyms = flatten(sym2).appendList(flatten(sym1));
3970        }
3971
3972        private List<Symbol> flatten(Symbol sym) {
3973            if (sym.kind == AMBIGUOUS) {
3974                return ((AmbiguityError)sym.baseSymbol()).ambiguousSyms;
3975            } else {
3976                return List.of(sym);
3977            }
3978        }
3979
3980        AmbiguityError addAmbiguousSymbol(Symbol s) {
3981            ambiguousSyms = ambiguousSyms.prepend(s);
3982            return this;
3983        }
3984
3985        @Override
3986        JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind,
3987                DiagnosticPosition pos,
3988                Symbol location,
3989                Type site,
3990                Name name,
3991                List<Type> argtypes,
3992                List<Type> typeargtypes) {
3993            List<Symbol> diagSyms = ambiguousSyms.reverse();
3994            Symbol s1 = diagSyms.head;
3995            Symbol s2 = diagSyms.tail.head;
3996            Name sname = s1.name;
3997            if (sname == names.init) sname = s1.owner.name;
3998            return diags.create(dkind, log.currentSource(),
3999                      pos, "ref.ambiguous", sname,
4000                      kindName(s1),
4001                      s1,
4002                      s1.location(site, types),
4003                      kindName(s2),
4004                      s2,
4005                      s2.location(site, types));
4006        }
4007
4008        /**
4009         * If multiple applicable methods are found during overload and none of them
4010         * is more specific than the others, attempt to merge their signatures.
4011         */
4012        Symbol mergeAbstracts(Type site) {
4013            List<Symbol> ambiguousInOrder = ambiguousSyms.reverse();
4014            for (Symbol s : ambiguousInOrder) {
4015                Type mt = types.memberType(site, s);
4016                boolean found = true;
4017                List<Type> allThrown = mt.getThrownTypes();
4018                for (Symbol s2 : ambiguousInOrder) {
4019                    Type mt2 = types.memberType(site, s2);
4020                    if ((s2.flags() & ABSTRACT) == 0 ||
4021                        !types.overrideEquivalent(mt, mt2) ||
4022                        !types.isSameTypes(s.erasure(types).getParameterTypes(),
4023                                       s2.erasure(types).getParameterTypes())) {
4024                        //ambiguity cannot be resolved
4025                        return this;
4026                    }
4027                    Type mst = mostSpecificReturnType(mt, mt2);
4028                    if (mst == null || mst != mt) {
4029                        found = false;
4030                        break;
4031                    }
4032                    allThrown = chk.intersect(allThrown, mt2.getThrownTypes());
4033                }
4034                if (found) {
4035                    //all ambiguous methods were abstract and one method had
4036                    //most specific return type then others
4037                    return (allThrown == mt.getThrownTypes()) ?
4038                            s : new MethodSymbol(
4039                                s.flags(),
4040                                s.name,
4041                                types.createMethodTypeWithThrown(mt, allThrown),
4042                                s.owner);
4043                }
4044            }
4045            return this;
4046        }
4047
4048        @Override
4049        protected Symbol access(Name name, TypeSymbol location) {
4050            Symbol firstAmbiguity = ambiguousSyms.last();
4051            return firstAmbiguity.kind == TYP ?
4052                    types.createErrorType(name, location, firstAmbiguity.type).tsym :
4053                    firstAmbiguity;
4054        }
4055    }
4056
4057    class BadVarargsMethod extends ResolveError {
4058
4059        ResolveError delegatedError;
4060
4061        BadVarargsMethod(ResolveError delegatedError) {
4062            super(delegatedError.kind, "badVarargs");
4063            this.delegatedError = delegatedError;
4064        }
4065
4066        @Override
4067        public Symbol baseSymbol() {
4068            return delegatedError.baseSymbol();
4069        }
4070
4071        @Override
4072        protected Symbol access(Name name, TypeSymbol location) {
4073            return delegatedError.access(name, location);
4074        }
4075
4076        @Override
4077        public boolean exists() {
4078            return true;
4079        }
4080
4081        @Override
4082        JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
4083            return delegatedError.getDiagnostic(dkind, pos, location, site, name, argtypes, typeargtypes);
4084        }
4085    }
4086
4087    /**
4088     * Helper class for method resolution diagnostic simplification.
4089     * Certain resolution diagnostic are rewritten as simpler diagnostic
4090     * where the enclosing resolution diagnostic (i.e. 'inapplicable method')
4091     * is stripped away, as it doesn't carry additional info. The logic
4092     * for matching a given diagnostic is given in terms of a template
4093     * hierarchy: a diagnostic template can be specified programmatically,
4094     * so that only certain diagnostics are matched. Each templete is then
4095     * associated with a rewriter object that carries out the task of rewtiting
4096     * the diagnostic to a simpler one.
4097     */
4098    static class MethodResolutionDiagHelper {
4099
4100        /**
4101         * A diagnostic rewriter transforms a method resolution diagnostic
4102         * into a simpler one
4103         */
4104        interface DiagnosticRewriter {
4105            JCDiagnostic rewriteDiagnostic(JCDiagnostic.Factory diags,
4106                    DiagnosticPosition preferedPos, DiagnosticSource preferredSource,
4107                    DiagnosticType preferredKind, JCDiagnostic d);
4108        }
4109
4110        /**
4111         * A diagnostic template is made up of two ingredients: (i) a regular
4112         * expression for matching a diagnostic key and (ii) a list of sub-templates
4113         * for matching diagnostic arguments.
4114         */
4115        static class Template {
4116
4117            /** regex used to match diag key */
4118            String regex;
4119
4120            /** templates used to match diagnostic args */
4121            Template[] subTemplates;
4122
4123            Template(String key, Template... subTemplates) {
4124                this.regex = key;
4125                this.subTemplates = subTemplates;
4126            }
4127
4128            /**
4129             * Returns true if the regex matches the diagnostic key and if
4130             * all diagnostic arguments are matches by corresponding sub-templates.
4131             */
4132            boolean matches(Object o) {
4133                JCDiagnostic d = (JCDiagnostic)o;
4134                Object[] args = d.getArgs();
4135                if (!d.getCode().matches(regex) ||
4136                        subTemplates.length != d.getArgs().length) {
4137                    return false;
4138                }
4139                for (int i = 0; i < args.length ; i++) {
4140                    if (!subTemplates[i].matches(args[i])) {
4141                        return false;
4142                    }
4143                }
4144                return true;
4145            }
4146        }
4147
4148        /** a dummy template that match any diagnostic argument */
4149        static final Template skip = new Template("") {
4150            @Override
4151            boolean matches(Object d) {
4152                return true;
4153            }
4154        };
4155
4156        /** rewriter map used for method resolution simplification */
4157        static final Map<Template, DiagnosticRewriter> rewriters = new LinkedHashMap<>();
4158
4159        static {
4160            String argMismatchRegex = MethodCheckDiag.ARG_MISMATCH.regex();
4161            rewriters.put(new Template(argMismatchRegex, skip),
4162                    new DiagnosticRewriter() {
4163                @Override
4164                public JCDiagnostic rewriteDiagnostic(JCDiagnostic.Factory diags,
4165                        DiagnosticPosition preferedPos, DiagnosticSource preferredSource,
4166                        DiagnosticType preferredKind, JCDiagnostic d) {
4167                    JCDiagnostic cause = (JCDiagnostic)d.getArgs()[0];
4168                    return diags.create(preferredKind, preferredSource, d.getDiagnosticPosition(),
4169                            "prob.found.req", cause);
4170                }
4171            });
4172        }
4173    }
4174
4175    enum MethodResolutionPhase {
4176        BASIC(false, false),
4177        BOX(true, false),
4178        VARARITY(true, true) {
4179            @Override
4180            public Symbol mergeResults(Symbol bestSoFar, Symbol sym) {
4181                //Check invariants (see {@code LookupHelper.shouldStop})
4182                Assert.check(bestSoFar.kind.isOverloadError() && bestSoFar.kind != AMBIGUOUS);
4183                if (!sym.kind.isOverloadError()) {
4184                    //varargs resolution successful
4185                    return sym;
4186                } else {
4187                    //pick best error
4188                    switch (bestSoFar.kind) {
4189                        case WRONG_MTH:
4190                        case WRONG_MTHS:
4191                            //Override previous errors if they were caused by argument mismatch.
4192                            //This generally means preferring current symbols - but we need to pay
4193                            //attention to the fact that the varargs lookup returns 'less' candidates
4194                            //than the previous rounds, and adjust that accordingly.
4195                            switch (sym.kind) {
4196                                case WRONG_MTH:
4197                                    //if the previous round matched more than one method, return that
4198                                    //result instead
4199                                    return bestSoFar.kind == WRONG_MTHS ?
4200                                            bestSoFar : sym;
4201                                case ABSENT_MTH:
4202                                    //do not override erroneous symbol if the arity lookup did not
4203                                    //match any method
4204                                    return bestSoFar;
4205                                case WRONG_MTHS:
4206                                default:
4207                                    //safe to override
4208                                    return sym;
4209                            }
4210                        default:
4211                            //otherwise, return first error
4212                            return bestSoFar;
4213                    }
4214                }
4215            }
4216        };
4217
4218        final boolean isBoxingRequired;
4219        final boolean isVarargsRequired;
4220
4221        MethodResolutionPhase(boolean isBoxingRequired, boolean isVarargsRequired) {
4222           this.isBoxingRequired = isBoxingRequired;
4223           this.isVarargsRequired = isVarargsRequired;
4224        }
4225
4226        public boolean isBoxingRequired() {
4227            return isBoxingRequired;
4228        }
4229
4230        public boolean isVarargsRequired() {
4231            return isVarargsRequired;
4232        }
4233
4234        public Symbol mergeResults(Symbol prev, Symbol sym) {
4235            return sym;
4236        }
4237    }
4238
4239    final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
4240
4241    /**
4242     * A resolution context is used to keep track of intermediate results of
4243     * overload resolution, such as list of method that are not applicable
4244     * (used to generate more precise diagnostics) and so on. Resolution contexts
4245     * can be nested - this means that when each overload resolution routine should
4246     * work within the resolution context it created.
4247     */
4248    class MethodResolutionContext {
4249
4250        private List<Candidate> candidates = List.nil();
4251
4252        MethodResolutionPhase step = null;
4253
4254        MethodCheck methodCheck = resolveMethodCheck;
4255
4256        private boolean internalResolution = false;
4257        private DeferredAttr.AttrMode attrMode = DeferredAttr.AttrMode.SPECULATIVE;
4258
4259        void addInapplicableCandidate(Symbol sym, JCDiagnostic details) {
4260            Candidate c = new Candidate(currentResolutionContext.step, sym, details, null);
4261            candidates = candidates.append(c);
4262        }
4263
4264        void addApplicableCandidate(Symbol sym, Type mtype) {
4265            Candidate c = new Candidate(currentResolutionContext.step, sym, null, mtype);
4266            candidates = candidates.append(c);
4267        }
4268
4269        DeferredAttrContext deferredAttrContext(Symbol sym, InferenceContext inferenceContext, ResultInfo pendingResult, Warner warn) {
4270            DeferredAttrContext parent = (pendingResult == null)
4271                ? deferredAttr.emptyDeferredAttrContext
4272                : pendingResult.checkContext.deferredAttrContext();
4273            return deferredAttr.new DeferredAttrContext(attrMode, sym, step,
4274                    inferenceContext, parent, warn);
4275        }
4276
4277        /**
4278         * This class represents an overload resolution candidate. There are two
4279         * kinds of candidates: applicable methods and inapplicable methods;
4280         * applicable methods have a pointer to the instantiated method type,
4281         * while inapplicable candidates contain further details about the
4282         * reason why the method has been considered inapplicable.
4283         */
4284        @SuppressWarnings("overrides")
4285        class Candidate {
4286
4287            final MethodResolutionPhase step;
4288            final Symbol sym;
4289            final JCDiagnostic details;
4290            final Type mtype;
4291
4292            private Candidate(MethodResolutionPhase step, Symbol sym, JCDiagnostic details, Type mtype) {
4293                this.step = step;
4294                this.sym = sym;
4295                this.details = details;
4296                this.mtype = mtype;
4297            }
4298
4299            @Override
4300            public boolean equals(Object o) {
4301                if (o instanceof Candidate) {
4302                    Symbol s1 = this.sym;
4303                    Symbol s2 = ((Candidate)o).sym;
4304                    if  ((s1 != s2 &&
4305                            (s1.overrides(s2, s1.owner.type.tsym, types, false) ||
4306                            (s2.overrides(s1, s2.owner.type.tsym, types, false)))) ||
4307                            ((s1.isConstructor() || s2.isConstructor()) && s1.owner != s2.owner))
4308                        return true;
4309                }
4310                return false;
4311            }
4312
4313            boolean isApplicable() {
4314                return mtype != null;
4315            }
4316        }
4317
4318        DeferredAttr.AttrMode attrMode() {
4319            return attrMode;
4320        }
4321
4322        boolean internal() {
4323            return internalResolution;
4324        }
4325    }
4326
4327    MethodResolutionContext currentResolutionContext = null;
4328}
4329