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

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

daniellansun commented on PR #3367:
URL: https://github.com/apache/groovy/pull/3367#issuecomment-7238471240

   Thanks for the fix and the test matrix in `Groovy12839`. The overall 
approach makes sense, and the patch applies cleanly to `GROOVY_6_0_X` as well 
(the `GrabResolverTest` failure on JDK 25 is an unrelated Restlet repo hiccup).
   
   I ran into a few issues while going through the diff that we should probably 
sort out before merging:
   
   1. Dynamic 0-arg calls on primitive `Fixed1` closures throw 
`NullPointerException` instead of `MissingMethodException`. For example, `{ int 
i -> 'i:' + i }()`, `c.call()`, or `c.doCall()` from dynamic code hits 
`Fixed1.doCall(Object)` via `MetaClassImpl`'s implicit-null 0-arg match, which 
lands in `coerceSole(null)` and `loneNullRefused()`. A closure class (and 
`@CompileStatic` `c.call()`) throws `MissingMethodException` here. Overriding 
`getMethodWithCaching` / `getMethodWithoutCaching` in `PackedClosureMetaClass` 
to return `null` for 0-arg `call`/`doCall` on `Fixed1` would route these 
through `invokeMethod` -> `dispatchAll(EMPTY)` without affecting 1-arg dispatch 
or `Fixed1`'s declared signatures.
   
   2. In `destructure()`, calling 
`DefaultTypeTransformation.castToType(element, t)` breaks two edge cases and 
unnecessarily re-boxes exact primitive wrappers: `{ double d -> 'd:' + d 
}.call([Float.POSITIVE_INFINITY])` (or `NEGATIVE_INFINITY`) throws 
`GroovyRuntimeException` instead of widening to `double` infinity, and a custom 
`List#toArray()` returning a narrowed array like `Byte[]` or `Float[]` throws 
`ArrayStoreException` when writing the widened wrapper back into `elements[i]`. 
Since the generated dispatch tables already emit 
`DefaultTypeTransformation.<type>Unbox` (which handles exact wrappers and all 
JLS 5.1.2 widenings including float infinities), we can just drop that 
`castToType` write once `widens(...)` passes.
   
   3. `paramInfo` is lazily initialized without `volatile`, and 
`ParameterTypes` only stores `nativeParamTypes` in a `volatile` (not `final`) 
field, so under JLS 17.4 another thread on ARM64 can see `nativeParamTypes == 
null` and fail in `getPT()` with `UnsupportedOperationException`. On top of 
that, `ParameterTypes#setParametersTypes` writes `parameterTypes` before 
`isVargsMethod`, so the new `paramInfo().isValidMethod(Class[])` calls can see 
a stale `isVargsMethod == false` on concurrent first use of a vararg closure 
even on x86. Making `paramInfo` `volatile`, calling `info.getParameterTypes()` 
before publishing it, and using `isValidMethod(Object[])` instead of 
`isValidMethod(Class[])` avoids both races (and drops a few temporary `Class[]` 
allocations) at no hot-path cost.
   
   4. A few Javadocs and comments in `PackedClosure` are out of date now. 
`Fixed1.doCall` still says a null argument is passed through (it now throws 
`NullPointerException` for primitive parameters) and does not mention 
`IllegalArgumentException` from destructuring. `FixedIt.doCall` switched to 
`coerceSole(a)` without updating its Javadoc. `FixedN.doCall` is missing 
`NullPointerException` / `IllegalArgumentException`, and its note that a 
non-array 1-param 0-arg call binds null no longer holds for primitives. The 
inline comments on `paramInfo` (line 608) and `dispatchAll` (line 854) also 
still describe the old paths.
   
   5. In `Groovy12839.groovy`, it would be good to add 0-arg routes (`c()`, 
`c.call()`, `c.doCall()`), `byte`/`short`/`float` closures along with 
`Byte`/`Short`/`Float`/`BigInteger`/`Float.POSITIVE_INFINITY`/`NEGATIVE_INFINITY`
 and a narrowed-`toArray()` `List` (which also covers the remaining testable 
branches in `primitiveRank`), a custom non-`Runnable` SAM interface with `[{ -> 
}]` (since `Closure` already implements `Runnable`), a 5-parameter non-vararg 
closure, and a perturbed-MOP check (`use(Category)` / `DelegatingMetaClass`). 
Also on line 171, `{ ['four'] }` has `maximumNumberOfParameters == 1` (implicit 
`it`), so the `: make()` branch is dead; switching the 0-arg factories to `{ -> 
... }` fixes that. A brief comment on line 233 explaining why `array*` is 
excluded would be helpful too.
   
   A few smaller things, none strictly blocking:
   
   - `call(Object)` shrank nicely from 37 B to 31 B, though `coerceArg` went 
from 27 B to 36 B (just over `MaxInlineSize=35`). Combining the two `return` 
lines into `if (t == Object.class || t.isInstance(arg) || (arg == null && 
!t.isPrimitive())) return arg;` brings it back to 34 B. Also, primitive 1-arg 
calls like `{ int x -> }.call(1)` currently hit `arg instanceof List` in 
`coerceSoleSlow` on every call; checking the primitive wrapper match first in 
`coerceSoleSlow` avoids that.
   - In `doCallAdapted`, coercing directly into `all[base + i]` avoids writing 
back into the shared `MetaClassHelper.ARRAY_WITH_NULL` on 0-arg calls (and 
drops the dead `provided.length == 0 && arity == 1` branch). 
`FixedN.doCall(null)` can then reuse a static `SINGLE_NULL` array, and 
`coerceSoleSlow` can allocate `new Object[]{list}` only when throwing 
`MissingMethodException`.
   - Under `ExpandoMetaClass` (e.g. `enableGlobally()`), `Fixed2..4` 
single-`List` calls go through `MetaClassImpl#tryListParamMetaMethod` into the 
erased `doCall` and still coerce `GString` rather than throwing 
`IllegalArgumentException`, and lone `null` throws `NPE` vs `MME`. Fine to 
leave for a follow-up if out of scope here.
   - Replicating `ClosureMetaClass.java:289`'s accidental `NPE` makes sense for 
6.0.x parity, though a short cross-reference comment there would help keep the 
two in sync if it ever changes.
   - A brief `COMPATIBILITY.md` entry (like the 6.0.1 packed-closure ones) 
would be nice for the 6.0.2 backport, and caching the 6 compiled class sets / 
`Closure.getMethod('call', Object[].class)` (plus 
`@ResourceLock(Resources.SYSTEM_PROPERTIES)`) would speed up `Groovy12839`.
   




> Packed closure with one typed parameter rejects a single List argument that a 
> closure class destructures
> --------------------------------------------------------------------------------------------------------
>
>                 Key: GROOVY-12839
>                 URL: https://issues.apache.org/jira/browse/GROOVY-12839
>             Project: Groovy
>          Issue Type: Bug
>          Components: groovy-runtime
>    Affects Versions: 6.0.0, 6.0.1
>            Reporter: Scott Murphy Heiberg
>            Priority: Blocker
>
> GEP-27 closure packing (@PackedClosures, -Dgroovy.target.closure.pack=true; 
> incubating) is meant to be indistinguishable from the closure class the same 
> literal compiles to. The class comment of 
> org.codehaus.groovy.runtime.PackedClosure says:
> {quote}
> Argument adaptation on every route replicates metaclass dispatch on a 
> generated closure class: arity mismatches raise MissingMethodException, a 
> single List destructures across a non-one-parameter signature, trailing-array 
> parameters vararg-collect, and per-parameter coercion follows the metaclass 
> compatibility rules
> {quote}
> A generated closure class does not limit the destructuring to "a 
> non-one-parameter signature". ClosureMetaClass#invokeMethod selects doCall 
> for the arguments as given, and when no doCall applies and the call has 
> exactly one argument that is a List, selects again for the elements of the 
> list and invokes that method with them. So a closure with one typed parameter 
> that is not a supertype of the list takes a one-element list as it takes the 
> element. The packed form keeps the list as the argument and fails.
> This is how Spock invokes a mock response closure (the arguments of the 
> invocation as one List), so a packed response closure with one typed 
> parameter fails. It was found that way.
> {code:groovy}
> class ListArg {
>     static void main(String[] args) {
>         Closure<Integer> c = { String s -> s.length() }
>         println c.call(['four'])
>     }
> }
> {code}
> Expected (and what {{java -cp groovy-6.0.1.jar groovy.ui.GroovyMain 
> ListArg.groovy}} prints):
> {noformat}
> 4
> {noformat}
> Actual with {{-Dgroovy.target.closure.pack=true}}, or with 
> @groovy.transform.PackedClosures on the class, dynamic or @CompileStatic:
> {noformat}
> groovy.lang.MissingMethodException: No signature of method: doCall for class: 
> org.codehaus.groovy.runtime.PackedClosure$Fixed1 is applicable for argument 
> types: (ArrayList) values: [[four]]
> {noformat}
> The same on every route: Closure#call(Object), Closure#call(Object...), 
> c(['four']), c.call(['four']) and c.doCall(['four']) from dynamic code. 
> Reproduced with 6.0.0, 6.0.1 and master (7.0.0-SNAPSHOT).
> Comparing each literal compiled both ways, with a single List or a single 
> null as the argument, shows the other places where the two differ for the 
> same reason (the packed form does not follow the two-step rule):
> || closure || argument || closure class || packed ||
> | \{ String s -> \} | ['four'] | s = 'four' | MissingMethodException |
> | \{ String s -> \} | [null] | s = null | MissingMethodException |
> | \{ int i -> \} | [1] | i = 1 | MissingMethodException |
> | \{ String[] a -> \} | [null], or a list holding one String[] | a = the 
> element | IllegalArgumentException |
> | \{ String[] a -> \} | [1] | MissingMethodException | 
> IllegalArgumentException |
> | \{ a, Object... b -> \} | ['four'] | a = ['four'], b = [] (the list is 
> accepted as it stands) | a = 'four', b = [] |
> | \{ List a, Object... b -> \} | ['four'] | a = ['four'], b = [] | 
> MissingMethodException |
> | \{ String a, String b -> \} | a list of a String and a GString | 
> IllegalArgumentException (the elements are passed unconverted) | binds, 
> converting the GString |
> | \{ String... a -> \}, \{ a, Object... b -> \} | null, called from dynamic 
> code | a = null | a = [] (first), MissingMethodException (second) |
> | \{ int i -> \} | null | NullPointerException | GroovyCastException |
> | \{ -> \}, \{ a, b -> \} | null | NullPointerException | 
> MissingMethodException |
> Closures whose single parameter accepts the list (Object, untyped, implicit 
> it, List, Collection, Iterable, an array of a type the list is an instance 
> of) already agree: the parameter is the list.
> Proposed fix (pull request to follow)
> In PackedClosure, destructure a single List argument exactly when the 
> signature does not accept the list as it stands 
> (ParameterTypes#isValidMethod, the test ClosureMetaClass applies), for any 
> number of parameters, and then treat the elements as ClosureMetaClass does: 
> MissingMethodException when no signature applies to them, no conversion 
> otherwise. The check sits behind the existing "argument is not an instance of 
> the parameter type" test, so a call whose argument the parameter takes 
> directly costs what it did.



--
This message was sent by Atlassian Jira
(v10.3.26#10030026)

Reply via email to