Infer.java revision 2705:4235749f4989
1128266Speter/*
2107484Speter * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
381404Speter * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4128266Speter *
581404Speter * This code is free software; you can redistribute it and/or modify it
681404Speter * under the terms of the GNU General Public License version 2 only, as
781404Speter * published by the Free Software Foundation.  Oracle designates this
881404Speter * particular file as subject to the "Classpath" exception as provided
981404Speter * by Oracle in the LICENSE file that accompanied this code.
1081404Speter *
1181404Speter * This code is distributed in the hope that it will be useful, but WITHOUT
1281404Speter * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
1381404Speter * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
1481404Speter * version 2 for more details (a copy is included in the LICENSE file that
1581404Speter * accompanied this code).
1681404Speter *
1717721Speter * You should have received a copy of the GNU General Public License version
18128266Speter * 2 along with this work; if not, write to the Free Software Foundation,
19128266Speter * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20128266Speter *
2117721Speter * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2217721Speter * or visit www.oracle.com if you need additional information or have any
2317721Speter * questions.
2417721Speter */
2517721Speter
2617721Speterpackage com.sun.tools.javac.comp;
2717721Speter
2817721Speterimport com.sun.tools.javac.tree.JCTree;
2917721Speterimport com.sun.tools.javac.tree.JCTree.JCTypeCast;
3017721Speterimport com.sun.tools.javac.tree.TreeInfo;
3117721Speterimport com.sun.tools.javac.util.*;
3217721Speterimport com.sun.tools.javac.util.GraphUtils.DottableNode;
3317721Speterimport com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
3417721Speterimport com.sun.tools.javac.util.List;
3581404Speterimport com.sun.tools.javac.code.*;
3681404Speterimport com.sun.tools.javac.code.Type.*;
3781404Speterimport com.sun.tools.javac.code.Type.UndetVar.InferenceBound;
3881404Speterimport com.sun.tools.javac.code.Symbol.*;
3981404Speterimport com.sun.tools.javac.comp.DeferredAttr.AttrMode;
40107484Speterimport com.sun.tools.javac.comp.Infer.GraphSolver.InferenceGraph;
4117721Speterimport com.sun.tools.javac.comp.Infer.GraphSolver.InferenceGraph.Node;
42107484Speterimport com.sun.tools.javac.comp.Resolve.InapplicableMethodException;
43107484Speterimport com.sun.tools.javac.comp.Resolve.VerboseResolutionMode;
44107484Speter
4581404Speterimport java.io.File;
46128266Speterimport java.io.FileWriter;
4781404Speterimport java.io.IOException;
4881404Speterimport java.util.ArrayList;
4981404Speterimport java.util.Collection;
5081404Speterimport java.util.Collections;
5181404Speterimport java.util.EnumMap;
5281404Speterimport java.util.EnumSet;
53128266Speterimport java.util.HashMap;
54128266Speterimport java.util.HashSet;
55128266Speterimport java.util.LinkedHashSet;
5681404Speterimport java.util.Map;
57128266Speterimport java.util.Properties;
58128266Speterimport java.util.Set;
59128266Speter
6081404Speterimport static com.sun.tools.javac.code.TypeTag.*;
6181404Speter
62128266Speter/** Helper class for type parameter inference, used by the attribution phase.
63128266Speter *
64128266Speter *  <p><b>This is NOT part of any supported API.
65128266Speter *  If you write code that depends on this, you do so at your own risk.
6681404Speter *  This code and its internal interfaces are subject to change or
67128266Speter *  deletion without notice.</b>
68128266Speter */
6981404Speterpublic class Infer {
70128266Speter    protected static final Context.Key<Infer> inferKey = new Context.Key<>();
71128266Speter
72128266Speter    Resolve rs;
73107484Speter    Check chk;
74128266Speter    Symtab syms;
75128266Speter    Types types;
76128266Speter    JCDiagnostic.Factory diags;
77128266Speter    Log log;
78128266Speter
7981404Speter    /** should the graph solver be used? */
8081404Speter    boolean allowGraphInference;
81128266Speter
82128266Speter    /**
83128266Speter     * folder in which the inference dependency graphs should be written.
8481404Speter     */
85128266Speter    final private String dependenciesFolder;
86128266Speter
87128266Speter    /**
88128266Speter     * List of graphs awaiting to be dumped to a file.
89128266Speter     */
90128266Speter    private List<String> pendingGraphs;
91128266Speter
92128266Speter    public static Infer instance(Context context) {
93128266Speter        Infer instance = context.get(inferKey);
9481404Speter        if (instance == null)
95128266Speter            instance = new Infer(context);
96128266Speter        return instance;
97128266Speter    }
98128266Speter
99128266Speter    protected Infer(Context context) {
100128266Speter        context.put(inferKey, this);
10181404Speter
10281404Speter        rs = Resolve.instance(context);
10381404Speter        chk = Check.instance(context);
10481404Speter        syms = Symtab.instance(context);
10581404Speter        types = Types.instance(context);
106128266Speter        diags = JCDiagnostic.Factory.instance(context);
107128266Speter        log = Log.instance(context);
108128266Speter        inferenceException = new InferenceException(diags);
109107484Speter        Options options = Options.instance(context);
11081404Speter        allowGraphInference = Source.instance(context).allowGraphInference()
11181404Speter                && options.isUnset("useLegacyInference");
11281404Speter        dependenciesFolder = options.get("dumpInferenceGraphsTo");
113128266Speter        pendingGraphs = List.nil();
114128266Speter    }
115128266Speter
116128266Speter    /** A value for prototypes that admit any type, including polymorphic ones. */
117128266Speter    public static final Type anyPoly = new JCNoType();
118128266Speter
119102840Speter   /**
120128266Speter    * This exception class is design to store a list of diagnostics corresponding
121102840Speter    * to inference errors that can arise during a method applicability check.
122128266Speter    */
123128266Speter    public static class InferenceException extends InapplicableMethodException {
124128266Speter        private static final long serialVersionUID = 0;
125128266Speter
126128266Speter        List<JCDiagnostic> messages = List.nil();
127128266Speter
12881404Speter        InferenceException(JCDiagnostic.Factory diags) {
129128266Speter            super(diags);
13081404Speter        }
131128266Speter
132128266Speter        @Override
133128266Speter        InapplicableMethodException setMessage() {
134128266Speter            //no message to set
135128266Speter            return this;
136128266Speter        }
137128266Speter
138128266Speter        @Override
139128266Speter        InapplicableMethodException setMessage(JCDiagnostic diag) {
140128266Speter            messages = messages.append(diag);
141128266Speter            return this;
14217721Speter        }
14381404Speter
14481404Speter        @Override
14581404Speter        public JCDiagnostic getDiagnostic() {
14681404Speter            return messages.head;
14781404Speter        }
14881404Speter
14917721Speter        void clear() {
15017721Speter            messages = List.nil();
15181404Speter        }
15281404Speter    }
15381404Speter
15481404Speter    protected final InferenceException inferenceException;
15581404Speter
15681404Speter    // <editor-fold defaultstate="collapsed" desc="Inference routines">
15781404Speter    /**
15881404Speter     * Main inference entry point - instantiate a generic method type
15981404Speter     * using given argument types and (possibly) an expected target-type.
16081404Speter     */
16181404Speter    Type instantiateMethod( Env<AttrContext> env,
16281404Speter                            List<Type> tvars,
16381404Speter                            MethodType mt,
164130303Speter                            Attr.ResultInfo resultInfo,
16581404Speter                            MethodSymbol msym,
16681404Speter                            List<Type> argtypes,
167102840Speter                            boolean allowBoxing,
168128266Speter                            boolean useVarargs,
169128266Speter                            Resolve.MethodResolutionContext resolveContext,
17017721Speter                            Warner warn) throws InferenceException {
17181404Speter        //-System.err.println("instantiateMethod(" + tvars + ", " + mt + ", " + argtypes + ")"); //DEBUG
17281404Speter        final InferenceContext inferenceContext = new InferenceContext(tvars);  //B0
17381404Speter        inferenceException.clear();
174107484Speter        try {
175102840Speter            DeferredAttr.DeferredAttrContext deferredAttrContext =
17681404Speter                        resolveContext.deferredAttrContext(msym, inferenceContext, resultInfo, warn);
17717721Speter
178128266Speter            resolveContext.methodCheck.argumentsAcceptable(env, deferredAttrContext,   //B2
179128266Speter                    argtypes, mt.getParameterTypes(), warn);
180128266Speter            if (allowGraphInference &&
181128266Speter                    resultInfo != null &&
182128266Speter                    !warn.hasNonSilentLint(Lint.LintCategory.UNCHECKED)) {
183128266Speter                //inject return constraints earlier
184128266Speter                checkWithinBounds(inferenceContext, warn); //propagation
185128266Speter                Type newRestype = generateReturnConstraints(env.tree, resultInfo,  //B3
186128266Speter                        mt, inferenceContext);
187128266Speter                mt = (MethodType)types.createMethodTypeWithReturn(mt, newRestype);
18881404Speter                //propagate outwards if needed
18981404Speter                if (resultInfo.checkContext.inferenceContext().free(resultInfo.pt)) {
19081404Speter                    //propagate inference context outwards and exit
19117721Speter                    inferenceContext.dupTo(resultInfo.checkContext.inferenceContext());
19281404Speter                    deferredAttrContext.complete();
193107484Speter                    return mt;
194107484Speter                }
195107484Speter            }
196128266Speter
19781404Speter            deferredAttrContext.complete();
19881404Speter
199128266Speter            // minimize as yet undetermined type variables
200107484Speter            if (allowGraphInference) {
20117721Speter                inferenceContext.solve(warn);
202102840Speter            } else {
20381404Speter                inferenceContext.solveLegacy(true, warn, LegacyInferenceSteps.EQ_LOWER.steps); //minimizeInst
204128266Speter            }
20581404Speter
20617721Speter            mt = (MethodType)inferenceContext.asInstType(mt);
207128266Speter
20881404Speter            if (!allowGraphInference &&
209107484Speter                    inferenceContext.restvars().nonEmpty() &&
21081404Speter                    resultInfo != null &&
21181404Speter                    !warn.hasNonSilentLint(Lint.LintCategory.UNCHECKED)) {
212107484Speter                generateReturnConstraints(env.tree, resultInfo, mt, inferenceContext);
213107484Speter                inferenceContext.solveLegacy(false, warn, LegacyInferenceSteps.EQ_UPPER.steps); //maximizeInst
21481404Speter                mt = (MethodType)inferenceContext.asInstType(mt);
215107484Speter            }
21681404Speter
217107484Speter            if (resultInfo != null && rs.verboseResolutionMode.contains(VerboseResolutionMode.DEFERRED_INST)) {
218107484Speter                log.note(env.tree.pos, "deferred.method.inst", msym, mt, resultInfo.pt);
219107484Speter            }
220128266Speter
22181404Speter            // return instantiated version of method type
222107484Speter            return mt;
22381404Speter        } finally {
22481404Speter            if (resultInfo != null || !allowGraphInference) {
225107484Speter                inferenceContext.notifyChange();
226102840Speter            } else {
227107484Speter                inferenceContext.notifyChange(inferenceContext.boundedVars());
22881404Speter            }
229107484Speter            if (resultInfo == null) {
23081404Speter                /* if the is no result info then we can clear the capture types
231107484Speter                 * cache without affecting any result info check
23281404Speter                 */
233107484Speter                inferenceContext.captureTypeCache.clear();
234102840Speter            }
23581404Speter            dumpGraphsIfNeeded(env.tree, msym, resolveContext);
23681404Speter        }
23781404Speter    }
23881404Speter
23981404Speter    private void dumpGraphsIfNeeded(DiagnosticPosition pos, Symbol msym, Resolve.MethodResolutionContext rsContext) {
24081404Speter        int round = 0;
24181404Speter        try {
24281404Speter            for (String graph : pendingGraphs.reverse()) {
243107484Speter                Assert.checkNonNull(dependenciesFolder);
24481404Speter                Name name = msym.name == msym.name.table.names.init ?
24581404Speter                        msym.owner.name : msym.name;
24681404Speter                String filename = String.format("%s@%s[mode=%s,step=%s]_%d.dot",
24781404Speter                        name,
24881404Speter                        pos.getStartPosition(),
24981404Speter                        rsContext.attrMode(),
25081404Speter                        rsContext.step,
25181404Speter                        round);
25281404Speter                File dotFile = new File(dependenciesFolder, filename);
25381404Speter                try (FileWriter fw = new FileWriter(dotFile)) {
25481404Speter                    fw.append(graph);
25581404Speter                }
25681404Speter                round++;
25781404Speter            }
25881404Speter        } catch (IOException ex) {
25981404Speter            Assert.error("Error occurred when dumping inference graph: " + ex.getMessage());
26081404Speter        } finally {
26181404Speter            pendingGraphs = List.nil();
26281404Speter        }
263107484Speter    }
26481404Speter
26581404Speter    /**
26681404Speter     * Generate constraints from the generic method's return type. If the method
26781404Speter     * call occurs in a context where a type T is expected, use the expected
26881404Speter     * type to derive more constraints on the generic method inference variables.
26981404Speter     */
27081404Speter    Type generateReturnConstraints(JCTree tree, Attr.ResultInfo resultInfo,
27181404Speter            MethodType mt, InferenceContext inferenceContext) {
27281404Speter        InferenceContext rsInfoInfContext = resultInfo.checkContext.inferenceContext();
27381404Speter        Type from = mt.getReturnType();
27481404Speter        if (mt.getReturnType().containsAny(inferenceContext.inferencevars) &&
27581404Speter                rsInfoInfContext != emptyContext) {
27681404Speter            from = types.capture(from);
27781404Speter            //add synthetic captured ivars
27881404Speter            for (Type t : from.getTypeArguments()) {
27981404Speter                if (t.hasTag(TYPEVAR) && ((TypeVar)t).isCaptured()) {
28081404Speter                    inferenceContext.addVar((TypeVar)t);
28181404Speter                }
28281404Speter            }
28381404Speter        }
28481404Speter        Type qtype = inferenceContext.asUndetVar(from);
28581404Speter        Type to = resultInfo.pt;
28681404Speter
28781404Speter        if (qtype.hasTag(VOID)) {
28881404Speter            to = syms.voidType;
28917721Speter        } else if (to.hasTag(NONE)) {
290128266Speter            to = from.isPrimitive() ? from : syms.objectType;
291128266Speter        } else if (qtype.hasTag(UNDETVAR)) {
292128266Speter            if (resultInfo.pt.isReference()) {
293128266Speter                to = generateReturnConstraintsUndetVarToReference(
29417721Speter                        tree, (UndetVar)qtype, to, resultInfo, inferenceContext);
295107484Speter            } else {
296107484Speter                if (to.isPrimitive()) {
297107484Speter                    to = generateReturnConstraintsPrimitive(tree, (UndetVar)qtype, to,
298128266Speter                        resultInfo, inferenceContext);
299128266Speter                }
300128266Speter            }
30181404Speter        }
30225839Speter        Assert.check(allowGraphInference || !rsInfoInfContext.free(to),
30381404Speter                "legacy inference engine cannot handle constraints on both sides of a subtyping assertion");
304107484Speter        //we need to skip capture?
30581404Speter        Warner retWarn = new Warner();
30681404Speter        if (!resultInfo.checkContext.compatible(qtype, rsInfoInfContext.asUndetVar(to), retWarn) ||
30781404Speter                //unchecked conversion is not allowed in source 7 mode
30881404Speter                (!allowGraphInference && retWarn.hasLint(Lint.LintCategory.UNCHECKED))) {
30981404Speter            throw inferenceException
310107484Speter                    .setMessage("infer.no.conforming.instance.exists",
31117721Speter                    inferenceContext.restvars(), mt.getReturnType(), to);
31281404Speter        }
31381404Speter        return from;
31481404Speter    }
31581404Speter
316128266Speter    private Type generateReturnConstraintsPrimitive(JCTree tree, UndetVar from,
317128266Speter            Type to, Attr.ResultInfo resultInfo, InferenceContext inferenceContext) {
318128266Speter        if (!allowGraphInference) {
319128266Speter            //if legacy, just return boxed type
320128266Speter            return types.boxedClass(to).type;
32181404Speter        }
32281404Speter        //if graph inference we need to skip conflicting boxed bounds...
323128266Speter        for (Type t : from.getBounds(InferenceBound.EQ, InferenceBound.UPPER,
324128266Speter                InferenceBound.LOWER)) {
32581404Speter            Type boundAsPrimitive = types.unboxedType(t);
32681404Speter            if (boundAsPrimitive == null || boundAsPrimitive.hasTag(NONE)) {
327107484Speter                continue;
328102840Speter            }
32981404Speter            return generateReferenceToTargetConstraint(tree, from, to,
33081404Speter                    resultInfo, inferenceContext);
33181404Speter        }
33281404Speter        return types.boxedClass(to).type;
333107484Speter    }
334107484Speter
335107484Speter    private Type generateReturnConstraintsUndetVarToReference(JCTree tree,
33617721Speter            UndetVar from, Type to, Attr.ResultInfo resultInfo,
337128266Speter            InferenceContext inferenceContext) {
338128266Speter        Type captureOfTo = types.capture(to);
339128266Speter        /* T is a reference type, but is not a wildcard-parameterized type, and either
340128266Speter         */
341128266Speter        if (captureOfTo == to) { //not a wildcard parameterized type
342128266Speter            /* i) B2 contains a bound of one of the forms alpha = S or S <: alpha,
343128266Speter             *      where S is a wildcard-parameterized type, or
344128266Speter             */
345128266Speter            for (Type t : from.getBounds(InferenceBound.EQ, InferenceBound.LOWER)) {
346128266Speter                Type captureOfBound = types.capture(t);
347128266Speter                if (captureOfBound != t) {
348128266Speter                    return generateReferenceToTargetConstraint(tree, from, to,
349128266Speter                            resultInfo, inferenceContext);
350128266Speter                }
351128266Speter            }
35281404Speter
353107484Speter            /* ii) B2 contains two bounds of the forms S1 <: alpha and S2 <: alpha,
35481404Speter             * where S1 and S2 have supertypes that are two different
355102840Speter             * parameterizations of the same generic class or interface.
35617721Speter             */
35781404Speter            for (Type aLowerBound : from.getBounds(InferenceBound.LOWER)) {
358128266Speter                for (Type anotherLowerBound : from.getBounds(InferenceBound.LOWER)) {
35981404Speter                    if (aLowerBound != anotherLowerBound &&
36025839Speter                            !inferenceContext.free(aLowerBound) &&
36181404Speter                            !inferenceContext.free(anotherLowerBound) &&
362102840Speter                            commonSuperWithDiffParameterization(aLowerBound, anotherLowerBound)) {
36317721Speter                        return generateReferenceToTargetConstraint(tree, from, to,
364107484Speter                            resultInfo, inferenceContext);
365107484Speter                    }
366107484Speter                }
367107484Speter            }
368107484Speter        }
36981404Speter
370128266Speter        /* T is a parameterization of a generic class or interface, G,
371107484Speter         * and B2 contains a bound of one of the forms alpha = S or S <: alpha,
37217721Speter         * where there exists no type of the form G<...> that is a
37381404Speter         * supertype of S, but the raw type G is a supertype of S
374107484Speter         */
37581404Speter        if (to.isParameterized()) {
376130303Speter            for (Type t : from.getBounds(InferenceBound.EQ, InferenceBound.LOWER)) {
377128266Speter                Type sup = types.asSuper(t, to.tsym);
378128266Speter                if (sup != null && sup.isRaw()) {
379128266Speter                    return generateReferenceToTargetConstraint(tree, from, to,
380128266Speter                            resultInfo, inferenceContext);
381128266Speter                }
382128266Speter            }
383128266Speter        }
384107484Speter        return to;
385102840Speter    }
386102840Speter
387107484Speter    private boolean commonSuperWithDiffParameterization(Type t, Type s) {
388107484Speter        for (Pair<Type, Type> supers : getParameterizedSupers(t, s)) {
389107484Speter            if (!types.isSameType(supers.fst, supers.snd)) return true;
390107484Speter        }
391102840Speter        return false;
39281404Speter    }
393107484Speter
394107484Speter    private Type generateReferenceToTargetConstraint(JCTree tree, UndetVar from,
395107484Speter            Type to, Attr.ResultInfo resultInfo,
396107484Speter            InferenceContext inferenceContext) {
39781404Speter        inferenceContext.solve(List.of(from.qtype), new Warner());
39881404Speter        inferenceContext.notifyChange();
39981404Speter        Type capturedType = resultInfo.checkContext.inferenceContext()
40081404Speter                .cachedCapture(tree, from.inst, false);
40181404Speter        if (types.isConvertible(capturedType,
40217721Speter                resultInfo.checkContext.inferenceContext().asUndetVar(to))) {
403107484Speter            //effectively skip additional return-type constraint generation (compatibility)
40481404Speter            return syms.objectType;
40581404Speter        }
40681404Speter        return to;
40781404Speter    }
40881404Speter
40981404Speter    /**
41081404Speter      * Infer cyclic inference variables as described in 15.12.2.8.
41181404Speter      */
41281404Speter    private void instantiateAsUninferredVars(List<Type> vars, InferenceContext inferenceContext) {
41381404Speter        ListBuffer<Type> todo = new ListBuffer<>();
41481404Speter        //step 1 - create fresh tvars
41581404Speter        for (Type t : vars) {
41681404Speter            UndetVar uv = (UndetVar)inferenceContext.asUndetVar(t);
41781404Speter            List<Type> upperBounds = uv.getBounds(InferenceBound.UPPER);
41881404Speter            if (Type.containsAny(upperBounds, vars)) {
41981404Speter                TypeSymbol fresh_tvar = new TypeVariableSymbol(Flags.SYNTHETIC, uv.qtype.tsym.name, null, uv.qtype.tsym.owner);
42081404Speter                fresh_tvar.type = new TypeVar(fresh_tvar, types.makeCompoundType(uv.getBounds(InferenceBound.UPPER)), null);
421107484Speter                todo.append(uv);
42281404Speter                uv.inst = fresh_tvar.type;
423107484Speter            } else if (upperBounds.nonEmpty()) {
42417721Speter                uv.inst = types.glb(upperBounds);
42581404Speter            } else {
42681404Speter                uv.inst = syms.objectType;
427107484Speter            }
42817721Speter        }
429107484Speter        //step 2 - replace fresh tvars in their bounds
430107484Speter        List<Type> formals = vars;
431107484Speter        for (Type t : todo) {
432107484Speter            UndetVar uv = (UndetVar)t;
433107484Speter            TypeVar ct = (TypeVar)uv.inst;
43481404Speter            ct.bound = types.glb(inferenceContext.asInstTypes(types.getBounds(ct)));
43581404Speter            if (ct.bound.isErroneous()) {
43681404Speter                //report inference error if glb fails
43781404Speter                reportBoundError(uv, BoundErrorKind.BAD_UPPER);
438107484Speter            }
43981404Speter            formals = formals.tail;
44081404Speter        }
441128266Speter    }
442128266Speter
44381404Speter    /**
444128266Speter     * Compute a synthetic method type corresponding to the requested polymorphic
445128266Speter     * method signature. The target return type is computed from the immediately
446128266Speter     * enclosing scope surrounding the polymorphic-signature call.
447128266Speter     */
448107484Speter    Type instantiatePolymorphicSignatureInstance(Env<AttrContext> env,
44981404Speter                                            MethodSymbol spMethod,  // sig. poly. method or null if none
45081404Speter                                            Resolve.MethodResolutionContext resolveContext,
45181404Speter                                            List<Type> argtypes) {
45281404Speter        final Type restype;
45381404Speter
45481404Speter        //The return type for a polymorphic signature call is computed from
455128266Speter        //the enclosing tree E, as follows: if E is a cast, then use the
456128266Speter        //target type of the cast expression as a return type; if E is an
457128266Speter        //expression statement, the return type is 'void' - otherwise the
458128266Speter        //return type is simply 'Object'. A correctness check ensures that
459128266Speter        //env.next refers to the lexically enclosing environment in which
460128266Speter        //the polymorphic signature call environment is nested.
461128266Speter
462128266Speter        switch (env.next.tree.getTag()) {
463128266Speter            case TYPECAST:
464128266Speter                JCTypeCast castTree = (JCTypeCast)env.next.tree;
465128266Speter                restype = (TreeInfo.skipParens(castTree.expr) == env.tree) ?
466107484Speter                    castTree.clazz.type :
46781404Speter                    syms.objectType;
468107484Speter                break;
469107484Speter            case EXEC:
47081404Speter                JCTree.JCExpressionStatement execTree =
47181404Speter                        (JCTree.JCExpressionStatement)env.next.tree;
472128266Speter                restype = (TreeInfo.skipParens(execTree.expr) == env.tree) ?
473128266Speter                    syms.voidType :
474128266Speter                    syms.objectType;
475128266Speter                break;
476128266Speter            default:
477128266Speter                restype = syms.objectType;
478128266Speter        }
479128266Speter
480128266Speter        List<Type> paramtypes = Type.map(argtypes, new ImplicitArgType(spMethod, resolveContext.step));
481107484Speter        List<Type> exType = spMethod != null ?
482128266Speter            spMethod.getThrownTypes() :
483107484Speter            List.of(syms.throwableType); // make it throw all exceptions
484107484Speter
485107484Speter        MethodType mtype = new MethodType(paramtypes,
486128266Speter                                          restype,
487128266Speter                                          exType,
488107484Speter                                          syms.methodClass);
489107484Speter        return mtype;
49081404Speter    }
49181404Speter    //where
49281404Speter        class ImplicitArgType extends DeferredAttr.DeferredTypeMap {
49381404Speter
49481404Speter            public ImplicitArgType(Symbol msym, Resolve.MethodResolutionPhase phase) {
49517721Speter                (rs.deferredAttr).super(AttrMode.SPECULATIVE, msym, phase);
49681404Speter            }
49781404Speter
49881404Speter            public Type apply(Type t) {
49981404Speter                t = types.erasure(super.apply(t));
50017721Speter                if (t.hasTag(BOT))
50181404Speter                    // nulls type as the marker type Null (which has no instances)
50281404Speter                    // infer as java.lang.Void for now
50317721Speter                    t = types.boxedClass(syms.voidType).type;
50481404Speter                return t;
50581404Speter            }
50681404Speter        }
507128266Speter
508102840Speter    /**
509102840Speter      * This method is used to infer a suitable target SAM in case the original
51081404Speter      * SAM type contains one or more wildcards. An inference process is applied
51117721Speter      * so that wildcard bounds, as well as explicit lambda/method ref parameters
51281404Speter      * (where applicable) are used to constraint the solution.
51317721Speter      */
51481404Speter    public Type instantiateFunctionalInterface(DiagnosticPosition pos, Type funcInterface,
515128266Speter            List<Type> paramTypes, Check.CheckContext checkContext) {
51617721Speter        if (types.capture(funcInterface) == funcInterface) {
51781404Speter            //if capture doesn't change the type then return the target unchanged
51881404Speter            //(this means the target contains no wildcards!)
51981404Speter            return funcInterface;
52081404Speter        } else {
52117721Speter            Type formalInterface = funcInterface.tsym.type;
52281404Speter            InferenceContext funcInterfaceContext =
52317721Speter                    new InferenceContext(funcInterface.tsym.type.getTypeArguments());
52481404Speter
525107484Speter            Assert.check(paramTypes != null);
526128266Speter            //get constraints from explicit params (this is done by
52781404Speter            //checking that explicit param types are equal to the ones
52817721Speter            //in the functional interface descriptors)
529102840Speter            List<Type> descParameterTypes = types.findDescriptorType(formalInterface).getParameterTypes();
53025839Speter            if (descParameterTypes.size() != paramTypes.size()) {
53181404Speter                checkContext.report(pos, diags.fragment("incompatible.arg.types.in.lambda"));
53225839Speter                return types.createErrorType(funcInterface);
533102840Speter            }
53425839Speter            for (Type p : descParameterTypes) {
53581404Speter                if (!types.isSameType(funcInterfaceContext.asUndetVar(p), paramTypes.head)) {
53625839Speter                    checkContext.report(pos, diags.fragment("no.suitable.functional.intf.inst", funcInterface));
53781404Speter                    return types.createErrorType(funcInterface);
53817721Speter                }
53981404Speter                paramTypes = paramTypes.tail;
54017721Speter            }
541102840Speter
54217721Speter            try {
54381404Speter                funcInterfaceContext.solve(funcInterfaceContext.boundedVars(), types.noWarnings);
54417721Speter            } catch (InferenceException ex) {
54581404Speter                checkContext.report(pos, diags.fragment("no.suitable.functional.intf.inst", funcInterface));
54681404Speter            }
54781404Speter
548107484Speter            List<Type> actualTypeargs = funcInterface.getTypeArguments();
549128266Speter            for (Type t : funcInterfaceContext.undetvars) {
550128266Speter                UndetVar uv = (UndetVar)t;
55181404Speter                if (uv.inst == null) {
55281404Speter                    uv.inst = actualTypeargs.head;
55381404Speter                }
55481404Speter                actualTypeargs = actualTypeargs.tail;
55581404Speter            }
55681404Speter
557128266Speter            Type owntype = funcInterfaceContext.asInstType(formalInterface);
558128266Speter            if (!chk.checkValidGenericType(owntype)) {
559128266Speter                //if the inferred functional interface type is not well-formed,
560128266Speter                //or if it's not a subtype of the original target, issue an error
561128266Speter                checkContext.report(pos, diags.fragment("no.suitable.functional.intf.inst", funcInterface));
562128266Speter            }
563128266Speter            //propagate constraints as per JLS 18.2.1
564128266Speter            checkContext.compatible(owntype, funcInterface, types.noWarnings);
565102840Speter            return owntype;
566102840Speter        }
567102840Speter    }
568102840Speter    // </editor-fold>
569128266Speter
570128266Speter    // <editor-fold defaultstate="collapsed" desc="Bound checking">
571128266Speter    /**
572128266Speter     * Check bounds and perform incorporation
573128266Speter     */
574107484Speter    void checkWithinBounds(InferenceContext inferenceContext,
575107484Speter                             Warner warn) throws InferenceException {
576102840Speter        MultiUndetVarListener mlistener = new MultiUndetVarListener(inferenceContext.undetvars);
577102840Speter        List<Type> saved_undet = inferenceContext.save();
57881404Speter        try {
57981404Speter            while (true) {
58081404Speter                mlistener.reset();
58181404Speter                if (!allowGraphInference) {
582128266Speter                    //in legacy mode we lack of transitivity, so bound check
583128266Speter                    //cannot be run in parallel with other incoprporation rounds
584128266Speter                    for (Type t : inferenceContext.undetvars) {
58581404Speter                        UndetVar uv = (UndetVar)t;
58681404Speter                        IncorporationStep.CHECK_BOUNDS.apply(uv, inferenceContext, warn);
587102840Speter                    }
588102840Speter                }
58981404Speter                for (Type t : inferenceContext.undetvars) {
59081404Speter                    UndetVar uv = (UndetVar)t;
59181404Speter                    //bound incorporation
59281404Speter                    EnumSet<IncorporationStep> incorporationSteps = allowGraphInference ?
59381404Speter                            incorporationStepsGraph : incorporationStepsLegacy;
59481404Speter                    for (IncorporationStep is : incorporationSteps) {
59581404Speter                        if (is.accepts(uv, inferenceContext)) {
59681404Speter                            is.apply(uv, inferenceContext, warn);
59781404Speter                        }
59881404Speter                    }
59917721Speter                }
60017721Speter                if (!mlistener.changed || !allowGraphInference) break;
601            }
602        }
603        finally {
604            mlistener.detach();
605            if (incorporationCache.size() == MAX_INCORPORATION_STEPS) {
606                inferenceContext.rollback(saved_undet);
607            }
608            incorporationCache.clear();
609        }
610    }
611    //where
612        /**
613         * This listener keeps track of changes on a group of inference variable
614         * bounds. Note: the listener must be detached (calling corresponding
615         * method) to make sure that the underlying inference variable is
616         * left in a clean state.
617         */
618        class MultiUndetVarListener implements UndetVar.UndetVarListener {
619
620            boolean changed;
621            List<Type> undetvars;
622
623            public MultiUndetVarListener(List<Type> undetvars) {
624                this.undetvars = undetvars;
625                for (Type t : undetvars) {
626                    UndetVar uv = (UndetVar)t;
627                    uv.listener = this;
628                }
629            }
630
631            public void varChanged(UndetVar uv, Set<InferenceBound> ibs) {
632                //avoid non-termination
633                if (incorporationCache.size() < MAX_INCORPORATION_STEPS) {
634                    changed = true;
635                }
636            }
637
638            void reset() {
639                changed = false;
640            }
641
642            void detach() {
643                for (Type t : undetvars) {
644                    UndetVar uv = (UndetVar)t;
645                    uv.listener = null;
646                }
647            }
648        }
649
650    /** max number of incorporation rounds */
651        static final int MAX_INCORPORATION_STEPS = 100;
652
653    /* If for two types t and s there is a least upper bound that contains
654     * parameterized types G1, G2 ... Gn, then there exists supertypes of 't' of the form
655     * G1<T1, ..., Tn>, G2<T1, ..., Tn>, ... Gn<T1, ..., Tn> and supertypes of 's' of the form
656     * G1<S1, ..., Sn>, G2<S1, ..., Sn>, ... Gn<S1, ..., Sn> which will be returned by this method.
657     * If no such common supertypes exists then an empty list is returned.
658     *
659     * As an example for the following input:
660     *
661     * t = java.util.ArrayList<java.lang.String>
662     * s = java.util.List<T>
663     *
664     * we get this ouput (singleton list):
665     *
666     * [Pair[java.util.List<java.lang.String>,java.util.List<T>]]
667     */
668    private List<Pair<Type, Type>> getParameterizedSupers(Type t, Type s) {
669        Type lubResult = types.lub(t, s);
670        if (lubResult == syms.errType || lubResult == syms.botType) {
671            return List.nil();
672        }
673        List<Type> supertypesToCheck = lubResult.isCompound() ?
674                ((IntersectionClassType)lubResult).getComponents() :
675                List.of(lubResult);
676        ListBuffer<Pair<Type, Type>> commonSupertypes = new ListBuffer<>();
677        for (Type sup : supertypesToCheck) {
678            if (sup.isParameterized()) {
679                Type asSuperOfT = asSuper(t, sup);
680                Type asSuperOfS = asSuper(s, sup);
681                commonSupertypes.add(new Pair<>(asSuperOfT, asSuperOfS));
682            }
683        }
684        return commonSupertypes.toList();
685    }
686    //where
687        private Type asSuper(Type t, Type sup) {
688            return (sup.hasTag(ARRAY)) ?
689                    new ArrayType(asSuper(types.elemtype(t), types.elemtype(sup)), syms.arrayClass) :
690                    types.asSuper(t, sup.tsym);
691        }
692
693    /**
694     * This enumeration defines an entry point for doing inference variable
695     * bound incorporation - it can be used to inject custom incorporation
696     * logic into the basic bound checking routine
697     */
698    enum IncorporationStep {
699        /**
700         * Performs basic bound checking - i.e. is the instantiated type for a given
701         * inference variable compatible with its bounds?
702         */
703        CHECK_BOUNDS() {
704            public void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn) {
705                Infer infer = inferenceContext.infer();
706                uv.substBounds(inferenceContext.inferenceVars(), inferenceContext.instTypes(), infer.types);
707                infer.checkCompatibleUpperBounds(uv, inferenceContext);
708                if (uv.inst != null) {
709                    Type inst = uv.inst;
710                    for (Type u : uv.getBounds(InferenceBound.UPPER)) {
711                        if (!isSubtype(inst, inferenceContext.asUndetVar(u), warn, infer)) {
712                            infer.reportBoundError(uv, BoundErrorKind.UPPER);
713                        }
714                    }
715                    for (Type l : uv.getBounds(InferenceBound.LOWER)) {
716                        if (!isSubtype(inferenceContext.asUndetVar(l), inst, warn, infer)) {
717                            infer.reportBoundError(uv, BoundErrorKind.LOWER);
718                        }
719                    }
720                    for (Type e : uv.getBounds(InferenceBound.EQ)) {
721                        if (!isSameType(inst, inferenceContext.asUndetVar(e), infer)) {
722                            infer.reportBoundError(uv, BoundErrorKind.EQ);
723                        }
724                    }
725                }
726            }
727
728            @Override
729            boolean accepts(UndetVar uv, InferenceContext inferenceContext) {
730                //applies to all undetvars
731                return true;
732            }
733        },
734        /**
735         * Check consistency of equality constraints. This is a slightly more aggressive
736         * inference routine that is designed as to maximize compatibility with JDK 7.
737         * Note: this is not used in graph mode.
738         */
739        EQ_CHECK_LEGACY() {
740            public void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn) {
741                Infer infer = inferenceContext.infer();
742                Type eq = null;
743                for (Type e : uv.getBounds(InferenceBound.EQ)) {
744                    Assert.check(!inferenceContext.free(e));
745                    if (eq != null && !isSameType(e, eq, infer)) {
746                        infer.reportBoundError(uv, BoundErrorKind.EQ);
747                    }
748                    eq = e;
749                    for (Type l : uv.getBounds(InferenceBound.LOWER)) {
750                        Assert.check(!inferenceContext.free(l));
751                        if (!isSubtype(l, e, warn, infer)) {
752                            infer.reportBoundError(uv, BoundErrorKind.BAD_EQ_LOWER);
753                        }
754                    }
755                    for (Type u : uv.getBounds(InferenceBound.UPPER)) {
756                        if (inferenceContext.free(u)) continue;
757                        if (!isSubtype(e, u, warn, infer)) {
758                            infer.reportBoundError(uv, BoundErrorKind.BAD_EQ_UPPER);
759                        }
760                    }
761                }
762            }
763
764            @Override
765            boolean accepts(UndetVar uv, InferenceContext inferenceContext) {
766                return !uv.isCaptured() && uv.getBounds(InferenceBound.EQ).nonEmpty();
767            }
768        },
769        /**
770         * Check consistency of equality constraints.
771         */
772        EQ_CHECK() {
773            @Override
774            public void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn) {
775                Infer infer = inferenceContext.infer();
776                for (Type e : uv.getBounds(InferenceBound.EQ)) {
777                    if (e.containsAny(inferenceContext.inferenceVars())) continue;
778                    for (Type u : uv.getBounds(InferenceBound.UPPER)) {
779                        if (!isSubtype(e, inferenceContext.asUndetVar(u), warn, infer)) {
780                            infer.reportBoundError(uv, BoundErrorKind.BAD_EQ_UPPER);
781                        }
782                    }
783                    for (Type l : uv.getBounds(InferenceBound.LOWER)) {
784                        if (!isSubtype(inferenceContext.asUndetVar(l), e, warn, infer)) {
785                            infer.reportBoundError(uv, BoundErrorKind.BAD_EQ_LOWER);
786                        }
787                    }
788                }
789            }
790
791            @Override
792            boolean accepts(UndetVar uv, InferenceContext inferenceContext) {
793                return !uv.isCaptured() && uv.getBounds(InferenceBound.EQ).nonEmpty();
794            }
795        },
796        /**
797         * Given a bound set containing {@code alpha <: T} and {@code alpha :> S}
798         * perform {@code S <: T} (which could lead to new bounds).
799         */
800        CROSS_UPPER_LOWER() {
801            public void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn) {
802                Infer infer = inferenceContext.infer();
803                for (Type b1 : uv.getBounds(InferenceBound.UPPER)) {
804                    for (Type b2 : uv.getBounds(InferenceBound.LOWER)) {
805                        isSubtype(inferenceContext.asUndetVar(b2), inferenceContext.asUndetVar(b1), warn , infer);
806                    }
807                }
808            }
809
810            @Override
811            boolean accepts(UndetVar uv, InferenceContext inferenceContext) {
812                return !uv.isCaptured() &&
813                        uv.getBounds(InferenceBound.UPPER).nonEmpty() &&
814                        uv.getBounds(InferenceBound.LOWER).nonEmpty();
815            }
816        },
817        /**
818         * Given a bound set containing {@code alpha <: T} and {@code alpha == S}
819         * perform {@code S <: T} (which could lead to new bounds).
820         */
821        CROSS_UPPER_EQ() {
822            public void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn) {
823                Infer infer = inferenceContext.infer();
824                for (Type b1 : uv.getBounds(InferenceBound.UPPER)) {
825                    for (Type b2 : uv.getBounds(InferenceBound.EQ)) {
826                        isSubtype(inferenceContext.asUndetVar(b2), inferenceContext.asUndetVar(b1), warn, infer);
827                    }
828                }
829            }
830
831            @Override
832            boolean accepts(UndetVar uv, InferenceContext inferenceContext) {
833                return !uv.isCaptured() &&
834                        uv.getBounds(InferenceBound.EQ).nonEmpty() &&
835                        uv.getBounds(InferenceBound.UPPER).nonEmpty();
836            }
837        },
838        /**
839         * Given a bound set containing {@code alpha :> S} and {@code alpha == T}
840         * perform {@code S <: T} (which could lead to new bounds).
841         */
842        CROSS_EQ_LOWER() {
843            public void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn) {
844                Infer infer = inferenceContext.infer();
845                for (Type b1 : uv.getBounds(InferenceBound.EQ)) {
846                    for (Type b2 : uv.getBounds(InferenceBound.LOWER)) {
847                        isSubtype(inferenceContext.asUndetVar(b2), inferenceContext.asUndetVar(b1), warn, infer);
848                    }
849                }
850            }
851
852            @Override
853            boolean accepts(UndetVar uv, InferenceContext inferenceContext) {
854                return !uv.isCaptured() &&
855                        uv.getBounds(InferenceBound.EQ).nonEmpty() &&
856                        uv.getBounds(InferenceBound.LOWER).nonEmpty();
857            }
858        },
859        /**
860         * Given a bound set containing {@code alpha <: P<T>} and
861         * {@code alpha <: P<S>} where P is a parameterized type,
862         * perform {@code T = S} (which could lead to new bounds).
863         */
864        CROSS_UPPER_UPPER() {
865            @Override
866            public void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn) {
867                Infer infer = inferenceContext.infer();
868                List<Type> boundList = uv.getBounds(InferenceBound.UPPER);
869                List<Type> boundListTail = boundList.tail;
870                while (boundList.nonEmpty()) {
871                    List<Type> tmpTail = boundListTail;
872                    while (tmpTail.nonEmpty()) {
873                        Type b1 = boundList.head;
874                        Type b2 = tmpTail.head;
875                        /* This wildcard check is temporary workaround. This code may need to be
876                         * revisited once spec bug JDK-7034922 is fixed.
877                         */
878                        if (b1 != b2 && !b1.hasTag(WILDCARD) && !b2.hasTag(WILDCARD)) {
879                            for (Pair<Type, Type> commonSupers : infer.getParameterizedSupers(b1, b2)) {
880                                List<Type> allParamsSuperBound1 = commonSupers.fst.allparams();
881                                List<Type> allParamsSuperBound2 = commonSupers.snd.allparams();
882                                while (allParamsSuperBound1.nonEmpty() && allParamsSuperBound2.nonEmpty()) {
883                                    //traverse the list of all params comparing them
884                                    if (!allParamsSuperBound1.head.hasTag(WILDCARD) &&
885                                        !allParamsSuperBound2.head.hasTag(WILDCARD)) {
886                                        if (!isSameType(inferenceContext.asUndetVar(allParamsSuperBound1.head),
887                                            inferenceContext.asUndetVar(allParamsSuperBound2.head), infer)) {
888                                            infer.reportBoundError(uv, BoundErrorKind.BAD_UPPER);
889                                        }
890                                    }
891                                    allParamsSuperBound1 = allParamsSuperBound1.tail;
892                                    allParamsSuperBound2 = allParamsSuperBound2.tail;
893                                }
894                                Assert.check(allParamsSuperBound1.isEmpty() && allParamsSuperBound2.isEmpty());
895                            }
896                        }
897                        tmpTail = tmpTail.tail;
898                    }
899                    boundList = boundList.tail;
900                    boundListTail = boundList.tail;
901                }
902            }
903
904            @Override
905            boolean accepts(UndetVar uv, InferenceContext inferenceContext) {
906                return !uv.isCaptured() &&
907                        uv.getBounds(InferenceBound.UPPER).nonEmpty();
908            }
909        },
910        /**
911         * Given a bound set containing {@code alpha == S} and {@code alpha == T}
912         * perform {@code S == T} (which could lead to new bounds).
913         */
914        CROSS_EQ_EQ() {
915            public void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn) {
916                Infer infer = inferenceContext.infer();
917                for (Type b1 : uv.getBounds(InferenceBound.EQ)) {
918                    for (Type b2 : uv.getBounds(InferenceBound.EQ)) {
919                        if (b1 != b2) {
920                            isSameType(inferenceContext.asUndetVar(b2), inferenceContext.asUndetVar(b1), infer);
921                        }
922                    }
923                }
924            }
925
926            @Override
927            boolean accepts(UndetVar uv, InferenceContext inferenceContext) {
928                return !uv.isCaptured() &&
929                        uv.getBounds(InferenceBound.EQ).nonEmpty();
930            }
931        },
932        /**
933         * Given a bound set containing {@code alpha <: beta} propagate lower bounds
934         * from alpha to beta; also propagate upper bounds from beta to alpha.
935         */
936        PROP_UPPER() {
937            public void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn) {
938                Infer infer = inferenceContext.infer();
939                for (Type b : uv.getBounds(InferenceBound.UPPER)) {
940                    if (inferenceContext.inferenceVars().contains(b)) {
941                        UndetVar uv2 = (UndetVar)inferenceContext.asUndetVar(b);
942                        if (uv2.isCaptured()) continue;
943                        //alpha <: beta
944                        //0. set beta :> alpha
945                        addBound(InferenceBound.LOWER, uv2, inferenceContext.asInstType(uv.qtype), infer);
946                        //1. copy alpha's lower to beta's
947                        for (Type l : uv.getBounds(InferenceBound.LOWER)) {
948                            addBound(InferenceBound.LOWER, uv2, inferenceContext.asInstType(l), infer);
949                        }
950                        //2. copy beta's upper to alpha's
951                        for (Type u : uv2.getBounds(InferenceBound.UPPER)) {
952                            addBound(InferenceBound.UPPER, uv, inferenceContext.asInstType(u), infer);
953                        }
954                    }
955                }
956            }
957
958            @Override
959            boolean accepts(UndetVar uv, InferenceContext inferenceContext) {
960                return !uv.isCaptured() &&
961                        uv.getBounds(InferenceBound.UPPER).nonEmpty();
962            }
963        },
964        /**
965         * Given a bound set containing {@code alpha :> beta} propagate lower bounds
966         * from beta to alpha; also propagate upper bounds from alpha to beta.
967         */
968        PROP_LOWER() {
969            public void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn) {
970                Infer infer = inferenceContext.infer();
971                for (Type b : uv.getBounds(InferenceBound.LOWER)) {
972                    if (inferenceContext.inferenceVars().contains(b)) {
973                        UndetVar uv2 = (UndetVar)inferenceContext.asUndetVar(b);
974                        if (uv2.isCaptured()) continue;
975                        //alpha :> beta
976                        //0. set beta <: alpha
977                        addBound(InferenceBound.UPPER, uv2, inferenceContext.asInstType(uv.qtype), infer);
978                        //1. copy alpha's upper to beta's
979                        for (Type u : uv.getBounds(InferenceBound.UPPER)) {
980                            addBound(InferenceBound.UPPER, uv2, inferenceContext.asInstType(u), infer);
981                        }
982                        //2. copy beta's lower to alpha's
983                        for (Type l : uv2.getBounds(InferenceBound.LOWER)) {
984                            addBound(InferenceBound.LOWER, uv, inferenceContext.asInstType(l), infer);
985                        }
986                    }
987                }
988            }
989
990            @Override
991            boolean accepts(UndetVar uv, InferenceContext inferenceContext) {
992                return !uv.isCaptured() &&
993                        uv.getBounds(InferenceBound.LOWER).nonEmpty();
994            }
995        },
996        /**
997         * Given a bound set containing {@code alpha == beta} propagate lower/upper
998         * bounds from alpha to beta and back.
999         */
1000        PROP_EQ() {
1001            public void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn) {
1002                Infer infer = inferenceContext.infer();
1003                for (Type b : uv.getBounds(InferenceBound.EQ)) {
1004                    if (inferenceContext.inferenceVars().contains(b)) {
1005                        UndetVar uv2 = (UndetVar)inferenceContext.asUndetVar(b);
1006                        if (uv2.isCaptured()) continue;
1007                        //alpha == beta
1008                        //0. set beta == alpha
1009                        addBound(InferenceBound.EQ, uv2, inferenceContext.asInstType(uv.qtype), infer);
1010                        //1. copy all alpha's bounds to beta's
1011                        for (InferenceBound ib : InferenceBound.values()) {
1012                            for (Type b2 : uv.getBounds(ib)) {
1013                                if (b2 != uv2) {
1014                                    addBound(ib, uv2, inferenceContext.asInstType(b2), infer);
1015                                }
1016                            }
1017                        }
1018                        //2. copy all beta's bounds to alpha's
1019                        for (InferenceBound ib : InferenceBound.values()) {
1020                            for (Type b2 : uv2.getBounds(ib)) {
1021                                if (b2 != uv) {
1022                                    addBound(ib, uv, inferenceContext.asInstType(b2), infer);
1023                                }
1024                            }
1025                        }
1026                    }
1027                }
1028            }
1029
1030            @Override
1031            boolean accepts(UndetVar uv, InferenceContext inferenceContext) {
1032                return !uv.isCaptured() &&
1033                        uv.getBounds(InferenceBound.EQ).nonEmpty();
1034            }
1035        };
1036
1037        abstract void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn);
1038
1039        boolean accepts(UndetVar uv, InferenceContext inferenceContext) {
1040            return !uv.isCaptured();
1041        }
1042
1043        boolean isSubtype(Type s, Type t, Warner warn, Infer infer) {
1044            return doIncorporationOp(IncorporationBinaryOpKind.IS_SUBTYPE, s, t, warn, infer);
1045        }
1046
1047        boolean isSameType(Type s, Type t, Infer infer) {
1048            return doIncorporationOp(IncorporationBinaryOpKind.IS_SAME_TYPE, s, t, null, infer);
1049        }
1050
1051        void addBound(InferenceBound ib, UndetVar uv, Type b, Infer infer) {
1052            doIncorporationOp(opFor(ib), uv, b, null, infer);
1053        }
1054
1055        IncorporationBinaryOpKind opFor(InferenceBound boundKind) {
1056            switch (boundKind) {
1057                case EQ:
1058                    return IncorporationBinaryOpKind.ADD_EQ_BOUND;
1059                case LOWER:
1060                    return IncorporationBinaryOpKind.ADD_LOWER_BOUND;
1061                case UPPER:
1062                    return IncorporationBinaryOpKind.ADD_UPPER_BOUND;
1063                default:
1064                    Assert.error("Can't get here!");
1065                    return null;
1066            }
1067        }
1068
1069        boolean doIncorporationOp(IncorporationBinaryOpKind opKind, Type op1, Type op2, Warner warn, Infer infer) {
1070            IncorporationBinaryOp newOp = infer.new IncorporationBinaryOp(opKind, op1, op2);
1071            Boolean res = infer.incorporationCache.get(newOp);
1072            if (res == null) {
1073                infer.incorporationCache.put(newOp, res = newOp.apply(warn));
1074            }
1075            return res;
1076        }
1077    }
1078
1079    /** incorporation steps to be executed when running in legacy mode */
1080    EnumSet<IncorporationStep> incorporationStepsLegacy = EnumSet.of(IncorporationStep.EQ_CHECK_LEGACY);
1081
1082    /** incorporation steps to be executed when running in graph mode */
1083    EnumSet<IncorporationStep> incorporationStepsGraph =
1084            EnumSet.complementOf(EnumSet.of(IncorporationStep.EQ_CHECK_LEGACY));
1085
1086    /**
1087     * Three kinds of basic operation are supported as part of an incorporation step:
1088     * (i) subtype check, (ii) same type check and (iii) bound addition (either
1089     * upper/lower/eq bound).
1090     */
1091    enum IncorporationBinaryOpKind {
1092        IS_SUBTYPE() {
1093            @Override
1094            boolean apply(Type op1, Type op2, Warner warn, Types types) {
1095                return types.isSubtypeUnchecked(op1, op2, warn);
1096            }
1097        },
1098        IS_SAME_TYPE() {
1099            @Override
1100            boolean apply(Type op1, Type op2, Warner warn, Types types) {
1101                return types.isSameType(op1, op2);
1102            }
1103        },
1104        ADD_UPPER_BOUND() {
1105            @Override
1106            boolean apply(Type op1, Type op2, Warner warn, Types types) {
1107                UndetVar uv = (UndetVar)op1;
1108                uv.addBound(InferenceBound.UPPER, op2, types);
1109                return true;
1110            }
1111        },
1112        ADD_LOWER_BOUND() {
1113            @Override
1114            boolean apply(Type op1, Type op2, Warner warn, Types types) {
1115                UndetVar uv = (UndetVar)op1;
1116                uv.addBound(InferenceBound.LOWER, op2, types);
1117                return true;
1118            }
1119        },
1120        ADD_EQ_BOUND() {
1121            @Override
1122            boolean apply(Type op1, Type op2, Warner warn, Types types) {
1123                UndetVar uv = (UndetVar)op1;
1124                uv.addBound(InferenceBound.EQ, op2, types);
1125                return true;
1126            }
1127        };
1128
1129        abstract boolean apply(Type op1, Type op2, Warner warn, Types types);
1130    }
1131
1132    /**
1133     * This class encapsulates a basic incorporation operation; incorporation
1134     * operations takes two type operands and a kind. Each operation performed
1135     * during an incorporation round is stored in a cache, so that operations
1136     * are not executed unnecessarily (which would potentially lead to adding
1137     * same bounds over and over).
1138     */
1139    class IncorporationBinaryOp {
1140
1141        IncorporationBinaryOpKind opKind;
1142        Type op1;
1143        Type op2;
1144
1145        IncorporationBinaryOp(IncorporationBinaryOpKind opKind, Type op1, Type op2) {
1146            this.opKind = opKind;
1147            this.op1 = op1;
1148            this.op2 = op2;
1149        }
1150
1151        @Override
1152        public boolean equals(Object o) {
1153            if (!(o instanceof IncorporationBinaryOp)) {
1154                return false;
1155            } else {
1156                IncorporationBinaryOp that = (IncorporationBinaryOp)o;
1157                return opKind == that.opKind &&
1158                        types.isSameType(op1, that.op1, true) &&
1159                        types.isSameType(op2, that.op2, true);
1160            }
1161        }
1162
1163        @Override
1164        public int hashCode() {
1165            int result = opKind.hashCode();
1166            result *= 127;
1167            result += types.hashCode(op1);
1168            result *= 127;
1169            result += types.hashCode(op2);
1170            return result;
1171        }
1172
1173        boolean apply(Warner warn) {
1174            return opKind.apply(op1, op2, warn, types);
1175        }
1176    }
1177
1178    /** an incorporation cache keeps track of all executed incorporation-related operations */
1179    Map<IncorporationBinaryOp, Boolean> incorporationCache = new HashMap<>();
1180
1181    /**
1182     * Make sure that the upper bounds we got so far lead to a solvable inference
1183     * variable by making sure that a glb exists.
1184     */
1185    void checkCompatibleUpperBounds(UndetVar uv, InferenceContext inferenceContext) {
1186        List<Type> hibounds =
1187                Type.filter(uv.getBounds(InferenceBound.UPPER), new BoundFilter(inferenceContext));
1188        Type hb = null;
1189        if (hibounds.isEmpty())
1190            hb = syms.objectType;
1191        else if (hibounds.tail.isEmpty())
1192            hb = hibounds.head;
1193        else
1194            hb = types.glb(hibounds);
1195        if (hb == null || hb.isErroneous())
1196            reportBoundError(uv, BoundErrorKind.BAD_UPPER);
1197    }
1198    //where
1199        protected static class BoundFilter implements Filter<Type> {
1200
1201            InferenceContext inferenceContext;
1202
1203            public BoundFilter(InferenceContext inferenceContext) {
1204                this.inferenceContext = inferenceContext;
1205            }
1206
1207            @Override
1208            public boolean accepts(Type t) {
1209                return !t.isErroneous() && !inferenceContext.free(t) &&
1210                        !t.hasTag(BOT);
1211            }
1212        }
1213
1214    /**
1215     * This enumeration defines all possible bound-checking related errors.
1216     */
1217    enum BoundErrorKind {
1218        /**
1219         * The (uninstantiated) inference variable has incompatible upper bounds.
1220         */
1221        BAD_UPPER() {
1222            @Override
1223            InapplicableMethodException setMessage(InferenceException ex, UndetVar uv) {
1224                return ex.setMessage("incompatible.upper.bounds", uv.qtype,
1225                        uv.getBounds(InferenceBound.UPPER));
1226            }
1227        },
1228        /**
1229         * An equality constraint is not compatible with an upper bound.
1230         */
1231        BAD_EQ_UPPER() {
1232            @Override
1233            InapplicableMethodException setMessage(InferenceException ex, UndetVar uv) {
1234                return ex.setMessage("incompatible.eq.upper.bounds", uv.qtype,
1235                        uv.getBounds(InferenceBound.EQ), uv.getBounds(InferenceBound.UPPER));
1236            }
1237        },
1238        /**
1239         * An equality constraint is not compatible with a lower bound.
1240         */
1241        BAD_EQ_LOWER() {
1242            @Override
1243            InapplicableMethodException setMessage(InferenceException ex, UndetVar uv) {
1244                return ex.setMessage("incompatible.eq.lower.bounds", uv.qtype,
1245                        uv.getBounds(InferenceBound.EQ), uv.getBounds(InferenceBound.LOWER));
1246            }
1247        },
1248        /**
1249         * Instantiated inference variable is not compatible with an upper bound.
1250         */
1251        UPPER() {
1252            @Override
1253            InapplicableMethodException setMessage(InferenceException ex, UndetVar uv) {
1254                return ex.setMessage("inferred.do.not.conform.to.upper.bounds", uv.inst,
1255                        uv.getBounds(InferenceBound.UPPER));
1256            }
1257        },
1258        /**
1259         * Instantiated inference variable is not compatible with a lower bound.
1260         */
1261        LOWER() {
1262            @Override
1263            InapplicableMethodException setMessage(InferenceException ex, UndetVar uv) {
1264                return ex.setMessage("inferred.do.not.conform.to.lower.bounds", uv.inst,
1265                        uv.getBounds(InferenceBound.LOWER));
1266            }
1267        },
1268        /**
1269         * Instantiated inference variable is not compatible with an equality constraint.
1270         */
1271        EQ() {
1272            @Override
1273            InapplicableMethodException setMessage(InferenceException ex, UndetVar uv) {
1274                return ex.setMessage("inferred.do.not.conform.to.eq.bounds", uv.inst,
1275                        uv.getBounds(InferenceBound.EQ));
1276            }
1277        };
1278
1279        abstract InapplicableMethodException setMessage(InferenceException ex, UndetVar uv);
1280    }
1281
1282    /**
1283     * Report a bound-checking error of given kind
1284     */
1285    void reportBoundError(UndetVar uv, BoundErrorKind bk) {
1286        throw bk.setMessage(inferenceException, uv);
1287    }
1288    // </editor-fold>
1289
1290    // <editor-fold defaultstate="collapsed" desc="Inference engine">
1291    /**
1292     * Graph inference strategy - act as an input to the inference solver; a strategy is
1293     * composed of two ingredients: (i) find a node to solve in the inference graph,
1294     * and (ii) tell th engine when we are done fixing inference variables
1295     */
1296    interface GraphStrategy {
1297
1298        /**
1299         * A NodeNotFoundException is thrown whenever an inference strategy fails
1300         * to pick the next node to solve in the inference graph.
1301         */
1302        public static class NodeNotFoundException extends RuntimeException {
1303            private static final long serialVersionUID = 0;
1304
1305            InferenceGraph graph;
1306
1307            public NodeNotFoundException(InferenceGraph graph) {
1308                this.graph = graph;
1309            }
1310        }
1311        /**
1312         * Pick the next node (leaf) to solve in the graph
1313         */
1314        Node pickNode(InferenceGraph g) throws NodeNotFoundException;
1315        /**
1316         * Is this the last step?
1317         */
1318        boolean done();
1319    }
1320
1321    /**
1322     * Simple solver strategy class that locates all leaves inside a graph
1323     * and picks the first leaf as the next node to solve
1324     */
1325    abstract class LeafSolver implements GraphStrategy {
1326        public Node pickNode(InferenceGraph g) {
1327            if (g.nodes.isEmpty()) {
1328                //should not happen
1329                throw new NodeNotFoundException(g);
1330            }
1331            return g.nodes.get(0);
1332        }
1333
1334        boolean isSubtype(Type s, Type t, Warner warn, Infer infer) {
1335            return doIncorporationOp(IncorporationBinaryOpKind.IS_SUBTYPE, s, t, warn, infer);
1336        }
1337
1338        boolean isSameType(Type s, Type t, Infer infer) {
1339            return doIncorporationOp(IncorporationBinaryOpKind.IS_SAME_TYPE, s, t, null, infer);
1340        }
1341
1342        void addBound(InferenceBound ib, UndetVar uv, Type b, Infer infer) {
1343            doIncorporationOp(opFor(ib), uv, b, null, infer);
1344        }
1345
1346        IncorporationBinaryOpKind opFor(InferenceBound boundKind) {
1347            switch (boundKind) {
1348                case EQ:
1349                    return IncorporationBinaryOpKind.ADD_EQ_BOUND;
1350                case LOWER:
1351                    return IncorporationBinaryOpKind.ADD_LOWER_BOUND;
1352                case UPPER:
1353                    return IncorporationBinaryOpKind.ADD_UPPER_BOUND;
1354                default:
1355                    Assert.error("Can't get here!");
1356                    return null;
1357            }
1358        }
1359
1360        boolean doIncorporationOp(IncorporationBinaryOpKind opKind, Type op1, Type op2, Warner warn, Infer infer) {
1361            IncorporationBinaryOp newOp = infer.new IncorporationBinaryOp(opKind, op1, op2);
1362            Boolean res = infer.incorporationCache.get(newOp);
1363            if (res == null) {
1364                infer.incorporationCache.put(newOp, res = newOp.apply(warn));
1365            }
1366            return res;
1367        }
1368    }
1369
1370    /**
1371     * This solver uses an heuristic to pick the best leaf - the heuristic
1372     * tries to select the node that has maximal probability to contain one
1373     * or more inference variables in a given list
1374     */
1375    abstract class BestLeafSolver extends LeafSolver {
1376
1377        /** list of ivars of which at least one must be solved */
1378        List<Type> varsToSolve;
1379
1380        BestLeafSolver(List<Type> varsToSolve) {
1381            this.varsToSolve = varsToSolve;
1382        }
1383
1384        /**
1385         * Computes a path that goes from a given node to the leafs in the graph.
1386         * Typically this will start from a node containing a variable in
1387         * {@code varsToSolve}. For any given path, the cost is computed as the total
1388         * number of type-variables that should be eagerly instantiated across that path.
1389         */
1390        Pair<List<Node>, Integer> computeTreeToLeafs(Node n) {
1391            Pair<List<Node>, Integer> cachedPath = treeCache.get(n);
1392            if (cachedPath == null) {
1393                //cache miss
1394                if (n.isLeaf()) {
1395                    //if leaf, stop
1396                    cachedPath = new Pair<>(List.of(n), n.data.length());
1397                } else {
1398                    //if non-leaf, proceed recursively
1399                    Pair<List<Node>, Integer> path = new Pair<>(List.of(n), n.data.length());
1400                    for (Node n2 : n.getAllDependencies()) {
1401                        if (n2 == n) continue;
1402                        Pair<List<Node>, Integer> subpath = computeTreeToLeafs(n2);
1403                        path = new Pair<>(path.fst.prependList(subpath.fst),
1404                                          path.snd + subpath.snd);
1405                    }
1406                    cachedPath = path;
1407                }
1408                //save results in cache
1409                treeCache.put(n, cachedPath);
1410            }
1411            return cachedPath;
1412        }
1413
1414        /** cache used to avoid redundant computation of tree costs */
1415        final Map<Node, Pair<List<Node>, Integer>> treeCache = new HashMap<>();
1416
1417        /** constant value used to mark non-existent paths */
1418        final Pair<List<Node>, Integer> noPath = new Pair<>(null, Integer.MAX_VALUE);
1419
1420        /**
1421         * Pick the leaf that minimize cost
1422         */
1423        @Override
1424        public Node pickNode(final InferenceGraph g) {
1425            treeCache.clear(); //graph changes at every step - cache must be cleared
1426            Pair<List<Node>, Integer> bestPath = noPath;
1427            for (Node n : g.nodes) {
1428                if (!Collections.disjoint(n.data, varsToSolve)) {
1429                    Pair<List<Node>, Integer> path = computeTreeToLeafs(n);
1430                    //discard all paths containing at least a node in the
1431                    //closure computed above
1432                    if (path.snd < bestPath.snd) {
1433                        bestPath = path;
1434                    }
1435                }
1436            }
1437            if (bestPath == noPath) {
1438                //no path leads there
1439                throw new NodeNotFoundException(g);
1440            }
1441            return bestPath.fst.head;
1442        }
1443    }
1444
1445    /**
1446     * The inference process can be thought of as a sequence of steps. Each step
1447     * instantiates an inference variable using a subset of the inference variable
1448     * bounds, if certain condition are met. Decisions such as the sequence in which
1449     * steps are applied, or which steps are to be applied are left to the inference engine.
1450     */
1451    enum InferenceStep {
1452
1453        /**
1454         * Instantiate an inference variables using one of its (ground) equality
1455         * constraints
1456         */
1457        EQ(InferenceBound.EQ) {
1458            @Override
1459            Type solve(UndetVar uv, InferenceContext inferenceContext) {
1460                return filterBounds(uv, inferenceContext).head;
1461            }
1462        },
1463        /**
1464         * Instantiate an inference variables using its (ground) lower bounds. Such
1465         * bounds are merged together using lub().
1466         */
1467        LOWER(InferenceBound.LOWER) {
1468            @Override
1469            Type solve(UndetVar uv, InferenceContext inferenceContext) {
1470                Infer infer = inferenceContext.infer();
1471                List<Type> lobounds = filterBounds(uv, inferenceContext);
1472                //note: lobounds should have at least one element
1473                Type owntype = lobounds.tail.tail == null  ? lobounds.head : infer.types.lub(lobounds);
1474                if (owntype.isPrimitive() || owntype.hasTag(ERROR)) {
1475                    throw infer.inferenceException
1476                        .setMessage("no.unique.minimal.instance.exists",
1477                                    uv.qtype, lobounds);
1478                } else {
1479                    return owntype;
1480                }
1481            }
1482        },
1483        /**
1484         * Infer uninstantiated/unbound inference variables occurring in 'throws'
1485         * clause as RuntimeException
1486         */
1487        THROWS(InferenceBound.UPPER) {
1488            @Override
1489            public boolean accepts(UndetVar t, InferenceContext inferenceContext) {
1490                if ((t.qtype.tsym.flags() & Flags.THROWS) == 0) {
1491                    //not a throws undet var
1492                    return false;
1493                }
1494                if (t.getBounds(InferenceBound.EQ, InferenceBound.LOWER, InferenceBound.UPPER)
1495                            .diff(t.getDeclaredBounds()).nonEmpty()) {
1496                    //not an unbounded undet var
1497                    return false;
1498                }
1499                Infer infer = inferenceContext.infer();
1500                for (Type db : t.getDeclaredBounds()) {
1501                    if (t.isInterface()) continue;
1502                    if (infer.types.asSuper(infer.syms.runtimeExceptionType, db.tsym) != null) {
1503                        //declared bound is a supertype of RuntimeException
1504                        return true;
1505                    }
1506                }
1507                //declared bound is more specific then RuntimeException - give up
1508                return false;
1509            }
1510
1511            @Override
1512            Type solve(UndetVar uv, InferenceContext inferenceContext) {
1513                return inferenceContext.infer().syms.runtimeExceptionType;
1514            }
1515        },
1516        /**
1517         * Instantiate an inference variables using its (ground) upper bounds. Such
1518         * bounds are merged together using glb().
1519         */
1520        UPPER(InferenceBound.UPPER) {
1521            @Override
1522            Type solve(UndetVar uv, InferenceContext inferenceContext) {
1523                Infer infer = inferenceContext.infer();
1524                List<Type> hibounds = filterBounds(uv, inferenceContext);
1525                //note: hibounds should have at least one element
1526                Type owntype = hibounds.tail.tail == null  ? hibounds.head : infer.types.glb(hibounds);
1527                if (owntype.isPrimitive() || owntype.hasTag(ERROR)) {
1528                    throw infer.inferenceException
1529                        .setMessage("no.unique.maximal.instance.exists",
1530                                    uv.qtype, hibounds);
1531                } else {
1532                    return owntype;
1533                }
1534            }
1535        },
1536        /**
1537         * Like the former; the only difference is that this step can only be applied
1538         * if all upper bounds are ground.
1539         */
1540        UPPER_LEGACY(InferenceBound.UPPER) {
1541            @Override
1542            public boolean accepts(UndetVar t, InferenceContext inferenceContext) {
1543                return !inferenceContext.free(t.getBounds(ib)) && !t.isCaptured();
1544            }
1545
1546            @Override
1547            Type solve(UndetVar uv, InferenceContext inferenceContext) {
1548                return UPPER.solve(uv, inferenceContext);
1549            }
1550        },
1551        /**
1552         * Like the former; the only difference is that this step can only be applied
1553         * if all upper/lower bounds are ground.
1554         */
1555        CAPTURED(InferenceBound.UPPER) {
1556            @Override
1557            public boolean accepts(UndetVar t, InferenceContext inferenceContext) {
1558                return t.isCaptured() &&
1559                        !inferenceContext.free(t.getBounds(InferenceBound.UPPER, InferenceBound.LOWER));
1560            }
1561
1562            @Override
1563            Type solve(UndetVar uv, InferenceContext inferenceContext) {
1564                Infer infer = inferenceContext.infer();
1565                Type upper = UPPER.filterBounds(uv, inferenceContext).nonEmpty() ?
1566                        UPPER.solve(uv, inferenceContext) :
1567                        infer.syms.objectType;
1568                Type lower = LOWER.filterBounds(uv, inferenceContext).nonEmpty() ?
1569                        LOWER.solve(uv, inferenceContext) :
1570                        infer.syms.botType;
1571                CapturedType prevCaptured = (CapturedType)uv.qtype;
1572                return new CapturedType(prevCaptured.tsym.name, prevCaptured.tsym.owner,
1573                                        upper, lower, prevCaptured.wildcard);
1574            }
1575        };
1576
1577        final InferenceBound ib;
1578
1579        InferenceStep(InferenceBound ib) {
1580            this.ib = ib;
1581        }
1582
1583        /**
1584         * Find an instantiated type for a given inference variable within
1585         * a given inference context
1586         */
1587        abstract Type solve(UndetVar uv, InferenceContext inferenceContext);
1588
1589        /**
1590         * Can the inference variable be instantiated using this step?
1591         */
1592        public boolean accepts(UndetVar t, InferenceContext inferenceContext) {
1593            return filterBounds(t, inferenceContext).nonEmpty() && !t.isCaptured();
1594        }
1595
1596        /**
1597         * Return the subset of ground bounds in a given bound set (i.e. eq/lower/upper)
1598         */
1599        List<Type> filterBounds(UndetVar uv, InferenceContext inferenceContext) {
1600            return Type.filter(uv.getBounds(ib), new BoundFilter(inferenceContext));
1601        }
1602    }
1603
1604    /**
1605     * This enumeration defines the sequence of steps to be applied when the
1606     * solver works in legacy mode. The steps in this enumeration reflect
1607     * the behavior of old inference routine (see JLS SE 7 15.12.2.7/15.12.2.8).
1608     */
1609    enum LegacyInferenceSteps {
1610
1611        EQ_LOWER(EnumSet.of(InferenceStep.EQ, InferenceStep.LOWER)),
1612        EQ_UPPER(EnumSet.of(InferenceStep.EQ, InferenceStep.UPPER_LEGACY));
1613
1614        final EnumSet<InferenceStep> steps;
1615
1616        LegacyInferenceSteps(EnumSet<InferenceStep> steps) {
1617            this.steps = steps;
1618        }
1619    }
1620
1621    /**
1622     * This enumeration defines the sequence of steps to be applied when the
1623     * graph solver is used. This order is defined so as to maximize compatibility
1624     * w.r.t. old inference routine (see JLS SE 7 15.12.2.7/15.12.2.8).
1625     */
1626    enum GraphInferenceSteps {
1627
1628        EQ(EnumSet.of(InferenceStep.EQ)),
1629        EQ_LOWER(EnumSet.of(InferenceStep.EQ, InferenceStep.LOWER)),
1630        EQ_LOWER_THROWS_UPPER_CAPTURED(EnumSet.of(InferenceStep.EQ, InferenceStep.LOWER, InferenceStep.UPPER, InferenceStep.THROWS, InferenceStep.CAPTURED));
1631
1632        final EnumSet<InferenceStep> steps;
1633
1634        GraphInferenceSteps(EnumSet<InferenceStep> steps) {
1635            this.steps = steps;
1636        }
1637    }
1638
1639    /**
1640     * There are two kinds of dependencies between inference variables. The basic
1641     * kind of dependency (or bound dependency) arises when a variable mention
1642     * another variable in one of its bounds. There's also a more subtle kind
1643     * of dependency that arises when a variable 'might' lead to better constraints
1644     * on another variable (this is typically the case with variables holding up
1645     * stuck expressions).
1646     */
1647    enum DependencyKind implements GraphUtils.DependencyKind {
1648
1649        /** bound dependency */
1650        BOUND("dotted"),
1651        /** stuck dependency */
1652        STUCK("dashed");
1653
1654        final String dotSyle;
1655
1656        private DependencyKind(String dotSyle) {
1657            this.dotSyle = dotSyle;
1658        }
1659    }
1660
1661    /**
1662     * This is the graph inference solver - the solver organizes all inference variables in
1663     * a given inference context by bound dependencies - in the general case, such dependencies
1664     * would lead to a cyclic directed graph (hence the name); the dependency info is used to build
1665     * an acyclic graph, where all cyclic variables are bundled together. An inference
1666     * step corresponds to solving a node in the acyclic graph - this is done by
1667     * relying on a given strategy (see GraphStrategy).
1668     */
1669    class GraphSolver {
1670
1671        InferenceContext inferenceContext;
1672        Map<Type, Set<Type>> stuckDeps;
1673        Warner warn;
1674
1675        GraphSolver(InferenceContext inferenceContext, Map<Type, Set<Type>> stuckDeps, Warner warn) {
1676            this.inferenceContext = inferenceContext;
1677            this.stuckDeps = stuckDeps;
1678            this.warn = warn;
1679        }
1680
1681        /**
1682         * Solve variables in a given inference context. The amount of variables
1683         * to be solved, and the way in which the underlying acyclic graph is explored
1684         * depends on the selected solver strategy.
1685         */
1686        void solve(GraphStrategy sstrategy) {
1687            checkWithinBounds(inferenceContext, warn); //initial propagation of bounds
1688            InferenceGraph inferenceGraph = new InferenceGraph(stuckDeps);
1689            while (!sstrategy.done()) {
1690                if (dependenciesFolder != null) {
1691                    //add this graph to the pending queue
1692                    pendingGraphs = pendingGraphs.prepend(inferenceGraph.toDot());
1693                }
1694                InferenceGraph.Node nodeToSolve = sstrategy.pickNode(inferenceGraph);
1695                List<Type> varsToSolve = List.from(nodeToSolve.data);
1696                List<Type> saved_undet = inferenceContext.save();
1697                try {
1698                    //repeat until all variables are solved
1699                    outer: while (Type.containsAny(inferenceContext.restvars(), varsToSolve)) {
1700                        //for each inference phase
1701                        for (GraphInferenceSteps step : GraphInferenceSteps.values()) {
1702                            if (inferenceContext.solveBasic(varsToSolve, step.steps)) {
1703                                checkWithinBounds(inferenceContext, warn);
1704                                continue outer;
1705                            }
1706                        }
1707                        //no progress
1708                        throw inferenceException.setMessage();
1709                    }
1710                }
1711                catch (InferenceException ex) {
1712                    //did we fail because of interdependent ivars?
1713                    inferenceContext.rollback(saved_undet);
1714                    instantiateAsUninferredVars(varsToSolve, inferenceContext);
1715                    checkWithinBounds(inferenceContext, warn);
1716                }
1717                inferenceGraph.deleteNode(nodeToSolve);
1718            }
1719        }
1720
1721        /**
1722         * The dependencies between the inference variables that need to be solved
1723         * form a (possibly cyclic) graph. This class reduces the original dependency graph
1724         * to an acyclic version, where cyclic nodes are folded into a single 'super node'.
1725         */
1726        class InferenceGraph {
1727
1728            /**
1729             * This class represents a node in the graph. Each node corresponds
1730             * to an inference variable and has edges (dependencies) on other
1731             * nodes. The node defines an entry point that can be used to receive
1732             * updates on the structure of the graph this node belongs to (used to
1733             * keep dependencies in sync).
1734             */
1735            class Node extends GraphUtils.TarjanNode<ListBuffer<Type>, Node> implements DottableNode<ListBuffer<Type>, Node> {
1736
1737                /** map listing all dependencies (grouped by kind) */
1738                EnumMap<DependencyKind, Set<Node>> deps;
1739
1740                Node(Type ivar) {
1741                    super(ListBuffer.of(ivar));
1742                    this.deps = new EnumMap<>(DependencyKind.class);
1743                }
1744
1745                @Override
1746                public GraphUtils.DependencyKind[] getSupportedDependencyKinds() {
1747                    return DependencyKind.values();
1748                }
1749
1750                public Iterable<? extends Node> getAllDependencies() {
1751                    return getDependencies(DependencyKind.values());
1752                }
1753
1754                @Override
1755                public Collection<? extends Node> getDependenciesByKind(GraphUtils.DependencyKind dk) {
1756                    return getDependencies((DependencyKind)dk);
1757                }
1758
1759                /**
1760                 * Retrieves all dependencies with given kind(s).
1761                 */
1762                protected Set<Node> getDependencies(DependencyKind... depKinds) {
1763                    Set<Node> buf = new LinkedHashSet<>();
1764                    for (DependencyKind dk : depKinds) {
1765                        Set<Node> depsByKind = deps.get(dk);
1766                        if (depsByKind != null) {
1767                            buf.addAll(depsByKind);
1768                        }
1769                    }
1770                    return buf;
1771                }
1772
1773                /**
1774                 * Adds dependency with given kind.
1775                 */
1776                protected void addDependency(DependencyKind dk, Node depToAdd) {
1777                    Set<Node> depsByKind = deps.get(dk);
1778                    if (depsByKind == null) {
1779                        depsByKind = new LinkedHashSet<>();
1780                        deps.put(dk, depsByKind);
1781                    }
1782                    depsByKind.add(depToAdd);
1783                }
1784
1785                /**
1786                 * Add multiple dependencies of same given kind.
1787                 */
1788                protected void addDependencies(DependencyKind dk, Set<Node> depsToAdd) {
1789                    for (Node n : depsToAdd) {
1790                        addDependency(dk, n);
1791                    }
1792                }
1793
1794                /**
1795                 * Remove a dependency, regardless of its kind.
1796                 */
1797                protected Set<DependencyKind> removeDependency(Node n) {
1798                    Set<DependencyKind> removedKinds = new HashSet<>();
1799                    for (DependencyKind dk : DependencyKind.values()) {
1800                        Set<Node> depsByKind = deps.get(dk);
1801                        if (depsByKind == null) continue;
1802                        if (depsByKind.remove(n)) {
1803                            removedKinds.add(dk);
1804                        }
1805                    }
1806                    return removedKinds;
1807                }
1808
1809                /**
1810                 * Compute closure of a give node, by recursively walking
1811                 * through all its dependencies (of given kinds)
1812                 */
1813                protected Set<Node> closure(DependencyKind... depKinds) {
1814                    boolean progress = true;
1815                    Set<Node> closure = new HashSet<>();
1816                    closure.add(this);
1817                    while (progress) {
1818                        progress = false;
1819                        for (Node n1 : new HashSet<>(closure)) {
1820                            progress = closure.addAll(n1.getDependencies(depKinds));
1821                        }
1822                    }
1823                    return closure;
1824                }
1825
1826                /**
1827                 * Is this node a leaf? This means either the node has no dependencies,
1828                 * or it just has self-dependencies.
1829                 */
1830                protected boolean isLeaf() {
1831                    //no deps, or only one self dep
1832                    Set<Node> allDeps = getDependencies(DependencyKind.BOUND, DependencyKind.STUCK);
1833                    if (allDeps.isEmpty()) return true;
1834                    for (Node n : allDeps) {
1835                        if (n != this) {
1836                            return false;
1837                        }
1838                    }
1839                    return true;
1840                }
1841
1842                /**
1843                 * Merge this node with another node, acquiring its dependencies.
1844                 * This routine is used to merge all cyclic node together and
1845                 * form an acyclic graph.
1846                 */
1847                protected void mergeWith(List<? extends Node> nodes) {
1848                    for (Node n : nodes) {
1849                        Assert.check(n.data.length() == 1, "Attempt to merge a compound node!");
1850                        data.appendList(n.data);
1851                        for (DependencyKind dk : DependencyKind.values()) {
1852                            addDependencies(dk, n.getDependencies(dk));
1853                        }
1854                    }
1855                    //update deps
1856                    EnumMap<DependencyKind, Set<Node>> deps2 = new EnumMap<>(DependencyKind.class);
1857                    for (DependencyKind dk : DependencyKind.values()) {
1858                        for (Node d : getDependencies(dk)) {
1859                            Set<Node> depsByKind = deps2.get(dk);
1860                            if (depsByKind == null) {
1861                                depsByKind = new LinkedHashSet<>();
1862                                deps2.put(dk, depsByKind);
1863                            }
1864                            if (data.contains(d.data.first())) {
1865                                depsByKind.add(this);
1866                            } else {
1867                                depsByKind.add(d);
1868                            }
1869                        }
1870                    }
1871                    deps = deps2;
1872                }
1873
1874                /**
1875                 * Notify all nodes that something has changed in the graph
1876                 * topology.
1877                 */
1878                private void graphChanged(Node from, Node to) {
1879                    for (DependencyKind dk : removeDependency(from)) {
1880                        if (to != null) {
1881                            addDependency(dk, to);
1882                        }
1883                    }
1884                }
1885
1886                @Override
1887                public Properties nodeAttributes() {
1888                    Properties p = new Properties();
1889                    p.put("label", "\"" + toString() + "\"");
1890                    return p;
1891                }
1892
1893                @Override
1894                public Properties dependencyAttributes(Node sink, GraphUtils.DependencyKind dk) {
1895                    Properties p = new Properties();
1896                    p.put("style", ((DependencyKind)dk).dotSyle);
1897                    if (dk == DependencyKind.STUCK) return p;
1898                    else {
1899                        StringBuilder buf = new StringBuilder();
1900                        String sep = "";
1901                        for (Type from : data) {
1902                            UndetVar uv = (UndetVar)inferenceContext.asUndetVar(from);
1903                            for (Type bound : uv.getBounds(InferenceBound.values())) {
1904                                if (bound.containsAny(List.from(sink.data))) {
1905                                    buf.append(sep);
1906                                    buf.append(bound);
1907                                    sep = ",";
1908                                }
1909                            }
1910                        }
1911                        p.put("label", "\"" + buf.toString() + "\"");
1912                    }
1913                    return p;
1914                }
1915            }
1916
1917            /** the nodes in the inference graph */
1918            ArrayList<Node> nodes;
1919
1920            InferenceGraph(Map<Type, Set<Type>> optDeps) {
1921                initNodes(optDeps);
1922            }
1923
1924            /**
1925             * Basic lookup helper for retrieving a graph node given an inference
1926             * variable type.
1927             */
1928            public Node findNode(Type t) {
1929                for (Node n : nodes) {
1930                    if (n.data.contains(t)) {
1931                        return n;
1932                    }
1933                }
1934                return null;
1935            }
1936
1937            /**
1938             * Delete a node from the graph. This update the underlying structure
1939             * of the graph (including dependencies) via listeners updates.
1940             */
1941            public void deleteNode(Node n) {
1942                Assert.check(nodes.contains(n));
1943                nodes.remove(n);
1944                notifyUpdate(n, null);
1945            }
1946
1947            /**
1948             * Notify all nodes of a change in the graph. If the target node is
1949             * {@code null} the source node is assumed to be removed.
1950             */
1951            void notifyUpdate(Node from, Node to) {
1952                for (Node n : nodes) {
1953                    n.graphChanged(from, to);
1954                }
1955            }
1956
1957            /**
1958             * Create the graph nodes. First a simple node is created for every inference
1959             * variables to be solved. Then Tarjan is used to found all connected components
1960             * in the graph. For each component containing more than one node, a super node is
1961             * created, effectively replacing the original cyclic nodes.
1962             */
1963            void initNodes(Map<Type, Set<Type>> stuckDeps) {
1964                //add nodes
1965                nodes = new ArrayList<>();
1966                for (Type t : inferenceContext.restvars()) {
1967                    nodes.add(new Node(t));
1968                }
1969                //add dependencies
1970                for (Node n_i : nodes) {
1971                    Type i = n_i.data.first();
1972                    Set<Type> optDepsByNode = stuckDeps.get(i);
1973                    for (Node n_j : nodes) {
1974                        Type j = n_j.data.first();
1975                        UndetVar uv_i = (UndetVar)inferenceContext.asUndetVar(i);
1976                        if (Type.containsAny(uv_i.getBounds(InferenceBound.values()), List.of(j))) {
1977                            //update i's bound dependencies
1978                            n_i.addDependency(DependencyKind.BOUND, n_j);
1979                        }
1980                        if (optDepsByNode != null && optDepsByNode.contains(j)) {
1981                            //update i's stuck dependencies
1982                            n_i.addDependency(DependencyKind.STUCK, n_j);
1983                        }
1984                    }
1985                }
1986                //merge cyclic nodes
1987                ArrayList<Node> acyclicNodes = new ArrayList<>();
1988                for (List<? extends Node> conSubGraph : GraphUtils.tarjan(nodes)) {
1989                    if (conSubGraph.length() > 1) {
1990                        Node root = conSubGraph.head;
1991                        root.mergeWith(conSubGraph.tail);
1992                        for (Node n : conSubGraph) {
1993                            notifyUpdate(n, root);
1994                        }
1995                    }
1996                    acyclicNodes.add(conSubGraph.head);
1997                }
1998                nodes = acyclicNodes;
1999            }
2000
2001            /**
2002             * Debugging: dot representation of this graph
2003             */
2004            String toDot() {
2005                StringBuilder buf = new StringBuilder();
2006                for (Type t : inferenceContext.undetvars) {
2007                    UndetVar uv = (UndetVar)t;
2008                    buf.append(String.format("var %s - upper bounds = %s, lower bounds = %s, eq bounds = %s\\n",
2009                            uv.qtype, uv.getBounds(InferenceBound.UPPER), uv.getBounds(InferenceBound.LOWER),
2010                            uv.getBounds(InferenceBound.EQ)));
2011                }
2012                return GraphUtils.toDot(nodes, "inferenceGraph" + hashCode(), buf.toString());
2013            }
2014        }
2015    }
2016    // </editor-fold>
2017
2018    // <editor-fold defaultstate="collapsed" desc="Inference context">
2019    /**
2020     * Functional interface for defining inference callbacks. Certain actions
2021     * (i.e. subtyping checks) might need to be redone after all inference variables
2022     * have been fixed.
2023     */
2024    interface FreeTypeListener {
2025        void typesInferred(InferenceContext inferenceContext);
2026    }
2027
2028    /**
2029     * An inference context keeps track of the set of variables that are free
2030     * in the current context. It provides utility methods for opening/closing
2031     * types to their corresponding free/closed forms. It also provide hooks for
2032     * attaching deferred post-inference action (see PendingCheck). Finally,
2033     * it can be used as an entry point for performing upper/lower bound inference
2034     * (see InferenceKind).
2035     */
2036     class InferenceContext {
2037
2038        /** list of inference vars as undet vars */
2039        List<Type> undetvars;
2040
2041        /** list of inference vars in this context */
2042        List<Type> inferencevars;
2043
2044        Map<FreeTypeListener, List<Type>> freeTypeListeners = new HashMap<>();
2045
2046        List<FreeTypeListener> freetypeListeners = List.nil();
2047
2048        public InferenceContext(List<Type> inferencevars) {
2049            this.undetvars = Type.map(inferencevars, fromTypeVarFun);
2050            this.inferencevars = inferencevars;
2051        }
2052        //where
2053            Mapping fromTypeVarFun = new Mapping("fromTypeVarFunWithBounds") {
2054                // mapping that turns inference variables into undet vars
2055                public Type apply(Type t) {
2056                    if (t.hasTag(TYPEVAR)) {
2057                        TypeVar tv = (TypeVar)t;
2058                        if (tv.isCaptured()) {
2059                            return new CapturedUndetVar((CapturedType)tv, types);
2060                        } else {
2061                            return new UndetVar(tv, types);
2062                        }
2063                    } else {
2064                        return t.map(this);
2065                    }
2066                }
2067            };
2068
2069        /**
2070         * add a new inference var to this inference context
2071         */
2072        void addVar(TypeVar t) {
2073            this.undetvars = this.undetvars.prepend(fromTypeVarFun.apply(t));
2074            this.inferencevars = this.inferencevars.prepend(t);
2075        }
2076
2077        /**
2078         * returns the list of free variables (as type-variables) in this
2079         * inference context
2080         */
2081        List<Type> inferenceVars() {
2082            return inferencevars;
2083        }
2084
2085        /**
2086         * returns the list of uninstantiated variables (as type-variables) in this
2087         * inference context
2088         */
2089        List<Type> restvars() {
2090            return filterVars(new Filter<UndetVar>() {
2091                public boolean accepts(UndetVar uv) {
2092                    return uv.inst == null;
2093                }
2094            });
2095        }
2096
2097        /**
2098         * returns the list of instantiated variables (as type-variables) in this
2099         * inference context
2100         */
2101        List<Type> instvars() {
2102            return filterVars(new Filter<UndetVar>() {
2103                public boolean accepts(UndetVar uv) {
2104                    return uv.inst != null;
2105                }
2106            });
2107        }
2108
2109        /**
2110         * Get list of bounded inference variables (where bound is other than
2111         * declared bounds).
2112         */
2113        final List<Type> boundedVars() {
2114            return filterVars(new Filter<UndetVar>() {
2115                public boolean accepts(UndetVar uv) {
2116                    return uv.getBounds(InferenceBound.UPPER)
2117                             .diff(uv.getDeclaredBounds())
2118                             .appendList(uv.getBounds(InferenceBound.EQ, InferenceBound.LOWER)).nonEmpty();
2119                }
2120            });
2121        }
2122
2123        /* Returns the corresponding inference variables.
2124         */
2125        private List<Type> filterVars(Filter<UndetVar> fu) {
2126            ListBuffer<Type> res = new ListBuffer<>();
2127            for (Type t : undetvars) {
2128                UndetVar uv = (UndetVar)t;
2129                if (fu.accepts(uv)) {
2130                    res.append(uv.qtype);
2131                }
2132            }
2133            return res.toList();
2134        }
2135
2136        /**
2137         * is this type free?
2138         */
2139        final boolean free(Type t) {
2140            return t.containsAny(inferencevars);
2141        }
2142
2143        final boolean free(List<Type> ts) {
2144            for (Type t : ts) {
2145                if (free(t)) return true;
2146            }
2147            return false;
2148        }
2149
2150        /**
2151         * Returns a list of free variables in a given type
2152         */
2153        final List<Type> freeVarsIn(Type t) {
2154            ListBuffer<Type> buf = new ListBuffer<>();
2155            for (Type iv : inferenceVars()) {
2156                if (t.contains(iv)) {
2157                    buf.add(iv);
2158                }
2159            }
2160            return buf.toList();
2161        }
2162
2163        final List<Type> freeVarsIn(List<Type> ts) {
2164            ListBuffer<Type> buf = new ListBuffer<>();
2165            for (Type t : ts) {
2166                buf.appendList(freeVarsIn(t));
2167            }
2168            ListBuffer<Type> buf2 = new ListBuffer<>();
2169            for (Type t : buf) {
2170                if (!buf2.contains(t)) {
2171                    buf2.add(t);
2172                }
2173            }
2174            return buf2.toList();
2175        }
2176
2177        /**
2178         * Replace all free variables in a given type with corresponding
2179         * undet vars (used ahead of subtyping/compatibility checks to allow propagation
2180         * of inference constraints).
2181         */
2182        final Type asUndetVar(Type t) {
2183            return types.subst(t, inferencevars, undetvars);
2184        }
2185
2186        final List<Type> asUndetVars(List<Type> ts) {
2187            ListBuffer<Type> buf = new ListBuffer<>();
2188            for (Type t : ts) {
2189                buf.append(asUndetVar(t));
2190            }
2191            return buf.toList();
2192        }
2193
2194        List<Type> instTypes() {
2195            ListBuffer<Type> buf = new ListBuffer<>();
2196            for (Type t : undetvars) {
2197                UndetVar uv = (UndetVar)t;
2198                buf.append(uv.inst != null ? uv.inst : uv.qtype);
2199            }
2200            return buf.toList();
2201        }
2202
2203        /**
2204         * Replace all free variables in a given type with corresponding
2205         * instantiated types - if one or more free variable has not been
2206         * fully instantiated, it will still be available in the resulting type.
2207         */
2208        Type asInstType(Type t) {
2209            return types.subst(t, inferencevars, instTypes());
2210        }
2211
2212        List<Type> asInstTypes(List<Type> ts) {
2213            ListBuffer<Type> buf = new ListBuffer<>();
2214            for (Type t : ts) {
2215                buf.append(asInstType(t));
2216            }
2217            return buf.toList();
2218        }
2219
2220        /**
2221         * Add custom hook for performing post-inference action
2222         */
2223        void addFreeTypeListener(List<Type> types, FreeTypeListener ftl) {
2224            freeTypeListeners.put(ftl, freeVarsIn(types));
2225        }
2226
2227        /**
2228         * Mark the inference context as complete and trigger evaluation
2229         * of all deferred checks.
2230         */
2231        void notifyChange() {
2232            notifyChange(inferencevars.diff(restvars()));
2233        }
2234
2235        void notifyChange(List<Type> inferredVars) {
2236            InferenceException thrownEx = null;
2237            for (Map.Entry<FreeTypeListener, List<Type>> entry :
2238                    new HashMap<>(freeTypeListeners).entrySet()) {
2239                if (!Type.containsAny(entry.getValue(), inferencevars.diff(inferredVars))) {
2240                    try {
2241                        entry.getKey().typesInferred(this);
2242                        freeTypeListeners.remove(entry.getKey());
2243                    } catch (InferenceException ex) {
2244                        if (thrownEx == null) {
2245                            thrownEx = ex;
2246                        }
2247                    }
2248                }
2249            }
2250            //inference exception multiplexing - present any inference exception
2251            //thrown when processing listeners as a single one
2252            if (thrownEx != null) {
2253                throw thrownEx;
2254            }
2255        }
2256
2257        /**
2258         * Save the state of this inference context
2259         */
2260        List<Type> save() {
2261            ListBuffer<Type> buf = new ListBuffer<>();
2262            for (Type t : undetvars) {
2263                UndetVar uv = (UndetVar)t;
2264                UndetVar uv2 = new UndetVar((TypeVar)uv.qtype, types);
2265                for (InferenceBound ib : InferenceBound.values()) {
2266                    for (Type b : uv.getBounds(ib)) {
2267                        uv2.addBound(ib, b, types);
2268                    }
2269                }
2270                uv2.inst = uv.inst;
2271                buf.add(uv2);
2272            }
2273            return buf.toList();
2274        }
2275
2276        /**
2277         * Restore the state of this inference context to the previous known checkpoint
2278         */
2279        void rollback(List<Type> saved_undet) {
2280             Assert.check(saved_undet != null && saved_undet.length() == undetvars.length());
2281            //restore bounds (note: we need to preserve the old instances)
2282            for (Type t : undetvars) {
2283                UndetVar uv = (UndetVar)t;
2284                UndetVar uv_saved = (UndetVar)saved_undet.head;
2285                for (InferenceBound ib : InferenceBound.values()) {
2286                    uv.setBounds(ib, uv_saved.getBounds(ib));
2287                }
2288                uv.inst = uv_saved.inst;
2289                saved_undet = saved_undet.tail;
2290            }
2291        }
2292
2293        /**
2294         * Copy variable in this inference context to the given context
2295         */
2296        void dupTo(final InferenceContext that) {
2297            that.inferencevars = that.inferencevars.appendList(
2298                    inferencevars.diff(that.inferencevars));
2299            that.undetvars = that.undetvars.appendList(
2300                    undetvars.diff(that.undetvars));
2301            //set up listeners to notify original inference contexts as
2302            //propagated vars are inferred in new context
2303            for (Type t : inferencevars) {
2304                that.freeTypeListeners.put(new FreeTypeListener() {
2305                    public void typesInferred(InferenceContext inferenceContext) {
2306                        InferenceContext.this.notifyChange();
2307                    }
2308                }, List.of(t));
2309            }
2310        }
2311
2312        private void solve(GraphStrategy ss, Warner warn) {
2313            solve(ss, new HashMap<Type, Set<Type>>(), warn);
2314        }
2315
2316        /**
2317         * Solve with given graph strategy.
2318         */
2319        private void solve(GraphStrategy ss, Map<Type, Set<Type>> stuckDeps, Warner warn) {
2320            GraphSolver s = new GraphSolver(this, stuckDeps, warn);
2321            s.solve(ss);
2322        }
2323
2324        /**
2325         * Solve all variables in this context.
2326         */
2327        public void solve(Warner warn) {
2328            solve(new LeafSolver() {
2329                public boolean done() {
2330                    return restvars().isEmpty();
2331                }
2332            }, warn);
2333        }
2334
2335        /**
2336         * Solve all variables in the given list.
2337         */
2338        public void solve(final List<Type> vars, Warner warn) {
2339            solve(new BestLeafSolver(vars) {
2340                public boolean done() {
2341                    return !free(asInstTypes(vars));
2342                }
2343            }, warn);
2344        }
2345
2346        /**
2347         * Solve at least one variable in given list.
2348         */
2349        public void solveAny(List<Type> varsToSolve, Map<Type, Set<Type>> optDeps, Warner warn) {
2350            solve(new BestLeafSolver(varsToSolve.intersect(restvars())) {
2351                public boolean done() {
2352                    return instvars().intersect(varsToSolve).nonEmpty();
2353                }
2354            }, optDeps, warn);
2355        }
2356
2357        /**
2358         * Apply a set of inference steps
2359         */
2360        private boolean solveBasic(EnumSet<InferenceStep> steps) {
2361            return solveBasic(inferencevars, steps);
2362        }
2363
2364        private boolean solveBasic(List<Type> varsToSolve, EnumSet<InferenceStep> steps) {
2365            boolean changed = false;
2366            for (Type t : varsToSolve.intersect(restvars())) {
2367                UndetVar uv = (UndetVar)asUndetVar(t);
2368                for (InferenceStep step : steps) {
2369                    if (step.accepts(uv, this)) {
2370                        uv.inst = step.solve(uv, this);
2371                        changed = true;
2372                        break;
2373                    }
2374                }
2375            }
2376            return changed;
2377        }
2378
2379        /**
2380         * Instantiate inference variables in legacy mode (JLS 15.12.2.7, 15.12.2.8).
2381         * During overload resolution, instantiation is done by doing a partial
2382         * inference process using eq/lower bound instantiation. During check,
2383         * we also instantiate any remaining vars by repeatedly using eq/upper
2384         * instantiation, until all variables are solved.
2385         */
2386        public void solveLegacy(boolean partial, Warner warn, EnumSet<InferenceStep> steps) {
2387            while (true) {
2388                boolean stuck = !solveBasic(steps);
2389                if (restvars().isEmpty() || partial) {
2390                    //all variables have been instantiated - exit
2391                    break;
2392                } else if (stuck) {
2393                    //some variables could not be instantiated because of cycles in
2394                    //upper bounds - provide a (possibly recursive) default instantiation
2395                    instantiateAsUninferredVars(restvars(), this);
2396                    break;
2397                } else {
2398                    //some variables have been instantiated - replace newly instantiated
2399                    //variables in remaining upper bounds and continue
2400                    for (Type t : undetvars) {
2401                        UndetVar uv = (UndetVar)t;
2402                        uv.substBounds(inferenceVars(), instTypes(), types);
2403                    }
2404                }
2405            }
2406            checkWithinBounds(this, warn);
2407        }
2408
2409        private Infer infer() {
2410            //back-door to infer
2411            return Infer.this;
2412        }
2413
2414        @Override
2415        public String toString() {
2416            return "Inference vars: " + inferencevars + '\n' +
2417                   "Undet vars: " + undetvars;
2418        }
2419
2420        /* Method Types.capture() generates a new type every time it's applied
2421         * to a wildcard parameterized type. This is intended functionality but
2422         * there are some cases when what you need is not to generate a new
2423         * captured type but to check that a previously generated captured type
2424         * is correct. There are cases when caching a captured type for later
2425         * reuse is sound. In general two captures from the same AST are equal.
2426         * This is why the tree is used as the key of the map below. This map
2427         * stores a Type per AST.
2428         */
2429        Map<JCTree, Type> captureTypeCache = new HashMap<>();
2430
2431        Type cachedCapture(JCTree tree, Type t, boolean readOnly) {
2432            Type captured = captureTypeCache.get(tree);
2433            if (captured != null) {
2434                return captured;
2435            }
2436
2437            Type result = types.capture(t);
2438            if (result != t && !readOnly) { // then t is a wildcard parameterized type
2439                captureTypeCache.put(tree, result);
2440            }
2441            return result;
2442        }
2443    }
2444
2445    final InferenceContext emptyContext = new InferenceContext(List.<Type>nil());
2446    // </editor-fold>
2447}
2448