Fri, 12 Nov 2010 12:33:52 +0000
6999067: cast for invokeExact call gets redundant cast to <type> warnings
Summary: Xlint:cast should not report cast used in order to specify target type in polymorphic signature calls
Reviewed-by: jjg
1 /*
2 * Copyright (c) 1999, 2009, 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.util.*;
31 import com.sun.tools.javac.util.List;
32 import com.sun.tools.javac.code.*;
33 import com.sun.tools.javac.code.Type.*;
34 import com.sun.tools.javac.code.Type.ForAll.ConstraintKind;
35 import com.sun.tools.javac.code.Symbol.*;
36 import com.sun.tools.javac.util.JCDiagnostic;
38 import static com.sun.tools.javac.code.TypeTags.*;
40 /** Helper class for type parameter inference, used by the attribution phase.
41 *
42 * <p><b>This is NOT part of any supported API.
43 * If you write code that depends on this, you do so at your own risk.
44 * This code and its internal interfaces are subject to change or
45 * deletion without notice.</b>
46 */
47 public class Infer {
48 protected static final Context.Key<Infer> inferKey =
49 new Context.Key<Infer>();
51 /** A value for prototypes that admit any type, including polymorphic ones. */
52 public static final Type anyPoly = new Type(NONE, null);
54 Symtab syms;
55 Types types;
56 Check chk;
57 Resolve rs;
58 JCDiagnostic.Factory diags;
60 public static Infer instance(Context context) {
61 Infer instance = context.get(inferKey);
62 if (instance == null)
63 instance = new Infer(context);
64 return instance;
65 }
67 protected Infer(Context context) {
68 context.put(inferKey, this);
69 syms = Symtab.instance(context);
70 types = Types.instance(context);
71 rs = Resolve.instance(context);
72 chk = Check.instance(context);
73 diags = JCDiagnostic.Factory.instance(context);
74 ambiguousNoInstanceException =
75 new NoInstanceException(true, diags);
76 unambiguousNoInstanceException =
77 new NoInstanceException(false, diags);
78 invalidInstanceException =
79 new InvalidInstanceException(diags);
81 }
83 public static class InferenceException extends Resolve.InapplicableMethodException {
84 private static final long serialVersionUID = 0;
86 InferenceException(JCDiagnostic.Factory diags) {
87 super(diags);
88 }
89 }
91 public static class NoInstanceException extends InferenceException {
92 private static final long serialVersionUID = 1;
94 boolean isAmbiguous; // exist several incomparable best instances?
96 NoInstanceException(boolean isAmbiguous, JCDiagnostic.Factory diags) {
97 super(diags);
98 this.isAmbiguous = isAmbiguous;
99 }
100 }
102 public static class InvalidInstanceException extends InferenceException {
103 private static final long serialVersionUID = 2;
105 InvalidInstanceException(JCDiagnostic.Factory diags) {
106 super(diags);
107 }
108 }
110 private final NoInstanceException ambiguousNoInstanceException;
111 private final NoInstanceException unambiguousNoInstanceException;
112 private final InvalidInstanceException invalidInstanceException;
114 /***************************************************************************
115 * Auxiliary type values and classes
116 ***************************************************************************/
118 /** A mapping that turns type variables into undetermined type variables.
119 */
120 Mapping fromTypeVarFun = new Mapping("fromTypeVarFun") {
121 public Type apply(Type t) {
122 if (t.tag == TYPEVAR) return new UndetVar(t);
123 else return t.map(this);
124 }
125 };
127 /** A mapping that returns its type argument with every UndetVar replaced
128 * by its `inst' field. Throws a NoInstanceException
129 * if this not possible because an `inst' field is null.
130 * Note: mutually referring undertvars will be left uninstantiated
131 * (that is, they will be replaced by the underlying type-variable).
132 */
134 Mapping getInstFun = new Mapping("getInstFun") {
135 public Type apply(Type t) {
136 switch (t.tag) {
137 case UNKNOWN:
138 throw ambiguousNoInstanceException
139 .setMessage("undetermined.type");
140 case UNDETVAR:
141 UndetVar that = (UndetVar) t;
142 if (that.inst == null)
143 throw ambiguousNoInstanceException
144 .setMessage("type.variable.has.undetermined.type",
145 that.qtype);
146 return isConstraintCyclic(that) ?
147 that.qtype :
148 apply(that.inst);
149 default:
150 return t.map(this);
151 }
152 }
154 private boolean isConstraintCyclic(UndetVar uv) {
155 Types.UnaryVisitor<Boolean> constraintScanner =
156 new Types.UnaryVisitor<Boolean>() {
158 List<Type> seen = List.nil();
160 Boolean visit(List<Type> ts) {
161 for (Type t : ts) {
162 if (visit(t)) return true;
163 }
164 return false;
165 }
167 public Boolean visitType(Type t, Void ignored) {
168 return false;
169 }
171 @Override
172 public Boolean visitClassType(ClassType t, Void ignored) {
173 if (t.isCompound()) {
174 return visit(types.supertype(t)) ||
175 visit(types.interfaces(t));
176 } else {
177 return visit(t.getTypeArguments());
178 }
179 }
180 @Override
181 public Boolean visitWildcardType(WildcardType t, Void ignored) {
182 return visit(t.type);
183 }
185 @Override
186 public Boolean visitUndetVar(UndetVar t, Void ignored) {
187 if (seen.contains(t)) {
188 return true;
189 } else {
190 seen = seen.prepend(t);
191 return visit(t.inst);
192 }
193 }
194 };
195 return constraintScanner.visit(uv);
196 }
197 };
199 /***************************************************************************
200 * Mini/Maximization of UndetVars
201 ***************************************************************************/
203 /** Instantiate undetermined type variable to its minimal upper bound.
204 * Throw a NoInstanceException if this not possible.
205 */
206 void maximizeInst(UndetVar that, Warner warn) throws NoInstanceException {
207 if (that.inst == null) {
208 if (that.hibounds.isEmpty())
209 that.inst = syms.objectType;
210 else if (that.hibounds.tail.isEmpty())
211 that.inst = that.hibounds.head;
212 else
213 that.inst = types.glb(that.hibounds);
214 }
215 if (that.inst == null ||
216 that.inst.isErroneous())
217 throw ambiguousNoInstanceException
218 .setMessage("no.unique.maximal.instance.exists",
219 that.qtype, that.hibounds);
220 }
221 //where
222 private boolean isSubClass(Type t, final List<Type> ts) {
223 t = t.baseType();
224 if (t.tag == TYPEVAR) {
225 List<Type> bounds = types.getBounds((TypeVar)t);
226 for (Type s : ts) {
227 if (!types.isSameType(t, s.baseType())) {
228 for (Type bound : bounds) {
229 if (!isSubClass(bound, List.of(s.baseType())))
230 return false;
231 }
232 }
233 }
234 } else {
235 for (Type s : ts) {
236 if (!t.tsym.isSubClass(s.baseType().tsym, types))
237 return false;
238 }
239 }
240 return true;
241 }
243 /** Instantiate undetermined type variable to the lub of all its lower bounds.
244 * Throw a NoInstanceException if this not possible.
245 */
246 void minimizeInst(UndetVar that, Warner warn) throws NoInstanceException {
247 if (that.inst == null) {
248 if (that.lobounds.isEmpty())
249 that.inst = syms.botType;
250 else if (that.lobounds.tail.isEmpty())
251 that.inst = that.lobounds.head.isPrimitive() ? syms.errType : that.lobounds.head;
252 else {
253 that.inst = types.lub(that.lobounds);
254 }
255 if (that.inst == null || that.inst.tag == ERROR)
256 throw ambiguousNoInstanceException
257 .setMessage("no.unique.minimal.instance.exists",
258 that.qtype, that.lobounds);
259 // VGJ: sort of inlined maximizeInst() below. Adding
260 // bounds can cause lobounds that are above hibounds.
261 if (that.hibounds.isEmpty())
262 return;
263 Type hb = null;
264 if (that.hibounds.tail.isEmpty())
265 hb = that.hibounds.head;
266 else for (List<Type> bs = that.hibounds;
267 bs.nonEmpty() && hb == null;
268 bs = bs.tail) {
269 if (isSubClass(bs.head, that.hibounds))
270 hb = types.fromUnknownFun.apply(bs.head);
271 }
272 if (hb == null ||
273 !types.isSubtypeUnchecked(hb, that.hibounds, warn) ||
274 !types.isSubtypeUnchecked(that.inst, hb, warn))
275 throw ambiguousNoInstanceException;
276 }
277 }
279 /***************************************************************************
280 * Exported Methods
281 ***************************************************************************/
283 /** Try to instantiate expression type `that' to given type `to'.
284 * If a maximal instantiation exists which makes this type
285 * a subtype of type `to', return the instantiated type.
286 * If no instantiation exists, or if several incomparable
287 * best instantiations exist throw a NoInstanceException.
288 */
289 public Type instantiateExpr(ForAll that,
290 Type to,
291 Warner warn) throws InferenceException {
292 List<Type> undetvars = Type.map(that.tvars, fromTypeVarFun);
293 for (List<Type> l = undetvars; l.nonEmpty(); l = l.tail) {
294 UndetVar uv = (UndetVar) l.head;
295 TypeVar tv = (TypeVar)uv.qtype;
296 ListBuffer<Type> hibounds = new ListBuffer<Type>();
297 for (Type t : that.getConstraints(tv, ConstraintKind.EXTENDS)) {
298 hibounds.append(types.subst(t, that.tvars, undetvars));
299 }
301 List<Type> inst = that.getConstraints(tv, ConstraintKind.EQUAL);
302 if (inst.nonEmpty() && inst.head.tag != BOT) {
303 uv.inst = inst.head;
304 }
305 uv.hibounds = hibounds.toList();
306 }
307 Type qtype1 = types.subst(that.qtype, that.tvars, undetvars);
308 if (!types.isSubtype(qtype1, to)) {
309 throw unambiguousNoInstanceException
310 .setMessage("infer.no.conforming.instance.exists",
311 that.tvars, that.qtype, to);
312 }
313 for (List<Type> l = undetvars; l.nonEmpty(); l = l.tail)
314 maximizeInst((UndetVar) l.head, warn);
315 // System.out.println(" = " + qtype1.map(getInstFun));//DEBUG
317 // check bounds
318 List<Type> targs = Type.map(undetvars, getInstFun);
319 if (Type.containsAny(targs, that.tvars)) {
320 //replace uninferred type-vars
321 targs = types.subst(targs,
322 that.tvars,
323 instaniateAsUninferredVars(undetvars, that.tvars));
324 }
325 return chk.checkType(warn.pos(), that.inst(targs, types), to);
326 }
327 //where
328 private List<Type> instaniateAsUninferredVars(List<Type> undetvars, List<Type> tvars) {
329 ListBuffer<Type> new_targs = ListBuffer.lb();
330 //step 1 - create syntethic captured vars
331 for (Type t : undetvars) {
332 UndetVar uv = (UndetVar)t;
333 Type newArg = new CapturedType(t.tsym.name, t.tsym, uv.inst, syms.botType, null);
334 new_targs = new_targs.append(newArg);
335 }
336 //step 2 - replace synthetic vars in their bounds
337 for (Type t : new_targs.toList()) {
338 CapturedType ct = (CapturedType)t;
339 ct.bound = types.subst(ct.bound, tvars, new_targs.toList());
340 WildcardType wt = new WildcardType(ct.bound, BoundKind.EXTENDS, syms.boundClass);
341 ct.wildcard = wt;
342 }
343 return new_targs.toList();
344 }
346 /** Instantiate method type `mt' by finding instantiations of
347 * `tvars' so that method can be applied to `argtypes'.
348 */
349 public Type instantiateMethod(final Env<AttrContext> env,
350 List<Type> tvars,
351 MethodType mt,
352 final Symbol msym,
353 final List<Type> argtypes,
354 final boolean allowBoxing,
355 final boolean useVarargs,
356 final Warner warn) throws InferenceException {
357 //-System.err.println("instantiateMethod(" + tvars + ", " + mt + ", " + argtypes + ")"); //DEBUG
358 List<Type> undetvars = Type.map(tvars, fromTypeVarFun);
359 List<Type> formals = mt.argtypes;
360 //need to capture exactly once - otherwise subsequent
361 //applicability checks might fail
362 final List<Type> capturedArgs = types.capture(argtypes);
363 List<Type> actuals = capturedArgs;
364 List<Type> actualsNoCapture = argtypes;
365 // instantiate all polymorphic argument types and
366 // set up lower bounds constraints for undetvars
367 Type varargsFormal = useVarargs ? formals.last() : null;
368 if (varargsFormal == null &&
369 actuals.size() != formals.size()) {
370 throw unambiguousNoInstanceException
371 .setMessage("infer.arg.length.mismatch");
372 }
373 while (actuals.nonEmpty() && formals.head != varargsFormal) {
374 Type formal = formals.head;
375 Type actual = actuals.head.baseType();
376 Type actualNoCapture = actualsNoCapture.head.baseType();
377 if (actual.tag == FORALL)
378 actual = instantiateArg((ForAll)actual, formal, tvars, warn);
379 Type undetFormal = types.subst(formal, tvars, undetvars);
380 boolean works = allowBoxing
381 ? types.isConvertible(actual, undetFormal, warn)
382 : types.isSubtypeUnchecked(actual, undetFormal, warn);
383 if (!works) {
384 throw unambiguousNoInstanceException
385 .setMessage("infer.no.conforming.assignment.exists",
386 tvars, actualNoCapture, formal);
387 }
388 formals = formals.tail;
389 actuals = actuals.tail;
390 actualsNoCapture = actualsNoCapture.tail;
391 }
393 if (formals.head != varargsFormal) // not enough args
394 throw unambiguousNoInstanceException.setMessage("infer.arg.length.mismatch");
396 // for varargs arguments as well
397 if (useVarargs) {
398 Type elemType = types.elemtype(varargsFormal);
399 Type elemUndet = types.subst(elemType, tvars, undetvars);
400 while (actuals.nonEmpty()) {
401 Type actual = actuals.head.baseType();
402 Type actualNoCapture = actualsNoCapture.head.baseType();
403 if (actual.tag == FORALL)
404 actual = instantiateArg((ForAll)actual, elemType, tvars, warn);
405 boolean works = types.isConvertible(actual, elemUndet, warn);
406 if (!works) {
407 throw unambiguousNoInstanceException
408 .setMessage("infer.no.conforming.assignment.exists",
409 tvars, actualNoCapture, elemType);
410 }
411 actuals = actuals.tail;
412 actualsNoCapture = actualsNoCapture.tail;
413 }
414 }
416 // minimize as yet undetermined type variables
417 for (Type t : undetvars)
418 minimizeInst((UndetVar) t, warn);
420 /** Type variables instantiated to bottom */
421 ListBuffer<Type> restvars = new ListBuffer<Type>();
423 /** Undet vars instantiated to bottom */
424 final ListBuffer<Type> restundet = new ListBuffer<Type>();
426 /** Instantiated types or TypeVars if under-constrained */
427 ListBuffer<Type> insttypes = new ListBuffer<Type>();
429 /** Instantiated types or UndetVars if under-constrained */
430 ListBuffer<Type> undettypes = new ListBuffer<Type>();
432 for (Type t : undetvars) {
433 UndetVar uv = (UndetVar)t;
434 if (uv.inst.tag == BOT) {
435 restvars.append(uv.qtype);
436 restundet.append(uv);
437 insttypes.append(uv.qtype);
438 undettypes.append(uv);
439 uv.inst = null;
440 } else {
441 insttypes.append(uv.inst);
442 undettypes.append(uv.inst);
443 }
444 }
445 checkWithinBounds(tvars, undettypes.toList(), warn);
447 mt = (MethodType)types.subst(mt, tvars, insttypes.toList());
449 if (!restvars.isEmpty()) {
450 // if there are uninstantiated variables,
451 // quantify result type with them
452 final List<Type> inferredTypes = insttypes.toList();
453 final List<Type> all_tvars = tvars; //this is the wrong tvars
454 final MethodType mt2 = new MethodType(mt.argtypes, null, mt.thrown, syms.methodClass);
455 mt2.restype = new ForAll(restvars.toList(), mt.restype) {
456 @Override
457 public List<Type> getConstraints(TypeVar tv, ConstraintKind ck) {
458 for (Type t : restundet.toList()) {
459 UndetVar uv = (UndetVar)t;
460 if (uv.qtype == tv) {
461 switch (ck) {
462 case EXTENDS: return uv.hibounds.appendList(types.subst(types.getBounds(tv), all_tvars, inferredTypes));
463 case SUPER: return uv.lobounds;
464 case EQUAL: return uv.inst != null ? List.of(uv.inst) : List.<Type>nil();
465 }
466 }
467 }
468 return List.nil();
469 }
471 @Override
472 public Type inst(List<Type> inferred, Types types) throws NoInstanceException {
473 List<Type> formals = types.subst(mt2.argtypes, tvars, inferred);
474 if (!rs.argumentsAcceptable(capturedArgs, formals,
475 allowBoxing, useVarargs, warn)) {
476 // inferred method is not applicable
477 throw invalidInstanceException.setMessage("inferred.do.not.conform.to.params", formals, argtypes);
478 }
479 // check that inferred bounds conform to their bounds
480 checkWithinBounds(all_tvars,
481 types.subst(inferredTypes, tvars, inferred), warn);
482 if (useVarargs) {
483 chk.checkVararg(env.tree.pos(), formals, msym, env);
484 }
485 return super.inst(inferred, types);
486 }};
487 return mt2;
488 }
489 else if (!rs.argumentsAcceptable(capturedArgs, mt.getParameterTypes(), allowBoxing, useVarargs, warn)) {
490 // inferred method is not applicable
491 throw invalidInstanceException.setMessage("inferred.do.not.conform.to.params", mt.getParameterTypes(), argtypes);
492 }
493 else {
494 // return instantiated version of method type
495 return mt;
496 }
497 }
498 //where
500 /** Try to instantiate argument type `that' to given type `to'.
501 * If this fails, try to insantiate `that' to `to' where
502 * every occurrence of a type variable in `tvars' is replaced
503 * by an unknown type.
504 */
505 private Type instantiateArg(ForAll that,
506 Type to,
507 List<Type> tvars,
508 Warner warn) throws InferenceException {
509 List<Type> targs;
510 try {
511 return instantiateExpr(that, to, warn);
512 } catch (NoInstanceException ex) {
513 Type to1 = to;
514 for (List<Type> l = tvars; l.nonEmpty(); l = l.tail)
515 to1 = types.subst(to1, List.of(l.head), List.of(syms.unknownType));
516 return instantiateExpr(that, to1, warn);
517 }
518 }
520 /** check that type parameters are within their bounds.
521 */
522 void checkWithinBounds(List<Type> tvars,
523 List<Type> arguments,
524 Warner warn)
525 throws InvalidInstanceException {
526 for (List<Type> tvs = tvars, args = arguments;
527 tvs.nonEmpty();
528 tvs = tvs.tail, args = args.tail) {
529 if (args.head instanceof UndetVar) continue;
530 List<Type> bounds = types.subst(types.getBounds((TypeVar)tvs.head), tvars, arguments);
531 if (!types.isSubtypeUnchecked(args.head, bounds, warn))
532 throw invalidInstanceException
533 .setMessage("inferred.do.not.conform.to.bounds",
534 args.head, bounds);
535 }
536 }
538 /**
539 * Compute a synthetic method type corresponding to the requested polymorphic
540 * method signature. If no explicit return type is supplied, a provisional
541 * return type is computed (just Object in case of non-transitional 292)
542 */
543 Type instantiatePolymorphicSignatureInstance(Env<AttrContext> env, Type site,
544 Name name,
545 MethodSymbol spMethod, // sig. poly. method or null if none
546 List<Type> argtypes,
547 List<Type> typeargtypes) {
548 final Type restype;
549 if (rs.allowTransitionalJSR292 && typeargtypes.nonEmpty()) {
550 restype = typeargtypes.head;
551 } else {
552 //The return type for a polymorphic signature call is computed from
553 //the enclosing tree E, as follows: if E is a cast, then use the
554 //target type of the cast expression as a return type; if E is an
555 //expression statement, the return type is 'void' - otherwise the
556 //return type is simply 'Object'. A correctness check ensures that
557 //env.next refers to the lexically enclosing environment in which
558 //the polymorphic signature call environment is nested.
560 switch (env.next.tree.getTag()) {
561 case JCTree.TYPECAST:
562 JCTypeCast castTree = (JCTypeCast)env.next.tree;
563 restype = (castTree.expr == env.tree) ?
564 castTree.clazz.type :
565 syms.objectType;
566 break;
567 case JCTree.EXEC:
568 JCTree.JCExpressionStatement execTree =
569 (JCTree.JCExpressionStatement)env.next.tree;
570 restype = (execTree.expr == env.tree) ?
571 syms.voidType :
572 syms.objectType;
573 break;
574 default:
575 restype = syms.objectType;
576 }
577 }
579 List<Type> paramtypes = Type.map(argtypes, implicitArgType);
580 List<Type> exType = spMethod != null ?
581 spMethod.getThrownTypes() :
582 List.of(syms.throwableType); // make it throw all exceptions
584 MethodType mtype = new MethodType(paramtypes,
585 restype,
586 exType,
587 syms.methodClass);
588 return mtype;
589 }
590 //where
591 Mapping implicitArgType = new Mapping ("implicitArgType") {
592 public Type apply(Type t) {
593 t = types.erasure(t);
594 if (t.tag == BOT)
595 // nulls type as the marker type Null (which has no instances)
596 // infer as java.lang.Void for now
597 t = types.boxedClass(syms.voidType).type;
598 return t;
599 }
600 };
601 }