Infer.java revision 4011:28a6e8d3ccc7
1/*
2 * Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package com.sun.tools.javac.comp;
27
28import com.sun.tools.javac.code.Type.UndetVar.UndetVarListener;
29import com.sun.tools.javac.tree.JCTree;
30import com.sun.tools.javac.tree.JCTree.JCTypeCast;
31import com.sun.tools.javac.tree.TreeInfo;
32import com.sun.tools.javac.util.*;
33import com.sun.tools.javac.util.GraphUtils.DottableNode;
34import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
35import com.sun.tools.javac.util.List;
36import com.sun.tools.javac.code.*;
37import com.sun.tools.javac.code.Type.*;
38import com.sun.tools.javac.code.Type.UndetVar.InferenceBound;
39import com.sun.tools.javac.code.Symbol.*;
40import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
41import com.sun.tools.javac.comp.DeferredAttr.DeferredAttrContext;
42import com.sun.tools.javac.comp.Infer.GraphSolver.InferenceGraph;
43import com.sun.tools.javac.comp.Infer.GraphSolver.InferenceGraph.Node;
44import com.sun.tools.javac.comp.Resolve.InapplicableMethodException;
45import com.sun.tools.javac.comp.Resolve.VerboseResolutionMode;
46
47import java.io.IOException;
48import java.io.Writer;
49import java.nio.file.Files;
50import java.nio.file.Path;
51import java.nio.file.Paths;
52import java.util.ArrayList;
53import java.util.Collection;
54import java.util.Collections;
55import java.util.EnumSet;
56import java.util.HashMap;
57import java.util.HashSet;
58import java.util.Map;
59import java.util.Optional;
60import java.util.Properties;
61import java.util.Set;
62import java.util.function.BiFunction;
63import java.util.function.BiPredicate;
64import java.util.stream.Collectors;
65
66import com.sun.tools.javac.main.Option;
67
68import static com.sun.tools.javac.code.TypeTag.*;
69
70/** Helper class for type parameter inference, used by the attribution phase.
71 *
72 *  <p><b>This is NOT part of any supported API.
73 *  If you write code that depends on this, you do so at your own risk.
74 *  This code and its internal interfaces are subject to change or
75 *  deletion without notice.</b>
76 */
77public class Infer {
78    protected static final Context.Key<Infer> inferKey = new Context.Key<>();
79
80    Resolve rs;
81    Check chk;
82    Symtab syms;
83    Types types;
84    JCDiagnostic.Factory diags;
85    Log log;
86
87    /** should the graph solver be used? */
88    boolean allowGraphInference;
89
90    /**
91     * folder in which the inference dependency graphs should be written.
92     */
93    private final String dependenciesFolder;
94
95    /**
96     * List of graphs awaiting to be dumped to a file.
97     */
98    private List<String> pendingGraphs;
99
100    public static Infer instance(Context context) {
101        Infer instance = context.get(inferKey);
102        if (instance == null)
103            instance = new Infer(context);
104        return instance;
105    }
106
107    protected Infer(Context context) {
108        context.put(inferKey, this);
109
110        rs = Resolve.instance(context);
111        chk = Check.instance(context);
112        syms = Symtab.instance(context);
113        types = Types.instance(context);
114        diags = JCDiagnostic.Factory.instance(context);
115        log = Log.instance(context);
116        inferenceException = new InferenceException(diags);
117        Options options = Options.instance(context);
118        allowGraphInference = Source.instance(context).allowGraphInference()
119                && options.isUnset("useLegacyInference");
120        dependenciesFolder = options.get("debug.dumpInferenceGraphsTo");
121        pendingGraphs = List.nil();
122
123        emptyContext = new InferenceContext(this, List.nil());
124    }
125
126    /** A value for prototypes that admit any type, including polymorphic ones. */
127    public static final Type anyPoly = new JCNoType();
128
129   /**
130    * This exception class is design to store a list of diagnostics corresponding
131    * to inference errors that can arise during a method applicability check.
132    */
133    public static class InferenceException extends InapplicableMethodException {
134        private static final long serialVersionUID = 0;
135
136        List<JCDiagnostic> messages = List.nil();
137
138        InferenceException(JCDiagnostic.Factory diags) {
139            super(diags);
140        }
141
142        @Override
143        InapplicableMethodException setMessage() {
144            //no message to set
145            return this;
146        }
147
148        @Override
149        InapplicableMethodException setMessage(JCDiagnostic diag) {
150            messages = messages.append(diag);
151            return this;
152        }
153
154        @Override
155        public JCDiagnostic getDiagnostic() {
156            return messages.head;
157        }
158
159        void clear() {
160            messages = List.nil();
161        }
162    }
163
164    protected final InferenceException inferenceException;
165
166    // <editor-fold defaultstate="collapsed" desc="Inference routines">
167    /**
168     * Main inference entry point - instantiate a generic method type
169     * using given argument types and (possibly) an expected target-type.
170     */
171    Type instantiateMethod( Env<AttrContext> env,
172                            List<Type> tvars,
173                            MethodType mt,
174                            Attr.ResultInfo resultInfo,
175                            MethodSymbol msym,
176                            List<Type> argtypes,
177                            boolean allowBoxing,
178                            boolean useVarargs,
179                            Resolve.MethodResolutionContext resolveContext,
180                            Warner warn) throws InferenceException {
181        //-System.err.println("instantiateMethod(" + tvars + ", " + mt + ", " + argtypes + ")"); //DEBUG
182        final InferenceContext inferenceContext = new InferenceContext(this, tvars);  //B0
183        inferenceException.clear();
184        try {
185            DeferredAttr.DeferredAttrContext deferredAttrContext =
186                        resolveContext.deferredAttrContext(msym, inferenceContext, resultInfo, warn);
187
188            resolveContext.methodCheck.argumentsAcceptable(env, deferredAttrContext,   //B2
189                    argtypes, mt.getParameterTypes(), warn);
190
191            if (allowGraphInference && resultInfo != null && resultInfo.pt == anyPoly) {
192                doIncorporation(inferenceContext, warn);
193                //we are inside method attribution - just return a partially inferred type
194                return new PartiallyInferredMethodType(mt, inferenceContext, env, warn);
195            } else if (allowGraphInference &&
196                    resultInfo != null &&
197                    !warn.hasNonSilentLint(Lint.LintCategory.UNCHECKED)) {
198                //inject return constraints earlier
199                doIncorporation(inferenceContext, warn); //propagation
200
201                boolean shouldPropagate = shouldPropagate(mt.getReturnType(), resultInfo, inferenceContext);
202
203                InferenceContext minContext = shouldPropagate ?
204                        inferenceContext.min(roots(mt, deferredAttrContext), true, warn) :
205                        inferenceContext;
206
207                Type newRestype = generateReturnConstraints(env.tree, resultInfo,  //B3
208                        mt, minContext);
209                mt = (MethodType)types.createMethodTypeWithReturn(mt, newRestype);
210
211                //propagate outwards if needed
212                if (shouldPropagate) {
213                    //propagate inference context outwards and exit
214                    minContext.dupTo(resultInfo.checkContext.inferenceContext());
215                    deferredAttrContext.complete();
216                    return mt;
217                }
218            }
219
220            deferredAttrContext.complete();
221
222            // minimize as yet undetermined type variables
223            if (allowGraphInference) {
224                inferenceContext.solve(warn);
225            } else {
226                inferenceContext.solveLegacy(true, warn, LegacyInferenceSteps.EQ_LOWER.steps); //minimizeInst
227            }
228
229            mt = (MethodType)inferenceContext.asInstType(mt);
230
231            if (!allowGraphInference &&
232                    inferenceContext.restvars().nonEmpty() &&
233                    resultInfo != null &&
234                    !warn.hasNonSilentLint(Lint.LintCategory.UNCHECKED)) {
235                generateReturnConstraints(env.tree, resultInfo, mt, inferenceContext);
236                inferenceContext.solveLegacy(false, warn, LegacyInferenceSteps.EQ_UPPER.steps); //maximizeInst
237                mt = (MethodType)inferenceContext.asInstType(mt);
238            }
239
240            if (resultInfo != null && rs.verboseResolutionMode.contains(VerboseResolutionMode.DEFERRED_INST)) {
241                log.note(env.tree.pos, "deferred.method.inst", msym, mt, resultInfo.pt);
242            }
243
244            // return instantiated version of method type
245            return mt;
246        } finally {
247            if (resultInfo != null || !allowGraphInference) {
248                inferenceContext.notifyChange();
249            } else {
250                inferenceContext.notifyChange(inferenceContext.boundedVars());
251            }
252            if (resultInfo == null) {
253                /* if the is no result info then we can clear the capture types
254                 * cache without affecting any result info check
255                 */
256                inferenceContext.captureTypeCache.clear();
257            }
258            dumpGraphsIfNeeded(env.tree, msym, resolveContext);
259        }
260    }
261    //where
262        private boolean shouldPropagate(Type restype, Attr.ResultInfo target, InferenceContext inferenceContext) {
263            return target.checkContext.inferenceContext() != emptyContext && //enclosing context is a generic method
264                        inferenceContext.free(restype) && //return type contains inference vars
265                        (!inferenceContext.inferencevars.contains(restype) || //no eager instantiation is required (as per 18.5.2)
266                                !needsEagerInstantiation((UndetVar)inferenceContext.asUndetVar(restype), target.pt, inferenceContext));
267        }
268
269        private List<Type> roots(MethodType mt, DeferredAttrContext deferredAttrContext) {
270            ListBuffer<Type> roots = new ListBuffer<>();
271            roots.add(mt.getReturnType());
272            if (deferredAttrContext != null && deferredAttrContext.mode == AttrMode.CHECK) {
273                roots.addAll(mt.getThrownTypes());
274                for (DeferredAttr.DeferredAttrNode n : deferredAttrContext.deferredAttrNodes) {
275                    roots.addAll(n.deferredStuckPolicy.stuckVars());
276                    roots.addAll(n.deferredStuckPolicy.depVars());
277                }
278            }
279            return roots.toList();
280        }
281
282    /**
283     * A partially infered method/constructor type; such a type can be checked multiple times
284     * against different targets.
285     */
286    public class PartiallyInferredMethodType extends MethodType {
287        public PartiallyInferredMethodType(MethodType mtype, InferenceContext inferenceContext, Env<AttrContext> env, Warner warn) {
288            super(mtype.getParameterTypes(), mtype.getReturnType(), mtype.getThrownTypes(), mtype.tsym);
289            this.inferenceContext = inferenceContext;
290            this.env = env;
291            this.warn = warn;
292        }
293
294        /** The inference context. */
295        final InferenceContext inferenceContext;
296
297        /** The attribution environment. */
298        Env<AttrContext> env;
299
300        /** The warner. */
301        final Warner warn;
302
303        @Override
304        public boolean isPartial() {
305            return true;
306        }
307
308        /**
309         * Checks this type against a target; this means generating return type constraints, solve
310         * and then roll back the results (to avoid poolluting the context).
311         */
312        Type check(Attr.ResultInfo resultInfo) {
313            Warner noWarnings = new Warner(null);
314            inferenceException.clear();
315            List<Type> saved_undet = null;
316            try {
317                /** we need to save the inference context before generating target type constraints.
318                 *  This constraints may pollute the inference context and make it useless in case we
319                 *  need to use it several times: with several targets.
320                 */
321                saved_undet = inferenceContext.save();
322                boolean unchecked = warn.hasNonSilentLint(Lint.LintCategory.UNCHECKED);
323                if (allowGraphInference && !unchecked) {
324                    boolean shouldPropagate = shouldPropagate(getReturnType(), resultInfo, inferenceContext);
325
326                    InferenceContext minContext = shouldPropagate ?
327                            inferenceContext.min(roots(asMethodType(), null), false, warn) :
328                            inferenceContext;
329
330                    MethodType other = (MethodType)minContext.update(asMethodType());
331                    Type newRestype = generateReturnConstraints(env.tree, resultInfo,  //B3
332                            other, minContext);
333
334                    if (shouldPropagate) {
335                        //propagate inference context outwards and exit
336                        minContext.dupTo(resultInfo.checkContext.inferenceContext(),
337                                resultInfo.checkContext.deferredAttrContext().insideOverloadPhase());
338                        return newRestype;
339                    }
340                }
341                inferenceContext.solve(noWarnings);
342                Type ret = inferenceContext.asInstType(this).getReturnType();
343                //inline logic from Attr.checkMethod - if unchecked conversion was required, erase
344                //return type _after_ resolution
345                return unchecked ? types.erasure(ret) : ret;
346            } catch (InferenceException ex) {
347                resultInfo.checkContext.report(null, ex.getDiagnostic());
348                Assert.error(); //cannot get here (the above should throw)
349                return null;
350            } finally {
351                if (saved_undet != null) {
352                    inferenceContext.rollback(saved_undet);
353                }
354            }
355        }
356    }
357
358    private void dumpGraphsIfNeeded(DiagnosticPosition pos, Symbol msym, Resolve.MethodResolutionContext rsContext) {
359        int round = 0;
360        try {
361            for (String graph : pendingGraphs.reverse()) {
362                Assert.checkNonNull(dependenciesFolder);
363                Name name = msym.name == msym.name.table.names.init ?
364                        msym.owner.name : msym.name;
365                String filename = String.format("%s@%s[mode=%s,step=%s]_%d.dot",
366                        name,
367                        pos.getStartPosition(),
368                        rsContext.attrMode(),
369                        rsContext.step,
370                        round);
371                Path dotFile = Paths.get(dependenciesFolder, filename);
372                try (Writer w = Files.newBufferedWriter(dotFile)) {
373                    w.append(graph);
374                }
375                round++;
376            }
377        } catch (IOException ex) {
378            Assert.error("Error occurred when dumping inference graph: " + ex.getMessage());
379        } finally {
380            pendingGraphs = List.nil();
381        }
382    }
383
384    /**
385     * Generate constraints from the generic method's return type. If the method
386     * call occurs in a context where a type T is expected, use the expected
387     * type to derive more constraints on the generic method inference variables.
388     */
389    Type generateReturnConstraints(JCTree tree, Attr.ResultInfo resultInfo,
390            MethodType mt, InferenceContext inferenceContext) {
391        InferenceContext rsInfoInfContext = resultInfo.checkContext.inferenceContext();
392        Type from = mt.getReturnType();
393        if (mt.getReturnType().containsAny(inferenceContext.inferencevars) &&
394                rsInfoInfContext != emptyContext) {
395            from = types.capture(from);
396            //add synthetic captured ivars
397            for (Type t : from.getTypeArguments()) {
398                if (t.hasTag(TYPEVAR) && ((TypeVar)t).isCaptured()) {
399                    inferenceContext.addVar((TypeVar)t);
400                }
401            }
402        }
403        Type qtype = inferenceContext.asUndetVar(from);
404        Type to = resultInfo.pt;
405
406        if (qtype.hasTag(VOID)) {
407            to = syms.voidType;
408        } else if (to.hasTag(NONE)) {
409            to = from.isPrimitive() ? from : syms.objectType;
410        } else if (qtype.hasTag(UNDETVAR)) {
411            if (needsEagerInstantiation((UndetVar)qtype, to, inferenceContext) &&
412                    (allowGraphInference || !to.isPrimitive())) {
413                to = generateReferenceToTargetConstraint(tree, (UndetVar)qtype, to, resultInfo, inferenceContext);
414            } else if (to.isPrimitive()) {
415                to = types.boxedClass(to).type;
416            }
417        } else if (rsInfoInfContext.free(resultInfo.pt)) {
418            //propagation - cache captured vars
419            qtype = inferenceContext.asUndetVar(rsInfoInfContext.cachedCapture(tree, from, false));
420        }
421        Assert.check(allowGraphInference || !rsInfoInfContext.free(to),
422                "legacy inference engine cannot handle constraints on both sides of a subtyping assertion");
423        //we need to skip capture?
424        Warner retWarn = new Warner();
425        if (!resultInfo.checkContext.compatible(qtype, rsInfoInfContext.asUndetVar(to), retWarn) ||
426                //unchecked conversion is not allowed in source 7 mode
427                (!allowGraphInference && retWarn.hasLint(Lint.LintCategory.UNCHECKED))) {
428            throw inferenceException
429                    .setMessage("infer.no.conforming.instance.exists",
430                    inferenceContext.restvars(), mt.getReturnType(), to);
431        }
432        return from;
433    }
434
435    private boolean needsEagerInstantiation(UndetVar from, Type to, InferenceContext inferenceContext) {
436        if (to.isPrimitive()) {
437            /* T is a primitive type, and one of the primitive wrapper classes is an instantiation,
438             * upper bound, or lower bound for alpha in B2.
439             */
440            for (Type t : from.getBounds(InferenceBound.values())) {
441                Type boundAsPrimitive = types.unboxedType(t);
442                if (boundAsPrimitive == null || boundAsPrimitive.hasTag(NONE)) {
443                    continue;
444                }
445                return true;
446            }
447            return false;
448        }
449
450        Type captureOfTo = types.capture(to);
451        /* T is a reference type, but is not a wildcard-parameterized type, and either
452         */
453        if (captureOfTo == to) { //not a wildcard parameterized type
454            /* i) B2 contains a bound of one of the forms alpha = S or S <: alpha,
455             *      where S is a wildcard-parameterized type, or
456             */
457            for (Type t : from.getBounds(InferenceBound.EQ, InferenceBound.LOWER)) {
458                Type captureOfBound = types.capture(t);
459                if (captureOfBound != t) {
460                    return true;
461                }
462            }
463
464            /* ii) B2 contains two bounds of the forms S1 <: alpha and S2 <: alpha,
465             * where S1 and S2 have supertypes that are two different
466             * parameterizations of the same generic class or interface.
467             */
468            for (Type aLowerBound : from.getBounds(InferenceBound.LOWER)) {
469                for (Type anotherLowerBound : from.getBounds(InferenceBound.LOWER)) {
470                    if (aLowerBound != anotherLowerBound &&
471                            !inferenceContext.free(aLowerBound) &&
472                            !inferenceContext.free(anotherLowerBound) &&
473                            commonSuperWithDiffParameterization(aLowerBound, anotherLowerBound)) {
474                        return true;
475                    }
476                }
477            }
478        }
479
480        /* T is a parameterization of a generic class or interface, G,
481         * and B2 contains a bound of one of the forms alpha = S or S <: alpha,
482         * where there exists no type of the form G<...> that is a
483         * supertype of S, but the raw type G is a supertype of S
484         */
485        if (to.isParameterized()) {
486            for (Type t : from.getBounds(InferenceBound.EQ, InferenceBound.LOWER)) {
487                Type sup = types.asSuper(t, to.tsym);
488                if (sup != null && sup.isRaw()) {
489                    return true;
490                }
491            }
492        }
493        return false;
494    }
495
496    private boolean commonSuperWithDiffParameterization(Type t, Type s) {
497        for (Pair<Type, Type> supers : getParameterizedSupers(t, s)) {
498            if (!types.isSameType(supers.fst, supers.snd)) return true;
499        }
500        return false;
501    }
502
503    private Type generateReferenceToTargetConstraint(JCTree tree, UndetVar from,
504            Type to, Attr.ResultInfo resultInfo,
505            InferenceContext inferenceContext) {
506        inferenceContext.solve(List.of(from.qtype), new Warner());
507        inferenceContext.notifyChange();
508        Type capturedType = resultInfo.checkContext.inferenceContext()
509                .cachedCapture(tree, from.getInst(), false);
510        if (types.isConvertible(capturedType,
511                resultInfo.checkContext.inferenceContext().asUndetVar(to))) {
512            //effectively skip additional return-type constraint generation (compatibility)
513            return syms.objectType;
514        }
515        return to;
516    }
517
518    /**
519      * Infer cyclic inference variables as described in 15.12.2.8.
520      */
521    void instantiateAsUninferredVars(List<Type> vars, InferenceContext inferenceContext) {
522        ListBuffer<Type> todo = new ListBuffer<>();
523        //step 1 - create fresh tvars
524        for (Type t : vars) {
525            UndetVar uv = (UndetVar)inferenceContext.asUndetVar(t);
526            List<Type> upperBounds = uv.getBounds(InferenceBound.UPPER);
527            if (Type.containsAny(upperBounds, vars)) {
528                TypeSymbol fresh_tvar = new TypeVariableSymbol(Flags.SYNTHETIC, uv.qtype.tsym.name, null, uv.qtype.tsym.owner);
529                fresh_tvar.type = new TypeVar(fresh_tvar, types.makeIntersectionType(uv.getBounds(InferenceBound.UPPER)), null);
530                todo.append(uv);
531                uv.setInst(fresh_tvar.type);
532            } else if (upperBounds.nonEmpty()) {
533                uv.setInst(types.glb(upperBounds));
534            } else {
535                uv.setInst(syms.objectType);
536            }
537        }
538        //step 2 - replace fresh tvars in their bounds
539        List<Type> formals = vars;
540        for (Type t : todo) {
541            UndetVar uv = (UndetVar)t;
542            TypeVar ct = (TypeVar)uv.getInst();
543            ct.bound = types.glb(inferenceContext.asInstTypes(types.getBounds(ct)));
544            if (ct.bound.isErroneous()) {
545                //report inference error if glb fails
546                reportBoundError(uv, InferenceBound.UPPER);
547            }
548            formals = formals.tail;
549        }
550    }
551
552    /**
553     * Compute a synthetic method type corresponding to the requested polymorphic
554     * method signature. The target return type is computed from the immediately
555     * enclosing scope surrounding the polymorphic-signature call.
556     */
557    Type instantiatePolymorphicSignatureInstance(Env<AttrContext> env,
558                                            MethodSymbol spMethod,  // sig. poly. method or null if none
559                                            Resolve.MethodResolutionContext resolveContext,
560                                            List<Type> argtypes) {
561        final Type restype;
562
563        if (spMethod == null || types.isSameType(spMethod.getReturnType(), syms.objectType, true)) {
564            // The return type of the polymorphic signature is polymorphic,
565            // and is computed from the enclosing tree E, as follows:
566            // if E is a cast, then use the target type of the cast expression
567            // as a return type; if E is an expression statement, the return
568            // type is 'void'; otherwise
569            // the return type is simply 'Object'. A correctness check ensures
570            // that env.next refers to the lexically enclosing environment in
571            // which the polymorphic signature call environment is nested.
572
573            switch (env.next.tree.getTag()) {
574                case TYPECAST:
575                    JCTypeCast castTree = (JCTypeCast)env.next.tree;
576                    restype = (TreeInfo.skipParens(castTree.expr) == env.tree) ?
577                              castTree.clazz.type :
578                              syms.objectType;
579                    break;
580                case EXEC:
581                    JCTree.JCExpressionStatement execTree =
582                            (JCTree.JCExpressionStatement)env.next.tree;
583                    restype = (TreeInfo.skipParens(execTree.expr) == env.tree) ?
584                              syms.voidType :
585                              syms.objectType;
586                    break;
587                default:
588                    restype = syms.objectType;
589            }
590        } else {
591            // The return type of the polymorphic signature is fixed
592            // (not polymorphic)
593            restype = spMethod.getReturnType();
594        }
595
596        List<Type> paramtypes = argtypes.map(new ImplicitArgType(spMethod, resolveContext.step));
597        List<Type> exType = spMethod != null ?
598            spMethod.getThrownTypes() :
599            List.of(syms.throwableType); // make it throw all exceptions
600
601        MethodType mtype = new MethodType(paramtypes,
602                                          restype,
603                                          exType,
604                                          syms.methodClass);
605        return mtype;
606    }
607    //where
608        class ImplicitArgType extends DeferredAttr.DeferredTypeMap {
609
610            public ImplicitArgType(Symbol msym, Resolve.MethodResolutionPhase phase) {
611                (rs.deferredAttr).super(AttrMode.SPECULATIVE, msym, phase);
612            }
613
614            @Override
615            public Type visitClassType(ClassType t, Void aVoid) {
616                return types.erasure(t);
617            }
618
619            @Override
620            public Type visitType(Type t, Void _unused) {
621                if (t.hasTag(DEFERRED)) {
622                    return visit(super.visitType(t, null));
623                } else if (t.hasTag(BOT))
624                    // nulls type as the marker type Null (which has no instances)
625                    // infer as java.lang.Void for now
626                    t = types.boxedClass(syms.voidType).type;
627                return t;
628            }
629        }
630
631    TypeMapping<Void> fromTypeVarFun = new TypeMapping<Void>() {
632        @Override
633        public Type visitTypeVar(TypeVar tv, Void aVoid) {
634            UndetVar uv = new UndetVar(tv, incorporationEngine(), types);
635            if ((tv.tsym.flags() & Flags.THROWS) != 0) {
636                uv.setThrow();
637            }
638            return uv;
639        }
640    };
641
642    /**
643      * This method is used to infer a suitable target SAM in case the original
644      * SAM type contains one or more wildcards. An inference process is applied
645      * so that wildcard bounds, as well as explicit lambda/method ref parameters
646      * (where applicable) are used to constraint the solution.
647      */
648    public Type instantiateFunctionalInterface(DiagnosticPosition pos, Type funcInterface,
649            List<Type> paramTypes, Check.CheckContext checkContext) {
650        if (types.capture(funcInterface) == funcInterface) {
651            //if capture doesn't change the type then return the target unchanged
652            //(this means the target contains no wildcards!)
653            return funcInterface;
654        } else {
655            Type formalInterface = funcInterface.tsym.type;
656            InferenceContext funcInterfaceContext =
657                    new InferenceContext(this, funcInterface.tsym.type.getTypeArguments());
658
659            Assert.check(paramTypes != null);
660            //get constraints from explicit params (this is done by
661            //checking that explicit param types are equal to the ones
662            //in the functional interface descriptors)
663            List<Type> descParameterTypes = types.findDescriptorType(formalInterface).getParameterTypes();
664            if (descParameterTypes.size() != paramTypes.size()) {
665                checkContext.report(pos, diags.fragment("incompatible.arg.types.in.lambda"));
666                return types.createErrorType(funcInterface);
667            }
668            for (Type p : descParameterTypes) {
669                if (!types.isSameType(funcInterfaceContext.asUndetVar(p), paramTypes.head)) {
670                    checkContext.report(pos, diags.fragment("no.suitable.functional.intf.inst", funcInterface));
671                    return types.createErrorType(funcInterface);
672                }
673                paramTypes = paramTypes.tail;
674            }
675
676            List<Type> actualTypeargs = funcInterface.getTypeArguments();
677            for (Type t : funcInterfaceContext.undetvars) {
678                UndetVar uv = (UndetVar)t;
679                Optional<Type> inst = uv.getBounds(InferenceBound.EQ).stream()
680                        .filter(b -> !b.containsAny(formalInterface.getTypeArguments())).findFirst();
681                uv.setInst(inst.orElse(actualTypeargs.head));
682                actualTypeargs = actualTypeargs.tail;
683            }
684
685            Type owntype = funcInterfaceContext.asInstType(formalInterface);
686            if (!chk.checkValidGenericType(owntype)) {
687                //if the inferred functional interface type is not well-formed,
688                //or if it's not a subtype of the original target, issue an error
689                checkContext.report(pos, diags.fragment("no.suitable.functional.intf.inst", funcInterface));
690            }
691            //propagate constraints as per JLS 18.2.1
692            checkContext.compatible(owntype, funcInterface, types.noWarnings);
693            return owntype;
694        }
695    }
696    // </editor-fold>
697
698    // <editor-fold defaultstate="collapsed" desc="Incorporation">
699
700    /**
701     * This class is the root of all incorporation actions.
702     */
703    public abstract class IncorporationAction {
704        UndetVar uv;
705        Type t;
706
707        IncorporationAction(UndetVar uv, Type t) {
708            this.uv = uv;
709            this.t = t;
710        }
711
712        public abstract IncorporationAction dup(UndetVar that);
713
714        /**
715         * Incorporation action entry-point. Subclasses should define the logic associated with
716         * this incorporation action.
717         */
718        abstract void apply(InferenceContext ic, Warner warn);
719
720        /**
721         * Helper function: perform subtyping through incorporation cache.
722         */
723        boolean isSubtype(Type s, Type t, Warner warn) {
724            return doIncorporationOp(IncorporationBinaryOpKind.IS_SUBTYPE, s, t, warn);
725        }
726
727        /**
728         * Helper function: perform type-equivalence through incorporation cache.
729         */
730        boolean isSameType(Type s, Type t) {
731            return doIncorporationOp(IncorporationBinaryOpKind.IS_SAME_TYPE, s, t, null);
732        }
733
734        @Override
735        public String toString() {
736            return String.format("%s[undet=%s,t=%s]", getClass().getSimpleName(), uv.qtype, t);
737        }
738    }
739
740    /**
741     * Bound-check incorporation action. A newly added bound is checked against existing bounds,
742     * to verify its compatibility; each bound is checked using either subtyping or type equivalence.
743     */
744    class CheckBounds extends IncorporationAction {
745
746        InferenceBound from;
747        BiFunction<InferenceContext, Type, Type> typeFunc;
748        BiPredicate<InferenceContext, Type> optFilter;
749
750        CheckBounds(UndetVar uv, Type t, InferenceBound from) {
751            this(uv, t, InferenceContext::asUndetVar, null, from);
752        }
753
754        CheckBounds(UndetVar uv, Type t, BiFunction<InferenceContext, Type, Type> typeFunc,
755                    BiPredicate<InferenceContext, Type> typeFilter, InferenceBound from) {
756            super(uv, t);
757            this.from = from;
758            this.typeFunc = typeFunc;
759            this.optFilter = typeFilter;
760        }
761
762        @Override
763        public IncorporationAction dup(UndetVar that) {
764            return new CheckBounds(that, t, typeFunc, optFilter, from);
765        }
766
767        @Override
768        void apply(InferenceContext inferenceContext, Warner warn) {
769            t = typeFunc.apply(inferenceContext, t);
770            if (optFilter != null && optFilter.test(inferenceContext, t)) return;
771            for (InferenceBound to : boundsToCheck()) {
772                for (Type b : uv.getBounds(to)) {
773                    b = typeFunc.apply(inferenceContext, b);
774                    if (optFilter != null && optFilter.test(inferenceContext, b)) continue;
775                    boolean success = checkBound(t, b, from, to, warn);
776                    if (!success) {
777                        report(from, to);
778                    }
779                }
780            }
781        }
782
783        /**
784         * The list of bound kinds to be checked.
785         */
786        EnumSet<InferenceBound> boundsToCheck() {
787            return (from == InferenceBound.EQ) ?
788                            EnumSet.allOf(InferenceBound.class) :
789                            EnumSet.complementOf(EnumSet.of(from));
790        }
791
792        /**
793         * Is source type 's' compatible with target type 't' given source and target bound kinds?
794         */
795        boolean checkBound(Type s, Type t, InferenceBound ib_s, InferenceBound ib_t, Warner warn) {
796            if (ib_s.lessThan(ib_t)) {
797                return isSubtype(s, t, warn);
798            } else if (ib_t.lessThan(ib_s)) {
799                return isSubtype(t, s, warn);
800            } else {
801                return isSameType(s, t);
802            }
803        }
804
805        /**
806         * Report a bound check error.
807         */
808        void report(InferenceBound from, InferenceBound to) {
809            //this is a workaround to preserve compatibility with existing messages
810            if (from == to) {
811                reportBoundError(uv, from);
812            } else if (from == InferenceBound.LOWER || to == InferenceBound.EQ) {
813                reportBoundError(uv, to, from);
814            } else {
815                reportBoundError(uv, from, to);
816            }
817        }
818
819        @Override
820        public String toString() {
821            return String.format("%s[undet=%s,t=%s,bound=%s]", getClass().getSimpleName(), uv.qtype, t, from);
822        }
823    }
824
825    /**
826     * Custom check executed by the legacy incorporation engine. Newly added bounds are checked
827     * against existing eq bounds.
828     */
829    class EqCheckLegacy extends CheckBounds {
830        EqCheckLegacy(UndetVar uv, Type t, InferenceBound from) {
831            super(uv, t, InferenceContext::asInstType, InferenceContext::free, from);
832        }
833
834        @Override
835        public IncorporationAction dup(UndetVar that) {
836            return new EqCheckLegacy(that, t, from);
837        }
838
839        @Override
840        EnumSet<InferenceBound> boundsToCheck() {
841            return (from == InferenceBound.EQ) ?
842                            EnumSet.allOf(InferenceBound.class) :
843                            EnumSet.of(InferenceBound.EQ);
844        }
845    }
846
847    /**
848     * Check that the inferred type conforms to all bounds.
849     */
850    class CheckInst extends CheckBounds {
851
852        EnumSet<InferenceBound> to;
853
854        CheckInst(UndetVar uv, InferenceBound ib, InferenceBound... rest) {
855            this(uv, EnumSet.of(ib, rest));
856        }
857
858        CheckInst(UndetVar uv, EnumSet<InferenceBound> to) {
859            super(uv, uv.getInst(), InferenceBound.EQ);
860            this.to = to;
861        }
862
863        @Override
864        public IncorporationAction dup(UndetVar that) {
865            return new CheckInst(that, to);
866        }
867
868        @Override
869        EnumSet<InferenceBound> boundsToCheck() {
870            return to;
871        }
872
873        @Override
874        void report(InferenceBound from, InferenceBound to) {
875            reportInstError(uv, to);
876        }
877    }
878
879    /**
880     * Replace undetvars in bounds and check that the inferred type conforms to all bounds.
881     */
882    class SubstBounds extends CheckInst {
883        SubstBounds(UndetVar uv) {
884            super(uv, InferenceBound.LOWER, InferenceBound.EQ, InferenceBound.UPPER);
885        }
886
887        @Override
888        public IncorporationAction dup(UndetVar that) {
889            return new SubstBounds(that);
890        }
891
892        @Override
893        void apply(InferenceContext inferenceContext, Warner warn) {
894            for (Type undet : inferenceContext.undetvars) {
895                //we could filter out variables not mentioning uv2...
896                UndetVar uv2 = (UndetVar)undet;
897                uv2.substBounds(List.of(uv.qtype), List.of(uv.getInst()), types);
898                checkCompatibleUpperBounds(uv2, inferenceContext);
899            }
900            super.apply(inferenceContext, warn);
901        }
902
903        /**
904         * Make sure that the upper bounds we got so far lead to a solvable inference
905         * variable by making sure that a glb exists.
906         */
907        void checkCompatibleUpperBounds(UndetVar uv, InferenceContext inferenceContext) {
908            List<Type> hibounds =
909                    Type.filter(uv.getBounds(InferenceBound.UPPER), new BoundFilter(inferenceContext));
910            final Type hb;
911            if (hibounds.isEmpty())
912                hb = syms.objectType;
913            else if (hibounds.tail.isEmpty())
914                hb = hibounds.head;
915            else
916                hb = types.glb(hibounds);
917            if (hb == null || hb.isErroneous())
918                reportBoundError(uv, InferenceBound.UPPER);
919        }
920    }
921
922    /**
923     * Perform pairwise comparison between common generic supertypes of two upper bounds.
924     */
925    class CheckUpperBounds extends IncorporationAction {
926
927        public CheckUpperBounds(UndetVar uv, Type t) {
928            super(uv, t);
929        }
930
931        @Override
932        public IncorporationAction dup(UndetVar that) {
933            return new CheckUpperBounds(that, t);
934        }
935
936        @Override
937        void apply(InferenceContext inferenceContext, Warner warn) {
938            List<Type> boundList = uv.getBounds(InferenceBound.UPPER).stream()
939                    .collect(types.closureCollector(true, types::isSameType));
940            for (Type b2 : boundList) {
941                if (t == b2) continue;
942                    /* This wildcard check is temporary workaround. This code may need to be
943                     * revisited once spec bug JDK-7034922 is fixed.
944                     */
945                if (t != b2 && !t.hasTag(WILDCARD) && !b2.hasTag(WILDCARD)) {
946                    for (Pair<Type, Type> commonSupers : getParameterizedSupers(t, b2)) {
947                        List<Type> allParamsSuperBound1 = commonSupers.fst.allparams();
948                        List<Type> allParamsSuperBound2 = commonSupers.snd.allparams();
949                        while (allParamsSuperBound1.nonEmpty() && allParamsSuperBound2.nonEmpty()) {
950                            //traverse the list of all params comparing them
951                            if (!allParamsSuperBound1.head.hasTag(WILDCARD) &&
952                                    !allParamsSuperBound2.head.hasTag(WILDCARD)) {
953                                if (!isSameType(inferenceContext.asUndetVar(allParamsSuperBound1.head),
954                                        inferenceContext.asUndetVar(allParamsSuperBound2.head))) {
955                                    reportBoundError(uv, InferenceBound.UPPER);
956                                }
957                            }
958                            allParamsSuperBound1 = allParamsSuperBound1.tail;
959                            allParamsSuperBound2 = allParamsSuperBound2.tail;
960                        }
961                        Assert.check(allParamsSuperBound1.isEmpty() && allParamsSuperBound2.isEmpty());
962                    }
963                }
964            }
965        }
966    }
967
968    /**
969     * Perform propagation of bounds. Given a constraint of the kind {@code alpha <: T}, three
970     * kind of propagation occur:
971     *
972     * <li>T is copied into all matching bounds (i.e. lower/eq bounds) B of alpha such that B=beta (forward propagation)</li>
973     * <li>if T=beta, matching bounds (i.e. upper bounds) of beta are copied into alpha (backwards propagation)</li>
974     * <li>if T=beta, sets a symmetric bound on beta (i.e. beta :> alpha) (symmetric propagation) </li>
975     */
976    class PropagateBounds extends IncorporationAction {
977
978        InferenceBound ib;
979
980        public PropagateBounds(UndetVar uv, Type t, InferenceBound ib) {
981            super(uv, t);
982            this.ib = ib;
983        }
984
985        @Override
986        public IncorporationAction dup(UndetVar that) {
987            return new PropagateBounds(that, t, ib);
988        }
989
990        void apply(InferenceContext inferenceContext, Warner warner) {
991            Type undetT = inferenceContext.asUndetVar(t);
992            if (undetT.hasTag(UNDETVAR) && !((UndetVar)undetT).isCaptured()) {
993                UndetVar uv2 = (UndetVar)undetT;
994                //symmetric propagation
995                uv2.addBound(ib.complement(), uv, types);
996                //backwards propagation
997                for (InferenceBound ib2 : backwards()) {
998                    for (Type b : uv2.getBounds(ib2)) {
999                        uv.addBound(ib2, b, types);
1000                    }
1001                }
1002            }
1003            //forward propagation
1004            for (InferenceBound ib2 : forward()) {
1005                for (Type l : uv.getBounds(ib2)) {
1006                    Type undet = inferenceContext.asUndetVar(l);
1007                    if (undet.hasTag(TypeTag.UNDETVAR) && !((UndetVar)undet).isCaptured()) {
1008                        UndetVar uv2 = (UndetVar)undet;
1009                        uv2.addBound(ib, inferenceContext.asInstType(t), types);
1010                    }
1011                }
1012            }
1013        }
1014
1015        EnumSet<InferenceBound> forward() {
1016            return (ib == InferenceBound.EQ) ?
1017                    EnumSet.of(InferenceBound.EQ) : EnumSet.complementOf(EnumSet.of(ib));
1018        }
1019
1020        EnumSet<InferenceBound> backwards() {
1021            return (ib == InferenceBound.EQ) ?
1022                    EnumSet.allOf(InferenceBound.class) : EnumSet.of(ib);
1023        }
1024
1025        @Override
1026        public String toString() {
1027            return String.format("%s[undet=%s,t=%s,bound=%s]", getClass().getSimpleName(), uv.qtype, t, ib);
1028        }
1029    }
1030
1031    /**
1032     * This class models an incorporation engine. The engine is responsible for listening to
1033     * changes in inference variables and register incorporation actions accordingly.
1034     */
1035    abstract class AbstractIncorporationEngine implements UndetVarListener {
1036
1037        @Override
1038        public void varInstantiated(UndetVar uv) {
1039            uv.incorporationActions.addFirst(new SubstBounds(uv));
1040        }
1041
1042        @Override
1043        public void varBoundChanged(UndetVar uv, InferenceBound ib, Type bound, boolean update) {
1044            if (uv.isCaptured()) return;
1045            uv.incorporationActions.addAll(getIncorporationActions(uv, ib, bound, update));
1046        }
1047
1048        abstract List<IncorporationAction> getIncorporationActions(UndetVar uv, InferenceBound ib, Type t, boolean update);
1049    }
1050
1051    /**
1052     * A legacy incorporation engine. Used for source <= 7.
1053     */
1054    AbstractIncorporationEngine legacyEngine = new AbstractIncorporationEngine() {
1055
1056        List<IncorporationAction> getIncorporationActions(UndetVar uv, InferenceBound ib, Type t, boolean update) {
1057            ListBuffer<IncorporationAction> actions = new ListBuffer<>();
1058            Type inst = uv.getInst();
1059            if (inst != null) {
1060                actions.add(new CheckInst(uv, ib));
1061            }
1062            actions.add(new EqCheckLegacy(uv, t, ib));
1063            return actions.toList();
1064        }
1065    };
1066
1067    /**
1068     * The standard incorporation engine. Used for source >= 8.
1069     */
1070    AbstractIncorporationEngine graphEngine = new AbstractIncorporationEngine() {
1071
1072        @Override
1073        List<IncorporationAction> getIncorporationActions(UndetVar uv, InferenceBound ib, Type t, boolean update) {
1074            ListBuffer<IncorporationAction> actions = new ListBuffer<>();
1075            Type inst = uv.getInst();
1076            if (inst != null) {
1077                actions.add(new CheckInst(uv, ib));
1078            }
1079            actions.add(new CheckBounds(uv, t, ib));
1080
1081            if (update) {
1082                return actions.toList();
1083            }
1084
1085            if (ib == InferenceBound.UPPER) {
1086                actions.add(new CheckUpperBounds(uv, t));
1087            }
1088
1089            actions.add(new PropagateBounds(uv, t, ib));
1090
1091            return actions.toList();
1092        }
1093    };
1094
1095    /**
1096     * Get the incorporation engine to be used in this compilation.
1097     */
1098    AbstractIncorporationEngine incorporationEngine() {
1099        return allowGraphInference ? graphEngine : legacyEngine;
1100    }
1101
1102    /** max number of incorporation rounds. */
1103    static final int MAX_INCORPORATION_STEPS = 10000;
1104
1105    /**
1106     * Check bounds and perform incorporation.
1107     */
1108    void doIncorporation(InferenceContext inferenceContext, Warner warn) throws InferenceException {
1109        try {
1110            boolean progress = true;
1111            int round = 0;
1112            while (progress && round < MAX_INCORPORATION_STEPS) {
1113                progress = false;
1114                for (Type t : inferenceContext.undetvars) {
1115                    UndetVar uv = (UndetVar)t;
1116                    if (!uv.incorporationActions.isEmpty()) {
1117                        progress = true;
1118                        uv.incorporationActions.removeFirst().apply(inferenceContext, warn);
1119                    }
1120                }
1121                round++;
1122            }
1123        } finally {
1124            incorporationCache.clear();
1125        }
1126    }
1127
1128    /* If for two types t and s there is a least upper bound that contains
1129     * parameterized types G1, G2 ... Gn, then there exists supertypes of 't' of the form
1130     * G1<T1, ..., Tn>, G2<T1, ..., Tn>, ... Gn<T1, ..., Tn> and supertypes of 's' of the form
1131     * G1<S1, ..., Sn>, G2<S1, ..., Sn>, ... Gn<S1, ..., Sn> which will be returned by this method.
1132     * If no such common supertypes exists then an empty list is returned.
1133     *
1134     * As an example for the following input:
1135     *
1136     * t = java.util.ArrayList<java.lang.String>
1137     * s = java.util.List<T>
1138     *
1139     * we get this ouput (singleton list):
1140     *
1141     * [Pair[java.util.List<java.lang.String>,java.util.List<T>]]
1142     */
1143    private List<Pair<Type, Type>> getParameterizedSupers(Type t, Type s) {
1144        Type lubResult = types.lub(t, s);
1145        if (lubResult == syms.errType || lubResult == syms.botType) {
1146            return List.nil();
1147        }
1148        List<Type> supertypesToCheck = lubResult.isIntersection() ?
1149                ((IntersectionClassType)lubResult).getComponents() :
1150                List.of(lubResult);
1151        ListBuffer<Pair<Type, Type>> commonSupertypes = new ListBuffer<>();
1152        for (Type sup : supertypesToCheck) {
1153            if (sup.isParameterized()) {
1154                Type asSuperOfT = asSuper(t, sup);
1155                Type asSuperOfS = asSuper(s, sup);
1156                commonSupertypes.add(new Pair<>(asSuperOfT, asSuperOfS));
1157            }
1158        }
1159        return commonSupertypes.toList();
1160    }
1161    //where
1162        private Type asSuper(Type t, Type sup) {
1163            return (sup.hasTag(ARRAY)) ?
1164                    new ArrayType(asSuper(types.elemtype(t), types.elemtype(sup)), syms.arrayClass) :
1165                    types.asSuper(t, sup.tsym);
1166        }
1167
1168    boolean doIncorporationOp(IncorporationBinaryOpKind opKind, Type op1, Type op2, Warner warn) {
1169            IncorporationBinaryOp newOp = new IncorporationBinaryOp(opKind, op1, op2);
1170            Boolean res = incorporationCache.get(newOp);
1171            if (res == null) {
1172                incorporationCache.put(newOp, res = newOp.apply(warn));
1173            }
1174            return res;
1175        }
1176
1177    /**
1178     * Three kinds of basic operation are supported as part of an incorporation step:
1179     * (i) subtype check, (ii) same type check and (iii) bound addition (either
1180     * upper/lower/eq bound).
1181     */
1182    enum IncorporationBinaryOpKind {
1183        IS_SUBTYPE() {
1184            @Override
1185            boolean apply(Type op1, Type op2, Warner warn, Types types) {
1186                return types.isSubtypeUnchecked(op1, op2, warn);
1187            }
1188        },
1189        IS_SAME_TYPE() {
1190            @Override
1191            boolean apply(Type op1, Type op2, Warner warn, Types types) {
1192                return types.isSameType(op1, op2);
1193            }
1194        };
1195
1196        abstract boolean apply(Type op1, Type op2, Warner warn, Types types);
1197    }
1198
1199    /**
1200     * This class encapsulates a basic incorporation operation; incorporation
1201     * operations takes two type operands and a kind. Each operation performed
1202     * during an incorporation round is stored in a cache, so that operations
1203     * are not executed unnecessarily (which would potentially lead to adding
1204     * same bounds over and over).
1205     */
1206    class IncorporationBinaryOp {
1207
1208        IncorporationBinaryOpKind opKind;
1209        Type op1;
1210        Type op2;
1211
1212        IncorporationBinaryOp(IncorporationBinaryOpKind opKind, Type op1, Type op2) {
1213            this.opKind = opKind;
1214            this.op1 = op1;
1215            this.op2 = op2;
1216        }
1217
1218        @Override
1219        public boolean equals(Object o) {
1220            if (!(o instanceof IncorporationBinaryOp)) {
1221                return false;
1222            } else {
1223                IncorporationBinaryOp that = (IncorporationBinaryOp)o;
1224                return opKind == that.opKind &&
1225                        types.isSameType(op1, that.op1, true) &&
1226                        types.isSameType(op2, that.op2, true);
1227            }
1228        }
1229
1230        @Override
1231        public int hashCode() {
1232            int result = opKind.hashCode();
1233            result *= 127;
1234            result += types.hashCode(op1);
1235            result *= 127;
1236            result += types.hashCode(op2);
1237            return result;
1238        }
1239
1240        boolean apply(Warner warn) {
1241            return opKind.apply(op1, op2, warn, types);
1242        }
1243    }
1244
1245    /** an incorporation cache keeps track of all executed incorporation-related operations */
1246    Map<IncorporationBinaryOp, Boolean> incorporationCache = new HashMap<>();
1247
1248    protected static class BoundFilter implements Filter<Type> {
1249
1250        InferenceContext inferenceContext;
1251
1252        public BoundFilter(InferenceContext inferenceContext) {
1253            this.inferenceContext = inferenceContext;
1254        }
1255
1256        @Override
1257        public boolean accepts(Type t) {
1258            return !t.isErroneous() && !inferenceContext.free(t) &&
1259                    !t.hasTag(BOT);
1260        }
1261    }
1262
1263    /**
1264     * Incorporation error: mismatch between inferred type and given bound.
1265     */
1266    void reportInstError(UndetVar uv, InferenceBound ib) {
1267        reportInferenceError(
1268                String.format("inferred.do.not.conform.to.%s.bounds", StringUtils.toLowerCase(ib.name())),
1269                uv.getInst(),
1270                uv.getBounds(ib));
1271    }
1272
1273    /**
1274     * Incorporation error: mismatch between two (or more) bounds of same kind.
1275     */
1276    void reportBoundError(UndetVar uv, InferenceBound ib) {
1277        reportInferenceError(
1278                String.format("incompatible.%s.bounds", StringUtils.toLowerCase(ib.name())),
1279                uv.qtype,
1280                uv.getBounds(ib));
1281    }
1282
1283    /**
1284     * Incorporation error: mismatch between two (or more) bounds of different kinds.
1285     */
1286    void reportBoundError(UndetVar uv, InferenceBound ib1, InferenceBound ib2) {
1287        reportInferenceError(
1288                String.format("incompatible.%s.%s.bounds",
1289                        StringUtils.toLowerCase(ib1.name()),
1290                        StringUtils.toLowerCase(ib2.name())),
1291                uv.qtype,
1292                uv.getBounds(ib1),
1293                uv.getBounds(ib2));
1294    }
1295
1296    /**
1297     * Helper method: reports an inference error.
1298     */
1299    void reportInferenceError(String key, Object... args) {
1300        throw inferenceException.setMessage(key, args);
1301    }
1302    // </editor-fold>
1303
1304    // <editor-fold defaultstate="collapsed" desc="Inference engine">
1305    /**
1306     * Graph inference strategy - act as an input to the inference solver; a strategy is
1307     * composed of two ingredients: (i) find a node to solve in the inference graph,
1308     * and (ii) tell th engine when we are done fixing inference variables
1309     */
1310    interface GraphStrategy {
1311
1312        /**
1313         * A NodeNotFoundException is thrown whenever an inference strategy fails
1314         * to pick the next node to solve in the inference graph.
1315         */
1316        public static class NodeNotFoundException extends RuntimeException {
1317            private static final long serialVersionUID = 0;
1318
1319            InferenceGraph graph;
1320
1321            public NodeNotFoundException(InferenceGraph graph) {
1322                this.graph = graph;
1323            }
1324        }
1325        /**
1326         * Pick the next node (leaf) to solve in the graph
1327         */
1328        Node pickNode(InferenceGraph g) throws NodeNotFoundException;
1329        /**
1330         * Is this the last step?
1331         */
1332        boolean done();
1333    }
1334
1335    /**
1336     * Simple solver strategy class that locates all leaves inside a graph
1337     * and picks the first leaf as the next node to solve
1338     */
1339    abstract class LeafSolver implements GraphStrategy {
1340        public Node pickNode(InferenceGraph g) {
1341            if (g.nodes.isEmpty()) {
1342                //should not happen
1343                throw new NodeNotFoundException(g);
1344            }
1345            return g.nodes.get(0);
1346        }
1347    }
1348
1349    /**
1350     * This solver uses an heuristic to pick the best leaf - the heuristic
1351     * tries to select the node that has maximal probability to contain one
1352     * or more inference variables in a given list
1353     */
1354    abstract class BestLeafSolver extends LeafSolver {
1355
1356        /** list of ivars of which at least one must be solved */
1357        List<Type> varsToSolve;
1358
1359        BestLeafSolver(List<Type> varsToSolve) {
1360            this.varsToSolve = varsToSolve;
1361        }
1362
1363        /**
1364         * Computes a path that goes from a given node to the leafs in the graph.
1365         * Typically this will start from a node containing a variable in
1366         * {@code varsToSolve}. For any given path, the cost is computed as the total
1367         * number of type-variables that should be eagerly instantiated across that path.
1368         */
1369        Pair<List<Node>, Integer> computeTreeToLeafs(Node n) {
1370            Pair<List<Node>, Integer> cachedPath = treeCache.get(n);
1371            if (cachedPath == null) {
1372                //cache miss
1373                if (n.isLeaf()) {
1374                    //if leaf, stop
1375                    cachedPath = new Pair<>(List.of(n), n.data.length());
1376                } else {
1377                    //if non-leaf, proceed recursively
1378                    Pair<List<Node>, Integer> path = new Pair<>(List.of(n), n.data.length());
1379                    for (Node n2 : n.getAllDependencies()) {
1380                        if (n2 == n) continue;
1381                        Pair<List<Node>, Integer> subpath = computeTreeToLeafs(n2);
1382                        path = new Pair<>(path.fst.prependList(subpath.fst),
1383                                          path.snd + subpath.snd);
1384                    }
1385                    cachedPath = path;
1386                }
1387                //save results in cache
1388                treeCache.put(n, cachedPath);
1389            }
1390            return cachedPath;
1391        }
1392
1393        /** cache used to avoid redundant computation of tree costs */
1394        final Map<Node, Pair<List<Node>, Integer>> treeCache = new HashMap<>();
1395
1396        /** constant value used to mark non-existent paths */
1397        final Pair<List<Node>, Integer> noPath = new Pair<>(null, Integer.MAX_VALUE);
1398
1399        /**
1400         * Pick the leaf that minimize cost
1401         */
1402        @Override
1403        public Node pickNode(final InferenceGraph g) {
1404            treeCache.clear(); //graph changes at every step - cache must be cleared
1405            Pair<List<Node>, Integer> bestPath = noPath;
1406            for (Node n : g.nodes) {
1407                if (!Collections.disjoint(n.data, varsToSolve)) {
1408                    Pair<List<Node>, Integer> path = computeTreeToLeafs(n);
1409                    //discard all paths containing at least a node in the
1410                    //closure computed above
1411                    if (path.snd < bestPath.snd) {
1412                        bestPath = path;
1413                    }
1414                }
1415            }
1416            if (bestPath == noPath) {
1417                //no path leads there
1418                throw new NodeNotFoundException(g);
1419            }
1420            return bestPath.fst.head;
1421        }
1422    }
1423
1424    /**
1425     * The inference process can be thought of as a sequence of steps. Each step
1426     * instantiates an inference variable using a subset of the inference variable
1427     * bounds, if certain condition are met. Decisions such as the sequence in which
1428     * steps are applied, or which steps are to be applied are left to the inference engine.
1429     */
1430    enum InferenceStep {
1431
1432        /**
1433         * Instantiate an inference variables using one of its (ground) equality
1434         * constraints
1435         */
1436        EQ(InferenceBound.EQ) {
1437            @Override
1438            Type solve(UndetVar uv, InferenceContext inferenceContext) {
1439                return filterBounds(uv, inferenceContext).head;
1440            }
1441        },
1442        /**
1443         * Instantiate an inference variables using its (ground) lower bounds. Such
1444         * bounds are merged together using lub().
1445         */
1446        LOWER(InferenceBound.LOWER) {
1447            @Override
1448            Type solve(UndetVar uv, InferenceContext inferenceContext) {
1449                Infer infer = inferenceContext.infer;
1450                List<Type> lobounds = filterBounds(uv, inferenceContext);
1451                //note: lobounds should have at least one element
1452                Type owntype = lobounds.tail.tail == null  ? lobounds.head : infer.types.lub(lobounds);
1453                if (owntype.isPrimitive() || owntype.hasTag(ERROR)) {
1454                    throw infer.inferenceException
1455                        .setMessage("no.unique.minimal.instance.exists",
1456                                    uv.qtype, lobounds);
1457                } else {
1458                    return owntype;
1459                }
1460            }
1461        },
1462        /**
1463         * Infer uninstantiated/unbound inference variables occurring in 'throws'
1464         * clause as RuntimeException
1465         */
1466        THROWS(InferenceBound.UPPER) {
1467            @Override
1468            public boolean accepts(UndetVar t, InferenceContext inferenceContext) {
1469                if (!t.isThrows()) {
1470                    //not a throws undet var
1471                    return false;
1472                }
1473                Types types = inferenceContext.types;
1474                Symtab syms = inferenceContext.infer.syms;
1475                return t.getBounds(InferenceBound.UPPER).stream()
1476                        .filter(b -> !inferenceContext.free(b))
1477                        .allMatch(u -> types.isSubtype(syms.runtimeExceptionType, u));
1478            }
1479
1480            @Override
1481            Type solve(UndetVar uv, InferenceContext inferenceContext) {
1482                return inferenceContext.infer.syms.runtimeExceptionType;
1483            }
1484        },
1485        /**
1486         * Instantiate an inference variables using its (ground) upper bounds. Such
1487         * bounds are merged together using glb().
1488         */
1489        UPPER(InferenceBound.UPPER) {
1490            @Override
1491            Type solve(UndetVar uv, InferenceContext inferenceContext) {
1492                Infer infer = inferenceContext.infer;
1493                List<Type> hibounds = filterBounds(uv, inferenceContext);
1494                //note: hibounds should have at least one element
1495                Type owntype = hibounds.tail.tail == null  ? hibounds.head : infer.types.glb(hibounds);
1496                if (owntype.isPrimitive() || owntype.hasTag(ERROR)) {
1497                    throw infer.inferenceException
1498                        .setMessage("no.unique.maximal.instance.exists",
1499                                    uv.qtype, hibounds);
1500                } else {
1501                    return owntype;
1502                }
1503            }
1504        },
1505        /**
1506         * Like the former; the only difference is that this step can only be applied
1507         * if all upper bounds are ground.
1508         */
1509        UPPER_LEGACY(InferenceBound.UPPER) {
1510            @Override
1511            public boolean accepts(UndetVar t, InferenceContext inferenceContext) {
1512                return !inferenceContext.free(t.getBounds(ib)) && !t.isCaptured();
1513            }
1514
1515            @Override
1516            Type solve(UndetVar uv, InferenceContext inferenceContext) {
1517                return UPPER.solve(uv, inferenceContext);
1518            }
1519        },
1520        /**
1521         * Like the former; the only difference is that this step can only be applied
1522         * if all upper/lower bounds are ground.
1523         */
1524        CAPTURED(InferenceBound.UPPER) {
1525            @Override
1526            public boolean accepts(UndetVar t, InferenceContext inferenceContext) {
1527                return t.isCaptured() &&
1528                        !inferenceContext.free(t.getBounds(InferenceBound.UPPER, InferenceBound.LOWER));
1529            }
1530
1531            @Override
1532            Type solve(UndetVar uv, InferenceContext inferenceContext) {
1533                Infer infer = inferenceContext.infer;
1534                Type upper = UPPER.filterBounds(uv, inferenceContext).nonEmpty() ?
1535                        UPPER.solve(uv, inferenceContext) :
1536                        infer.syms.objectType;
1537                Type lower = LOWER.filterBounds(uv, inferenceContext).nonEmpty() ?
1538                        LOWER.solve(uv, inferenceContext) :
1539                        infer.syms.botType;
1540                CapturedType prevCaptured = (CapturedType)uv.qtype;
1541                return new CapturedType(prevCaptured.tsym.name, prevCaptured.tsym.owner,
1542                                        upper, lower, prevCaptured.wildcard);
1543            }
1544        };
1545
1546        final InferenceBound ib;
1547
1548        InferenceStep(InferenceBound ib) {
1549            this.ib = ib;
1550        }
1551
1552        /**
1553         * Find an instantiated type for a given inference variable within
1554         * a given inference context
1555         */
1556        abstract Type solve(UndetVar uv, InferenceContext inferenceContext);
1557
1558        /**
1559         * Can the inference variable be instantiated using this step?
1560         */
1561        public boolean accepts(UndetVar t, InferenceContext inferenceContext) {
1562            return filterBounds(t, inferenceContext).nonEmpty() && !t.isCaptured();
1563        }
1564
1565        /**
1566         * Return the subset of ground bounds in a given bound set (i.e. eq/lower/upper)
1567         */
1568        List<Type> filterBounds(UndetVar uv, InferenceContext inferenceContext) {
1569            return Type.filter(uv.getBounds(ib), new BoundFilter(inferenceContext));
1570        }
1571    }
1572
1573    /**
1574     * This enumeration defines the sequence of steps to be applied when the
1575     * solver works in legacy mode. The steps in this enumeration reflect
1576     * the behavior of old inference routine (see JLS SE 7 15.12.2.7/15.12.2.8).
1577     */
1578    enum LegacyInferenceSteps {
1579
1580        EQ_LOWER(EnumSet.of(InferenceStep.EQ, InferenceStep.LOWER)),
1581        EQ_UPPER(EnumSet.of(InferenceStep.EQ, InferenceStep.UPPER_LEGACY));
1582
1583        final EnumSet<InferenceStep> steps;
1584
1585        LegacyInferenceSteps(EnumSet<InferenceStep> steps) {
1586            this.steps = steps;
1587        }
1588    }
1589
1590    /**
1591     * This enumeration defines the sequence of steps to be applied when the
1592     * graph solver is used. This order is defined so as to maximize compatibility
1593     * w.r.t. old inference routine (see JLS SE 7 15.12.2.7/15.12.2.8).
1594     */
1595    enum GraphInferenceSteps {
1596
1597        EQ(EnumSet.of(InferenceStep.EQ)),
1598        EQ_LOWER(EnumSet.of(InferenceStep.EQ, InferenceStep.LOWER)),
1599        EQ_LOWER_THROWS_UPPER_CAPTURED(EnumSet.of(InferenceStep.EQ, InferenceStep.LOWER, InferenceStep.UPPER, InferenceStep.THROWS, InferenceStep.CAPTURED));
1600
1601        final EnumSet<InferenceStep> steps;
1602
1603        GraphInferenceSteps(EnumSet<InferenceStep> steps) {
1604            this.steps = steps;
1605        }
1606    }
1607
1608    /**
1609     * There are two kinds of dependencies between inference variables. The basic
1610     * kind of dependency (or bound dependency) arises when a variable mention
1611     * another variable in one of its bounds. There's also a more subtle kind
1612     * of dependency that arises when a variable 'might' lead to better constraints
1613     * on another variable (this is typically the case with variables holding up
1614     * stuck expressions).
1615     */
1616    enum DependencyKind implements GraphUtils.DependencyKind {
1617
1618        /** bound dependency */
1619        BOUND("dotted"),
1620        /** stuck dependency */
1621        STUCK("dashed");
1622
1623        final String dotSyle;
1624
1625        private DependencyKind(String dotSyle) {
1626            this.dotSyle = dotSyle;
1627        }
1628    }
1629
1630    /**
1631     * This is the graph inference solver - the solver organizes all inference variables in
1632     * a given inference context by bound dependencies - in the general case, such dependencies
1633     * would lead to a cyclic directed graph (hence the name); the dependency info is used to build
1634     * an acyclic graph, where all cyclic variables are bundled together. An inference
1635     * step corresponds to solving a node in the acyclic graph - this is done by
1636     * relying on a given strategy (see GraphStrategy).
1637     */
1638    class GraphSolver {
1639
1640        InferenceContext inferenceContext;
1641        Warner warn;
1642
1643        GraphSolver(InferenceContext inferenceContext, Warner warn) {
1644            this.inferenceContext = inferenceContext;
1645            this.warn = warn;
1646        }
1647
1648        /**
1649         * Solve variables in a given inference context. The amount of variables
1650         * to be solved, and the way in which the underlying acyclic graph is explored
1651         * depends on the selected solver strategy.
1652         */
1653        void solve(GraphStrategy sstrategy) {
1654            doIncorporation(inferenceContext, warn); //initial propagation of bounds
1655            InferenceGraph inferenceGraph = new InferenceGraph();
1656            while (!sstrategy.done()) {
1657                if (dependenciesFolder != null) {
1658                    //add this graph to the pending queue
1659                    pendingGraphs = pendingGraphs.prepend(inferenceGraph.toDot());
1660                }
1661                InferenceGraph.Node nodeToSolve = sstrategy.pickNode(inferenceGraph);
1662                List<Type> varsToSolve = List.from(nodeToSolve.data);
1663                List<Type> saved_undet = inferenceContext.save();
1664                try {
1665                    //repeat until all variables are solved
1666                    outer: while (Type.containsAny(inferenceContext.restvars(), varsToSolve)) {
1667                        //for each inference phase
1668                        for (GraphInferenceSteps step : GraphInferenceSteps.values()) {
1669                            if (inferenceContext.solveBasic(varsToSolve, step.steps).nonEmpty()) {
1670                                doIncorporation(inferenceContext, warn);
1671                                continue outer;
1672                            }
1673                        }
1674                        //no progress
1675                        throw inferenceException.setMessage();
1676                    }
1677                }
1678                catch (InferenceException ex) {
1679                    //did we fail because of interdependent ivars?
1680                    inferenceContext.rollback(saved_undet);
1681                    instantiateAsUninferredVars(varsToSolve, inferenceContext);
1682                    doIncorporation(inferenceContext, warn);
1683                }
1684                inferenceGraph.deleteNode(nodeToSolve);
1685            }
1686        }
1687
1688        /**
1689         * The dependencies between the inference variables that need to be solved
1690         * form a (possibly cyclic) graph. This class reduces the original dependency graph
1691         * to an acyclic version, where cyclic nodes are folded into a single 'super node'.
1692         */
1693        class InferenceGraph {
1694
1695            /**
1696             * This class represents a node in the graph. Each node corresponds
1697             * to an inference variable and has edges (dependencies) on other
1698             * nodes. The node defines an entry point that can be used to receive
1699             * updates on the structure of the graph this node belongs to (used to
1700             * keep dependencies in sync).
1701             */
1702            class Node extends GraphUtils.TarjanNode<ListBuffer<Type>, Node> implements DottableNode<ListBuffer<Type>, Node> {
1703
1704                /** node dependencies */
1705                Set<Node> deps;
1706
1707                Node(Type ivar) {
1708                    super(ListBuffer.of(ivar));
1709                    this.deps = new HashSet<>();
1710                }
1711
1712                @Override
1713                public GraphUtils.DependencyKind[] getSupportedDependencyKinds() {
1714                    return new GraphUtils.DependencyKind[] { DependencyKind.BOUND };
1715                }
1716
1717                public Iterable<? extends Node> getAllDependencies() {
1718                    return deps;
1719                }
1720
1721                @Override
1722                public Collection<? extends Node> getDependenciesByKind(GraphUtils.DependencyKind dk) {
1723                    if (dk == DependencyKind.BOUND) {
1724                        return deps;
1725                    } else {
1726                        throw new IllegalStateException();
1727                    }
1728                }
1729
1730                /**
1731                 * Adds dependency with given kind.
1732                 */
1733                protected void addDependency(Node depToAdd) {
1734                    deps.add(depToAdd);
1735                }
1736
1737                /**
1738                 * Add multiple dependencies of same given kind.
1739                 */
1740                protected void addDependencies(Set<Node> depsToAdd) {
1741                    for (Node n : depsToAdd) {
1742                        addDependency(n);
1743                    }
1744                }
1745
1746                /**
1747                 * Remove a dependency, regardless of its kind.
1748                 */
1749                protected boolean removeDependency(Node n) {
1750                    return deps.remove(n);
1751                }
1752
1753                /**
1754                 * Is this node a leaf? This means either the node has no dependencies,
1755                 * or it just has self-dependencies.
1756                 */
1757                protected boolean isLeaf() {
1758                    //no deps, or only one self dep
1759                    if (deps.isEmpty()) return true;
1760                    for (Node n : deps) {
1761                        if (n != this) {
1762                            return false;
1763                        }
1764                    }
1765                    return true;
1766                }
1767
1768                /**
1769                 * Merge this node with another node, acquiring its dependencies.
1770                 * This routine is used to merge all cyclic node together and
1771                 * form an acyclic graph.
1772                 */
1773                protected void mergeWith(List<? extends Node> nodes) {
1774                    for (Node n : nodes) {
1775                        Assert.check(n.data.length() == 1, "Attempt to merge a compound node!");
1776                        data.appendList(n.data);
1777                        addDependencies(n.deps);
1778                    }
1779                    //update deps
1780                    Set<Node> deps2 = new HashSet<>();
1781                    for (Node d : deps) {
1782                        if (data.contains(d.data.first())) {
1783                            deps2.add(this);
1784                        } else {
1785                            deps2.add(d);
1786                        }
1787                    }
1788                    deps = deps2;
1789                }
1790
1791                /**
1792                 * Notify all nodes that something has changed in the graph
1793                 * topology.
1794                 */
1795                private void graphChanged(Node from, Node to) {
1796                    if (removeDependency(from)) {
1797                        if (to != null) {
1798                            addDependency(to);
1799                        }
1800                    }
1801                }
1802
1803                @Override
1804                public Properties nodeAttributes() {
1805                    Properties p = new Properties();
1806                    p.put("label", "\"" + toString() + "\"");
1807                    return p;
1808                }
1809
1810                @Override
1811                public Properties dependencyAttributes(Node sink, GraphUtils.DependencyKind dk) {
1812                    Properties p = new Properties();
1813                    p.put("style", ((DependencyKind)dk).dotSyle);
1814                    StringBuilder buf = new StringBuilder();
1815                    String sep = "";
1816                    for (Type from : data) {
1817                        UndetVar uv = (UndetVar)inferenceContext.asUndetVar(from);
1818                        for (Type bound : uv.getBounds(InferenceBound.values())) {
1819                            if (bound.containsAny(List.from(sink.data))) {
1820                                buf.append(sep);
1821                                buf.append(bound);
1822                                sep = ",";
1823                            }
1824                        }
1825                    }
1826                    p.put("label", "\"" + buf.toString() + "\"");
1827                    return p;
1828                }
1829            }
1830
1831            /** the nodes in the inference graph */
1832            ArrayList<Node> nodes;
1833
1834            InferenceGraph() {
1835                initNodes();
1836            }
1837
1838            /**
1839             * Basic lookup helper for retrieving a graph node given an inference
1840             * variable type.
1841             */
1842            public Node findNode(Type t) {
1843                for (Node n : nodes) {
1844                    if (n.data.contains(t)) {
1845                        return n;
1846                    }
1847                }
1848                return null;
1849            }
1850
1851            /**
1852             * Delete a node from the graph. This update the underlying structure
1853             * of the graph (including dependencies) via listeners updates.
1854             */
1855            public void deleteNode(Node n) {
1856                Assert.check(nodes.contains(n));
1857                nodes.remove(n);
1858                notifyUpdate(n, null);
1859            }
1860
1861            /**
1862             * Notify all nodes of a change in the graph. If the target node is
1863             * {@code null} the source node is assumed to be removed.
1864             */
1865            void notifyUpdate(Node from, Node to) {
1866                for (Node n : nodes) {
1867                    n.graphChanged(from, to);
1868                }
1869            }
1870
1871            /**
1872             * Create the graph nodes. First a simple node is created for every inference
1873             * variables to be solved. Then Tarjan is used to found all connected components
1874             * in the graph. For each component containing more than one node, a super node is
1875             * created, effectively replacing the original cyclic nodes.
1876             */
1877            void initNodes() {
1878                //add nodes
1879                nodes = new ArrayList<>();
1880                for (Type t : inferenceContext.restvars()) {
1881                    nodes.add(new Node(t));
1882                }
1883                //add dependencies
1884                for (Node n_i : nodes) {
1885                    Type i = n_i.data.first();
1886                    for (Node n_j : nodes) {
1887                        Type j = n_j.data.first();
1888                        UndetVar uv_i = (UndetVar)inferenceContext.asUndetVar(i);
1889                        if (Type.containsAny(uv_i.getBounds(InferenceBound.values()), List.of(j))) {
1890                            //update i's bound dependencies
1891                            n_i.addDependency(n_j);
1892                        }
1893                    }
1894                }
1895                //merge cyclic nodes
1896                ArrayList<Node> acyclicNodes = new ArrayList<>();
1897                for (List<? extends Node> conSubGraph : GraphUtils.tarjan(nodes)) {
1898                    if (conSubGraph.length() > 1) {
1899                        Node root = conSubGraph.head;
1900                        root.mergeWith(conSubGraph.tail);
1901                        for (Node n : conSubGraph) {
1902                            notifyUpdate(n, root);
1903                        }
1904                    }
1905                    acyclicNodes.add(conSubGraph.head);
1906                }
1907                nodes = acyclicNodes;
1908            }
1909
1910            /**
1911             * Debugging: dot representation of this graph
1912             */
1913            String toDot() {
1914                StringBuilder buf = new StringBuilder();
1915                for (Type t : inferenceContext.undetvars) {
1916                    UndetVar uv = (UndetVar)t;
1917                    buf.append(String.format("var %s - upper bounds = %s, lower bounds = %s, eq bounds = %s\\n",
1918                            uv.qtype, uv.getBounds(InferenceBound.UPPER), uv.getBounds(InferenceBound.LOWER),
1919                            uv.getBounds(InferenceBound.EQ)));
1920                }
1921                return GraphUtils.toDot(nodes, "inferenceGraph" + hashCode(), buf.toString());
1922            }
1923        }
1924    }
1925    // </editor-fold>
1926
1927    // <editor-fold defaultstate="collapsed" desc="Inference context">
1928    /**
1929     * Functional interface for defining inference callbacks. Certain actions
1930     * (i.e. subtyping checks) might need to be redone after all inference variables
1931     * have been fixed.
1932     */
1933    interface FreeTypeListener {
1934        void typesInferred(InferenceContext inferenceContext);
1935    }
1936
1937    final InferenceContext emptyContext;
1938    // </editor-fold>
1939}
1940