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
| 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:
There was a problem hiding this comment.
Let's do it in a follow-up PR since it requires some refactoring on S6909
| 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.
|
Code Review ✅ Approved 4 resolved / 4 findingsImplements the S9142 rule to detect expensive compilation or preparation operations inside loops, resolving several edge cases including false positives on loop-once calls and field mutations. No issues found. ✅ 4 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
✅ Edge Case: Loop-once check ignores enclosing outer loops
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 |






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