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