Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix PMD rule LiteralsFirstInComparisons for compareTo* and contentEquals #448

Merged
Show file tree
Hide file tree
Changes from 28 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
23ce336
form
pinguin3245678 Dec 27, 2024
1f33b73
Use new `J.SwitchExpression` constructor
knutwannheden Jan 23, 2025
b38ff0a
Use new `J.SwitchExpression` constructor
knutwannheden Jan 23, 2025
3725b4a
Merge remote-tracking branch 'f/Fix-PMD-rule-LiteralsFirstInCompariso…
Jan 25, 2025
52676bf
tmp fix invertConditional_compareToIgnoreCase
Jan 25, 2025
883f9cf
wip
Jan 25, 2025
1d3c8de
tmp fix
Jan 25, 2025
d33d0aa
move EqualsAvoidsNullVisitor into Recipe
pinguin3245678 Feb 7, 2025
a99ae40
conduct preconditions
pinguin3245678 Feb 7, 2025
b53e380
static import
pinguin3245678 Feb 7, 2025
decf84b
Merge branch 'main' into Fix-PMD-rule-LiteralsFirstInComparisons-for-…
Feb 7, 2025
8512dbf
duplicate retainCompareToAsToNotChangeOrder
Feb 9, 2025
df5a264
Merge branch 'main' into Fix-PMD-rule-LiteralsFirstInComparisons-for-…
Feb 9, 2025
7d9975f
undo
Feb 9, 2025
0ae11da
resolve comparison
Feb 9, 2025
d238c49
Merge branch 'main' into Fix-PMD-rule-LiteralsFirstInComparisons-for-…
Feb 9, 2025
d2124a5
invertConditionalButKeepComparisonOrder
Feb 9, 2025
dac658c
@Issue("https://github.com/openrewrite/rewrite-static-analysis/issues…
Feb 9, 2025
7b1b55c
@Issue("https://github.com/openrewrite/rewrite-static-analysis/issues…
Feb 9, 2025
21ca2f7
extend invertConditionalButKeepComparisonOrder
Feb 9, 2025
045ce06
keepOrderForSameType
Feb 9, 2025
2e556b2
remove duplication
Feb 9, 2025
905573f
inline
Feb 9, 2025
ac52710
inline
Feb 9, 2025
f6016dd
inline
Feb 9, 2025
8b8bd10
inline
Feb 9, 2025
74cd190
form
Feb 9, 2025
46f143b
Revert "form"
Feb 9, 2025
5818a6e
remove duplicated tests, wrapping visitor and clean-ups
MBoegers Feb 10, 2025
c20e777
fix style and import
MBoegers Feb 10, 2025
fe68ae1
Update src/main/java/org/openrewrite/staticanalysis/EqualsAvoidsNull.…
MBoegers Feb 10, 2025
ce96ade
reintroduced variable after GitHUb removed it..
MBoegers Feb 10, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
171 changes: 151 additions & 20 deletions src/main/java/org/openrewrite/staticanalysis/EqualsAvoidsNull.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,34 @@
*/
package org.openrewrite.staticanalysis;

import org.apache.commons.lang3.ObjectUtils;
import org.jspecify.annotations.Nullable;
import org.openrewrite.*;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Preconditions;
import org.openrewrite.Recipe;
import org.openrewrite.Tree;
import org.openrewrite.TreeVisitor;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.JavaVisitor;
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.search.UsesMethod;
import org.openrewrite.java.style.Checkstyle;
import org.openrewrite.java.style.EqualsAvoidsNullStyle;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.Flag;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JLeftPadded;
import org.openrewrite.java.tree.JavaSourceFile;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.java.tree.Space;
import org.openrewrite.marker.Markers;

import java.time.Duration;
import java.util.Collections;
import java.util.Set;

import static java.time.Duration.ofMinutes;
import static java.util.Collections.singleton;
import static java.util.Collections.singletonList;
import static java.util.Objects.requireNonNull;

public class EqualsAvoidsNull extends Recipe {
Expand All @@ -44,34 +59,150 @@ public String getDescription() {

@Override
public Set<String> getTags() {
return Collections.singleton("RSPEC-S1132");
return singleton("RSPEC-S1132");
}

@Override
public Duration getEstimatedEffortPerOccurrence() {
return Duration.ofMinutes(10);
return ofMinutes(10);
}

private static final String JAVA_LANG_STRING = "java.lang.String";

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
JavaIsoVisitor<ExecutionContext> replacementVisitor = new JavaIsoVisitor<ExecutionContext>() {
@Override
public J visit(@Nullable Tree tree, ExecutionContext ctx) {
if (tree instanceof JavaSourceFile) {
JavaSourceFile cu = (JavaSourceFile) requireNonNull(tree);
EqualsAvoidsNullStyle style = cu.getStyle(EqualsAvoidsNullStyle.class);
if (style == null) {
style = Checkstyle.equalsAvoidsNull();
return Preconditions.check(
Preconditions.or(
new UsesMethod<>(JAVA_LANG_STRING + " contentEquals(..)"),
new UsesMethod<>(JAVA_LANG_STRING + " equals(..)"),
new UsesMethod<>(JAVA_LANG_STRING + " equalsIgnoreCase(..)")),
new JavaIsoVisitor<ExecutionContext>() {

@Override
public J visit(@Nullable Tree tree, ExecutionContext ctx) {
if (tree instanceof JavaSourceFile) {
JavaSourceFile cu = (JavaSourceFile) requireNonNull(tree);
return new JavaVisitor<ExecutionContext>() {

private final MethodMatcher EQUALS =
new MethodMatcher(JAVA_LANG_STRING + " equals(java.lang.Object)");
private final MethodMatcher EQUALS_IGNORE_CASE =
new MethodMatcher(JAVA_LANG_STRING + " equalsIgnoreCase(" + JAVA_LANG_STRING + ")");
private final MethodMatcher CONTENT_EQUALS = new MethodMatcher(JAVA_LANG_STRING
+ " contentEquals(java.lang.CharSequence)");

@Override
public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext p) {
J.MethodInvocation m = (J.MethodInvocation) super.visitMethodInvocation(method, p);
if (m.getSelect() != null
&& !(m.getSelect() instanceof J.Literal)
&& isStringComparisonMethod(m)
&& hasCompatibleArgument(m)) {
maybeHandleParentBinary(m, getCursor().getParentTreeCursor().getValue());
Expression firstArgument = m.getArguments().get(0);
return firstArgument.getType() == JavaType.Primitive.Null
? literalsFirstInComparisonsNull(m, firstArgument)
: literalsFirstInComparisons(m, firstArgument);
}
return m;
}

private boolean hasCompatibleArgument(J.MethodInvocation m) {
if (m.getArguments().isEmpty()) {
return false;
}
Expression firstArgument = m.getArguments().get(0);
if (firstArgument instanceof J.Literal) {
return true;
}
if (firstArgument instanceof J.FieldAccess) {
firstArgument = ((J.FieldAccess) firstArgument).getName();
}
if (firstArgument instanceof J.Identifier) {
JavaType.Variable fieldType = ((J.Identifier) firstArgument).getFieldType();
return fieldType != null && fieldType.hasFlags(Flag.Static, Flag.Final);
}
return false;
}

private boolean isStringComparisonMethod(J.MethodInvocation methodInvocation) {
return EQUALS.matches(methodInvocation)
|| !ObjectUtils
.defaultIfNull(cu.getStyle(EqualsAvoidsNullStyle.class),
Checkstyle.equalsAvoidsNull())
.getIgnoreEqualsIgnoreCase()
&& EQUALS_IGNORE_CASE.matches(methodInvocation)
|| CONTENT_EQUALS.matches(methodInvocation);
}

private void maybeHandleParentBinary(J.MethodInvocation m, final Tree parent) {
if (parent instanceof J.Binary) {
if (((J.Binary) parent).getOperator() == J.Binary.Type.And
&& ((J.Binary) parent).getLeft() instanceof J.Binary) {
J.Binary potentialNullCheck = (J.Binary) ((J.Binary) parent).getLeft();
if (isNullLiteral(potentialNullCheck.getLeft())
&& matchesSelect(potentialNullCheck.getRight(),
requireNonNull(m.getSelect()))
|| isNullLiteral(potentialNullCheck.getRight())
&& matchesSelect(potentialNullCheck.getLeft(),
requireNonNull(m.getSelect()))) {
doAfterVisit(new JavaVisitor<ExecutionContext>() {

private final J.Binary scope = (J.Binary) parent;
private boolean done;

@Override
public @Nullable J visit(@Nullable Tree tree, ExecutionContext p) {
return done
? (J) tree
: super.visit(tree, p);
}

@Override
public J visitBinary(J.Binary binary, ExecutionContext p) {
if (scope.isScope(binary)) {
done = true;
return binary.getRight().withPrefix(binary.getPrefix());
}
return super.visitBinary(binary, p);
}
});
}
}
}
}

private boolean isNullLiteral(Expression expression) {
return expression instanceof J.Literal && ((J.Literal) expression).getType() == JavaType.Primitive.Null;
}

private boolean matchesSelect(Expression expression, Expression select) {
return expression.printTrimmed(getCursor()).replaceAll("\\s", "")
.equals(select.printTrimmed(getCursor()).replaceAll("\\s", ""));
}

private J.Binary literalsFirstInComparisonsNull(J.MethodInvocation m,
Expression firstArgument) {
return new J.Binary(Tree.randomId(),
m.getPrefix(),
Markers.EMPTY,
requireNonNull(m.getSelect()),
JLeftPadded.build(J.Binary.Type.Equal).withBefore(Space.SINGLE_SPACE),
firstArgument.withPrefix(Space.SINGLE_SPACE),
JavaType.Primitive.Boolean);
}

private J.MethodInvocation literalsFirstInComparisons(J.MethodInvocation m,
Expression firstArgument) {
return m.withSelect(firstArgument.withPrefix(requireNonNull(m.getSelect()).getPrefix()))
.withArguments(singletonList(m.getSelect().withPrefix(Space.EMPTY)));
}
}.visitNonNull(cu, ctx);
}
//noinspection DataFlowIssue
return (J) tree;
}
return new EqualsAvoidsNullVisitor<>(style).visitNonNull(cu, ctx);
}
//noinspection DataFlowIssue
return (J) tree;
}
};
return Preconditions.check(
new UsesMethod<>("java.lang.String *quals*(..)"),
replacementVisitor
);
}
}

This file was deleted.

Loading