Mon, 03 Jun 2013 17:09:26 -0700
8006615: [doclint] move remaining messages into resource bundle
Reviewed-by: mcimadamore, vromero
1 /*
2 * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
26 package com.sun.tools.javac.comp;
28 import com.sun.tools.javac.tree.JCTree;
29 import com.sun.tools.javac.tree.JCTree.JCTypeCast;
30 import com.sun.tools.javac.tree.TreeInfo;
31 import com.sun.tools.javac.util.*;
32 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
33 import com.sun.tools.javac.util.List;
34 import com.sun.tools.javac.code.*;
35 import com.sun.tools.javac.code.Type.*;
36 import com.sun.tools.javac.code.Type.UndetVar.InferenceBound;
37 import com.sun.tools.javac.code.Symbol.*;
38 import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
39 import com.sun.tools.javac.comp.Infer.GraphSolver.InferenceGraph;
40 import com.sun.tools.javac.comp.Infer.GraphSolver.InferenceGraph.Node;
41 import com.sun.tools.javac.comp.Resolve.InapplicableMethodException;
42 import com.sun.tools.javac.comp.Resolve.VerboseResolutionMode;
44 import java.util.HashMap;
45 import java.util.Map;
46 import java.util.Set;
48 import java.util.ArrayList;
49 import java.util.Collections;
50 import java.util.EnumSet;
51 import java.util.HashSet;
53 import static com.sun.tools.javac.code.TypeTag.*;
55 /** Helper class for type parameter inference, used by the attribution phase.
56 *
57 * <p><b>This is NOT part of any supported API.
58 * If you write code that depends on this, you do so at your own risk.
59 * This code and its internal interfaces are subject to change or
60 * deletion without notice.</b>
61 */
62 public class Infer {
63 protected static final Context.Key<Infer> inferKey =
64 new Context.Key<Infer>();
66 Resolve rs;
67 Check chk;
68 Symtab syms;
69 Types types;
70 JCDiagnostic.Factory diags;
71 Log log;
73 /** should the graph solver be used? */
74 boolean allowGraphInference;
76 public static Infer instance(Context context) {
77 Infer instance = context.get(inferKey);
78 if (instance == null)
79 instance = new Infer(context);
80 return instance;
81 }
83 protected Infer(Context context) {
84 context.put(inferKey, this);
86 rs = Resolve.instance(context);
87 chk = Check.instance(context);
88 syms = Symtab.instance(context);
89 types = Types.instance(context);
90 diags = JCDiagnostic.Factory.instance(context);
91 log = Log.instance(context);
92 inferenceException = new InferenceException(diags);
93 Options options = Options.instance(context);
94 allowGraphInference = Source.instance(context).allowGraphInference()
95 && options.isUnset("useLegacyInference");
96 }
98 /** A value for prototypes that admit any type, including polymorphic ones. */
99 public static final Type anyPoly = new Type(NONE, null);
101 /**
102 * This exception class is design to store a list of diagnostics corresponding
103 * to inference errors that can arise during a method applicability check.
104 */
105 public static class InferenceException extends InapplicableMethodException {
106 private static final long serialVersionUID = 0;
108 List<JCDiagnostic> messages = List.nil();
110 InferenceException(JCDiagnostic.Factory diags) {
111 super(diags);
112 }
114 @Override
115 InapplicableMethodException setMessage(JCDiagnostic diag) {
116 messages = messages.append(diag);
117 return this;
118 }
120 @Override
121 public JCDiagnostic getDiagnostic() {
122 return messages.head;
123 }
125 void clear() {
126 messages = List.nil();
127 }
128 }
130 protected final InferenceException inferenceException;
132 // <editor-fold defaultstate="collapsed" desc="Inference routines">
133 /**
134 * Main inference entry point - instantiate a generic method type
135 * using given argument types and (possibly) an expected target-type.
136 */
137 public Type instantiateMethod(Env<AttrContext> env,
138 List<Type> tvars,
139 MethodType mt,
140 Attr.ResultInfo resultInfo,
141 Symbol msym,
142 List<Type> argtypes,
143 boolean allowBoxing,
144 boolean useVarargs,
145 Resolve.MethodResolutionContext resolveContext,
146 Warner warn) throws InferenceException {
147 //-System.err.println("instantiateMethod(" + tvars + ", " + mt + ", " + argtypes + ")"); //DEBUG
148 final InferenceContext inferenceContext = new InferenceContext(tvars);
149 inferenceException.clear();
150 try {
151 DeferredAttr.DeferredAttrContext deferredAttrContext =
152 resolveContext.deferredAttrContext(msym, inferenceContext, resultInfo, warn);
154 resolveContext.methodCheck.argumentsAcceptable(env, deferredAttrContext,
155 argtypes, mt.getParameterTypes(), warn);
157 if (allowGraphInference &&
158 resultInfo != null &&
159 !warn.hasNonSilentLint(Lint.LintCategory.UNCHECKED)) {
160 //inject return constraints earlier
161 checkWithinBounds(inferenceContext, warn); //propagation
162 generateReturnConstraints(resultInfo, mt, inferenceContext);
163 //propagate outwards if needed
164 if (resultInfo.checkContext.inferenceContext().free(resultInfo.pt)) {
165 //propagate inference context outwards and exit
166 inferenceContext.dupTo(resultInfo.checkContext.inferenceContext());
167 deferredAttrContext.complete();
168 return mt;
169 }
170 }
172 deferredAttrContext.complete();
174 // minimize as yet undetermined type variables
175 if (allowGraphInference) {
176 inferenceContext.solve(warn);
177 } else {
178 inferenceContext.solveLegacy(true, warn, LegacyInferenceSteps.EQ_LOWER.steps); //minimizeInst
179 }
181 mt = (MethodType)inferenceContext.asInstType(mt);
183 if (!allowGraphInference &&
184 inferenceContext.restvars().nonEmpty() &&
185 resultInfo != null &&
186 !warn.hasNonSilentLint(Lint.LintCategory.UNCHECKED)) {
187 generateReturnConstraints(resultInfo, mt, inferenceContext);
188 inferenceContext.solveLegacy(false, warn, LegacyInferenceSteps.EQ_UPPER.steps); //maximizeInst
189 mt = (MethodType)inferenceContext.asInstType(mt);
190 }
192 if (resultInfo != null && rs.verboseResolutionMode.contains(VerboseResolutionMode.DEFERRED_INST)) {
193 log.note(env.tree.pos, "deferred.method.inst", msym, mt, resultInfo.pt);
194 }
196 // return instantiated version of method type
197 return mt;
198 } finally {
199 if (resultInfo != null || !allowGraphInference) {
200 inferenceContext.notifyChange();
201 } else {
202 inferenceContext.notifyChange(inferenceContext.boundedVars());
203 }
204 }
205 }
207 /**
208 * Generate constraints from the generic method's return type. If the method
209 * call occurs in a context where a type T is expected, use the expected
210 * type to derive more constraints on the generic method inference variables.
211 */
212 void generateReturnConstraints(Attr.ResultInfo resultInfo,
213 MethodType mt, InferenceContext inferenceContext) {
214 Type qtype1 = inferenceContext.asFree(mt.getReturnType());
215 Type to = returnConstraintTarget(qtype1, resultInfo.pt);
216 Assert.check(allowGraphInference || !resultInfo.checkContext.inferenceContext().free(to),
217 "legacy inference engine cannot handle constraints on both sides of a subtyping assertion");
218 //we need to skip capture?
219 Warner retWarn = new Warner();
220 if (!resultInfo.checkContext.compatible(qtype1, resultInfo.checkContext.inferenceContext().asFree(to), retWarn) ||
221 //unchecked conversion is not allowed
222 retWarn.hasLint(Lint.LintCategory.UNCHECKED)) {
223 throw inferenceException
224 .setMessage("infer.no.conforming.instance.exists",
225 inferenceContext.restvars(), mt.getReturnType(), to);
226 }
227 }
228 //where
229 private Type returnConstraintTarget(Type from, Type to) {
230 if (from.hasTag(VOID)) {
231 return syms.voidType;
232 } else if (to.hasTag(NONE)) {
233 return from.isPrimitive() ? from : syms.objectType;
234 } else if (from.hasTag(UNDETVAR) && to.isPrimitive()) {
235 if (!allowGraphInference) {
236 //if legacy, just return boxed type
237 return types.boxedClass(to).type;
238 }
239 //if graph inference we need to skip conflicting boxed bounds...
240 UndetVar uv = (UndetVar)from;
241 for (Type t : uv.getBounds(InferenceBound.EQ, InferenceBound.LOWER)) {
242 Type boundAsPrimitive = types.unboxedType(t);
243 if (boundAsPrimitive == null) continue;
244 if (types.isConvertible(boundAsPrimitive, to)) {
245 //effectively skip return-type constraint generation (compatibility)
246 return syms.objectType;
247 }
248 }
249 return types.boxedClass(to).type;
250 } else {
251 return to;
252 }
253 }
255 /**
256 * Infer cyclic inference variables as described in 15.12.2.8.
257 */
258 private void instantiateAsUninferredVars(List<Type> vars, InferenceContext inferenceContext) {
259 ListBuffer<Type> todo = ListBuffer.lb();
260 //step 1 - create fresh tvars
261 for (Type t : vars) {
262 UndetVar uv = (UndetVar)inferenceContext.asFree(t);
263 List<Type> upperBounds = uv.getBounds(InferenceBound.UPPER);
264 if (Type.containsAny(upperBounds, vars)) {
265 TypeSymbol fresh_tvar = new TypeVariableSymbol(Flags.SYNTHETIC, uv.qtype.tsym.name, null, uv.qtype.tsym.owner);
266 fresh_tvar.type = new TypeVar(fresh_tvar, types.makeCompoundType(uv.getBounds(InferenceBound.UPPER)), null);
267 todo.append(uv);
268 uv.inst = fresh_tvar.type;
269 } else if (upperBounds.nonEmpty()) {
270 uv.inst = types.glb(upperBounds);
271 } else {
272 uv.inst = syms.objectType;
273 }
274 }
275 //step 2 - replace fresh tvars in their bounds
276 List<Type> formals = vars;
277 for (Type t : todo) {
278 UndetVar uv = (UndetVar)t;
279 TypeVar ct = (TypeVar)uv.inst;
280 ct.bound = types.glb(inferenceContext.asInstTypes(types.getBounds(ct)));
281 if (ct.bound.isErroneous()) {
282 //report inference error if glb fails
283 reportBoundError(uv, BoundErrorKind.BAD_UPPER);
284 }
285 formals = formals.tail;
286 }
287 }
289 /**
290 * Compute a synthetic method type corresponding to the requested polymorphic
291 * method signature. The target return type is computed from the immediately
292 * enclosing scope surrounding the polymorphic-signature call.
293 */
294 Type instantiatePolymorphicSignatureInstance(Env<AttrContext> env,
295 MethodSymbol spMethod, // sig. poly. method or null if none
296 Resolve.MethodResolutionContext resolveContext,
297 List<Type> argtypes) {
298 final Type restype;
300 //The return type for a polymorphic signature call is computed from
301 //the enclosing tree E, as follows: if E is a cast, then use the
302 //target type of the cast expression as a return type; if E is an
303 //expression statement, the return type is 'void' - otherwise the
304 //return type is simply 'Object'. A correctness check ensures that
305 //env.next refers to the lexically enclosing environment in which
306 //the polymorphic signature call environment is nested.
308 switch (env.next.tree.getTag()) {
309 case TYPECAST:
310 JCTypeCast castTree = (JCTypeCast)env.next.tree;
311 restype = (TreeInfo.skipParens(castTree.expr) == env.tree) ?
312 castTree.clazz.type :
313 syms.objectType;
314 break;
315 case EXEC:
316 JCTree.JCExpressionStatement execTree =
317 (JCTree.JCExpressionStatement)env.next.tree;
318 restype = (TreeInfo.skipParens(execTree.expr) == env.tree) ?
319 syms.voidType :
320 syms.objectType;
321 break;
322 default:
323 restype = syms.objectType;
324 }
326 List<Type> paramtypes = Type.map(argtypes, new ImplicitArgType(spMethod, resolveContext.step));
327 List<Type> exType = spMethod != null ?
328 spMethod.getThrownTypes() :
329 List.of(syms.throwableType); // make it throw all exceptions
331 MethodType mtype = new MethodType(paramtypes,
332 restype,
333 exType,
334 syms.methodClass);
335 return mtype;
336 }
337 //where
338 class ImplicitArgType extends DeferredAttr.DeferredTypeMap {
340 public ImplicitArgType(Symbol msym, Resolve.MethodResolutionPhase phase) {
341 rs.deferredAttr.super(AttrMode.SPECULATIVE, msym, phase);
342 }
344 public Type apply(Type t) {
345 t = types.erasure(super.apply(t));
346 if (t.hasTag(BOT))
347 // nulls type as the marker type Null (which has no instances)
348 // infer as java.lang.Void for now
349 t = types.boxedClass(syms.voidType).type;
350 return t;
351 }
352 }
354 /**
355 * This method is used to infer a suitable target SAM in case the original
356 * SAM type contains one or more wildcards. An inference process is applied
357 * so that wildcard bounds, as well as explicit lambda/method ref parameters
358 * (where applicable) are used to constraint the solution.
359 */
360 public Type instantiateFunctionalInterface(DiagnosticPosition pos, Type funcInterface,
361 List<Type> paramTypes, Check.CheckContext checkContext) {
362 if (types.capture(funcInterface) == funcInterface) {
363 //if capture doesn't change the type then return the target unchanged
364 //(this means the target contains no wildcards!)
365 return funcInterface;
366 } else {
367 Type formalInterface = funcInterface.tsym.type;
368 InferenceContext funcInterfaceContext =
369 new InferenceContext(funcInterface.tsym.type.getTypeArguments());
371 Assert.check(paramTypes != null);
372 //get constraints from explicit params (this is done by
373 //checking that explicit param types are equal to the ones
374 //in the functional interface descriptors)
375 List<Type> descParameterTypes = types.findDescriptorType(formalInterface).getParameterTypes();
376 if (descParameterTypes.size() != paramTypes.size()) {
377 checkContext.report(pos, diags.fragment("incompatible.arg.types.in.lambda"));
378 return types.createErrorType(funcInterface);
379 }
380 for (Type p : descParameterTypes) {
381 if (!types.isSameType(funcInterfaceContext.asFree(p), paramTypes.head)) {
382 checkContext.report(pos, diags.fragment("no.suitable.functional.intf.inst", funcInterface));
383 return types.createErrorType(funcInterface);
384 }
385 paramTypes = paramTypes.tail;
386 }
388 try {
389 funcInterfaceContext.solve(funcInterfaceContext.boundedVars(), types.noWarnings);
390 } catch (InferenceException ex) {
391 checkContext.report(pos, diags.fragment("no.suitable.functional.intf.inst", funcInterface));
392 }
394 List<Type> actualTypeargs = funcInterface.getTypeArguments();
395 for (Type t : funcInterfaceContext.undetvars) {
396 UndetVar uv = (UndetVar)t;
397 if (uv.inst == null) {
398 uv.inst = actualTypeargs.head;
399 }
400 actualTypeargs = actualTypeargs.tail;
401 }
403 Type owntype = funcInterfaceContext.asInstType(formalInterface);
404 if (!chk.checkValidGenericType(owntype)) {
405 //if the inferred functional interface type is not well-formed,
406 //or if it's not a subtype of the original target, issue an error
407 checkContext.report(pos, diags.fragment("no.suitable.functional.intf.inst", funcInterface));
408 }
409 return owntype;
410 }
411 }
412 // </editor-fold>
414 // <editor-fold defaultstate="collapsed" desc="Bound checking">
415 /**
416 * Check bounds and perform incorporation
417 */
418 void checkWithinBounds(InferenceContext inferenceContext,
419 Warner warn) throws InferenceException {
420 MultiUndetVarListener mlistener = new MultiUndetVarListener(inferenceContext.undetvars);
421 try {
422 while (true) {
423 mlistener.reset();
424 if (!allowGraphInference) {
425 //in legacy mode we lack of transitivity, so bound check
426 //cannot be run in parallel with other incoprporation rounds
427 for (Type t : inferenceContext.undetvars) {
428 UndetVar uv = (UndetVar)t;
429 IncorporationStep.CHECK_BOUNDS.apply(uv, inferenceContext, warn);
430 }
431 }
432 for (Type t : inferenceContext.undetvars) {
433 UndetVar uv = (UndetVar)t;
434 //bound incorporation
435 EnumSet<IncorporationStep> incorporationSteps = allowGraphInference ?
436 incorporationStepsGraph : incorporationStepsLegacy;
437 for (IncorporationStep is : incorporationSteps) {
438 is.apply(uv, inferenceContext, warn);
439 }
440 }
441 if (!mlistener.changed || !allowGraphInference) break;
442 }
443 }
444 finally {
445 mlistener.detach();
446 }
447 }
448 //where
449 /**
450 * This listener keeps track of changes on a group of inference variable
451 * bounds. Note: the listener must be detached (calling corresponding
452 * method) to make sure that the underlying inference variable is
453 * left in a clean state.
454 */
455 class MultiUndetVarListener implements UndetVar.UndetVarListener {
457 int rounds;
458 boolean changed;
459 List<Type> undetvars;
461 public MultiUndetVarListener(List<Type> undetvars) {
462 this.undetvars = undetvars;
463 for (Type t : undetvars) {
464 UndetVar uv = (UndetVar)t;
465 uv.listener = this;
466 }
467 }
469 public void varChanged(UndetVar uv, Set<InferenceBound> ibs) {
470 //avoid non-termination
471 if (rounds < MAX_INCORPORATION_STEPS) {
472 changed = true;
473 }
474 }
476 void reset() {
477 rounds++;
478 changed = false;
479 }
481 void detach() {
482 for (Type t : undetvars) {
483 UndetVar uv = (UndetVar)t;
484 uv.listener = null;
485 }
486 }
487 };
489 /** max number of incorporation rounds */
490 static final int MAX_INCORPORATION_STEPS = 100;
492 /**
493 * This enumeration defines an entry point for doing inference variable
494 * bound incorporation - it can be used to inject custom incorporation
495 * logic into the basic bound checking routine
496 */
497 enum IncorporationStep {
498 /**
499 * Performs basic bound checking - i.e. is the instantiated type for a given
500 * inference variable compatible with its bounds?
501 */
502 CHECK_BOUNDS() {
503 public void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn) {
504 Infer infer = inferenceContext.infer();
505 uv.substBounds(inferenceContext.inferenceVars(), inferenceContext.instTypes(), infer.types);
506 infer.checkCompatibleUpperBounds(uv, inferenceContext);
507 if (uv.inst != null) {
508 Type inst = uv.inst;
509 for (Type u : uv.getBounds(InferenceBound.UPPER)) {
510 if (!infer.types.isSubtypeUnchecked(inst, inferenceContext.asFree(u), warn)) {
511 infer.reportBoundError(uv, BoundErrorKind.UPPER);
512 }
513 }
514 for (Type l : uv.getBounds(InferenceBound.LOWER)) {
515 if (!infer.types.isSubtypeUnchecked(inferenceContext.asFree(l), inst, warn)) {
516 infer.reportBoundError(uv, BoundErrorKind.LOWER);
517 }
518 }
519 for (Type e : uv.getBounds(InferenceBound.EQ)) {
520 if (!infer.types.isSameType(inst, inferenceContext.asFree(e))) {
521 infer.reportBoundError(uv, BoundErrorKind.EQ);
522 }
523 }
524 }
525 }
526 },
527 /**
528 * Check consistency of equality constraints. This is a slightly more aggressive
529 * inference routine that is designed as to maximize compatibility with JDK 7.
530 * Note: this is not used in graph mode.
531 */
532 EQ_CHECK_LEGACY() {
533 public void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn) {
534 Infer infer = inferenceContext.infer();
535 Type eq = null;
536 for (Type e : uv.getBounds(InferenceBound.EQ)) {
537 Assert.check(!inferenceContext.free(e));
538 if (eq != null && !infer.types.isSameType(e, eq)) {
539 infer.reportBoundError(uv, BoundErrorKind.EQ);
540 }
541 eq = e;
542 for (Type l : uv.getBounds(InferenceBound.LOWER)) {
543 Assert.check(!inferenceContext.free(l));
544 if (!infer.types.isSubtypeUnchecked(l, e, warn)) {
545 infer.reportBoundError(uv, BoundErrorKind.BAD_EQ_LOWER);
546 }
547 }
548 for (Type u : uv.getBounds(InferenceBound.UPPER)) {
549 if (inferenceContext.free(u)) continue;
550 if (!infer.types.isSubtypeUnchecked(e, u, warn)) {
551 infer.reportBoundError(uv, BoundErrorKind.BAD_EQ_UPPER);
552 }
553 }
554 }
555 }
556 },
557 /**
558 * Check consistency of equality constraints.
559 */
560 EQ_CHECK() {
561 public void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn) {
562 Infer infer = inferenceContext.infer();
563 for (Type e : uv.getBounds(InferenceBound.EQ)) {
564 if (e.containsAny(inferenceContext.inferenceVars())) continue;
565 for (Type u : uv.getBounds(InferenceBound.UPPER)) {
566 if (!infer.types.isSubtypeUnchecked(e, inferenceContext.asFree(u), warn)) {
567 infer.reportBoundError(uv, BoundErrorKind.BAD_EQ_UPPER);
568 }
569 }
570 for (Type l : uv.getBounds(InferenceBound.LOWER)) {
571 if (!infer.types.isSubtypeUnchecked(inferenceContext.asFree(l), e, warn)) {
572 infer.reportBoundError(uv, BoundErrorKind.BAD_EQ_LOWER);
573 }
574 }
575 }
576 }
577 },
578 /**
579 * Given a bound set containing {@code alpha <: T} and {@code alpha :> S}
580 * perform {@code S <: T} (which could lead to new bounds).
581 */
582 CROSS_UPPER_LOWER() {
583 public void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn) {
584 Infer infer = inferenceContext.infer();
585 for (Type b1 : uv.getBounds(InferenceBound.UPPER)) {
586 for (Type b2 : uv.getBounds(InferenceBound.LOWER)) {
587 infer.types.isSubtypeUnchecked(inferenceContext.asFree(b2), inferenceContext.asFree(b1));
588 }
589 }
590 }
591 },
592 /**
593 * Given a bound set containing {@code alpha <: T} and {@code alpha == S}
594 * perform {@code S <: T} (which could lead to new bounds).
595 */
596 CROSS_UPPER_EQ() {
597 public void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn) {
598 Infer infer = inferenceContext.infer();
599 for (Type b1 : uv.getBounds(InferenceBound.UPPER)) {
600 for (Type b2 : uv.getBounds(InferenceBound.EQ)) {
601 infer.types.isSubtypeUnchecked(inferenceContext.asFree(b2), inferenceContext.asFree(b1));
602 }
603 }
604 }
605 },
606 /**
607 * Given a bound set containing {@code alpha :> S} and {@code alpha == T}
608 * perform {@code S <: T} (which could lead to new bounds).
609 */
610 CROSS_EQ_LOWER() {
611 public void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn) {
612 Infer infer = inferenceContext.infer();
613 for (Type b1 : uv.getBounds(InferenceBound.EQ)) {
614 for (Type b2 : uv.getBounds(InferenceBound.LOWER)) {
615 infer.types.isSubtypeUnchecked(inferenceContext.asFree(b2), inferenceContext.asFree(b1));
616 }
617 }
618 }
619 },
620 /**
621 * Given a bound set containing {@code alpha == S} and {@code alpha == T}
622 * perform {@code S == T} (which could lead to new bounds).
623 */
624 CROSS_EQ_EQ() {
625 public void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn) {
626 Infer infer = inferenceContext.infer();
627 for (Type b1 : uv.getBounds(InferenceBound.EQ)) {
628 for (Type b2 : uv.getBounds(InferenceBound.EQ)) {
629 if (b1 != b2) {
630 infer.types.isSameType(inferenceContext.asFree(b2), inferenceContext.asFree(b1));
631 }
632 }
633 }
634 }
635 },
636 /**
637 * Given a bound set containing {@code alpha <: beta} propagate lower bounds
638 * from alpha to beta; also propagate upper bounds from beta to alpha.
639 */
640 PROP_UPPER() {
641 public void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn) {
642 Infer infer = inferenceContext.infer();
643 for (Type b : uv.getBounds(InferenceBound.UPPER)) {
644 if (inferenceContext.inferenceVars().contains(b)) {
645 UndetVar uv2 = (UndetVar)inferenceContext.asFree(b);
646 //alpha <: beta
647 //0. set beta :> alpha
648 uv2.addBound(InferenceBound.LOWER, uv.qtype, infer.types);
649 //1. copy alpha's lower to beta's
650 for (Type l : uv.getBounds(InferenceBound.LOWER)) {
651 uv2.addBound(InferenceBound.LOWER, inferenceContext.asInstType(l), infer.types);
652 }
653 //2. copy beta's upper to alpha's
654 for (Type u : uv2.getBounds(InferenceBound.UPPER)) {
655 uv.addBound(InferenceBound.UPPER, inferenceContext.asInstType(u), infer.types);
656 }
657 }
658 }
659 }
660 },
661 /**
662 * Given a bound set containing {@code alpha :> beta} propagate lower bounds
663 * from beta to alpha; also propagate upper bounds from alpha to beta.
664 */
665 PROP_LOWER() {
666 public void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn) {
667 Infer infer = inferenceContext.infer();
668 for (Type b : uv.getBounds(InferenceBound.LOWER)) {
669 if (inferenceContext.inferenceVars().contains(b)) {
670 UndetVar uv2 = (UndetVar)inferenceContext.asFree(b);
671 //alpha :> beta
672 //0. set beta <: alpha
673 uv2.addBound(InferenceBound.UPPER, uv.qtype, infer.types);
674 //1. copy alpha's upper to beta's
675 for (Type u : uv.getBounds(InferenceBound.UPPER)) {
676 uv2.addBound(InferenceBound.UPPER, inferenceContext.asInstType(u), infer.types);
677 }
678 //2. copy beta's lower to alpha's
679 for (Type l : uv2.getBounds(InferenceBound.LOWER)) {
680 uv.addBound(InferenceBound.LOWER, inferenceContext.asInstType(l), infer.types);
681 }
682 }
683 }
684 }
685 },
686 /**
687 * Given a bound set containing {@code alpha == beta} propagate lower/upper
688 * bounds from alpha to beta and back.
689 */
690 PROP_EQ() {
691 public void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn) {
692 Infer infer = inferenceContext.infer();
693 for (Type b : uv.getBounds(InferenceBound.EQ)) {
694 if (inferenceContext.inferenceVars().contains(b)) {
695 UndetVar uv2 = (UndetVar)inferenceContext.asFree(b);
696 //alpha == beta
697 //0. set beta == alpha
698 uv2.addBound(InferenceBound.EQ, uv.qtype, infer.types);
699 //1. copy all alpha's bounds to beta's
700 for (InferenceBound ib : InferenceBound.values()) {
701 for (Type b2 : uv.getBounds(ib)) {
702 if (b2 != uv2) {
703 uv2.addBound(ib, inferenceContext.asInstType(b2), infer.types);
704 }
705 }
706 }
707 //2. copy all beta's bounds to alpha's
708 for (InferenceBound ib : InferenceBound.values()) {
709 for (Type b2 : uv2.getBounds(ib)) {
710 if (b2 != uv) {
711 uv.addBound(ib, inferenceContext.asInstType(b2), infer.types);
712 }
713 }
714 }
715 }
716 }
717 }
718 };
720 abstract void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn);
721 }
723 /** incorporation steps to be executed when running in legacy mode */
724 EnumSet<IncorporationStep> incorporationStepsLegacy = EnumSet.of(IncorporationStep.EQ_CHECK_LEGACY);
726 /** incorporation steps to be executed when running in graph mode */
727 EnumSet<IncorporationStep> incorporationStepsGraph =
728 EnumSet.complementOf(EnumSet.of(IncorporationStep.EQ_CHECK_LEGACY));
730 /**
731 * Make sure that the upper bounds we got so far lead to a solvable inference
732 * variable by making sure that a glb exists.
733 */
734 void checkCompatibleUpperBounds(UndetVar uv, InferenceContext inferenceContext) {
735 List<Type> hibounds =
736 Type.filter(uv.getBounds(InferenceBound.UPPER), new BoundFilter(inferenceContext));
737 Type hb = null;
738 if (hibounds.isEmpty())
739 hb = syms.objectType;
740 else if (hibounds.tail.isEmpty())
741 hb = hibounds.head;
742 else
743 hb = types.glb(hibounds);
744 if (hb == null || hb.isErroneous())
745 reportBoundError(uv, BoundErrorKind.BAD_UPPER);
746 }
747 //where
748 protected static class BoundFilter implements Filter<Type> {
750 InferenceContext inferenceContext;
752 public BoundFilter(InferenceContext inferenceContext) {
753 this.inferenceContext = inferenceContext;
754 }
756 @Override
757 public boolean accepts(Type t) {
758 return !t.isErroneous() && !inferenceContext.free(t) &&
759 !t.hasTag(BOT);
760 }
761 };
763 /**
764 * This enumeration defines all possible bound-checking related errors.
765 */
766 enum BoundErrorKind {
767 /**
768 * The (uninstantiated) inference variable has incompatible upper bounds.
769 */
770 BAD_UPPER() {
771 @Override
772 InapplicableMethodException setMessage(InferenceException ex, UndetVar uv) {
773 return ex.setMessage("incompatible.upper.bounds", uv.qtype,
774 uv.getBounds(InferenceBound.UPPER));
775 }
776 },
777 /**
778 * An equality constraint is not compatible with an upper bound.
779 */
780 BAD_EQ_UPPER() {
781 @Override
782 InapplicableMethodException setMessage(InferenceException ex, UndetVar uv) {
783 return ex.setMessage("incompatible.eq.upper.bounds", uv.qtype,
784 uv.getBounds(InferenceBound.EQ), uv.getBounds(InferenceBound.UPPER));
785 }
786 },
787 /**
788 * An equality constraint is not compatible with a lower bound.
789 */
790 BAD_EQ_LOWER() {
791 @Override
792 InapplicableMethodException setMessage(InferenceException ex, UndetVar uv) {
793 return ex.setMessage("incompatible.eq.lower.bounds", uv.qtype,
794 uv.getBounds(InferenceBound.EQ), uv.getBounds(InferenceBound.LOWER));
795 }
796 },
797 /**
798 * Instantiated inference variable is not compatible with an upper bound.
799 */
800 UPPER() {
801 @Override
802 InapplicableMethodException setMessage(InferenceException ex, UndetVar uv) {
803 return ex.setMessage("inferred.do.not.conform.to.upper.bounds", uv.inst,
804 uv.getBounds(InferenceBound.UPPER));
805 }
806 },
807 /**
808 * Instantiated inference variable is not compatible with a lower bound.
809 */
810 LOWER() {
811 @Override
812 InapplicableMethodException setMessage(InferenceException ex, UndetVar uv) {
813 return ex.setMessage("inferred.do.not.conform.to.lower.bounds", uv.inst,
814 uv.getBounds(InferenceBound.LOWER));
815 }
816 },
817 /**
818 * Instantiated inference variable is not compatible with an equality constraint.
819 */
820 EQ() {
821 @Override
822 InapplicableMethodException setMessage(InferenceException ex, UndetVar uv) {
823 return ex.setMessage("inferred.do.not.conform.to.eq.bounds", uv.inst,
824 uv.getBounds(InferenceBound.EQ));
825 }
826 };
828 abstract InapplicableMethodException setMessage(InferenceException ex, UndetVar uv);
829 }
831 /**
832 * Report a bound-checking error of given kind
833 */
834 void reportBoundError(UndetVar uv, BoundErrorKind bk) {
835 throw bk.setMessage(inferenceException, uv);
836 }
837 // </editor-fold>
839 // <editor-fold defaultstate="collapsed" desc="Inference engine">
840 /**
841 * Graph inference strategy - act as an input to the inference solver; a strategy is
842 * composed of two ingredients: (i) find a node to solve in the inference graph,
843 * and (ii) tell th engine when we are done fixing inference variables
844 */
845 interface GraphStrategy {
846 /**
847 * Pick the next node (leaf) to solve in the graph
848 */
849 Node pickNode(InferenceGraph g);
850 /**
851 * Is this the last step?
852 */
853 boolean done();
854 }
856 /**
857 * Simple solver strategy class that locates all leaves inside a graph
858 * and picks the first leaf as the next node to solve
859 */
860 abstract class LeafSolver implements GraphStrategy {
861 public Node pickNode(InferenceGraph g) {
862 Assert.check(!g.nodes.isEmpty(), "No nodes to solve!");
863 return g.nodes.get(0);
864 }
865 }
867 /**
868 * This solver uses an heuristic to pick the best leaf - the heuristic
869 * tries to select the node that has maximal probability to contain one
870 * or more inference variables in a given list
871 */
872 abstract class BestLeafSolver extends LeafSolver {
874 List<Type> varsToSolve;
876 BestLeafSolver(List<Type> varsToSolve) {
877 this.varsToSolve = varsToSolve;
878 }
880 /**
881 * Computes the cost associated with a given node; the cost is computed
882 * as the total number of type-variables that should be eagerly instantiated
883 * in order to get to some of the variables in {@code varsToSolve} from
884 * a given node
885 */
886 void computeCostIfNeeded(Node n, Map<Node, Integer> costMap) {
887 if (costMap.containsKey(n)) {
888 return;
889 } else if (!Collections.disjoint(n.data, varsToSolve)) {
890 costMap.put(n, n.data.size());
891 } else {
892 int subcost = Integer.MAX_VALUE;
893 costMap.put(n, subcost); //avoid loops
894 for (Node n2 : n.getDependencies()) {
895 computeCostIfNeeded(n2, costMap);
896 subcost = Math.min(costMap.get(n2), subcost);
897 }
898 //update cost map to reflect real cost
899 costMap.put(n, subcost == Integer.MAX_VALUE ?
900 Integer.MAX_VALUE :
901 n.data.size() + subcost);
902 }
903 }
905 /**
906 * Pick the leaf that minimize cost
907 */
908 @Override
909 public Node pickNode(final InferenceGraph g) {
910 final Map<Node, Integer> costMap = new HashMap<Node, Integer>();
911 ArrayList<Node> leaves = new ArrayList<Node>();
912 for (Node n : g.nodes) {
913 computeCostIfNeeded(n, costMap);
914 if (n.isLeaf(n)) {
915 leaves.add(n);
916 }
917 }
918 Assert.check(!leaves.isEmpty(), "No nodes to solve!");
919 Collections.sort(leaves, new java.util.Comparator<Node>() {
920 public int compare(Node n1, Node n2) {
921 return costMap.get(n1) - costMap.get(n2);
922 }
923 });
924 return leaves.get(0);
925 }
926 }
928 /**
929 * The inference process can be thought of as a sequence of steps. Each step
930 * instantiates an inference variable using a subset of the inference variable
931 * bounds, if certain condition are met. Decisions such as the sequence in which
932 * steps are applied, or which steps are to be applied are left to the inference engine.
933 */
934 enum InferenceStep {
936 /**
937 * Instantiate an inference variables using one of its (ground) equality
938 * constraints
939 */
940 EQ(InferenceBound.EQ) {
941 @Override
942 Type solve(UndetVar uv, InferenceContext inferenceContext) {
943 return filterBounds(uv, inferenceContext).head;
944 }
945 },
946 /**
947 * Instantiate an inference variables using its (ground) lower bounds. Such
948 * bounds are merged together using lub().
949 */
950 LOWER(InferenceBound.LOWER) {
951 @Override
952 Type solve(UndetVar uv, InferenceContext inferenceContext) {
953 Infer infer = inferenceContext.infer();
954 List<Type> lobounds = filterBounds(uv, inferenceContext);
955 Type owntype = infer.types.lub(lobounds);
956 if (owntype.hasTag(ERROR)) {
957 throw infer.inferenceException
958 .setMessage("no.unique.minimal.instance.exists",
959 uv.qtype, lobounds);
960 } else {
961 return owntype;
962 }
963 }
964 },
965 /**
966 * Instantiate an inference variables using its (ground) upper bounds. Such
967 * bounds are merged together using glb().
968 */
969 UPPER(InferenceBound.UPPER) {
970 @Override
971 Type solve(UndetVar uv, InferenceContext inferenceContext) {
972 Infer infer = inferenceContext.infer();
973 List<Type> hibounds = filterBounds(uv, inferenceContext);
974 Type owntype = infer.types.glb(hibounds);
975 if (owntype.isErroneous()) {
976 throw infer.inferenceException
977 .setMessage("no.unique.maximal.instance.exists",
978 uv.qtype, hibounds);
979 } else {
980 return owntype;
981 }
982 }
983 },
984 /**
985 * Like the former; the only difference is that this step can only be applied
986 * if all upper bounds are ground.
987 */
988 UPPER_LEGACY(InferenceBound.UPPER) {
989 @Override
990 public boolean accepts(UndetVar t, InferenceContext inferenceContext) {
991 return !inferenceContext.free(t.getBounds(ib));
992 }
994 @Override
995 Type solve(UndetVar uv, InferenceContext inferenceContext) {
996 return UPPER.solve(uv, inferenceContext);
997 }
998 };
1000 final InferenceBound ib;
1002 InferenceStep(InferenceBound ib) {
1003 this.ib = ib;
1004 }
1006 /**
1007 * Find an instantiated type for a given inference variable within
1008 * a given inference context
1009 */
1010 abstract Type solve(UndetVar uv, InferenceContext inferenceContext);
1012 /**
1013 * Can the inference variable be instantiated using this step?
1014 */
1015 public boolean accepts(UndetVar t, InferenceContext inferenceContext) {
1016 return filterBounds(t, inferenceContext).nonEmpty();
1017 }
1019 /**
1020 * Return the subset of ground bounds in a given bound set (i.e. eq/lower/upper)
1021 */
1022 List<Type> filterBounds(UndetVar uv, InferenceContext inferenceContext) {
1023 return Type.filter(uv.getBounds(ib), new BoundFilter(inferenceContext));
1024 }
1025 }
1027 /**
1028 * This enumeration defines the sequence of steps to be applied when the
1029 * solver works in legacy mode. The steps in this enumeration reflect
1030 * the behavior of old inference routine (see JLS SE 7 15.12.2.7/15.12.2.8).
1031 */
1032 enum LegacyInferenceSteps {
1034 EQ_LOWER(EnumSet.of(InferenceStep.EQ, InferenceStep.LOWER)),
1035 EQ_UPPER(EnumSet.of(InferenceStep.EQ, InferenceStep.UPPER_LEGACY));
1037 final EnumSet<InferenceStep> steps;
1039 LegacyInferenceSteps(EnumSet<InferenceStep> steps) {
1040 this.steps = steps;
1041 }
1042 }
1044 /**
1045 * This enumeration defines the sequence of steps to be applied when the
1046 * graph solver is used. This order is defined so as to maximize compatibility
1047 * w.r.t. old inference routine (see JLS SE 7 15.12.2.7/15.12.2.8).
1048 */
1049 enum GraphInferenceSteps {
1051 EQ(EnumSet.of(InferenceStep.EQ)),
1052 EQ_LOWER(EnumSet.of(InferenceStep.EQ, InferenceStep.LOWER)),
1053 EQ_LOWER_UPPER(EnumSet.of(InferenceStep.EQ, InferenceStep.LOWER, InferenceStep.UPPER));
1055 final EnumSet<InferenceStep> steps;
1057 GraphInferenceSteps(EnumSet<InferenceStep> steps) {
1058 this.steps = steps;
1059 }
1060 }
1062 /**
1063 * This is the graph inference solver - the solver organizes all inference variables in
1064 * a given inference context by bound dependencies - in the general case, such dependencies
1065 * would lead to a cyclic directed graph (hence the name); the dependency info is used to build
1066 * an acyclic graph, where all cyclic variables are bundled together. An inference
1067 * step corresponds to solving a node in the acyclic graph - this is done by
1068 * relying on a given strategy (see GraphStrategy).
1069 */
1070 class GraphSolver {
1072 InferenceContext inferenceContext;
1073 Warner warn;
1075 GraphSolver(InferenceContext inferenceContext, Warner warn) {
1076 this.inferenceContext = inferenceContext;
1077 this.warn = warn;
1078 }
1080 /**
1081 * Solve variables in a given inference context. The amount of variables
1082 * to be solved, and the way in which the underlying acyclic graph is explored
1083 * depends on the selected solver strategy.
1084 */
1085 void solve(GraphStrategy sstrategy) {
1086 checkWithinBounds(inferenceContext, warn); //initial propagation of bounds
1087 InferenceGraph inferenceGraph = new InferenceGraph();
1088 while (!sstrategy.done()) {
1089 InferenceGraph.Node nodeToSolve = sstrategy.pickNode(inferenceGraph);
1090 List<Type> varsToSolve = List.from(nodeToSolve.data);
1091 inferenceContext.save();
1092 try {
1093 //repeat until all variables are solved
1094 outer: while (Type.containsAny(inferenceContext.restvars(), varsToSolve)) {
1095 //for each inference phase
1096 for (GraphInferenceSteps step : GraphInferenceSteps.values()) {
1097 if (inferenceContext.solveBasic(varsToSolve, step.steps)) {
1098 checkWithinBounds(inferenceContext, warn);
1099 continue outer;
1100 }
1101 }
1102 //no progress
1103 throw inferenceException;
1104 }
1105 }
1106 catch (InferenceException ex) {
1107 inferenceContext.rollback();
1108 instantiateAsUninferredVars(varsToSolve, inferenceContext);
1109 checkWithinBounds(inferenceContext, warn);
1110 }
1111 inferenceGraph.deleteNode(nodeToSolve);
1112 }
1113 }
1115 /**
1116 * The dependencies between the inference variables that need to be solved
1117 * form a (possibly cyclic) graph. This class reduces the original dependency graph
1118 * to an acyclic version, where cyclic nodes are folded into a single 'super node'.
1119 */
1120 class InferenceGraph {
1122 /**
1123 * This class represents a node in the graph. Each node corresponds
1124 * to an inference variable and has edges (dependencies) on other
1125 * nodes. The node defines an entry point that can be used to receive
1126 * updates on the structure of the graph this node belongs to (used to
1127 * keep dependencies in sync).
1128 */
1129 class Node extends GraphUtils.TarjanNode<ListBuffer<Type>> {
1131 Set<Node> deps;
1133 Node(Type ivar) {
1134 super(ListBuffer.of(ivar));
1135 this.deps = new HashSet<Node>();
1136 }
1138 @Override
1139 public Iterable<? extends Node> getDependencies() {
1140 return deps;
1141 }
1143 @Override
1144 public String printDependency(GraphUtils.Node<ListBuffer<Type>> to) {
1145 StringBuilder buf = new StringBuilder();
1146 String sep = "";
1147 for (Type from : data) {
1148 UndetVar uv = (UndetVar)inferenceContext.asFree(from);
1149 for (Type bound : uv.getBounds(InferenceBound.values())) {
1150 if (bound.containsAny(List.from(to.data))) {
1151 buf.append(sep);
1152 buf.append(bound);
1153 sep = ",";
1154 }
1155 }
1156 }
1157 return buf.toString();
1158 }
1160 boolean isLeaf(Node n) {
1161 //no deps, or only one self dep
1162 return (n.deps.isEmpty() ||
1163 n.deps.size() == 1 && n.deps.contains(n));
1164 }
1166 void mergeWith(List<? extends Node> nodes) {
1167 for (Node n : nodes) {
1168 Assert.check(n.data.length() == 1, "Attempt to merge a compound node!");
1169 data.appendList(n.data);
1170 deps.addAll(n.deps);
1171 }
1172 //update deps
1173 Set<Node> deps2 = new HashSet<Node>();
1174 for (Node d : deps) {
1175 if (data.contains(d.data.first())) {
1176 deps2.add(this);
1177 } else {
1178 deps2.add(d);
1179 }
1180 }
1181 deps = deps2;
1182 }
1184 void graphChanged(Node from, Node to) {
1185 if (deps.contains(from)) {
1186 deps.remove(from);
1187 if (to != null) {
1188 deps.add(to);
1189 }
1190 }
1191 }
1192 }
1194 /** the nodes in the inference graph */
1195 ArrayList<Node> nodes;
1197 InferenceGraph() {
1198 initNodes();
1199 }
1201 /**
1202 * Delete a node from the graph. This update the underlying structure
1203 * of the graph (including dependencies) via listeners updates.
1204 */
1205 public void deleteNode(Node n) {
1206 Assert.check(nodes.contains(n));
1207 nodes.remove(n);
1208 notifyUpdate(n, null);
1209 }
1211 /**
1212 * Notify all nodes of a change in the graph. If the target node is
1213 * {@code null} the source node is assumed to be removed.
1214 */
1215 void notifyUpdate(Node from, Node to) {
1216 for (Node n : nodes) {
1217 n.graphChanged(from, to);
1218 }
1219 }
1221 /**
1222 * Create the graph nodes. First a simple node is created for every inference
1223 * variables to be solved. Then Tarjan is used to found all connected components
1224 * in the graph. For each component containing more than one node, a super node is
1225 * created, effectively replacing the original cyclic nodes.
1226 */
1227 void initNodes() {
1228 nodes = new ArrayList<Node>();
1229 for (Type t : inferenceContext.restvars()) {
1230 nodes.add(new Node(t));
1231 }
1232 for (Node n_i : nodes) {
1233 Type i = n_i.data.first();
1234 for (Node n_j : nodes) {
1235 Type j = n_j.data.first();
1236 UndetVar uv_i = (UndetVar)inferenceContext.asFree(i);
1237 if (Type.containsAny(uv_i.getBounds(InferenceBound.values()), List.of(j))) {
1238 //update i's deps
1239 n_i.deps.add(n_j);
1240 }
1241 }
1242 }
1243 ArrayList<Node> acyclicNodes = new ArrayList<Node>();
1244 for (List<? extends Node> conSubGraph : GraphUtils.tarjan(nodes)) {
1245 if (conSubGraph.length() > 1) {
1246 Node root = conSubGraph.head;
1247 root.mergeWith(conSubGraph.tail);
1248 for (Node n : conSubGraph) {
1249 notifyUpdate(n, root);
1250 }
1251 }
1252 acyclicNodes.add(conSubGraph.head);
1253 }
1254 nodes = acyclicNodes;
1255 }
1257 /**
1258 * Debugging: dot representation of this graph
1259 */
1260 String toDot() {
1261 StringBuilder buf = new StringBuilder();
1262 for (Type t : inferenceContext.undetvars) {
1263 UndetVar uv = (UndetVar)t;
1264 buf.append(String.format("var %s - upper bounds = %s, lower bounds = %s, eq bounds = %s\\n",
1265 uv.qtype, uv.getBounds(InferenceBound.UPPER), uv.getBounds(InferenceBound.LOWER),
1266 uv.getBounds(InferenceBound.EQ)));
1267 }
1268 return GraphUtils.toDot(nodes, "inferenceGraph" + hashCode(), buf.toString());
1269 }
1270 }
1271 }
1272 // </editor-fold>
1274 // <editor-fold defaultstate="collapsed" desc="Inference context">
1275 /**
1276 * Functional interface for defining inference callbacks. Certain actions
1277 * (i.e. subtyping checks) might need to be redone after all inference variables
1278 * have been fixed.
1279 */
1280 interface FreeTypeListener {
1281 void typesInferred(InferenceContext inferenceContext);
1282 }
1284 /**
1285 * An inference context keeps track of the set of variables that are free
1286 * in the current context. It provides utility methods for opening/closing
1287 * types to their corresponding free/closed forms. It also provide hooks for
1288 * attaching deferred post-inference action (see PendingCheck). Finally,
1289 * it can be used as an entry point for performing upper/lower bound inference
1290 * (see InferenceKind).
1291 */
1292 class InferenceContext {
1294 /** list of inference vars as undet vars */
1295 List<Type> undetvars;
1297 /** list of inference vars in this context */
1298 List<Type> inferencevars;
1300 /** backed up inference variables */
1301 List<Type> saved_undet;
1303 java.util.Map<FreeTypeListener, List<Type>> freeTypeListeners =
1304 new java.util.HashMap<FreeTypeListener, List<Type>>();
1306 List<FreeTypeListener> freetypeListeners = List.nil();
1308 public InferenceContext(List<Type> inferencevars) {
1309 this.undetvars = Type.map(inferencevars, fromTypeVarFun);
1310 this.inferencevars = inferencevars;
1311 }
1312 //where
1313 Mapping fromTypeVarFun = new Mapping("fromTypeVarFunWithBounds") {
1314 // mapping that turns inference variables into undet vars
1315 public Type apply(Type t) {
1316 if (t.hasTag(TYPEVAR)) return new UndetVar((TypeVar)t, types);
1317 else return t.map(this);
1318 }
1319 };
1321 /**
1322 * returns the list of free variables (as type-variables) in this
1323 * inference context
1324 */
1325 List<Type> inferenceVars() {
1326 return inferencevars;
1327 }
1329 /**
1330 * returns the list of uninstantiated variables (as type-variables) in this
1331 * inference context
1332 */
1333 List<Type> restvars() {
1334 return filterVars(new Filter<UndetVar>() {
1335 public boolean accepts(UndetVar uv) {
1336 return uv.inst == null;
1337 }
1338 });
1339 }
1341 /**
1342 * returns the list of instantiated variables (as type-variables) in this
1343 * inference context
1344 */
1345 List<Type> instvars() {
1346 return filterVars(new Filter<UndetVar>() {
1347 public boolean accepts(UndetVar uv) {
1348 return uv.inst != null;
1349 }
1350 });
1351 }
1353 /**
1354 * Get list of bounded inference variables (where bound is other than
1355 * declared bounds).
1356 */
1357 final List<Type> boundedVars() {
1358 return filterVars(new Filter<UndetVar>() {
1359 public boolean accepts(UndetVar uv) {
1360 return uv.getBounds(InferenceBound.UPPER)
1361 .diff(uv.getDeclaredBounds())
1362 .appendList(uv.getBounds(InferenceBound.EQ, InferenceBound.LOWER)).nonEmpty();
1363 }
1364 });
1365 }
1367 private List<Type> filterVars(Filter<UndetVar> fu) {
1368 ListBuffer<Type> res = ListBuffer.lb();
1369 for (Type t : undetvars) {
1370 UndetVar uv = (UndetVar)t;
1371 if (fu.accepts(uv)) {
1372 res.append(uv.qtype);
1373 }
1374 }
1375 return res.toList();
1376 }
1378 /**
1379 * is this type free?
1380 */
1381 final boolean free(Type t) {
1382 return t.containsAny(inferencevars);
1383 }
1385 final boolean free(List<Type> ts) {
1386 for (Type t : ts) {
1387 if (free(t)) return true;
1388 }
1389 return false;
1390 }
1392 /**
1393 * Returns a list of free variables in a given type
1394 */
1395 final List<Type> freeVarsIn(Type t) {
1396 ListBuffer<Type> buf = ListBuffer.lb();
1397 for (Type iv : inferenceVars()) {
1398 if (t.contains(iv)) {
1399 buf.add(iv);
1400 }
1401 }
1402 return buf.toList();
1403 }
1405 final List<Type> freeVarsIn(List<Type> ts) {
1406 ListBuffer<Type> buf = ListBuffer.lb();
1407 for (Type t : ts) {
1408 buf.appendList(freeVarsIn(t));
1409 }
1410 ListBuffer<Type> buf2 = ListBuffer.lb();
1411 for (Type t : buf) {
1412 if (!buf2.contains(t)) {
1413 buf2.add(t);
1414 }
1415 }
1416 return buf2.toList();
1417 }
1419 /**
1420 * Replace all free variables in a given type with corresponding
1421 * undet vars (used ahead of subtyping/compatibility checks to allow propagation
1422 * of inference constraints).
1423 */
1424 final Type asFree(Type t) {
1425 return types.subst(t, inferencevars, undetvars);
1426 }
1428 final List<Type> asFree(List<Type> ts) {
1429 ListBuffer<Type> buf = ListBuffer.lb();
1430 for (Type t : ts) {
1431 buf.append(asFree(t));
1432 }
1433 return buf.toList();
1434 }
1436 List<Type> instTypes() {
1437 ListBuffer<Type> buf = ListBuffer.lb();
1438 for (Type t : undetvars) {
1439 UndetVar uv = (UndetVar)t;
1440 buf.append(uv.inst != null ? uv.inst : uv.qtype);
1441 }
1442 return buf.toList();
1443 }
1445 /**
1446 * Replace all free variables in a given type with corresponding
1447 * instantiated types - if one or more free variable has not been
1448 * fully instantiated, it will still be available in the resulting type.
1449 */
1450 Type asInstType(Type t) {
1451 return types.subst(t, inferencevars, instTypes());
1452 }
1454 List<Type> asInstTypes(List<Type> ts) {
1455 ListBuffer<Type> buf = ListBuffer.lb();
1456 for (Type t : ts) {
1457 buf.append(asInstType(t));
1458 }
1459 return buf.toList();
1460 }
1462 /**
1463 * Add custom hook for performing post-inference action
1464 */
1465 void addFreeTypeListener(List<Type> types, FreeTypeListener ftl) {
1466 freeTypeListeners.put(ftl, freeVarsIn(types));
1467 }
1469 /**
1470 * Mark the inference context as complete and trigger evaluation
1471 * of all deferred checks.
1472 */
1473 void notifyChange() {
1474 notifyChange(inferencevars.diff(restvars()));
1475 }
1477 void notifyChange(List<Type> inferredVars) {
1478 InferenceException thrownEx = null;
1479 for (Map.Entry<FreeTypeListener, List<Type>> entry :
1480 new HashMap<FreeTypeListener, List<Type>>(freeTypeListeners).entrySet()) {
1481 if (!Type.containsAny(entry.getValue(), inferencevars.diff(inferredVars))) {
1482 try {
1483 entry.getKey().typesInferred(this);
1484 freeTypeListeners.remove(entry.getKey());
1485 } catch (InferenceException ex) {
1486 if (thrownEx == null) {
1487 thrownEx = ex;
1488 }
1489 }
1490 }
1491 }
1492 //inference exception multiplexing - present any inference exception
1493 //thrown when processing listeners as a single one
1494 if (thrownEx != null) {
1495 throw thrownEx;
1496 }
1497 }
1499 /**
1500 * Save the state of this inference context
1501 */
1502 void save() {
1503 ListBuffer<Type> buf = ListBuffer.lb();
1504 for (Type t : undetvars) {
1505 UndetVar uv = (UndetVar)t;
1506 UndetVar uv2 = new UndetVar((TypeVar)uv.qtype, types);
1507 for (InferenceBound ib : InferenceBound.values()) {
1508 for (Type b : uv.getBounds(ib)) {
1509 uv2.addBound(ib, b, types);
1510 }
1511 }
1512 uv2.inst = uv.inst;
1513 buf.add(uv2);
1514 }
1515 saved_undet = buf.toList();
1516 }
1518 /**
1519 * Restore the state of this inference context to the previous known checkpoint
1520 */
1521 void rollback() {
1522 Assert.check(saved_undet != null && saved_undet.length() == undetvars.length());
1523 undetvars = saved_undet;
1524 saved_undet = null;
1525 }
1527 /**
1528 * Copy variable in this inference context to the given context
1529 */
1530 void dupTo(final InferenceContext that) {
1531 that.inferencevars = that.inferencevars.appendList(inferencevars);
1532 that.undetvars = that.undetvars.appendList(undetvars);
1533 //set up listeners to notify original inference contexts as
1534 //propagated vars are inferred in new context
1535 for (Type t : inferencevars) {
1536 that.freeTypeListeners.put(new FreeTypeListener() {
1537 public void typesInferred(InferenceContext inferenceContext) {
1538 InferenceContext.this.notifyChange();
1539 }
1540 }, List.of(t));
1541 }
1542 }
1544 /**
1545 * Solve with given graph strategy.
1546 */
1547 private void solve(GraphStrategy ss, Warner warn) {
1548 GraphSolver s = new GraphSolver(this, warn);
1549 s.solve(ss);
1550 }
1552 /**
1553 * Solve all variables in this context.
1554 */
1555 public void solve(Warner warn) {
1556 solve(new LeafSolver() {
1557 public boolean done() {
1558 return restvars().isEmpty();
1559 }
1560 }, warn);
1561 }
1563 /**
1564 * Solve all variables in the given list.
1565 */
1566 public void solve(final List<Type> vars, Warner warn) {
1567 solve(new BestLeafSolver(vars) {
1568 public boolean done() {
1569 return !free(asInstTypes(vars));
1570 }
1571 }, warn);
1572 }
1574 /**
1575 * Solve at least one variable in given list.
1576 */
1577 public void solveAny(List<Type> varsToSolve, Warner warn) {
1578 checkWithinBounds(this, warn); //propagate bounds
1579 List<Type> boundedVars = boundedVars().intersect(restvars()).intersect(varsToSolve);
1580 if (boundedVars.isEmpty()) {
1581 throw inferenceException.setMessage("cyclic.inference",
1582 freeVarsIn(varsToSolve));
1583 }
1584 solve(new BestLeafSolver(boundedVars) {
1585 public boolean done() {
1586 return instvars().intersect(varsToSolve).nonEmpty();
1587 }
1588 }, warn);
1589 }
1591 /**
1592 * Apply a set of inference steps
1593 */
1594 private boolean solveBasic(EnumSet<InferenceStep> steps) {
1595 return solveBasic(inferencevars, steps);
1596 }
1598 private boolean solveBasic(List<Type> varsToSolve, EnumSet<InferenceStep> steps) {
1599 boolean changed = false;
1600 for (Type t : varsToSolve.intersect(restvars())) {
1601 UndetVar uv = (UndetVar)asFree(t);
1602 for (InferenceStep step : steps) {
1603 if (step.accepts(uv, this)) {
1604 uv.inst = step.solve(uv, this);
1605 changed = true;
1606 break;
1607 }
1608 }
1609 }
1610 return changed;
1611 }
1613 /**
1614 * Instantiate inference variables in legacy mode (JLS 15.12.2.7, 15.12.2.8).
1615 * During overload resolution, instantiation is done by doing a partial
1616 * inference process using eq/lower bound instantiation. During check,
1617 * we also instantiate any remaining vars by repeatedly using eq/upper
1618 * instantiation, until all variables are solved.
1619 */
1620 public void solveLegacy(boolean partial, Warner warn, EnumSet<InferenceStep> steps) {
1621 while (true) {
1622 boolean stuck = !solveBasic(steps);
1623 if (restvars().isEmpty() || partial) {
1624 //all variables have been instantiated - exit
1625 break;
1626 } else if (stuck) {
1627 //some variables could not be instantiated because of cycles in
1628 //upper bounds - provide a (possibly recursive) default instantiation
1629 instantiateAsUninferredVars(restvars(), this);
1630 break;
1631 } else {
1632 //some variables have been instantiated - replace newly instantiated
1633 //variables in remaining upper bounds and continue
1634 for (Type t : undetvars) {
1635 UndetVar uv = (UndetVar)t;
1636 uv.substBounds(inferenceVars(), instTypes(), types);
1637 }
1638 }
1639 }
1640 checkWithinBounds(this, warn);
1641 }
1643 private Infer infer() {
1644 //back-door to infer
1645 return Infer.this;
1646 }
1647 }
1649 final InferenceContext emptyContext = new InferenceContext(List.<Type>nil());
1650 // </editor-fold>
1651 }