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

Thu, 04 Aug 2016 23:36:47 -0700

author
asaha
date
Thu, 04 Aug 2016 23:36:47 -0700
changeset 3270
8a30511b2ea4
parent 2904
14891e981af0
child 3295
859dc787b52b
permissions
-rw-r--r--

8162511: 8u111 L10n resource file updates
Summary: 8u111 L10n resource file updates
Reviewed-by: coffeys
Contributed-by: li.jiang@oracle.com

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

mercurial