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

Fri, 09 May 2014 20:33:21 -0700

author
mfang
date
Fri, 09 May 2014 20:33:21 -0700
changeset 2388
0add97444be9
parent 2369
77352397867a
child 2382
14979dd5e034
permissions
-rw-r--r--

8041424: 8u20 l10n resource file translation update 1
Reviewed-by: naoto, yhuang

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

mercurial