Skip to content

Commit

Permalink
SONARJAVA-4837 S6878 Fix FP on record methods (#4727)
Browse files Browse the repository at this point in the history
  • Loading branch information
leonardo-pilastri-sonarsource authored Mar 20, 2024
1 parent 2f70d6b commit 8a4de4d
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ int notAComponentAccessTwice(Object obj){
}

int allComponentsPlusAMethod(Object obj){
if (obj instanceof Point p) { // Noncompliant
if (obj instanceof Point p) { // Compliant, using record pattern would not allow access to p.notAComponent
return p.x() + p.y() + p.notAComponent();
}
return 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.sonar.check.Rule;
import org.sonar.plugins.java.api.IssuableSubscriptionVisitor;
import org.sonar.plugins.java.api.JavaFileScannerContext;
Expand All @@ -36,7 +37,6 @@
import org.sonar.plugins.java.api.tree.TypePatternTree;
import org.sonar.plugins.java.api.tree.VariableTree;


@Rule(key = "S6878")
public class RecordPatternInsteadOfFieldAccessCheck extends IssuableSubscriptionVisitor implements JavaVersionAwareVisitor {

Expand Down Expand Up @@ -97,7 +97,11 @@ private void checkTypePatternVariableUsage(VariableTree patternVariable) {

private static boolean isEveryRecordComponentUsed(Set<MemberSelectExpressionTree> secondaryLocationsTrees, Symbol.TypeSymbol recordSymbol) {
var recordComponentNames = recordComponentNames(recordSymbol);
return !recordComponentNames.isEmpty() && secondaryLocationsTrees.stream().map(mse -> mse.identifier().name()).toList().containsAll(recordComponentNames);
return !recordComponentNames.isEmpty() &&
secondaryLocationsTrees.stream()
.map(mse -> mse.identifier().name())
.collect(Collectors.toSet())
.equals(recordComponentNames);
}

private static boolean isNotRecordGetter(MemberSelectExpressionTree mse) {
Expand All @@ -115,14 +119,14 @@ private static boolean isRecordPattern(TypePatternTree typePattern) {
return typePattern.patternVariable().type().symbolType().isSubtypeOf("java.lang.Record");
}

private static List<String> recordComponentNames(Symbol.TypeSymbol recordSymbol) {
private static Set<String> recordComponentNames(Symbol.TypeSymbol recordSymbol) {
return recordSymbol
.memberSymbols()
.stream()
.filter(Symbol::isVariableSymbol)
.map(Symbol.VariableSymbol.class::cast)
.map(Symbol.VariableSymbol::name)
.toList();
.collect(Collectors.toSet());
}

}

0 comments on commit 8a4de4d

Please sign in to comment.