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