[ 
https://issues.apache.org/jira/browse/GROOVY-12767?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=18146737#comment-18146737
 ] 

ASF GitHub Bot commented on GROOVY-12767:
-----------------------------------------

daniellansun commented on code in PR #3307:
URL: https://github.com/apache/groovy/pull/3307#discussion_r4614518121


##########
src/test/groovy/groovy/transform/stc/LoopsSTCTest.groovy:
##########
@@ -456,4 +456,76 @@ class LoopsSTCTest extends StaticTypeCheckingTestCase {
             }
         '''
     }
+
+    // GROOVY-12767
+    @Test
+    void testForAwaitLoopElementType() {
+        assertScript '''
+            import java.util.concurrent.Flow
+
+            int fromList(List<Integer> source) {
+                int sum = 0
+                for await (Integer x in source) { sum += x }
+                for await (x in source) { sum += x.intValue() }
+                sum
+            }
+            int fromIterator(Iterator<Integer> source) {
+                int sum = 0
+                for await (x in source) { sum += x.intValue() }
+                sum
+            }
+            int fromArray(Integer[] source) {
+                int sum = 0
+                for await (int x in source) { sum += x }
+                for await (x in source) { sum += x.intValue() }
+                sum
+            }
+            int fromPublisher(Flow.Publisher<Integer> source) {

Review Comment:
   Optional, not blocking: this method is type-checked, which is enough to pin 
the `Publisher` typings, but it is never called. If you want a runtime case as 
well, a tiny re-subscribable stub is safer than `SubmissionPublisher`: the 
built-in adapter's iterable is single-use, so two `for await` loops over the 
same publisher instance would not be a fair test.



##########
src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java:
##########
@@ -3417,6 +3421,36 @@ public static ClassNode inferLoopElementType(final 
ClassNode collectionType) {
         return componentType;
     }
 
+    /**
+     * Returns {@code Iterable<E>} for the call a {@code for await} loop makes 
to
+     * convert its source, {@code AsyncSupport.toIterable(source)}, where 
{@code E}
+     * is the element type of an array, {@code Iterable}, {@code Iterator} or
+     * {@code Flow.Publisher} source. The method declares {@code <T> 
Iterable<T>}
+     * and takes an {@code Object}, so nothing else gives {@code T} a type.
+     *
+     * @return the type, or {@code null} for another method or kind of source
+     */
+    private static ClassNode forAwaitIterableType(final MethodNode method, 
final ClassNode[] argumentTypes) {
+        if (argumentTypes.length != 1 || !"toIterable".equals(method.getName())
+                || !ASYNC_SUPPORT_TYPE.equals(method.getDeclaringClass())) {
+            return null;
+        }
+        ClassNode sourceType = argumentTypes[0];
+        ClassNode elementType;
+        if (sourceType.isArray()) {
+            elementType = sourceType.getComponentType();
+            if (isPrimitiveType(elementType)) return null; // not a source the 
conversion accepts

Review Comment:
   Optional, not blocking: this fail-closed arm matches `toIterable`'s 
`instanceof Object[]` check, so a primitive array correctly stays untyped. A 
small negative test (`for await (int x in int[])` rejected / untyped `x` stays 
`Object`) would cover the branch Codecov reports as partial. The javadoc's "an 
array" is also a little broader than the implementation; "non-primitive array" 
would match the code.





> 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
>            Priority: Major
>
> 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)

Reply via email to