src/share/classes/com/sun/tools/javac/comp/Infer.java

Thu, 24 May 2018 16:48:51 +0800

author
aoqi
date
Thu, 24 May 2018 16:48:51 +0800
changeset 3295
859dc787b52b
parent 2904
14891e981af0
parent 2893
ca5783d9a597
permissions
-rw-r--r--

Merge

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

mercurial