Infer.java revision 2855:0bc7ba363b7f
1/* 2 * Copyright (c) 1999, 2014, 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.TypeMapping; 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.Infer.GraphSolver.InferenceGraph; 42import com.sun.tools.javac.comp.Infer.GraphSolver.InferenceGraph.Node; 43import com.sun.tools.javac.comp.Resolve.InapplicableMethodException; 44import com.sun.tools.javac.comp.Resolve.VerboseResolutionMode; 45 46import java.io.File; 47import java.io.FileWriter; 48import java.io.IOException; 49import java.util.ArrayList; 50import java.util.Collection; 51import java.util.Collections; 52import java.util.EnumMap; 53import java.util.EnumSet; 54import java.util.HashMap; 55import java.util.HashSet; 56import java.util.LinkedHashSet; 57import java.util.Map; 58import java.util.Properties; 59import java.util.Set; 60 61import static com.sun.tools.javac.code.TypeTag.*; 62 63/** Helper class for type parameter inference, used by the attribution phase. 64 * 65 * <p><b>This is NOT part of any supported API. 66 * If you write code that depends on this, you do so at your own risk. 67 * This code and its internal interfaces are subject to change or 68 * deletion without notice.</b> 69 */ 70public class Infer { 71 protected static final Context.Key<Infer> inferKey = new Context.Key<>(); 72 73 Resolve rs; 74 Check chk; 75 Symtab syms; 76 Types types; 77 JCDiagnostic.Factory diags; 78 Log log; 79 80 /** should the graph solver be used? */ 81 boolean allowGraphInference; 82 83 /** 84 * folder in which the inference dependency graphs should be written. 85 */ 86 final private String dependenciesFolder; 87 88 /** 89 * List of graphs awaiting to be dumped to a file. 90 */ 91 private List<String> pendingGraphs; 92 93 public static Infer instance(Context context) { 94 Infer instance = context.get(inferKey); 95 if (instance == null) 96 instance = new Infer(context); 97 return instance; 98 } 99 100 protected Infer(Context context) { 101 context.put(inferKey, this); 102 103 rs = Resolve.instance(context); 104 chk = Check.instance(context); 105 syms = Symtab.instance(context); 106 types = Types.instance(context); 107 diags = JCDiagnostic.Factory.instance(context); 108 log = Log.instance(context); 109 inferenceException = new InferenceException(diags); 110 Options options = Options.instance(context); 111 allowGraphInference = Source.instance(context).allowGraphInference() 112 && options.isUnset("useLegacyInference"); 113 dependenciesFolder = options.get("dumpInferenceGraphsTo"); 114 pendingGraphs = List.nil(); 115 } 116 117 /** A value for prototypes that admit any type, including polymorphic ones. */ 118 public static final Type anyPoly = new JCNoType(); 119 120 /** 121 * This exception class is design to store a list of diagnostics corresponding 122 * to inference errors that can arise during a method applicability check. 123 */ 124 public static class InferenceException extends InapplicableMethodException { 125 private static final long serialVersionUID = 0; 126 127 List<JCDiagnostic> messages = List.nil(); 128 129 InferenceException(JCDiagnostic.Factory diags) { 130 super(diags); 131 } 132 133 @Override 134 InapplicableMethodException setMessage() { 135 //no message to set 136 return this; 137 } 138 139 @Override 140 InapplicableMethodException setMessage(JCDiagnostic diag) { 141 messages = messages.append(diag); 142 return this; 143 } 144 145 @Override 146 public JCDiagnostic getDiagnostic() { 147 return messages.head; 148 } 149 150 void clear() { 151 messages = List.nil(); 152 } 153 } 154 155 protected final InferenceException inferenceException; 156 157 // <editor-fold defaultstate="collapsed" desc="Inference routines"> 158 /** 159 * Main inference entry point - instantiate a generic method type 160 * using given argument types and (possibly) an expected target-type. 161 */ 162 Type instantiateMethod( Env<AttrContext> env, 163 List<Type> tvars, 164 MethodType mt, 165 Attr.ResultInfo resultInfo, 166 MethodSymbol msym, 167 List<Type> argtypes, 168 boolean allowBoxing, 169 boolean useVarargs, 170 Resolve.MethodResolutionContext resolveContext, 171 Warner warn) throws InferenceException { 172 //-System.err.println("instantiateMethod(" + tvars + ", " + mt + ", " + argtypes + ")"); //DEBUG 173 final InferenceContext inferenceContext = new InferenceContext(tvars); //B0 174 inferenceException.clear(); 175 try { 176 DeferredAttr.DeferredAttrContext deferredAttrContext = 177 resolveContext.deferredAttrContext(msym, inferenceContext, resultInfo, warn); 178 179 resolveContext.methodCheck.argumentsAcceptable(env, deferredAttrContext, //B2 180 argtypes, mt.getParameterTypes(), warn); 181 if (allowGraphInference && 182 resultInfo != null && 183 !warn.hasNonSilentLint(Lint.LintCategory.UNCHECKED)) { 184 //inject return constraints earlier 185 checkWithinBounds(inferenceContext, warn); //propagation 186 Type newRestype = generateReturnConstraints(env.tree, resultInfo, //B3 187 mt, inferenceContext); 188 mt = (MethodType)types.createMethodTypeWithReturn(mt, newRestype); 189 //propagate outwards if needed 190 if (resultInfo.checkContext.inferenceContext().free(resultInfo.pt)) { 191 //propagate inference context outwards and exit 192 inferenceContext.dupTo(resultInfo.checkContext.inferenceContext()); 193 deferredAttrContext.complete(); 194 return mt; 195 } 196 } 197 198 deferredAttrContext.complete(); 199 200 // minimize as yet undetermined type variables 201 if (allowGraphInference) { 202 inferenceContext.solve(warn); 203 } else { 204 inferenceContext.solveLegacy(true, warn, LegacyInferenceSteps.EQ_LOWER.steps); //minimizeInst 205 } 206 207 mt = (MethodType)inferenceContext.asInstType(mt); 208 209 if (!allowGraphInference && 210 inferenceContext.restvars().nonEmpty() && 211 resultInfo != null && 212 !warn.hasNonSilentLint(Lint.LintCategory.UNCHECKED)) { 213 generateReturnConstraints(env.tree, resultInfo, mt, inferenceContext); 214 inferenceContext.solveLegacy(false, warn, LegacyInferenceSteps.EQ_UPPER.steps); //maximizeInst 215 mt = (MethodType)inferenceContext.asInstType(mt); 216 } 217 218 if (resultInfo != null && rs.verboseResolutionMode.contains(VerboseResolutionMode.DEFERRED_INST)) { 219 log.note(env.tree.pos, "deferred.method.inst", msym, mt, resultInfo.pt); 220 } 221 222 // return instantiated version of method type 223 return mt; 224 } finally { 225 if (resultInfo != null || !allowGraphInference) { 226 inferenceContext.notifyChange(); 227 } else { 228 inferenceContext.notifyChange(inferenceContext.boundedVars()); 229 } 230 if (resultInfo == null) { 231 /* if the is no result info then we can clear the capture types 232 * cache without affecting any result info check 233 */ 234 inferenceContext.captureTypeCache.clear(); 235 } 236 dumpGraphsIfNeeded(env.tree, msym, resolveContext); 237 } 238 } 239 240 private void dumpGraphsIfNeeded(DiagnosticPosition pos, Symbol msym, Resolve.MethodResolutionContext rsContext) { 241 int round = 0; 242 try { 243 for (String graph : pendingGraphs.reverse()) { 244 Assert.checkNonNull(dependenciesFolder); 245 Name name = msym.name == msym.name.table.names.init ? 246 msym.owner.name : msym.name; 247 String filename = String.format("%s@%s[mode=%s,step=%s]_%d.dot", 248 name, 249 pos.getStartPosition(), 250 rsContext.attrMode(), 251 rsContext.step, 252 round); 253 File dotFile = new File(dependenciesFolder, filename); 254 try (FileWriter fw = new FileWriter(dotFile)) { 255 fw.append(graph); 256 } 257 round++; 258 } 259 } catch (IOException ex) { 260 Assert.error("Error occurred when dumping inference graph: " + ex.getMessage()); 261 } finally { 262 pendingGraphs = List.nil(); 263 } 264 } 265 266 /** 267 * Generate constraints from the generic method's return type. If the method 268 * call occurs in a context where a type T is expected, use the expected 269 * type to derive more constraints on the generic method inference variables. 270 */ 271 Type generateReturnConstraints(JCTree tree, Attr.ResultInfo resultInfo, 272 MethodType mt, InferenceContext inferenceContext) { 273 InferenceContext rsInfoInfContext = resultInfo.checkContext.inferenceContext(); 274 Type from = mt.getReturnType(); 275 if (mt.getReturnType().containsAny(inferenceContext.inferencevars) && 276 rsInfoInfContext != emptyContext) { 277 from = types.capture(from); 278 //add synthetic captured ivars 279 for (Type t : from.getTypeArguments()) { 280 if (t.hasTag(TYPEVAR) && ((TypeVar)t).isCaptured()) { 281 inferenceContext.addVar((TypeVar)t); 282 } 283 } 284 } 285 Type qtype = inferenceContext.asUndetVar(from); 286 Type to = resultInfo.pt; 287 288 if (qtype.hasTag(VOID)) { 289 to = syms.voidType; 290 } else if (to.hasTag(NONE)) { 291 to = from.isPrimitive() ? from : syms.objectType; 292 } else if (qtype.hasTag(UNDETVAR)) { 293 if (resultInfo.pt.isReference()) { 294 to = generateReturnConstraintsUndetVarToReference( 295 tree, (UndetVar)qtype, to, resultInfo, inferenceContext); 296 } else { 297 if (to.isPrimitive()) { 298 to = generateReturnConstraintsPrimitive(tree, (UndetVar)qtype, to, 299 resultInfo, inferenceContext); 300 } 301 } 302 } 303 Assert.check(allowGraphInference || !rsInfoInfContext.free(to), 304 "legacy inference engine cannot handle constraints on both sides of a subtyping assertion"); 305 //we need to skip capture? 306 Warner retWarn = new Warner(); 307 if (!resultInfo.checkContext.compatible(qtype, rsInfoInfContext.asUndetVar(to), retWarn) || 308 //unchecked conversion is not allowed in source 7 mode 309 (!allowGraphInference && retWarn.hasLint(Lint.LintCategory.UNCHECKED))) { 310 throw inferenceException 311 .setMessage("infer.no.conforming.instance.exists", 312 inferenceContext.restvars(), mt.getReturnType(), to); 313 } 314 return from; 315 } 316 317 private Type generateReturnConstraintsPrimitive(JCTree tree, UndetVar from, 318 Type to, Attr.ResultInfo resultInfo, InferenceContext inferenceContext) { 319 if (!allowGraphInference) { 320 //if legacy, just return boxed type 321 return types.boxedClass(to).type; 322 } 323 //if graph inference we need to skip conflicting boxed bounds... 324 for (Type t : from.getBounds(InferenceBound.EQ, InferenceBound.UPPER, 325 InferenceBound.LOWER)) { 326 Type boundAsPrimitive = types.unboxedType(t); 327 if (boundAsPrimitive == null || boundAsPrimitive.hasTag(NONE)) { 328 continue; 329 } 330 return generateReferenceToTargetConstraint(tree, from, to, 331 resultInfo, inferenceContext); 332 } 333 return types.boxedClass(to).type; 334 } 335 336 private Type generateReturnConstraintsUndetVarToReference(JCTree tree, 337 UndetVar from, Type to, Attr.ResultInfo resultInfo, 338 InferenceContext inferenceContext) { 339 Type captureOfTo = types.capture(to); 340 /* T is a reference type, but is not a wildcard-parameterized type, and either 341 */ 342 if (captureOfTo == to) { //not a wildcard parameterized type 343 /* i) B2 contains a bound of one of the forms alpha = S or S <: alpha, 344 * where S is a wildcard-parameterized type, or 345 */ 346 for (Type t : from.getBounds(InferenceBound.EQ, InferenceBound.LOWER)) { 347 Type captureOfBound = types.capture(t); 348 if (captureOfBound != t) { 349 return generateReferenceToTargetConstraint(tree, from, to, 350 resultInfo, inferenceContext); 351 } 352 } 353 354 /* ii) B2 contains two bounds of the forms S1 <: alpha and S2 <: alpha, 355 * where S1 and S2 have supertypes that are two different 356 * parameterizations of the same generic class or interface. 357 */ 358 for (Type aLowerBound : from.getBounds(InferenceBound.LOWER)) { 359 for (Type anotherLowerBound : from.getBounds(InferenceBound.LOWER)) { 360 if (aLowerBound != anotherLowerBound && 361 !inferenceContext.free(aLowerBound) && 362 !inferenceContext.free(anotherLowerBound) && 363 commonSuperWithDiffParameterization(aLowerBound, anotherLowerBound)) { 364 return generateReferenceToTargetConstraint(tree, from, to, 365 resultInfo, inferenceContext); 366 } 367 } 368 } 369 } 370 371 /* T is a parameterization of a generic class or interface, G, 372 * and B2 contains a bound of one of the forms alpha = S or S <: alpha, 373 * where there exists no type of the form G<...> that is a 374 * supertype of S, but the raw type G is a supertype of S 375 */ 376 if (to.isParameterized()) { 377 for (Type t : from.getBounds(InferenceBound.EQ, InferenceBound.LOWER)) { 378 Type sup = types.asSuper(t, to.tsym); 379 if (sup != null && sup.isRaw()) { 380 return generateReferenceToTargetConstraint(tree, from, to, 381 resultInfo, inferenceContext); 382 } 383 } 384 } 385 return to; 386 } 387 388 private boolean commonSuperWithDiffParameterization(Type t, Type s) { 389 for (Pair<Type, Type> supers : getParameterizedSupers(t, s)) { 390 if (!types.isSameType(supers.fst, supers.snd)) return true; 391 } 392 return false; 393 } 394 395 private Type generateReferenceToTargetConstraint(JCTree tree, UndetVar from, 396 Type to, Attr.ResultInfo resultInfo, 397 InferenceContext inferenceContext) { 398 inferenceContext.solve(List.of(from.qtype), new Warner()); 399 inferenceContext.notifyChange(); 400 Type capturedType = resultInfo.checkContext.inferenceContext() 401 .cachedCapture(tree, from.inst, false); 402 if (types.isConvertible(capturedType, 403 resultInfo.checkContext.inferenceContext().asUndetVar(to))) { 404 //effectively skip additional return-type constraint generation (compatibility) 405 return syms.objectType; 406 } 407 return to; 408 } 409 410 /** 411 * Infer cyclic inference variables as described in 15.12.2.8. 412 */ 413 private void instantiateAsUninferredVars(List<Type> vars, InferenceContext inferenceContext) { 414 ListBuffer<Type> todo = new ListBuffer<>(); 415 //step 1 - create fresh tvars 416 for (Type t : vars) { 417 UndetVar uv = (UndetVar)inferenceContext.asUndetVar(t); 418 List<Type> upperBounds = uv.getBounds(InferenceBound.UPPER); 419 if (Type.containsAny(upperBounds, vars)) { 420 TypeSymbol fresh_tvar = new TypeVariableSymbol(Flags.SYNTHETIC, uv.qtype.tsym.name, null, uv.qtype.tsym.owner); 421 fresh_tvar.type = new TypeVar(fresh_tvar, types.makeIntersectionType(uv.getBounds(InferenceBound.UPPER)), null); 422 todo.append(uv); 423 uv.inst = fresh_tvar.type; 424 } else if (upperBounds.nonEmpty()) { 425 uv.inst = types.glb(upperBounds); 426 } else { 427 uv.inst = syms.objectType; 428 } 429 } 430 //step 2 - replace fresh tvars in their bounds 431 List<Type> formals = vars; 432 for (Type t : todo) { 433 UndetVar uv = (UndetVar)t; 434 TypeVar ct = (TypeVar)uv.inst; 435 ct.bound = types.glb(inferenceContext.asInstTypes(types.getBounds(ct))); 436 if (ct.bound.isErroneous()) { 437 //report inference error if glb fails 438 reportBoundError(uv, BoundErrorKind.BAD_UPPER); 439 } 440 formals = formals.tail; 441 } 442 } 443 444 /** 445 * Compute a synthetic method type corresponding to the requested polymorphic 446 * method signature. The target return type is computed from the immediately 447 * enclosing scope surrounding the polymorphic-signature call. 448 */ 449 Type instantiatePolymorphicSignatureInstance(Env<AttrContext> env, 450 MethodSymbol spMethod, // sig. poly. method or null if none 451 Resolve.MethodResolutionContext resolveContext, 452 List<Type> argtypes) { 453 final Type restype; 454 455 //The return type for a polymorphic signature call is computed from 456 //the enclosing tree E, as follows: if E is a cast, then use the 457 //target type of the cast expression as a return type; if E is an 458 //expression statement, the return type is 'void' - otherwise the 459 //return type is simply 'Object'. A correctness check ensures that 460 //env.next refers to the lexically enclosing environment in which 461 //the polymorphic signature call environment is nested. 462 463 switch (env.next.tree.getTag()) { 464 case TYPECAST: 465 JCTypeCast castTree = (JCTypeCast)env.next.tree; 466 restype = (TreeInfo.skipParens(castTree.expr) == env.tree) ? 467 castTree.clazz.type : 468 syms.objectType; 469 break; 470 case EXEC: 471 JCTree.JCExpressionStatement execTree = 472 (JCTree.JCExpressionStatement)env.next.tree; 473 restype = (TreeInfo.skipParens(execTree.expr) == env.tree) ? 474 syms.voidType : 475 syms.objectType; 476 break; 477 default: 478 restype = syms.objectType; 479 } 480 481 List<Type> paramtypes = argtypes.map(new ImplicitArgType(spMethod, resolveContext.step)); 482 List<Type> exType = spMethod != null ? 483 spMethod.getThrownTypes() : 484 List.of(syms.throwableType); // make it throw all exceptions 485 486 MethodType mtype = new MethodType(paramtypes, 487 restype, 488 exType, 489 syms.methodClass); 490 return mtype; 491 } 492 //where 493 class ImplicitArgType extends DeferredAttr.DeferredTypeMap { 494 495 public ImplicitArgType(Symbol msym, Resolve.MethodResolutionPhase phase) { 496 (rs.deferredAttr).super(AttrMode.SPECULATIVE, msym, phase); 497 } 498 499 @Override 500 public Type visitClassType(ClassType t, Void aVoid) { 501 return types.erasure(t); 502 } 503 504 @Override 505 public Type visitType(Type t, Void _unused) { 506 if (t.hasTag(DEFERRED)) { 507 return visit(super.visitType(t, null)); 508 } else if (t.hasTag(BOT)) 509 // nulls type as the marker type Null (which has no instances) 510 // infer as java.lang.Void for now 511 t = types.boxedClass(syms.voidType).type; 512 return t; 513 } 514 } 515 516 /** 517 * This method is used to infer a suitable target SAM in case the original 518 * SAM type contains one or more wildcards. An inference process is applied 519 * so that wildcard bounds, as well as explicit lambda/method ref parameters 520 * (where applicable) are used to constraint the solution. 521 */ 522 public Type instantiateFunctionalInterface(DiagnosticPosition pos, Type funcInterface, 523 List<Type> paramTypes, Check.CheckContext checkContext) { 524 if (types.capture(funcInterface) == funcInterface) { 525 //if capture doesn't change the type then return the target unchanged 526 //(this means the target contains no wildcards!) 527 return funcInterface; 528 } else { 529 Type formalInterface = funcInterface.tsym.type; 530 InferenceContext funcInterfaceContext = 531 new InferenceContext(funcInterface.tsym.type.getTypeArguments()); 532 533 Assert.check(paramTypes != null); 534 //get constraints from explicit params (this is done by 535 //checking that explicit param types are equal to the ones 536 //in the functional interface descriptors) 537 List<Type> descParameterTypes = types.findDescriptorType(formalInterface).getParameterTypes(); 538 if (descParameterTypes.size() != paramTypes.size()) { 539 checkContext.report(pos, diags.fragment("incompatible.arg.types.in.lambda")); 540 return types.createErrorType(funcInterface); 541 } 542 for (Type p : descParameterTypes) { 543 if (!types.isSameType(funcInterfaceContext.asUndetVar(p), paramTypes.head)) { 544 checkContext.report(pos, diags.fragment("no.suitable.functional.intf.inst", funcInterface)); 545 return types.createErrorType(funcInterface); 546 } 547 paramTypes = paramTypes.tail; 548 } 549 550 try { 551 funcInterfaceContext.solve(funcInterfaceContext.boundedVars(), types.noWarnings); 552 } catch (InferenceException ex) { 553 checkContext.report(pos, diags.fragment("no.suitable.functional.intf.inst", funcInterface)); 554 } 555 556 List<Type> actualTypeargs = funcInterface.getTypeArguments(); 557 for (Type t : funcInterfaceContext.undetvars) { 558 UndetVar uv = (UndetVar)t; 559 if (uv.inst == null) { 560 uv.inst = actualTypeargs.head; 561 } 562 actualTypeargs = actualTypeargs.tail; 563 } 564 565 Type owntype = funcInterfaceContext.asInstType(formalInterface); 566 if (!chk.checkValidGenericType(owntype)) { 567 //if the inferred functional interface type is not well-formed, 568 //or if it's not a subtype of the original target, issue an error 569 checkContext.report(pos, diags.fragment("no.suitable.functional.intf.inst", funcInterface)); 570 } 571 //propagate constraints as per JLS 18.2.1 572 checkContext.compatible(owntype, funcInterface, types.noWarnings); 573 return owntype; 574 } 575 } 576 // </editor-fold> 577 578 // <editor-fold defaultstate="collapsed" desc="Bound checking"> 579 /** 580 * Check bounds and perform incorporation 581 */ 582 void checkWithinBounds(InferenceContext inferenceContext, 583 Warner warn) throws InferenceException { 584 MultiUndetVarListener mlistener = new MultiUndetVarListener(inferenceContext.undetvars); 585 List<Type> saved_undet = inferenceContext.save(); 586 try { 587 while (true) { 588 mlistener.reset(); 589 if (!allowGraphInference) { 590 //in legacy mode we lack of transitivity, so bound check 591 //cannot be run in parallel with other incoprporation rounds 592 for (Type t : inferenceContext.undetvars) { 593 UndetVar uv = (UndetVar)t; 594 IncorporationStep.CHECK_BOUNDS.apply(uv, inferenceContext, warn); 595 } 596 } 597 for (Type t : inferenceContext.undetvars) { 598 UndetVar uv = (UndetVar)t; 599 //bound incorporation 600 EnumSet<IncorporationStep> incorporationSteps = allowGraphInference ? 601 incorporationStepsGraph : incorporationStepsLegacy; 602 for (IncorporationStep is : incorporationSteps) { 603 if (is.accepts(uv, inferenceContext)) { 604 is.apply(uv, inferenceContext, warn); 605 } 606 } 607 } 608 if (!mlistener.changed || !allowGraphInference) break; 609 } 610 } 611 finally { 612 mlistener.detach(); 613 if (incorporationCache.size() == MAX_INCORPORATION_STEPS) { 614 inferenceContext.rollback(saved_undet); 615 } 616 incorporationCache.clear(); 617 } 618 } 619 //where 620 /** 621 * This listener keeps track of changes on a group of inference variable 622 * bounds. Note: the listener must be detached (calling corresponding 623 * method) to make sure that the underlying inference variable is 624 * left in a clean state. 625 */ 626 class MultiUndetVarListener implements UndetVar.UndetVarListener { 627 628 boolean changed; 629 List<Type> undetvars; 630 631 public MultiUndetVarListener(List<Type> undetvars) { 632 this.undetvars = undetvars; 633 for (Type t : undetvars) { 634 UndetVar uv = (UndetVar)t; 635 uv.listener = this; 636 } 637 } 638 639 public void varChanged(UndetVar uv, Set<InferenceBound> ibs) { 640 //avoid non-termination 641 if (incorporationCache.size() < MAX_INCORPORATION_STEPS) { 642 changed = true; 643 } 644 } 645 646 void reset() { 647 changed = false; 648 } 649 650 void detach() { 651 for (Type t : undetvars) { 652 UndetVar uv = (UndetVar)t; 653 uv.listener = null; 654 } 655 } 656 } 657 658 /** max number of incorporation rounds */ 659 static final int MAX_INCORPORATION_STEPS = 100; 660 661 /* If for two types t and s there is a least upper bound that contains 662 * parameterized types G1, G2 ... Gn, then there exists supertypes of 't' of the form 663 * G1<T1, ..., Tn>, G2<T1, ..., Tn>, ... Gn<T1, ..., Tn> and supertypes of 's' of the form 664 * G1<S1, ..., Sn>, G2<S1, ..., Sn>, ... Gn<S1, ..., Sn> which will be returned by this method. 665 * If no such common supertypes exists then an empty list is returned. 666 * 667 * As an example for the following input: 668 * 669 * t = java.util.ArrayList<java.lang.String> 670 * s = java.util.List<T> 671 * 672 * we get this ouput (singleton list): 673 * 674 * [Pair[java.util.List<java.lang.String>,java.util.List<T>]] 675 */ 676 private List<Pair<Type, Type>> getParameterizedSupers(Type t, Type s) { 677 Type lubResult = types.lub(t, s); 678 if (lubResult == syms.errType || lubResult == syms.botType) { 679 return List.nil(); 680 } 681 List<Type> supertypesToCheck = lubResult.isIntersection() ? 682 ((IntersectionClassType)lubResult).getComponents() : 683 List.of(lubResult); 684 ListBuffer<Pair<Type, Type>> commonSupertypes = new ListBuffer<>(); 685 for (Type sup : supertypesToCheck) { 686 if (sup.isParameterized()) { 687 Type asSuperOfT = asSuper(t, sup); 688 Type asSuperOfS = asSuper(s, sup); 689 commonSupertypes.add(new Pair<>(asSuperOfT, asSuperOfS)); 690 } 691 } 692 return commonSupertypes.toList(); 693 } 694 //where 695 private Type asSuper(Type t, Type sup) { 696 return (sup.hasTag(ARRAY)) ? 697 new ArrayType(asSuper(types.elemtype(t), types.elemtype(sup)), syms.arrayClass) : 698 types.asSuper(t, sup.tsym); 699 } 700 701 /** 702 * This enumeration defines an entry point for doing inference variable 703 * bound incorporation - it can be used to inject custom incorporation 704 * logic into the basic bound checking routine 705 */ 706 enum IncorporationStep { 707 /** 708 * Performs basic bound checking - i.e. is the instantiated type for a given 709 * inference variable compatible with its bounds? 710 */ 711 CHECK_BOUNDS() { 712 public void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn) { 713 Infer infer = inferenceContext.infer(); 714 uv.substBounds(inferenceContext.inferenceVars(), inferenceContext.instTypes(), infer.types); 715 infer.checkCompatibleUpperBounds(uv, inferenceContext); 716 if (uv.inst != null) { 717 Type inst = uv.inst; 718 for (Type u : uv.getBounds(InferenceBound.UPPER)) { 719 if (!isSubtype(inst, inferenceContext.asUndetVar(u), warn, infer)) { 720 infer.reportBoundError(uv, BoundErrorKind.UPPER); 721 } 722 } 723 for (Type l : uv.getBounds(InferenceBound.LOWER)) { 724 if (!isSubtype(inferenceContext.asUndetVar(l), inst, warn, infer)) { 725 infer.reportBoundError(uv, BoundErrorKind.LOWER); 726 } 727 } 728 for (Type e : uv.getBounds(InferenceBound.EQ)) { 729 if (!isSameType(inst, inferenceContext.asUndetVar(e), infer)) { 730 infer.reportBoundError(uv, BoundErrorKind.EQ); 731 } 732 } 733 } 734 } 735 736 @Override 737 boolean accepts(UndetVar uv, InferenceContext inferenceContext) { 738 //applies to all undetvars 739 return true; 740 } 741 }, 742 /** 743 * Check consistency of equality constraints. This is a slightly more aggressive 744 * inference routine that is designed as to maximize compatibility with JDK 7. 745 * Note: this is not used in graph mode. 746 */ 747 EQ_CHECK_LEGACY() { 748 public void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn) { 749 Infer infer = inferenceContext.infer(); 750 Type eq = null; 751 for (Type e : uv.getBounds(InferenceBound.EQ)) { 752 Assert.check(!inferenceContext.free(e)); 753 if (eq != null && !isSameType(e, eq, infer)) { 754 infer.reportBoundError(uv, BoundErrorKind.EQ); 755 } 756 eq = e; 757 for (Type l : uv.getBounds(InferenceBound.LOWER)) { 758 Assert.check(!inferenceContext.free(l)); 759 if (!isSubtype(l, e, warn, infer)) { 760 infer.reportBoundError(uv, BoundErrorKind.BAD_EQ_LOWER); 761 } 762 } 763 for (Type u : uv.getBounds(InferenceBound.UPPER)) { 764 if (inferenceContext.free(u)) continue; 765 if (!isSubtype(e, u, warn, infer)) { 766 infer.reportBoundError(uv, BoundErrorKind.BAD_EQ_UPPER); 767 } 768 } 769 } 770 } 771 772 @Override 773 boolean accepts(UndetVar uv, InferenceContext inferenceContext) { 774 return !uv.isCaptured() && uv.getBounds(InferenceBound.EQ).nonEmpty(); 775 } 776 }, 777 /** 778 * Check consistency of equality constraints. 779 */ 780 EQ_CHECK() { 781 @Override 782 public void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn) { 783 Infer infer = inferenceContext.infer(); 784 for (Type e : uv.getBounds(InferenceBound.EQ)) { 785 if (e.containsAny(inferenceContext.inferenceVars())) continue; 786 for (Type u : uv.getBounds(InferenceBound.UPPER)) { 787 if (!isSubtype(e, inferenceContext.asUndetVar(u), warn, infer)) { 788 infer.reportBoundError(uv, BoundErrorKind.BAD_EQ_UPPER); 789 } 790 } 791 for (Type l : uv.getBounds(InferenceBound.LOWER)) { 792 if (!isSubtype(inferenceContext.asUndetVar(l), e, warn, infer)) { 793 infer.reportBoundError(uv, BoundErrorKind.BAD_EQ_LOWER); 794 } 795 } 796 } 797 } 798 799 @Override 800 boolean accepts(UndetVar uv, InferenceContext inferenceContext) { 801 return !uv.isCaptured() && uv.getBounds(InferenceBound.EQ).nonEmpty(); 802 } 803 }, 804 /** 805 * Given a bound set containing {@code alpha <: T} and {@code alpha :> S} 806 * perform {@code S <: T} (which could lead to new bounds). 807 */ 808 CROSS_UPPER_LOWER() { 809 public void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn) { 810 Infer infer = inferenceContext.infer(); 811 for (Type b1 : uv.getBounds(InferenceBound.UPPER)) { 812 for (Type b2 : uv.getBounds(InferenceBound.LOWER)) { 813 isSubtype(inferenceContext.asUndetVar(b2), inferenceContext.asUndetVar(b1), warn , infer); 814 } 815 } 816 } 817 818 @Override 819 boolean accepts(UndetVar uv, InferenceContext inferenceContext) { 820 return !uv.isCaptured() && 821 uv.getBounds(InferenceBound.UPPER).nonEmpty() && 822 uv.getBounds(InferenceBound.LOWER).nonEmpty(); 823 } 824 }, 825 /** 826 * Given a bound set containing {@code alpha <: T} and {@code alpha == S} 827 * perform {@code S <: T} (which could lead to new bounds). 828 */ 829 CROSS_UPPER_EQ() { 830 public void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn) { 831 Infer infer = inferenceContext.infer(); 832 for (Type b1 : uv.getBounds(InferenceBound.UPPER)) { 833 for (Type b2 : uv.getBounds(InferenceBound.EQ)) { 834 isSubtype(inferenceContext.asUndetVar(b2), inferenceContext.asUndetVar(b1), warn, infer); 835 } 836 } 837 } 838 839 @Override 840 boolean accepts(UndetVar uv, InferenceContext inferenceContext) { 841 return !uv.isCaptured() && 842 uv.getBounds(InferenceBound.EQ).nonEmpty() && 843 uv.getBounds(InferenceBound.UPPER).nonEmpty(); 844 } 845 }, 846 /** 847 * Given a bound set containing {@code alpha :> S} and {@code alpha == T} 848 * perform {@code S <: T} (which could lead to new bounds). 849 */ 850 CROSS_EQ_LOWER() { 851 public void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn) { 852 Infer infer = inferenceContext.infer(); 853 for (Type b1 : uv.getBounds(InferenceBound.EQ)) { 854 for (Type b2 : uv.getBounds(InferenceBound.LOWER)) { 855 isSubtype(inferenceContext.asUndetVar(b2), inferenceContext.asUndetVar(b1), warn, infer); 856 } 857 } 858 } 859 860 @Override 861 boolean accepts(UndetVar uv, InferenceContext inferenceContext) { 862 return !uv.isCaptured() && 863 uv.getBounds(InferenceBound.EQ).nonEmpty() && 864 uv.getBounds(InferenceBound.LOWER).nonEmpty(); 865 } 866 }, 867 /** 868 * Given a bound set containing {@code alpha <: P<T>} and 869 * {@code alpha <: P<S>} where P is a parameterized type, 870 * perform {@code T = S} (which could lead to new bounds). 871 */ 872 CROSS_UPPER_UPPER() { 873 @Override 874 public void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn) { 875 Infer infer = inferenceContext.infer(); 876 List<Type> boundList = uv.getBounds(InferenceBound.UPPER); 877 List<Type> boundListTail = boundList.tail; 878 while (boundList.nonEmpty()) { 879 List<Type> tmpTail = boundListTail; 880 while (tmpTail.nonEmpty()) { 881 Type b1 = boundList.head; 882 Type b2 = tmpTail.head; 883 /* This wildcard check is temporary workaround. This code may need to be 884 * revisited once spec bug JDK-7034922 is fixed. 885 */ 886 if (b1 != b2 && !b1.hasTag(WILDCARD) && !b2.hasTag(WILDCARD)) { 887 for (Pair<Type, Type> commonSupers : infer.getParameterizedSupers(b1, b2)) { 888 List<Type> allParamsSuperBound1 = commonSupers.fst.allparams(); 889 List<Type> allParamsSuperBound2 = commonSupers.snd.allparams(); 890 while (allParamsSuperBound1.nonEmpty() && allParamsSuperBound2.nonEmpty()) { 891 //traverse the list of all params comparing them 892 if (!allParamsSuperBound1.head.hasTag(WILDCARD) && 893 !allParamsSuperBound2.head.hasTag(WILDCARD)) { 894 if (!isSameType(inferenceContext.asUndetVar(allParamsSuperBound1.head), 895 inferenceContext.asUndetVar(allParamsSuperBound2.head), infer)) { 896 infer.reportBoundError(uv, BoundErrorKind.BAD_UPPER); 897 } 898 } 899 allParamsSuperBound1 = allParamsSuperBound1.tail; 900 allParamsSuperBound2 = allParamsSuperBound2.tail; 901 } 902 Assert.check(allParamsSuperBound1.isEmpty() && allParamsSuperBound2.isEmpty()); 903 } 904 } 905 tmpTail = tmpTail.tail; 906 } 907 boundList = boundList.tail; 908 boundListTail = boundList.tail; 909 } 910 } 911 912 @Override 913 boolean accepts(UndetVar uv, InferenceContext inferenceContext) { 914 return !uv.isCaptured() && 915 uv.getBounds(InferenceBound.UPPER).nonEmpty(); 916 } 917 }, 918 /** 919 * Given a bound set containing {@code alpha == S} and {@code alpha == T} 920 * perform {@code S == T} (which could lead to new bounds). 921 */ 922 CROSS_EQ_EQ() { 923 public void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn) { 924 Infer infer = inferenceContext.infer(); 925 for (Type b1 : uv.getBounds(InferenceBound.EQ)) { 926 for (Type b2 : uv.getBounds(InferenceBound.EQ)) { 927 if (b1 != b2) { 928 isSameType(inferenceContext.asUndetVar(b2), inferenceContext.asUndetVar(b1), infer); 929 } 930 } 931 } 932 } 933 934 @Override 935 boolean accepts(UndetVar uv, InferenceContext inferenceContext) { 936 return !uv.isCaptured() && 937 uv.getBounds(InferenceBound.EQ).nonEmpty(); 938 } 939 }, 940 /** 941 * Given a bound set containing {@code alpha <: beta} propagate lower bounds 942 * from alpha to beta; also propagate upper bounds from beta to alpha. 943 */ 944 PROP_UPPER() { 945 public void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn) { 946 Infer infer = inferenceContext.infer(); 947 for (Type b : uv.getBounds(InferenceBound.UPPER)) { 948 if (inferenceContext.inferenceVars().contains(b)) { 949 UndetVar uv2 = (UndetVar)inferenceContext.asUndetVar(b); 950 if (uv2.isCaptured()) continue; 951 //alpha <: beta 952 //0. set beta :> alpha 953 addBound(InferenceBound.LOWER, uv2, inferenceContext.asInstType(uv.qtype), infer); 954 //1. copy alpha's lower to beta's 955 for (Type l : uv.getBounds(InferenceBound.LOWER)) { 956 addBound(InferenceBound.LOWER, uv2, inferenceContext.asInstType(l), infer); 957 } 958 //2. copy beta's upper to alpha's 959 for (Type u : uv2.getBounds(InferenceBound.UPPER)) { 960 addBound(InferenceBound.UPPER, uv, inferenceContext.asInstType(u), infer); 961 } 962 } 963 } 964 } 965 966 @Override 967 boolean accepts(UndetVar uv, InferenceContext inferenceContext) { 968 return !uv.isCaptured() && 969 uv.getBounds(InferenceBound.UPPER).nonEmpty(); 970 } 971 }, 972 /** 973 * Given a bound set containing {@code alpha :> beta} propagate lower bounds 974 * from beta to alpha; also propagate upper bounds from alpha to beta. 975 */ 976 PROP_LOWER() { 977 public void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn) { 978 Infer infer = inferenceContext.infer(); 979 for (Type b : uv.getBounds(InferenceBound.LOWER)) { 980 if (inferenceContext.inferenceVars().contains(b)) { 981 UndetVar uv2 = (UndetVar)inferenceContext.asUndetVar(b); 982 if (uv2.isCaptured()) continue; 983 //alpha :> beta 984 //0. set beta <: alpha 985 addBound(InferenceBound.UPPER, uv2, inferenceContext.asInstType(uv.qtype), infer); 986 //1. copy alpha's upper to beta's 987 for (Type u : uv.getBounds(InferenceBound.UPPER)) { 988 addBound(InferenceBound.UPPER, uv2, inferenceContext.asInstType(u), infer); 989 } 990 //2. copy beta's lower to alpha's 991 for (Type l : uv2.getBounds(InferenceBound.LOWER)) { 992 addBound(InferenceBound.LOWER, uv, inferenceContext.asInstType(l), infer); 993 } 994 } 995 } 996 } 997 998 @Override 999 boolean accepts(UndetVar uv, InferenceContext inferenceContext) { 1000 return !uv.isCaptured() && 1001 uv.getBounds(InferenceBound.LOWER).nonEmpty(); 1002 } 1003 }, 1004 /** 1005 * Given a bound set containing {@code alpha == beta} propagate lower/upper 1006 * bounds from alpha to beta and back. 1007 */ 1008 PROP_EQ() { 1009 public void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn) { 1010 Infer infer = inferenceContext.infer(); 1011 for (Type b : uv.getBounds(InferenceBound.EQ)) { 1012 if (inferenceContext.inferenceVars().contains(b)) { 1013 UndetVar uv2 = (UndetVar)inferenceContext.asUndetVar(b); 1014 if (uv2.isCaptured()) continue; 1015 //alpha == beta 1016 //0. set beta == alpha 1017 addBound(InferenceBound.EQ, uv2, inferenceContext.asInstType(uv.qtype), infer); 1018 //1. copy all alpha's bounds to beta's 1019 for (InferenceBound ib : InferenceBound.values()) { 1020 for (Type b2 : uv.getBounds(ib)) { 1021 if (b2 != uv2) { 1022 addBound(ib, uv2, inferenceContext.asInstType(b2), infer); 1023 } 1024 } 1025 } 1026 //2. copy all beta's bounds to alpha's 1027 for (InferenceBound ib : InferenceBound.values()) { 1028 for (Type b2 : uv2.getBounds(ib)) { 1029 if (b2 != uv) { 1030 addBound(ib, uv, inferenceContext.asInstType(b2), infer); 1031 } 1032 } 1033 } 1034 } 1035 } 1036 } 1037 1038 @Override 1039 boolean accepts(UndetVar uv, InferenceContext inferenceContext) { 1040 return !uv.isCaptured() && 1041 uv.getBounds(InferenceBound.EQ).nonEmpty(); 1042 } 1043 }; 1044 1045 abstract void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn); 1046 1047 boolean accepts(UndetVar uv, InferenceContext inferenceContext) { 1048 return !uv.isCaptured(); 1049 } 1050 1051 boolean isSubtype(Type s, Type t, Warner warn, Infer infer) { 1052 return doIncorporationOp(IncorporationBinaryOpKind.IS_SUBTYPE, s, t, warn, infer); 1053 } 1054 1055 boolean isSameType(Type s, Type t, Infer infer) { 1056 return doIncorporationOp(IncorporationBinaryOpKind.IS_SAME_TYPE, s, t, null, infer); 1057 } 1058 1059 void addBound(InferenceBound ib, UndetVar uv, Type b, Infer infer) { 1060 doIncorporationOp(opFor(ib), uv, b, null, infer); 1061 } 1062 1063 IncorporationBinaryOpKind opFor(InferenceBound boundKind) { 1064 switch (boundKind) { 1065 case EQ: 1066 return IncorporationBinaryOpKind.ADD_EQ_BOUND; 1067 case LOWER: 1068 return IncorporationBinaryOpKind.ADD_LOWER_BOUND; 1069 case UPPER: 1070 return IncorporationBinaryOpKind.ADD_UPPER_BOUND; 1071 default: 1072 Assert.error("Can't get here!"); 1073 return null; 1074 } 1075 } 1076 1077 boolean doIncorporationOp(IncorporationBinaryOpKind opKind, Type op1, Type op2, Warner warn, Infer infer) { 1078 IncorporationBinaryOp newOp = infer.new IncorporationBinaryOp(opKind, op1, op2); 1079 Boolean res = infer.incorporationCache.get(newOp); 1080 if (res == null) { 1081 infer.incorporationCache.put(newOp, res = newOp.apply(warn)); 1082 } 1083 return res; 1084 } 1085 } 1086 1087 /** incorporation steps to be executed when running in legacy mode */ 1088 EnumSet<IncorporationStep> incorporationStepsLegacy = EnumSet.of(IncorporationStep.EQ_CHECK_LEGACY); 1089 1090 /** incorporation steps to be executed when running in graph mode */ 1091 EnumSet<IncorporationStep> incorporationStepsGraph = 1092 EnumSet.complementOf(EnumSet.of(IncorporationStep.EQ_CHECK_LEGACY)); 1093 1094 /** 1095 * Three kinds of basic operation are supported as part of an incorporation step: 1096 * (i) subtype check, (ii) same type check and (iii) bound addition (either 1097 * upper/lower/eq bound). 1098 */ 1099 enum IncorporationBinaryOpKind { 1100 IS_SUBTYPE() { 1101 @Override 1102 boolean apply(Type op1, Type op2, Warner warn, Types types) { 1103 return types.isSubtypeUnchecked(op1, op2, warn); 1104 } 1105 }, 1106 IS_SAME_TYPE() { 1107 @Override 1108 boolean apply(Type op1, Type op2, Warner warn, Types types) { 1109 return types.isSameType(op1, op2); 1110 } 1111 }, 1112 ADD_UPPER_BOUND() { 1113 @Override 1114 boolean apply(Type op1, Type op2, Warner warn, Types types) { 1115 UndetVar uv = (UndetVar)op1; 1116 uv.addBound(InferenceBound.UPPER, op2, types); 1117 return true; 1118 } 1119 }, 1120 ADD_LOWER_BOUND() { 1121 @Override 1122 boolean apply(Type op1, Type op2, Warner warn, Types types) { 1123 UndetVar uv = (UndetVar)op1; 1124 uv.addBound(InferenceBound.LOWER, op2, types); 1125 return true; 1126 } 1127 }, 1128 ADD_EQ_BOUND() { 1129 @Override 1130 boolean apply(Type op1, Type op2, Warner warn, Types types) { 1131 UndetVar uv = (UndetVar)op1; 1132 uv.addBound(InferenceBound.EQ, op2, types); 1133 return true; 1134 } 1135 }; 1136 1137 abstract boolean apply(Type op1, Type op2, Warner warn, Types types); 1138 } 1139 1140 /** 1141 * This class encapsulates a basic incorporation operation; incorporation 1142 * operations takes two type operands and a kind. Each operation performed 1143 * during an incorporation round is stored in a cache, so that operations 1144 * are not executed unnecessarily (which would potentially lead to adding 1145 * same bounds over and over). 1146 */ 1147 class IncorporationBinaryOp { 1148 1149 IncorporationBinaryOpKind opKind; 1150 Type op1; 1151 Type op2; 1152 1153 IncorporationBinaryOp(IncorporationBinaryOpKind opKind, Type op1, Type op2) { 1154 this.opKind = opKind; 1155 this.op1 = op1; 1156 this.op2 = op2; 1157 } 1158 1159 @Override 1160 public boolean equals(Object o) { 1161 if (!(o instanceof IncorporationBinaryOp)) { 1162 return false; 1163 } else { 1164 IncorporationBinaryOp that = (IncorporationBinaryOp)o; 1165 return opKind == that.opKind && 1166 types.isSameType(op1, that.op1, true) && 1167 types.isSameType(op2, that.op2, true); 1168 } 1169 } 1170 1171 @Override 1172 public int hashCode() { 1173 int result = opKind.hashCode(); 1174 result *= 127; 1175 result += types.hashCode(op1); 1176 result *= 127; 1177 result += types.hashCode(op2); 1178 return result; 1179 } 1180 1181 boolean apply(Warner warn) { 1182 return opKind.apply(op1, op2, warn, types); 1183 } 1184 } 1185 1186 /** an incorporation cache keeps track of all executed incorporation-related operations */ 1187 Map<IncorporationBinaryOp, Boolean> incorporationCache = new HashMap<>(); 1188 1189 /** 1190 * Make sure that the upper bounds we got so far lead to a solvable inference 1191 * variable by making sure that a glb exists. 1192 */ 1193 void checkCompatibleUpperBounds(UndetVar uv, InferenceContext inferenceContext) { 1194 List<Type> hibounds = 1195 Type.filter(uv.getBounds(InferenceBound.UPPER), new BoundFilter(inferenceContext)); 1196 Type hb = null; 1197 if (hibounds.isEmpty()) 1198 hb = syms.objectType; 1199 else if (hibounds.tail.isEmpty()) 1200 hb = hibounds.head; 1201 else 1202 hb = types.glb(hibounds); 1203 if (hb == null || hb.isErroneous()) 1204 reportBoundError(uv, BoundErrorKind.BAD_UPPER); 1205 } 1206 //where 1207 protected static class BoundFilter implements Filter<Type> { 1208 1209 InferenceContext inferenceContext; 1210 1211 public BoundFilter(InferenceContext inferenceContext) { 1212 this.inferenceContext = inferenceContext; 1213 } 1214 1215 @Override 1216 public boolean accepts(Type t) { 1217 return !t.isErroneous() && !inferenceContext.free(t) && 1218 !t.hasTag(BOT); 1219 } 1220 } 1221 1222 /** 1223 * This enumeration defines all possible bound-checking related errors. 1224 */ 1225 enum BoundErrorKind { 1226 /** 1227 * The (uninstantiated) inference variable has incompatible upper bounds. 1228 */ 1229 BAD_UPPER() { 1230 @Override 1231 InapplicableMethodException setMessage(InferenceException ex, UndetVar uv) { 1232 return ex.setMessage("incompatible.upper.bounds", uv.qtype, 1233 uv.getBounds(InferenceBound.UPPER)); 1234 } 1235 }, 1236 /** 1237 * An equality constraint is not compatible with an upper bound. 1238 */ 1239 BAD_EQ_UPPER() { 1240 @Override 1241 InapplicableMethodException setMessage(InferenceException ex, UndetVar uv) { 1242 return ex.setMessage("incompatible.eq.upper.bounds", uv.qtype, 1243 uv.getBounds(InferenceBound.EQ), uv.getBounds(InferenceBound.UPPER)); 1244 } 1245 }, 1246 /** 1247 * An equality constraint is not compatible with a lower bound. 1248 */ 1249 BAD_EQ_LOWER() { 1250 @Override 1251 InapplicableMethodException setMessage(InferenceException ex, UndetVar uv) { 1252 return ex.setMessage("incompatible.eq.lower.bounds", uv.qtype, 1253 uv.getBounds(InferenceBound.EQ), uv.getBounds(InferenceBound.LOWER)); 1254 } 1255 }, 1256 /** 1257 * Instantiated inference variable is not compatible with an upper bound. 1258 */ 1259 UPPER() { 1260 @Override 1261 InapplicableMethodException setMessage(InferenceException ex, UndetVar uv) { 1262 return ex.setMessage("inferred.do.not.conform.to.upper.bounds", uv.inst, 1263 uv.getBounds(InferenceBound.UPPER)); 1264 } 1265 }, 1266 /** 1267 * Instantiated inference variable is not compatible with a lower bound. 1268 */ 1269 LOWER() { 1270 @Override 1271 InapplicableMethodException setMessage(InferenceException ex, UndetVar uv) { 1272 return ex.setMessage("inferred.do.not.conform.to.lower.bounds", uv.inst, 1273 uv.getBounds(InferenceBound.LOWER)); 1274 } 1275 }, 1276 /** 1277 * Instantiated inference variable is not compatible with an equality constraint. 1278 */ 1279 EQ() { 1280 @Override 1281 InapplicableMethodException setMessage(InferenceException ex, UndetVar uv) { 1282 return ex.setMessage("inferred.do.not.conform.to.eq.bounds", uv.inst, 1283 uv.getBounds(InferenceBound.EQ)); 1284 } 1285 }; 1286 1287 abstract InapplicableMethodException setMessage(InferenceException ex, UndetVar uv); 1288 } 1289 1290 /** 1291 * Report a bound-checking error of given kind 1292 */ 1293 void reportBoundError(UndetVar uv, BoundErrorKind bk) { 1294 throw bk.setMessage(inferenceException, uv); 1295 } 1296 // </editor-fold> 1297 1298 // <editor-fold defaultstate="collapsed" desc="Inference engine"> 1299 /** 1300 * Graph inference strategy - act as an input to the inference solver; a strategy is 1301 * composed of two ingredients: (i) find a node to solve in the inference graph, 1302 * and (ii) tell th engine when we are done fixing inference variables 1303 */ 1304 interface GraphStrategy { 1305 1306 /** 1307 * A NodeNotFoundException is thrown whenever an inference strategy fails 1308 * to pick the next node to solve in the inference graph. 1309 */ 1310 public static class NodeNotFoundException extends RuntimeException { 1311 private static final long serialVersionUID = 0; 1312 1313 InferenceGraph graph; 1314 1315 public NodeNotFoundException(InferenceGraph graph) { 1316 this.graph = graph; 1317 } 1318 } 1319 /** 1320 * Pick the next node (leaf) to solve in the graph 1321 */ 1322 Node pickNode(InferenceGraph g) throws NodeNotFoundException; 1323 /** 1324 * Is this the last step? 1325 */ 1326 boolean done(); 1327 } 1328 1329 /** 1330 * Simple solver strategy class that locates all leaves inside a graph 1331 * and picks the first leaf as the next node to solve 1332 */ 1333 abstract class LeafSolver implements GraphStrategy { 1334 public Node pickNode(InferenceGraph g) { 1335 if (g.nodes.isEmpty()) { 1336 //should not happen 1337 throw new NodeNotFoundException(g); 1338 } 1339 return g.nodes.get(0); 1340 } 1341 1342 boolean isSubtype(Type s, Type t, Warner warn, Infer infer) { 1343 return doIncorporationOp(IncorporationBinaryOpKind.IS_SUBTYPE, s, t, warn, infer); 1344 } 1345 1346 boolean isSameType(Type s, Type t, Infer infer) { 1347 return doIncorporationOp(IncorporationBinaryOpKind.IS_SAME_TYPE, s, t, null, infer); 1348 } 1349 1350 void addBound(InferenceBound ib, UndetVar uv, Type b, Infer infer) { 1351 doIncorporationOp(opFor(ib), uv, b, null, infer); 1352 } 1353 1354 IncorporationBinaryOpKind opFor(InferenceBound boundKind) { 1355 switch (boundKind) { 1356 case EQ: 1357 return IncorporationBinaryOpKind.ADD_EQ_BOUND; 1358 case LOWER: 1359 return IncorporationBinaryOpKind.ADD_LOWER_BOUND; 1360 case UPPER: 1361 return IncorporationBinaryOpKind.ADD_UPPER_BOUND; 1362 default: 1363 Assert.error("Can't get here!"); 1364 return null; 1365 } 1366 } 1367 1368 boolean doIncorporationOp(IncorporationBinaryOpKind opKind, Type op1, Type op2, Warner warn, Infer infer) { 1369 IncorporationBinaryOp newOp = infer.new IncorporationBinaryOp(opKind, op1, op2); 1370 Boolean res = infer.incorporationCache.get(newOp); 1371 if (res == null) { 1372 infer.incorporationCache.put(newOp, res = newOp.apply(warn)); 1373 } 1374 return res; 1375 } 1376 } 1377 1378 /** 1379 * This solver uses an heuristic to pick the best leaf - the heuristic 1380 * tries to select the node that has maximal probability to contain one 1381 * or more inference variables in a given list 1382 */ 1383 abstract class BestLeafSolver extends LeafSolver { 1384 1385 /** list of ivars of which at least one must be solved */ 1386 List<Type> varsToSolve; 1387 1388 BestLeafSolver(List<Type> varsToSolve) { 1389 this.varsToSolve = varsToSolve; 1390 } 1391 1392 /** 1393 * Computes a path that goes from a given node to the leafs in the graph. 1394 * Typically this will start from a node containing a variable in 1395 * {@code varsToSolve}. For any given path, the cost is computed as the total 1396 * number of type-variables that should be eagerly instantiated across that path. 1397 */ 1398 Pair<List<Node>, Integer> computeTreeToLeafs(Node n) { 1399 Pair<List<Node>, Integer> cachedPath = treeCache.get(n); 1400 if (cachedPath == null) { 1401 //cache miss 1402 if (n.isLeaf()) { 1403 //if leaf, stop 1404 cachedPath = new Pair<>(List.of(n), n.data.length()); 1405 } else { 1406 //if non-leaf, proceed recursively 1407 Pair<List<Node>, Integer> path = new Pair<>(List.of(n), n.data.length()); 1408 for (Node n2 : n.getAllDependencies()) { 1409 if (n2 == n) continue; 1410 Pair<List<Node>, Integer> subpath = computeTreeToLeafs(n2); 1411 path = new Pair<>(path.fst.prependList(subpath.fst), 1412 path.snd + subpath.snd); 1413 } 1414 cachedPath = path; 1415 } 1416 //save results in cache 1417 treeCache.put(n, cachedPath); 1418 } 1419 return cachedPath; 1420 } 1421 1422 /** cache used to avoid redundant computation of tree costs */ 1423 final Map<Node, Pair<List<Node>, Integer>> treeCache = new HashMap<>(); 1424 1425 /** constant value used to mark non-existent paths */ 1426 final Pair<List<Node>, Integer> noPath = new Pair<>(null, Integer.MAX_VALUE); 1427 1428 /** 1429 * Pick the leaf that minimize cost 1430 */ 1431 @Override 1432 public Node pickNode(final InferenceGraph g) { 1433 treeCache.clear(); //graph changes at every step - cache must be cleared 1434 Pair<List<Node>, Integer> bestPath = noPath; 1435 for (Node n : g.nodes) { 1436 if (!Collections.disjoint(n.data, varsToSolve)) { 1437 Pair<List<Node>, Integer> path = computeTreeToLeafs(n); 1438 //discard all paths containing at least a node in the 1439 //closure computed above 1440 if (path.snd < bestPath.snd) { 1441 bestPath = path; 1442 } 1443 } 1444 } 1445 if (bestPath == noPath) { 1446 //no path leads there 1447 throw new NodeNotFoundException(g); 1448 } 1449 return bestPath.fst.head; 1450 } 1451 } 1452 1453 /** 1454 * The inference process can be thought of as a sequence of steps. Each step 1455 * instantiates an inference variable using a subset of the inference variable 1456 * bounds, if certain condition are met. Decisions such as the sequence in which 1457 * steps are applied, or which steps are to be applied are left to the inference engine. 1458 */ 1459 enum InferenceStep { 1460 1461 /** 1462 * Instantiate an inference variables using one of its (ground) equality 1463 * constraints 1464 */ 1465 EQ(InferenceBound.EQ) { 1466 @Override 1467 Type solve(UndetVar uv, InferenceContext inferenceContext) { 1468 return filterBounds(uv, inferenceContext).head; 1469 } 1470 }, 1471 /** 1472 * Instantiate an inference variables using its (ground) lower bounds. Such 1473 * bounds are merged together using lub(). 1474 */ 1475 LOWER(InferenceBound.LOWER) { 1476 @Override 1477 Type solve(UndetVar uv, InferenceContext inferenceContext) { 1478 Infer infer = inferenceContext.infer(); 1479 List<Type> lobounds = filterBounds(uv, inferenceContext); 1480 //note: lobounds should have at least one element 1481 Type owntype = lobounds.tail.tail == null ? lobounds.head : infer.types.lub(lobounds); 1482 if (owntype.isPrimitive() || owntype.hasTag(ERROR)) { 1483 throw infer.inferenceException 1484 .setMessage("no.unique.minimal.instance.exists", 1485 uv.qtype, lobounds); 1486 } else { 1487 return owntype; 1488 } 1489 } 1490 }, 1491 /** 1492 * Infer uninstantiated/unbound inference variables occurring in 'throws' 1493 * clause as RuntimeException 1494 */ 1495 THROWS(InferenceBound.UPPER) { 1496 @Override 1497 public boolean accepts(UndetVar t, InferenceContext inferenceContext) { 1498 if ((t.qtype.tsym.flags() & Flags.THROWS) == 0) { 1499 //not a throws undet var 1500 return false; 1501 } 1502 if (t.getBounds(InferenceBound.EQ, InferenceBound.LOWER, InferenceBound.UPPER) 1503 .diff(t.getDeclaredBounds()).nonEmpty()) { 1504 //not an unbounded undet var 1505 return false; 1506 } 1507 Infer infer = inferenceContext.infer(); 1508 for (Type db : t.getDeclaredBounds()) { 1509 if (t.isInterface()) continue; 1510 if (infer.types.asSuper(infer.syms.runtimeExceptionType, db.tsym) != null) { 1511 //declared bound is a supertype of RuntimeException 1512 return true; 1513 } 1514 } 1515 //declared bound is more specific then RuntimeException - give up 1516 return false; 1517 } 1518 1519 @Override 1520 Type solve(UndetVar uv, InferenceContext inferenceContext) { 1521 return inferenceContext.infer().syms.runtimeExceptionType; 1522 } 1523 }, 1524 /** 1525 * Instantiate an inference variables using its (ground) upper bounds. Such 1526 * bounds are merged together using glb(). 1527 */ 1528 UPPER(InferenceBound.UPPER) { 1529 @Override 1530 Type solve(UndetVar uv, InferenceContext inferenceContext) { 1531 Infer infer = inferenceContext.infer(); 1532 List<Type> hibounds = filterBounds(uv, inferenceContext); 1533 //note: hibounds should have at least one element 1534 Type owntype = hibounds.tail.tail == null ? hibounds.head : infer.types.glb(hibounds); 1535 if (owntype.isPrimitive() || owntype.hasTag(ERROR)) { 1536 throw infer.inferenceException 1537 .setMessage("no.unique.maximal.instance.exists", 1538 uv.qtype, hibounds); 1539 } else { 1540 return owntype; 1541 } 1542 } 1543 }, 1544 /** 1545 * Like the former; the only difference is that this step can only be applied 1546 * if all upper bounds are ground. 1547 */ 1548 UPPER_LEGACY(InferenceBound.UPPER) { 1549 @Override 1550 public boolean accepts(UndetVar t, InferenceContext inferenceContext) { 1551 return !inferenceContext.free(t.getBounds(ib)) && !t.isCaptured(); 1552 } 1553 1554 @Override 1555 Type solve(UndetVar uv, InferenceContext inferenceContext) { 1556 return UPPER.solve(uv, inferenceContext); 1557 } 1558 }, 1559 /** 1560 * Like the former; the only difference is that this step can only be applied 1561 * if all upper/lower bounds are ground. 1562 */ 1563 CAPTURED(InferenceBound.UPPER) { 1564 @Override 1565 public boolean accepts(UndetVar t, InferenceContext inferenceContext) { 1566 return t.isCaptured() && 1567 !inferenceContext.free(t.getBounds(InferenceBound.UPPER, InferenceBound.LOWER)); 1568 } 1569 1570 @Override 1571 Type solve(UndetVar uv, InferenceContext inferenceContext) { 1572 Infer infer = inferenceContext.infer(); 1573 Type upper = UPPER.filterBounds(uv, inferenceContext).nonEmpty() ? 1574 UPPER.solve(uv, inferenceContext) : 1575 infer.syms.objectType; 1576 Type lower = LOWER.filterBounds(uv, inferenceContext).nonEmpty() ? 1577 LOWER.solve(uv, inferenceContext) : 1578 infer.syms.botType; 1579 CapturedType prevCaptured = (CapturedType)uv.qtype; 1580 return new CapturedType(prevCaptured.tsym.name, prevCaptured.tsym.owner, 1581 upper, lower, prevCaptured.wildcard); 1582 } 1583 }; 1584 1585 final InferenceBound ib; 1586 1587 InferenceStep(InferenceBound ib) { 1588 this.ib = ib; 1589 } 1590 1591 /** 1592 * Find an instantiated type for a given inference variable within 1593 * a given inference context 1594 */ 1595 abstract Type solve(UndetVar uv, InferenceContext inferenceContext); 1596 1597 /** 1598 * Can the inference variable be instantiated using this step? 1599 */ 1600 public boolean accepts(UndetVar t, InferenceContext inferenceContext) { 1601 return filterBounds(t, inferenceContext).nonEmpty() && !t.isCaptured(); 1602 } 1603 1604 /** 1605 * Return the subset of ground bounds in a given bound set (i.e. eq/lower/upper) 1606 */ 1607 List<Type> filterBounds(UndetVar uv, InferenceContext inferenceContext) { 1608 return Type.filter(uv.getBounds(ib), new BoundFilter(inferenceContext)); 1609 } 1610 } 1611 1612 /** 1613 * This enumeration defines the sequence of steps to be applied when the 1614 * solver works in legacy mode. The steps in this enumeration reflect 1615 * the behavior of old inference routine (see JLS SE 7 15.12.2.7/15.12.2.8). 1616 */ 1617 enum LegacyInferenceSteps { 1618 1619 EQ_LOWER(EnumSet.of(InferenceStep.EQ, InferenceStep.LOWER)), 1620 EQ_UPPER(EnumSet.of(InferenceStep.EQ, InferenceStep.UPPER_LEGACY)); 1621 1622 final EnumSet<InferenceStep> steps; 1623 1624 LegacyInferenceSteps(EnumSet<InferenceStep> steps) { 1625 this.steps = steps; 1626 } 1627 } 1628 1629 /** 1630 * This enumeration defines the sequence of steps to be applied when the 1631 * graph solver is used. This order is defined so as to maximize compatibility 1632 * w.r.t. old inference routine (see JLS SE 7 15.12.2.7/15.12.2.8). 1633 */ 1634 enum GraphInferenceSteps { 1635 1636 EQ(EnumSet.of(InferenceStep.EQ)), 1637 EQ_LOWER(EnumSet.of(InferenceStep.EQ, InferenceStep.LOWER)), 1638 EQ_LOWER_THROWS_UPPER_CAPTURED(EnumSet.of(InferenceStep.EQ, InferenceStep.LOWER, InferenceStep.UPPER, InferenceStep.THROWS, InferenceStep.CAPTURED)); 1639 1640 final EnumSet<InferenceStep> steps; 1641 1642 GraphInferenceSteps(EnumSet<InferenceStep> steps) { 1643 this.steps = steps; 1644 } 1645 } 1646 1647 /** 1648 * There are two kinds of dependencies between inference variables. The basic 1649 * kind of dependency (or bound dependency) arises when a variable mention 1650 * another variable in one of its bounds. There's also a more subtle kind 1651 * of dependency that arises when a variable 'might' lead to better constraints 1652 * on another variable (this is typically the case with variables holding up 1653 * stuck expressions). 1654 */ 1655 enum DependencyKind implements GraphUtils.DependencyKind { 1656 1657 /** bound dependency */ 1658 BOUND("dotted"), 1659 /** stuck dependency */ 1660 STUCK("dashed"); 1661 1662 final String dotSyle; 1663 1664 private DependencyKind(String dotSyle) { 1665 this.dotSyle = dotSyle; 1666 } 1667 } 1668 1669 /** 1670 * This is the graph inference solver - the solver organizes all inference variables in 1671 * a given inference context by bound dependencies - in the general case, such dependencies 1672 * would lead to a cyclic directed graph (hence the name); the dependency info is used to build 1673 * an acyclic graph, where all cyclic variables are bundled together. An inference 1674 * step corresponds to solving a node in the acyclic graph - this is done by 1675 * relying on a given strategy (see GraphStrategy). 1676 */ 1677 class GraphSolver { 1678 1679 InferenceContext inferenceContext; 1680 Map<Type, Set<Type>> stuckDeps; 1681 Warner warn; 1682 1683 GraphSolver(InferenceContext inferenceContext, Map<Type, Set<Type>> stuckDeps, Warner warn) { 1684 this.inferenceContext = inferenceContext; 1685 this.stuckDeps = stuckDeps; 1686 this.warn = warn; 1687 } 1688 1689 /** 1690 * Solve variables in a given inference context. The amount of variables 1691 * to be solved, and the way in which the underlying acyclic graph is explored 1692 * depends on the selected solver strategy. 1693 */ 1694 void solve(GraphStrategy sstrategy) { 1695 checkWithinBounds(inferenceContext, warn); //initial propagation of bounds 1696 InferenceGraph inferenceGraph = new InferenceGraph(stuckDeps); 1697 while (!sstrategy.done()) { 1698 if (dependenciesFolder != null) { 1699 //add this graph to the pending queue 1700 pendingGraphs = pendingGraphs.prepend(inferenceGraph.toDot()); 1701 } 1702 InferenceGraph.Node nodeToSolve = sstrategy.pickNode(inferenceGraph); 1703 List<Type> varsToSolve = List.from(nodeToSolve.data); 1704 List<Type> saved_undet = inferenceContext.save(); 1705 try { 1706 //repeat until all variables are solved 1707 outer: while (Type.containsAny(inferenceContext.restvars(), varsToSolve)) { 1708 //for each inference phase 1709 for (GraphInferenceSteps step : GraphInferenceSteps.values()) { 1710 if (inferenceContext.solveBasic(varsToSolve, step.steps)) { 1711 checkWithinBounds(inferenceContext, warn); 1712 continue outer; 1713 } 1714 } 1715 //no progress 1716 throw inferenceException.setMessage(); 1717 } 1718 } 1719 catch (InferenceException ex) { 1720 //did we fail because of interdependent ivars? 1721 inferenceContext.rollback(saved_undet); 1722 instantiateAsUninferredVars(varsToSolve, inferenceContext); 1723 checkWithinBounds(inferenceContext, warn); 1724 } 1725 inferenceGraph.deleteNode(nodeToSolve); 1726 } 1727 } 1728 1729 /** 1730 * The dependencies between the inference variables that need to be solved 1731 * form a (possibly cyclic) graph. This class reduces the original dependency graph 1732 * to an acyclic version, where cyclic nodes are folded into a single 'super node'. 1733 */ 1734 class InferenceGraph { 1735 1736 /** 1737 * This class represents a node in the graph. Each node corresponds 1738 * to an inference variable and has edges (dependencies) on other 1739 * nodes. The node defines an entry point that can be used to receive 1740 * updates on the structure of the graph this node belongs to (used to 1741 * keep dependencies in sync). 1742 */ 1743 class Node extends GraphUtils.TarjanNode<ListBuffer<Type>, Node> implements DottableNode<ListBuffer<Type>, Node> { 1744 1745 /** map listing all dependencies (grouped by kind) */ 1746 EnumMap<DependencyKind, Set<Node>> deps; 1747 1748 Node(Type ivar) { 1749 super(ListBuffer.of(ivar)); 1750 this.deps = new EnumMap<>(DependencyKind.class); 1751 } 1752 1753 @Override 1754 public GraphUtils.DependencyKind[] getSupportedDependencyKinds() { 1755 return DependencyKind.values(); 1756 } 1757 1758 public Iterable<? extends Node> getAllDependencies() { 1759 return getDependencies(DependencyKind.values()); 1760 } 1761 1762 @Override 1763 public Collection<? extends Node> getDependenciesByKind(GraphUtils.DependencyKind dk) { 1764 return getDependencies((DependencyKind)dk); 1765 } 1766 1767 /** 1768 * Retrieves all dependencies with given kind(s). 1769 */ 1770 protected Set<Node> getDependencies(DependencyKind... depKinds) { 1771 Set<Node> buf = new LinkedHashSet<>(); 1772 for (DependencyKind dk : depKinds) { 1773 Set<Node> depsByKind = deps.get(dk); 1774 if (depsByKind != null) { 1775 buf.addAll(depsByKind); 1776 } 1777 } 1778 return buf; 1779 } 1780 1781 /** 1782 * Adds dependency with given kind. 1783 */ 1784 protected void addDependency(DependencyKind dk, Node depToAdd) { 1785 Set<Node> depsByKind = deps.get(dk); 1786 if (depsByKind == null) { 1787 depsByKind = new LinkedHashSet<>(); 1788 deps.put(dk, depsByKind); 1789 } 1790 depsByKind.add(depToAdd); 1791 } 1792 1793 /** 1794 * Add multiple dependencies of same given kind. 1795 */ 1796 protected void addDependencies(DependencyKind dk, Set<Node> depsToAdd) { 1797 for (Node n : depsToAdd) { 1798 addDependency(dk, n); 1799 } 1800 } 1801 1802 /** 1803 * Remove a dependency, regardless of its kind. 1804 */ 1805 protected Set<DependencyKind> removeDependency(Node n) { 1806 Set<DependencyKind> removedKinds = new HashSet<>(); 1807 for (DependencyKind dk : DependencyKind.values()) { 1808 Set<Node> depsByKind = deps.get(dk); 1809 if (depsByKind == null) continue; 1810 if (depsByKind.remove(n)) { 1811 removedKinds.add(dk); 1812 } 1813 } 1814 return removedKinds; 1815 } 1816 1817 /** 1818 * Compute closure of a give node, by recursively walking 1819 * through all its dependencies (of given kinds) 1820 */ 1821 protected Set<Node> closure(DependencyKind... depKinds) { 1822 boolean progress = true; 1823 Set<Node> closure = new HashSet<>(); 1824 closure.add(this); 1825 while (progress) { 1826 progress = false; 1827 for (Node n1 : new HashSet<>(closure)) { 1828 progress = closure.addAll(n1.getDependencies(depKinds)); 1829 } 1830 } 1831 return closure; 1832 } 1833 1834 /** 1835 * Is this node a leaf? This means either the node has no dependencies, 1836 * or it just has self-dependencies. 1837 */ 1838 protected boolean isLeaf() { 1839 //no deps, or only one self dep 1840 Set<Node> allDeps = getDependencies(DependencyKind.BOUND, DependencyKind.STUCK); 1841 if (allDeps.isEmpty()) return true; 1842 for (Node n : allDeps) { 1843 if (n != this) { 1844 return false; 1845 } 1846 } 1847 return true; 1848 } 1849 1850 /** 1851 * Merge this node with another node, acquiring its dependencies. 1852 * This routine is used to merge all cyclic node together and 1853 * form an acyclic graph. 1854 */ 1855 protected void mergeWith(List<? extends Node> nodes) { 1856 for (Node n : nodes) { 1857 Assert.check(n.data.length() == 1, "Attempt to merge a compound node!"); 1858 data.appendList(n.data); 1859 for (DependencyKind dk : DependencyKind.values()) { 1860 addDependencies(dk, n.getDependencies(dk)); 1861 } 1862 } 1863 //update deps 1864 EnumMap<DependencyKind, Set<Node>> deps2 = new EnumMap<>(DependencyKind.class); 1865 for (DependencyKind dk : DependencyKind.values()) { 1866 for (Node d : getDependencies(dk)) { 1867 Set<Node> depsByKind = deps2.get(dk); 1868 if (depsByKind == null) { 1869 depsByKind = new LinkedHashSet<>(); 1870 deps2.put(dk, depsByKind); 1871 } 1872 if (data.contains(d.data.first())) { 1873 depsByKind.add(this); 1874 } else { 1875 depsByKind.add(d); 1876 } 1877 } 1878 } 1879 deps = deps2; 1880 } 1881 1882 /** 1883 * Notify all nodes that something has changed in the graph 1884 * topology. 1885 */ 1886 private void graphChanged(Node from, Node to) { 1887 for (DependencyKind dk : removeDependency(from)) { 1888 if (to != null) { 1889 addDependency(dk, to); 1890 } 1891 } 1892 } 1893 1894 @Override 1895 public Properties nodeAttributes() { 1896 Properties p = new Properties(); 1897 p.put("label", "\"" + toString() + "\""); 1898 return p; 1899 } 1900 1901 @Override 1902 public Properties dependencyAttributes(Node sink, GraphUtils.DependencyKind dk) { 1903 Properties p = new Properties(); 1904 p.put("style", ((DependencyKind)dk).dotSyle); 1905 if (dk == DependencyKind.STUCK) return p; 1906 else { 1907 StringBuilder buf = new StringBuilder(); 1908 String sep = ""; 1909 for (Type from : data) { 1910 UndetVar uv = (UndetVar)inferenceContext.asUndetVar(from); 1911 for (Type bound : uv.getBounds(InferenceBound.values())) { 1912 if (bound.containsAny(List.from(sink.data))) { 1913 buf.append(sep); 1914 buf.append(bound); 1915 sep = ","; 1916 } 1917 } 1918 } 1919 p.put("label", "\"" + buf.toString() + "\""); 1920 } 1921 return p; 1922 } 1923 } 1924 1925 /** the nodes in the inference graph */ 1926 ArrayList<Node> nodes; 1927 1928 InferenceGraph(Map<Type, Set<Type>> optDeps) { 1929 initNodes(optDeps); 1930 } 1931 1932 /** 1933 * Basic lookup helper for retrieving a graph node given an inference 1934 * variable type. 1935 */ 1936 public Node findNode(Type t) { 1937 for (Node n : nodes) { 1938 if (n.data.contains(t)) { 1939 return n; 1940 } 1941 } 1942 return null; 1943 } 1944 1945 /** 1946 * Delete a node from the graph. This update the underlying structure 1947 * of the graph (including dependencies) via listeners updates. 1948 */ 1949 public void deleteNode(Node n) { 1950 Assert.check(nodes.contains(n)); 1951 nodes.remove(n); 1952 notifyUpdate(n, null); 1953 } 1954 1955 /** 1956 * Notify all nodes of a change in the graph. If the target node is 1957 * {@code null} the source node is assumed to be removed. 1958 */ 1959 void notifyUpdate(Node from, Node to) { 1960 for (Node n : nodes) { 1961 n.graphChanged(from, to); 1962 } 1963 } 1964 1965 /** 1966 * Create the graph nodes. First a simple node is created for every inference 1967 * variables to be solved. Then Tarjan is used to found all connected components 1968 * in the graph. For each component containing more than one node, a super node is 1969 * created, effectively replacing the original cyclic nodes. 1970 */ 1971 void initNodes(Map<Type, Set<Type>> stuckDeps) { 1972 //add nodes 1973 nodes = new ArrayList<>(); 1974 for (Type t : inferenceContext.restvars()) { 1975 nodes.add(new Node(t)); 1976 } 1977 //add dependencies 1978 for (Node n_i : nodes) { 1979 Type i = n_i.data.first(); 1980 Set<Type> optDepsByNode = stuckDeps.get(i); 1981 for (Node n_j : nodes) { 1982 Type j = n_j.data.first(); 1983 UndetVar uv_i = (UndetVar)inferenceContext.asUndetVar(i); 1984 if (Type.containsAny(uv_i.getBounds(InferenceBound.values()), List.of(j))) { 1985 //update i's bound dependencies 1986 n_i.addDependency(DependencyKind.BOUND, n_j); 1987 } 1988 if (optDepsByNode != null && optDepsByNode.contains(j)) { 1989 //update i's stuck dependencies 1990 n_i.addDependency(DependencyKind.STUCK, n_j); 1991 } 1992 } 1993 } 1994 //merge cyclic nodes 1995 ArrayList<Node> acyclicNodes = new ArrayList<>(); 1996 for (List<? extends Node> conSubGraph : GraphUtils.tarjan(nodes)) { 1997 if (conSubGraph.length() > 1) { 1998 Node root = conSubGraph.head; 1999 root.mergeWith(conSubGraph.tail); 2000 for (Node n : conSubGraph) { 2001 notifyUpdate(n, root); 2002 } 2003 } 2004 acyclicNodes.add(conSubGraph.head); 2005 } 2006 nodes = acyclicNodes; 2007 } 2008 2009 /** 2010 * Debugging: dot representation of this graph 2011 */ 2012 String toDot() { 2013 StringBuilder buf = new StringBuilder(); 2014 for (Type t : inferenceContext.undetvars) { 2015 UndetVar uv = (UndetVar)t; 2016 buf.append(String.format("var %s - upper bounds = %s, lower bounds = %s, eq bounds = %s\\n", 2017 uv.qtype, uv.getBounds(InferenceBound.UPPER), uv.getBounds(InferenceBound.LOWER), 2018 uv.getBounds(InferenceBound.EQ))); 2019 } 2020 return GraphUtils.toDot(nodes, "inferenceGraph" + hashCode(), buf.toString()); 2021 } 2022 } 2023 } 2024 // </editor-fold> 2025 2026 // <editor-fold defaultstate="collapsed" desc="Inference context"> 2027 /** 2028 * Functional interface for defining inference callbacks. Certain actions 2029 * (i.e. subtyping checks) might need to be redone after all inference variables 2030 * have been fixed. 2031 */ 2032 interface FreeTypeListener { 2033 void typesInferred(InferenceContext inferenceContext); 2034 } 2035 2036 /** 2037 * An inference context keeps track of the set of variables that are free 2038 * in the current context. It provides utility methods for opening/closing 2039 * types to their corresponding free/closed forms. It also provide hooks for 2040 * attaching deferred post-inference action (see PendingCheck). Finally, 2041 * it can be used as an entry point for performing upper/lower bound inference 2042 * (see InferenceKind). 2043 */ 2044 class InferenceContext { 2045 2046 /** list of inference vars as undet vars */ 2047 List<Type> undetvars; 2048 2049 /** list of inference vars in this context */ 2050 List<Type> inferencevars; 2051 2052 Map<FreeTypeListener, List<Type>> freeTypeListeners = new HashMap<>(); 2053 2054 List<FreeTypeListener> freetypeListeners = List.nil(); 2055 2056 public InferenceContext(List<Type> inferencevars) { 2057 this.undetvars = inferencevars.map(fromTypeVarFun); 2058 this.inferencevars = inferencevars; 2059 } 2060 //where 2061 TypeMapping<Void> fromTypeVarFun = new TypeMapping<Void>() { 2062 @Override 2063 public Type visitTypeVar(TypeVar tv, Void aVoid) { 2064 return new UndetVar(tv, types); 2065 } 2066 2067 @Override 2068 public Type visitCapturedType(CapturedType t, Void aVoid) { 2069 return new CapturedUndetVar(t, types); 2070 } 2071 }; 2072 2073 /** 2074 * add a new inference var to this inference context 2075 */ 2076 void addVar(TypeVar t) { 2077 this.undetvars = this.undetvars.prepend(fromTypeVarFun.apply(t)); 2078 this.inferencevars = this.inferencevars.prepend(t); 2079 } 2080 2081 /** 2082 * returns the list of free variables (as type-variables) in this 2083 * inference context 2084 */ 2085 List<Type> inferenceVars() { 2086 return inferencevars; 2087 } 2088 2089 /** 2090 * returns the list of uninstantiated variables (as type-variables) in this 2091 * inference context 2092 */ 2093 List<Type> restvars() { 2094 return filterVars(new Filter<UndetVar>() { 2095 public boolean accepts(UndetVar uv) { 2096 return uv.inst == null; 2097 } 2098 }); 2099 } 2100 2101 /** 2102 * returns the list of instantiated variables (as type-variables) in this 2103 * inference context 2104 */ 2105 List<Type> instvars() { 2106 return filterVars(new Filter<UndetVar>() { 2107 public boolean accepts(UndetVar uv) { 2108 return uv.inst != null; 2109 } 2110 }); 2111 } 2112 2113 /** 2114 * Get list of bounded inference variables (where bound is other than 2115 * declared bounds). 2116 */ 2117 final List<Type> boundedVars() { 2118 return filterVars(new Filter<UndetVar>() { 2119 public boolean accepts(UndetVar uv) { 2120 return uv.getBounds(InferenceBound.UPPER) 2121 .diff(uv.getDeclaredBounds()) 2122 .appendList(uv.getBounds(InferenceBound.EQ, InferenceBound.LOWER)).nonEmpty(); 2123 } 2124 }); 2125 } 2126 2127 /* Returns the corresponding inference variables. 2128 */ 2129 private List<Type> filterVars(Filter<UndetVar> fu) { 2130 ListBuffer<Type> res = new ListBuffer<>(); 2131 for (Type t : undetvars) { 2132 UndetVar uv = (UndetVar)t; 2133 if (fu.accepts(uv)) { 2134 res.append(uv.qtype); 2135 } 2136 } 2137 return res.toList(); 2138 } 2139 2140 /** 2141 * is this type free? 2142 */ 2143 final boolean free(Type t) { 2144 return t.containsAny(inferencevars); 2145 } 2146 2147 final boolean free(List<Type> ts) { 2148 for (Type t : ts) { 2149 if (free(t)) return true; 2150 } 2151 return false; 2152 } 2153 2154 /** 2155 * Returns a list of free variables in a given type 2156 */ 2157 final List<Type> freeVarsIn(Type t) { 2158 ListBuffer<Type> buf = new ListBuffer<>(); 2159 for (Type iv : inferenceVars()) { 2160 if (t.contains(iv)) { 2161 buf.add(iv); 2162 } 2163 } 2164 return buf.toList(); 2165 } 2166 2167 final List<Type> freeVarsIn(List<Type> ts) { 2168 ListBuffer<Type> buf = new ListBuffer<>(); 2169 for (Type t : ts) { 2170 buf.appendList(freeVarsIn(t)); 2171 } 2172 ListBuffer<Type> buf2 = new ListBuffer<>(); 2173 for (Type t : buf) { 2174 if (!buf2.contains(t)) { 2175 buf2.add(t); 2176 } 2177 } 2178 return buf2.toList(); 2179 } 2180 2181 /** 2182 * Replace all free variables in a given type with corresponding 2183 * undet vars (used ahead of subtyping/compatibility checks to allow propagation 2184 * of inference constraints). 2185 */ 2186 final Type asUndetVar(Type t) { 2187 return types.subst(t, inferencevars, undetvars); 2188 } 2189 2190 final List<Type> asUndetVars(List<Type> ts) { 2191 ListBuffer<Type> buf = new ListBuffer<>(); 2192 for (Type t : ts) { 2193 buf.append(asUndetVar(t)); 2194 } 2195 return buf.toList(); 2196 } 2197 2198 List<Type> instTypes() { 2199 ListBuffer<Type> buf = new ListBuffer<>(); 2200 for (Type t : undetvars) { 2201 UndetVar uv = (UndetVar)t; 2202 buf.append(uv.inst != null ? uv.inst : uv.qtype); 2203 } 2204 return buf.toList(); 2205 } 2206 2207 /** 2208 * Replace all free variables in a given type with corresponding 2209 * instantiated types - if one or more free variable has not been 2210 * fully instantiated, it will still be available in the resulting type. 2211 */ 2212 Type asInstType(Type t) { 2213 return types.subst(t, inferencevars, instTypes()); 2214 } 2215 2216 List<Type> asInstTypes(List<Type> ts) { 2217 ListBuffer<Type> buf = new ListBuffer<>(); 2218 for (Type t : ts) { 2219 buf.append(asInstType(t)); 2220 } 2221 return buf.toList(); 2222 } 2223 2224 /** 2225 * Add custom hook for performing post-inference action 2226 */ 2227 void addFreeTypeListener(List<Type> types, FreeTypeListener ftl) { 2228 freeTypeListeners.put(ftl, freeVarsIn(types)); 2229 } 2230 2231 /** 2232 * Mark the inference context as complete and trigger evaluation 2233 * of all deferred checks. 2234 */ 2235 void notifyChange() { 2236 notifyChange(inferencevars.diff(restvars())); 2237 } 2238 2239 void notifyChange(List<Type> inferredVars) { 2240 InferenceException thrownEx = null; 2241 for (Map.Entry<FreeTypeListener, List<Type>> entry : 2242 new HashMap<>(freeTypeListeners).entrySet()) { 2243 if (!Type.containsAny(entry.getValue(), inferencevars.diff(inferredVars))) { 2244 try { 2245 entry.getKey().typesInferred(this); 2246 freeTypeListeners.remove(entry.getKey()); 2247 } catch (InferenceException ex) { 2248 if (thrownEx == null) { 2249 thrownEx = ex; 2250 } 2251 } 2252 } 2253 } 2254 //inference exception multiplexing - present any inference exception 2255 //thrown when processing listeners as a single one 2256 if (thrownEx != null) { 2257 throw thrownEx; 2258 } 2259 } 2260 2261 /** 2262 * Save the state of this inference context 2263 */ 2264 List<Type> save() { 2265 ListBuffer<Type> buf = new ListBuffer<>(); 2266 for (Type t : undetvars) { 2267 UndetVar uv = (UndetVar)t; 2268 UndetVar uv2 = new UndetVar((TypeVar)uv.qtype, types); 2269 for (InferenceBound ib : InferenceBound.values()) { 2270 for (Type b : uv.getBounds(ib)) { 2271 uv2.addBound(ib, b, types); 2272 } 2273 } 2274 uv2.inst = uv.inst; 2275 buf.add(uv2); 2276 } 2277 return buf.toList(); 2278 } 2279 2280 /** 2281 * Restore the state of this inference context to the previous known checkpoint 2282 */ 2283 void rollback(List<Type> saved_undet) { 2284 Assert.check(saved_undet != null && saved_undet.length() == undetvars.length()); 2285 //restore bounds (note: we need to preserve the old instances) 2286 for (Type t : undetvars) { 2287 UndetVar uv = (UndetVar)t; 2288 UndetVar uv_saved = (UndetVar)saved_undet.head; 2289 for (InferenceBound ib : InferenceBound.values()) { 2290 uv.setBounds(ib, uv_saved.getBounds(ib)); 2291 } 2292 uv.inst = uv_saved.inst; 2293 saved_undet = saved_undet.tail; 2294 } 2295 } 2296 2297 /** 2298 * Copy variable in this inference context to the given context 2299 */ 2300 void dupTo(final InferenceContext that) { 2301 that.inferencevars = that.inferencevars.appendList( 2302 inferencevars.diff(that.inferencevars)); 2303 that.undetvars = that.undetvars.appendList( 2304 undetvars.diff(that.undetvars)); 2305 //set up listeners to notify original inference contexts as 2306 //propagated vars are inferred in new context 2307 for (Type t : inferencevars) { 2308 that.freeTypeListeners.put(new FreeTypeListener() { 2309 public void typesInferred(InferenceContext inferenceContext) { 2310 InferenceContext.this.notifyChange(); 2311 } 2312 }, List.of(t)); 2313 } 2314 } 2315 2316 private void solve(GraphStrategy ss, Warner warn) { 2317 solve(ss, new HashMap<Type, Set<Type>>(), warn); 2318 } 2319 2320 /** 2321 * Solve with given graph strategy. 2322 */ 2323 private void solve(GraphStrategy ss, Map<Type, Set<Type>> stuckDeps, Warner warn) { 2324 GraphSolver s = new GraphSolver(this, stuckDeps, warn); 2325 s.solve(ss); 2326 } 2327 2328 /** 2329 * Solve all variables in this context. 2330 */ 2331 public void solve(Warner warn) { 2332 solve(new LeafSolver() { 2333 public boolean done() { 2334 return restvars().isEmpty(); 2335 } 2336 }, warn); 2337 } 2338 2339 /** 2340 * Solve all variables in the given list. 2341 */ 2342 public void solve(final List<Type> vars, Warner warn) { 2343 solve(new BestLeafSolver(vars) { 2344 public boolean done() { 2345 return !free(asInstTypes(vars)); 2346 } 2347 }, warn); 2348 } 2349 2350 /** 2351 * Solve at least one variable in given list. 2352 */ 2353 public void solveAny(List<Type> varsToSolve, Map<Type, Set<Type>> optDeps, Warner warn) { 2354 solve(new BestLeafSolver(varsToSolve.intersect(restvars())) { 2355 public boolean done() { 2356 return instvars().intersect(varsToSolve).nonEmpty(); 2357 } 2358 }, optDeps, warn); 2359 } 2360 2361 /** 2362 * Apply a set of inference steps 2363 */ 2364 private boolean solveBasic(EnumSet<InferenceStep> steps) { 2365 return solveBasic(inferencevars, steps); 2366 } 2367 2368 private boolean solveBasic(List<Type> varsToSolve, EnumSet<InferenceStep> steps) { 2369 boolean changed = false; 2370 for (Type t : varsToSolve.intersect(restvars())) { 2371 UndetVar uv = (UndetVar)asUndetVar(t); 2372 for (InferenceStep step : steps) { 2373 if (step.accepts(uv, this)) { 2374 uv.inst = step.solve(uv, this); 2375 changed = true; 2376 break; 2377 } 2378 } 2379 } 2380 return changed; 2381 } 2382 2383 /** 2384 * Instantiate inference variables in legacy mode (JLS 15.12.2.7, 15.12.2.8). 2385 * During overload resolution, instantiation is done by doing a partial 2386 * inference process using eq/lower bound instantiation. During check, 2387 * we also instantiate any remaining vars by repeatedly using eq/upper 2388 * instantiation, until all variables are solved. 2389 */ 2390 public void solveLegacy(boolean partial, Warner warn, EnumSet<InferenceStep> steps) { 2391 while (true) { 2392 boolean stuck = !solveBasic(steps); 2393 if (restvars().isEmpty() || partial) { 2394 //all variables have been instantiated - exit 2395 break; 2396 } else if (stuck) { 2397 //some variables could not be instantiated because of cycles in 2398 //upper bounds - provide a (possibly recursive) default instantiation 2399 instantiateAsUninferredVars(restvars(), this); 2400 break; 2401 } else { 2402 //some variables have been instantiated - replace newly instantiated 2403 //variables in remaining upper bounds and continue 2404 for (Type t : undetvars) { 2405 UndetVar uv = (UndetVar)t; 2406 uv.substBounds(inferenceVars(), instTypes(), types); 2407 } 2408 } 2409 } 2410 checkWithinBounds(this, warn); 2411 } 2412 2413 private Infer infer() { 2414 //back-door to infer 2415 return Infer.this; 2416 } 2417 2418 @Override 2419 public String toString() { 2420 return "Inference vars: " + inferencevars + '\n' + 2421 "Undet vars: " + undetvars; 2422 } 2423 2424 /* Method Types.capture() generates a new type every time it's applied 2425 * to a wildcard parameterized type. This is intended functionality but 2426 * there are some cases when what you need is not to generate a new 2427 * captured type but to check that a previously generated captured type 2428 * is correct. There are cases when caching a captured type for later 2429 * reuse is sound. In general two captures from the same AST are equal. 2430 * This is why the tree is used as the key of the map below. This map 2431 * stores a Type per AST. 2432 */ 2433 Map<JCTree, Type> captureTypeCache = new HashMap<>(); 2434 2435 Type cachedCapture(JCTree tree, Type t, boolean readOnly) { 2436 Type captured = captureTypeCache.get(tree); 2437 if (captured != null) { 2438 return captured; 2439 } 2440 2441 Type result = types.capture(t); 2442 if (result != t && !readOnly) { // then t is a wildcard parameterized type 2443 captureTypeCache.put(tree, result); 2444 } 2445 return result; 2446 } 2447 } 2448 2449 final InferenceContext emptyContext = new InferenceContext(List.<Type>nil()); 2450 // </editor-fold> 2451} 2452