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