Scott Murphy Heiberg created GROOVY-12562:
---------------------------------------------

             Summary: STC: instanceof narrows a variable where the check does 
not guard the code
                 Key: GROOVY-12562
                 URL: https://issues.apache.org/jira/browse/GROOVY-12562
             Project: Groovy
          Issue Type: Bug
          Components: Static Type Checker
    Affects Versions: 5.0.8, 4.0.33, 6.0.0
            Reporter: Scott Murphy Heiberg


The type checker narrows a variable after any {{instanceof}} check on it, for 
the rest of the expression or statement, wherever the check is. Under 
{{@CompileStatic}} the program then fails with a ClassCastException:

{code:groovy}
@groovy.transform.CompileStatic
String f(CharSequence cs) { 'x' + (cs instanceof String) + cs.length() }
f(new StringBuilder('ab')) // ClassCastException: StringBuilder cannot be cast 
to String (5.0.8, 6.0.0)
{code}

The same holds for {{foo(cs instanceof String, cs.length())}}, {{[cs instanceof 
String, cs]}} and {{(cs instanceof String) == cs.isEmpty()}}. A comparison with 
{{false}} narrows the wrong branch, and the condition of a loop narrows after 
the loop:

{code:groovy}
@groovy.transform.CompileStatic
int h(Object x) { if ((x instanceof String) == false) { return x.length() }; 0 }
h(42) // ClassCastException: Integer cannot be cast to String

@groovy.transform.CompileStatic
int g(Object x) { while (x instanceof String) { break }; x.length() }
g(42) // ClassCastException
{code}

The last two fail in 4.0.33, 5.0.8 and 6.0.0, the first in 5.0.8 and 6.0.0.

Expected: a check narrows only where its outcome guards what follows (the 
condition of an if, while, for, assert or conditional expression, and operands 
of &&, || and ! there); {{(x instanceof T) == true}} narrows like the check and 
{{== false}} like its negation; a loop condition narrows inside the loop only.



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

Reply via email to