Paul King created GROOVY-12767:
----------------------------------
Summary: STC: the element type of a for await loop is always Object
Key: GROOVY-12767
URL: https://issues.apache.org/jira/browse/GROOVY-12767
Project: Groovy
Issue Type: Bug
Reporter: Paul King
Under {{@CompileStatic}} or {{@TypeChecked}}, the loop variable of a {{for
await}} loop is typed {{Object}}, whatever the source. A typed loop variable is
rejected, and an untyped one can't call the element's methods. The equivalent
plain {{for}} loop compiles.
{code:groovy}
@groovy.transform.CompileStatic
void m() {
List<Integer> src = [1, 2]
for (Integer x in src) { } // ok
for await (Integer x in src) { } // [Static type checking] - Cannot loop
with element of type java.lang.Integer
// with collection of type
java.lang.Iterable<java.lang.Object>
for await (x in src) { x.intValue() } // Cannot find matching method
java.lang.Object#intValue()
}
{code}
The same happens for {{Iterator<Integer>}}, {{Integer[]}},
{{AsyncChannel<Integer>}} and {{Flow.Publisher<Integer>}} (for example
{{SubmissionPublisher<Integer>}}). Seen on 6.0.0 and master.
Cause: the parser rewrites the loop to iterate over
{{AsyncSupport.toIterable(source)}}
({{AsyncTransformHelper.wrapForAwaitLoop}}), declared as {{<T> Iterable<T>
toIterable(Object source)}}. Nothing binds {{T}}, so the type checker sees
{{Iterable<Object>}}. The error message also names that rewritten type rather
than the type of the source.
Expected: the element type of the source, as for a plain {{for}} loop: {{E}}
for an {{Iterable<E>}}, {{Iterator<E>}}, {{E[]}} or {{Stream<E>}} (an
{{AsyncChannel<E>}} is an {{Iterable<E>}}), and {{T}} for a
{{Flow.Publisher<T>}}. Other sources, such as types handled through an
{{AwaitableAdapter}}, stay {{Object}}.
Possible fixes:
* *Type checker* (preferred): {{wrapForAwaitLoop}} records the original source
expression on the {{ForStatement}} as node metadata, and
{{StaticTypeCheckingVisitor.visitForLoop}} takes the element type from that
expression's type: {{inferLoopElementType}} as for a plain loop, plus
{{Flow.Publisher<T>}}. Covers typed and untyped loop variables and corrects the
error message. It changes no runtime methods or generated calls, so code
compiled with the fix still runs on a 6.0.0 runtime.
* *Typed temporary variable*: declare the temporary as {{Iterable<V>}} when the
loop variable has a type {{V}}. A smaller change, but an untyped loop variable
stays {{Object}}.
* *Typed {{toIterable}} overloads* ({{Iterable<T>}}, {{Iterator<T>}}, {{T[]}},
{{Flow.Publisher<T>}}): new {{@GroovyABI}} methods, so statically compiled code
would need the newer runtime.
Workaround: use an untyped loop variable and cast in the body.
--
This message was sent by Atlassian Jira
(v10.3.26#10030026)