SONARJAVA-6706 Implement new rule S2330 - #5867
Conversation
Detect array covariance where an array of a derived type is assigned to a variable declared as an array of its base type, which can lead to ArrayStoreException at runtime.
| private void visitReturnStatement(ReturnStatementTree tree) { | ||
| var expression = tree.expression(); | ||
| if (expression == null) { | ||
| return; | ||
| } | ||
| Tree enclosing = ExpressionUtils.getEnclosingTree(tree, Tree.Kind.METHOD, Tree.Kind.LAMBDA_EXPRESSION); | ||
| if (enclosing != null) { | ||
| var lhsType = enclosing instanceof LambdaExpressionTree lambda | ||
| ? lambda.symbol().returnType().type() | ||
| : ((MethodTree) enclosing).returnType().symbolType(); | ||
| checkArrayCovariance(lhsType, expression); | ||
| } | ||
| } |
There was a problem hiding this comment.
💡 Edge Case: Expression-bodied lambdas escape covariance detection
The return-path handling only fires on Tree.Kind.RETURN_STATEMENT, but an expression-bodied lambda such as Supplier<Fruit[]> s = () -> new Apple[1]; has no return statement node (its body is an ExpressionTree, not a block with a return). Such covariant lambda bodies are therefore never checked, a false negative compared to the block-lambda case that is tested at ArrayCovarianceCheckSample.java:85-89. Consider also handling LAMBDA_EXPRESSION nodes directly: when the body is an ExpressionTree, compare lambda.symbol().returnType().type() against the body expression's type.
Was this helpful? React with 👍 / 👎
CI failed: 1 ruling test failure in the integration test suite caused by new rule S2330 producing unexpected issue differences against the baseline.Overview1 ruling integration test failure was observed where the new rule S2330 introduced 63 issue differences against the expected baseline during FailuresRuling Test Baseline Mismatch from New Rule S2330 (confidence: high)
Summary
Code Review 👍 Approved with suggestions 0 resolved / 1 findingsImplements rule S2330 to detect unsafe array covariance and prevent runtime ArrayStoreExceptions. Expression-bodied lambdas currently escape covariance detection and should be handled in return-path logic. 💡 Edge Case: Expression-bodied lambdas escape covariance detection📄 java-checks/src/main/java/org/sonar/java/checks/ArrayCovarianceCheck.java:79-91 The return-path handling only fires on Tree.Kind.RETURN_STATEMENT, but an expression-bodied lambda such as 🤖 Prompt for agentsTip Comment 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 |
|
|
❌ Ruling needs updating. A fix PR has been created: #5868 Please review and merge it into your branch. |


Detect array covariance where an array of a derived type is assigned to a variable declared as an array of its base type, which can lead to ArrayStoreException at runtime.