Scott Murphy Heiberg created GROOVY-12603:
---------------------------------------------

             Summary: Compound assignment, increment or decrement of a trait 
field inside a closure or lambda loses the update or fails
                 Key: GROOVY-12603
                 URL: https://issues.apache.org/jira/browse/GROOVY-12603
             Project: Groovy
          Issue Type: Bug
    Affects Versions: 5.0.8, 4.0.33, 6.0.0
            Reporter: Scott Murphy Heiberg


{code:groovy}
trait T {
    private int x = 1
    def m() { [1].each { x++ }; [1].each { x += 2 }; x }
}
class C implements T {}
new C().m()
{code}
Actual: m() returns 1 because both updates are lost. With @CompileStatic on the 
trait, the += throws GroovyCastException: Cannot cast object '3' with class 
'java.lang.Integer' to class 'T'. For a static field, or inside a lambda, 
@CompileStatic fails at compile time instead ("Cannot access method: T__x$get() 
of class: java.lang.Object", or an ASM instruction selection error). The same 
applies to public and static fields, x--, ++x, and the other compound operators.

Expected: x += 2 and the other compound operators update the field, as they do 
in a trait method body. x++, x--, ++x and --x are rejected at compile time with 
"Postfix/Prefix expressions on trait fields/properties are not supported in 
traits", as they are in a trait method body.

Cause: the trait transformation rewrites x op= y into x = x op y and rejects 
prefix and postfix operations on trait fields, but that rewriter never visited 
closure or lambda bodies. The field reference inside the closure was turned 
into a field-helper getter call, and the operator was applied to the call 
result.

Seen in 4.0.33, 5.0.8 and 6.0.0.



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

Reply via email to