RFR: 8295020: javac emits incorrect code for for-each on an intersection type.
Maurizio Cimadamore
mcimadamore at openjdk.org
Fri Oct 14 10:14:07 UTC 2022
On Fri, 14 Oct 2022 04:16:33 GMT, Srikanth Adayapalam <sadayapalam at openjdk.org> wrote:
> Eliminate needless casts and ensure invoked method is looked up against the appropriate receiver type
Marked as reviewed by mcimadamore (Reviewer).
src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Lower.java line 3521:
> 3519: if (iterableType.getTypeArguments().nonEmpty())
> 3520: iteratorTarget = types.erasure(iterableType.getTypeArguments().head);
> 3521: tree.expr.type = types.erasure(types.skipTypeVars(tree.expr.type, false));
Shouldn't types already be erased by now (Lower runs after TransTypes?)
src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Lower.java line 3523:
> 3521: tree.expr.type = types.erasure(types.skipTypeVars(tree.expr.type, false));
> 3522: if (types.asSuper(tree.expr.type, syms.iterableType.tsym) == null)
> 3523: tree.expr = make.TypeCast(types.erasure(iterableType), tree.expr);
Can we use the `coerce` function here, which is used to conditionally add a cast if required?
src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Lower.java line 3526:
> 3524: Symbol iterator = lookupMethod(tree.expr.pos(),
> 3525: names.iterator,
> 3526: tree.expr.type,
The real problem here is that the target type of the cast (which ends up in tree.expr.type) and the type used for the lookup in the old code (eType) diverge. The latter might still have references to the source type - e.g. in this case to the covariant MyIterable, so looking up a method there will result in an iterator of some unexpected type. This is not wrong per se, but it should be fixed one way or another (e.g. by always using Iterable, as you have done), or by correctly honoring the covariant type.
A really unfortunate combination of issues here - there is a latent discrepancy of types (eType != tree.expr.type), but that only results in bugs when a cast to Iterable is added (which only happens for interaction types).
-------------
PR: https://git.openjdk.org/jdk/pull/10710
More information about the compiler-dev
mailing list