SONARJAVA-6722 Implement S9142: Expensive compilation or preparation operations should not be performed inside loops - #5893
Conversation
|
❌ Ruling needs updating. A fix PR has been created: #5894 Please review and merge it into your branch. |
Ruling Diff SummaryDetected changes in 2 rule files: 0 issues removed, 11 issues added. S9142 (
|
|
|
❌ Ruling needs updating. A fix PR has been created: #5894 Please review and merge it into your branch. |
Use a String-specific issue message, skip OpenJDK split fast-path and for-initializers, and require all Pattern.compile arguments to be loop-invariant.
0765dd5 to
a3a2611
Compare
Code Review ✅ Approved 3 resolved / 3 findingsImplements rule S9142 to detect expensive compilation or preparation operations inside loops, addressing misleading regex messages, test coverage gaps, and loop-invariant false positives. ✅ 3 resolved✅ Quality: Misleading message for String instance regex methods
✅ Edge Case: Missing test coverage for key edge cases
✅ Edge Case: Invariance check misses field mutations, causing false positives
OptionsAuto-apply is off → Gitar will not commit updates to this branch. Comment with these commands to change the behavior for this request:
Was this helpful? React with 👍 / 👎 | Gitar |
|
| return false; | ||
| } | ||
|
|
||
| private static boolean isLoopInvariant(ExpressionTree arg, Tree loop) { |
There was a problem hiding this comment.
Checking for loop invariants sounds like something that would be nice to extract as a common helper, I checked and rule S6909 defines a very similar method:
| return String.format("Move this \"%s\" call outside the loop.", ExpressionUtils.methodName(mit).name()); | ||
| } | ||
|
|
||
| private static boolean isInForInitializer(Tree tree, Tree loop) { |
There was a problem hiding this comment.
FP found by an LLM:
The iterable expression in an enhanced for-loop (e.g. for (String s : text.split(";")) or for (String s : Pattern.compile(";").split(text))) is evaluated only once before the loop starts (JLS §14.14.2).
Because isInForInitializer only checks ForStatementTree.initializer(), calls inside ForEachStatement.expression() will be flagged as false positives.






Summary by Gitar
CompilationOrPreparationInLoopCheck(S9142) to detect regex compilation and database preparation inside loopsS9142rule verificationS9142This will update automatically on new commits.