[
https://issues.apache.org/jira/browse/GROOVY-12562?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=18134489#comment-18134489
]
ASF GitHub Bot commented on GROOVY-12562:
-----------------------------------------
testlens-app[bot] commented on PR #3091:
URL: https://github.com/apache/groovy/pull/3091#issuecomment-6509261545
## ✅ All tests passed ✅
🏷️ Commit: 94a3fd60930134ecea1851f6722a764a62fe65f7
▶️ Tests: 119259 executed
⚪️ Checks: 26/26 completed
---
_Learn more about TestLens at
[testlens.app/docs](https://testlens.app/docs/features/pr-comment/)._
> 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: 4.0.33, 5.0.8, 6.0.0
> Reporter: Scott Murphy Heiberg
> Priority: Major
>
> 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.
> PR: https://github.com/apache/groovy/pull/3091
--
This message was sent by Atlassian Jira
(v10.3.26#10030026)