Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/*
* Copyright 2021 the original author or authors.
Copy link
Member

Choose a reason for hiding this comment

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

Might want to adjust ./gradle/licenceHeader.txt and this here to set the right year.

* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openrewrite.staticanalysis;

import org.openrewrite.ExecutionContext;
import org.openrewrite.Preconditions;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.search.UsesType;
import org.openrewrite.java.tree.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class EqualsToContentEquals extends Recipe {
private static final MethodMatcher equals_matcher = new MethodMatcher("java.lang.String equals(..)");
private static final List<String> TYPE_NAMES = Arrays.asList(
"java.lang.StringBuffer",
"java.lang.StringBuilder",
"java.lang.CharSequence"
);
@SuppressWarnings("unchecked")
private static final TreeVisitor<?, ExecutionContext> PRECONDITION =
Preconditions.or(TYPE_NAMES.stream().map(s -> new UsesType<>(s, false)).toArray(UsesType[]::new));
private static final List<MethodMatcher> toString_matchers = TYPE_NAMES.stream()
.map(obj -> new MethodMatcher(obj + " toString()")).collect(Collectors.toList());

@Override
public String getDisplayName() {
return "Use contentEquals to compare StringBuilder to a String";
}
@Override
public String getDescription() {
return "Use contentEquals to compare StringBuilder to a String.";
}

public TreeVisitor<?, ExecutionContext> getVisitor() {
return Preconditions.check(PRECONDITION, new EqualsToContentEqualsVisitor());
}

private static class EqualsToContentEqualsVisitor extends JavaIsoVisitor<ExecutionContext> {
@Override
public J.MethodInvocation visitMethodInvocation(J.MethodInvocation mi, ExecutionContext ctx) {
J.MethodInvocation m = super.visitMethodInvocation(mi, ctx);
J.Identifier methodName = m.getName();
// create method matcher on equals(String)
if (equals_matcher.matches(m)) {
Expression argument = m.getArguments().get(0);

// checks whether the argument is a toString() method call on a StringBuffer or CharSequence
if (toString_matchers.stream().anyMatch(matcher -> matcher.matches(argument))) {
J.MethodInvocation inv = (J.MethodInvocation) argument;
Expression newArg = inv.getSelect();
if (inv.getSelect() == null) { return m; }

Stream<JavaType> TYPES = Stream.of(
JavaType.buildType("java.lang.StringBuilder"),
JavaType.buildType("java.lang.StringBuffer"),
JavaType.buildType("java.lang.CharSequence")
);
Copy link
Member

Choose a reason for hiding this comment

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

We can probably also move these to a field above.


if (TYPES.anyMatch(type -> TypeUtils.isOfType(newArg.getType(), type))) {
// strip out the toString() on the argument
List<Expression> args = new ArrayList<>(1);
args.add(newArg);
m = m.withArguments(args);
// rename the method to contentEquals
methodName = m.getName().withSimpleName("contentEquals");
}
}
}

return m.withName(methodName);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
/*
* Copyright 2021 the original author or authors.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openrewrite.staticanalysis;

import org.junit.jupiter.api.Test;
import org.openrewrite.java.JavaParser;
import org.openrewrite.test.RecipeSpec;
import org.openrewrite.test.RewriteTest;

import static org.openrewrite.java.Assertions.java;

public class EqualsToContentEqualsTest implements RewriteTest {

@Override
public void defaults(RecipeSpec spec) {
spec
.parser(JavaParser.fromJavaVersion())
.recipe(new EqualsToContentEquals());
}

@Test
public void replaceStringBuilder() {
//language=java
rewriteRun(
java(
"""
class SomeClass {
boolean foo(StringBuilder sb) {
String str = "example string";
return str.equals(sb.toString());
}
}
""",
"""
class SomeClass {
boolean foo(StringBuilder sb) {
String str = "example string";
return str.contentEquals(sb);
}
}
"""
)
);
}

@Test
public void onlyRunsOnCorrectInvocations() {
//language=java
rewriteRun(
java(
"""
class SomeClass {
boolean foo(int number, String str) {
return str.equals(number.toString());
}
}
"""
)
);
}

@Test
void runsOnStringBuffer() {
//language=java
rewriteRun(
java(
"""
class SomeClass {
boolean foo(StringBuffer sb, String str) {
return str.equals(sb.toString());
}
}
""",
"""
class SomeClass {
boolean foo(StringBuffer sb, String str) {
return str.contentEquals(sb);
}
}
"""
)
);
}

@Test
void runsOnCharSequence() {
//language=java
rewriteRun(
java(
"""
class SomeClass {
boolean foo(CharSequence cs, String str) {
return str.equals(cs.toString());
}
}
""",
"""
class SomeClass {
boolean foo(CharSequence cs, String str) {
return str.contentEquals(cs);
}
}
"""
)
);
}
}