I’ve noticed when a behavior is checked “inside loops”, a Sonar rule checks for “for” loops, “foreach” loops and “while” loops : " Kind.FOR_STATEMENT , Kind.FOR_EACH_STATEMENT and Kind.WHILE_STATEMENT " (see rule ‘java:S3012’ for example)
I can see why Kind.DO_STATEMENT (do… while) is not listed because it’s rarely used (even if it could be added at no cost) but why stream().forEach(...) is not taken into account ?
Is it something possible with Sonar and static analysis ? Or is it considered out of static analysis scope ? More generally, I would have same question for code called by a function into a loop, is there a way to “navigate” to the function source code, and consider it’s inside the loop ?
Wow, this is unexpected… and something which has been missed during the implementation. There is usually no reason at all to avoid do-while statements when targeting loops, especially in this rule. The case has most certainly been completely forgotten while working on the rule (ticket created: SONARJAVA-4206). Don’t hesitate to let us know if there is others, and we will fix it.
That’s a good question… for which I have no satisfactory answer. Most of our rules have been written/specified before the democratization of stream operations in java… and therefore this use case has most probably been ignored. To be included, we would need to review all our rules and consider these new cases. We plan to do such a massive review/update in the close future, but it takes time and reviewing 600+ rules for their consistency/validity is a tremendous work that we are not yet ready to begin.
It is possible, it simply requires another approach (checking for stream() method invocations and their subsequent function calls). We didn’t implement it much yet, but it should be doable. Depending of the complexity of what you want to check, it might however be closer to symbolic execution than pure static analysis.
That’s much harder. Considering the code as “within” the loop is a matter of rule implementation… Navigating from method invocation to its chained method invocation. It also requires code availability.
For code being present in the same file under analysis, you can probably follow the symbols, through the semantic API, and from there investigate the body of the method.
For code outside the file, this won’t be possible with our current approach.