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 6 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
32 changes: 16 additions & 16 deletions src/main/java/org/openrewrite/staticanalysis/EqualsAvoidsNull.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/
package org.openrewrite.staticanalysis;

import org.apache.commons.lang3.ObjectUtils;
import org.jspecify.annotations.Nullable;
import org.openrewrite.*;
import org.openrewrite.java.JavaIsoVisitor;
Expand Down Expand Up @@ -54,24 +55,23 @@ public Duration getEstimatedEffortPerOccurrence() {

@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(
// new UsesMethod<>("java.lang.String *quals*(..)"),
new UsesMethod<>("java.lang.String *(..)"),
new JavaIsoVisitor<ExecutionContext>() {
@Override
public J visit(@Nullable Tree tree, ExecutionContext ctx) {
if (tree instanceof JavaSourceFile) {
JavaSourceFile cu = (JavaSourceFile) requireNonNull(tree);
return new EqualsAvoidsNullVisitor<>(
ObjectUtils.defaultIfNull(cu.getStyle(EqualsAvoidsNullStyle.class),
Checkstyle.equalsAvoidsNull()))
.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
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,18 @@ public class EqualsAvoidsNullVisitor<P> extends JavaVisitor<P> {
private static final String JAVA_LANG_STRING = "java.lang.String ";
private static final MethodMatcher EQUALS = new MethodMatcher(JAVA_LANG_STRING + "equals(java.lang.Object)");
private static final MethodMatcher EQUALS_IGNORE_CASE = new MethodMatcher(JAVA_LANG_STRING + "equalsIgnoreCase(java.lang.String)");
private static final MethodMatcher COMPARE_TO = new MethodMatcher(JAVA_LANG_STRING + "compareTo(java.lang.String)");
private static final MethodMatcher COMPARE_TO_IGNORE_CASE = new MethodMatcher(JAVA_LANG_STRING + "compareToIgnoreCase(java.lang.String)");
private static final MethodMatcher CONTENT_EQUALS = new MethodMatcher(JAVA_LANG_STRING + "contentEquals(java.lang.CharSequence)");

EqualsAvoidsNullStyle style;

@Override
public J visitMethodInvocation(J.MethodInvocation method, P p) {
J.MethodInvocation m = (J.MethodInvocation) super.visitMethodInvocation(method, p);
boolean stringComparisonMethod = isStringComparisonMethod(m);
if (m.getSelect() != null && !(m.getSelect() instanceof J.Literal) &&
isStringComparisonMethod(m) && hasCompatibleArgument(m)) {
stringComparisonMethod && hasCompatibleArgument(m)) {

maybeHandleParentBinary(m);

Expand Down Expand Up @@ -90,7 +93,9 @@ private boolean hasCompatibleArgument(J.MethodInvocation m) {
private boolean isStringComparisonMethod(J.MethodInvocation methodInvocation) {
return EQUALS.matches(methodInvocation) ||
(!style.getIgnoreEqualsIgnoreCase() && EQUALS_IGNORE_CASE.matches(methodInvocation)) ||
CONTENT_EQUALS.matches(methodInvocation);
CONTENT_EQUALS.matches(methodInvocation) ||
COMPARE_TO.matches(methodInvocation) ||
COMPARE_TO_IGNORE_CASE.matches(methodInvocation);
}

private void maybeHandleParentBinary(J.MethodInvocation m) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,58 @@ public class A {
);
}

@DocumentExample
@Test
void invertConditional_compareTo() {
rewriteRun(
//language=java
java(
"""
public class A {
{
String s = null;
if(s.compareTo("test")) {}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm wondering if we should add & then invert any comparison with < 0 here for instance, as indicated in #362 (comment). As it stands I think we're using an int in an if. 😕

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we decide to keep the flip for compareTo, we have to also migrate the comparison. Otherwise, we would also flip the semantic, see #442.

Copy link
Contributor

@MBoegers MBoegers Feb 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ATM, the implementation exclude the flip of < and > needed for compareTo, this can be done later.

}
}
""",
"""
public class A {
{
String s = null;
if("test".compareTo(s)) {}
}
}
"""
)
);
}

@DocumentExample
@Test
void invertConditional_compareToIgnoreCase() {
rewriteRun(
//language=java
java(
"""
public class A {
{
String s = null;
if(s.compareToIgnoreCase("test")) {}
}
}
""",
"""
public class A {
{
String s = null;
if("test".compareToIgnoreCase(s)) {}
}
}
"""
)
);
}

@Test
void removeUnnecessaryNullCheck() {
rewriteRun(
Expand Down Expand Up @@ -447,6 +499,15 @@ public class A {
System.out.println(s.compareToIgnoreCase("test"));
}
}
""",
"""
public class A {
{
String s = null;
System.out.println("test".compareTo(s));
System.out.println("test".compareToIgnoreCase(s));
}
}
"""
)
);
Expand Down
Loading