Skip to content

Commit

Permalink
SONARJAVA-4898 Fix issue reporting of java:S6218
Browse files Browse the repository at this point in the history
  • Loading branch information
Wohops committed Mar 4, 2024
1 parent 22d78bf commit 0b76498
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ public String toString() {
}
}

record MissingEverything(Object[] objects) { // Noncompliant {{Override equals, hashCode and toString to consider array's content in the method}}
record MissingEverything( // Noncompliant [[sc=10;ec=27;secondary=28]] {{Override equals, hashCode and toString to consider array's content in the method}}
Object[] objects) {
static Object defaultValue = null;
void doNothing(){}
}
Expand Down Expand Up @@ -85,4 +86,11 @@ public int hashCode() {
return 42;
}
}

record multipleArrays( // Noncompliant [[sc=10;ec=24;secondary=92,95]]
Object a,
int[] b,
Object c,
java.util.Collection<Object[]> d, // not an array
int... e) {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,12 @@
import java.util.Optional;
import org.sonar.check.Rule;
import org.sonar.plugins.java.api.IssuableSubscriptionVisitor;
import org.sonar.plugins.java.api.JavaFileScannerContext;
import org.sonar.plugins.java.api.semantic.MethodMatchers;
import org.sonar.plugins.java.api.tree.ClassTree;
import org.sonar.plugins.java.api.tree.MethodTree;
import org.sonar.plugins.java.api.tree.Tree;
import org.sonar.plugins.java.api.tree.VariableTree;

@Rule(key = "S6218")
public class MissingOverridesInRecordWithArrayComponentCheck extends IssuableSubscriptionVisitor {
Expand Down Expand Up @@ -61,14 +63,22 @@ public List<Tree.Kind> nodesToVisit() {
public void visitNode(Tree tree) {
ClassTree targetRecord = (ClassTree) tree;

boolean recordHasArrayComponent = targetRecord.recordComponents().stream()
.anyMatch(component -> component.symbol().type().isArray());
if (!recordHasArrayComponent) {
List<VariableTree> recordArrayComponents = targetRecord.recordComponents().stream()
.filter(component -> component.symbol().type().isArray())
.toList();

if (recordArrayComponents.isEmpty()) {
return;
}

Optional<String> message = inspectRecord(targetRecord);
message.ifPresent(composedMessage -> reportIssue(targetRecord, composedMessage));
inspectRecord(targetRecord)
.ifPresent(composedMessage -> reportIssue(targetRecord.simpleName(), composedMessage, secondaries(recordArrayComponents), null));
}

private static List<JavaFileScannerContext.Location> secondaries(List<VariableTree> recordArrayComponents) {
return recordArrayComponents.stream()
.map(arrayComponent -> new JavaFileScannerContext.Location("Array", arrayComponent))
.toList();
}

public static Optional<String> inspectRecord(ClassTree tree) {
Expand Down

0 comments on commit 0b76498

Please sign in to comment.