Skip to content

fix: remove unused imports after deleting a method argument #5710

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
Expand Up @@ -35,6 +35,8 @@ public static void foo(int n1, int n2) {}
public static void foo(int n1, int n2, int n3) {}
public B() {}
public B(int n) {}
public static void foo(String s) {}
public static void foo(java.util.List<?> l) {}
}
""";

Expand Down Expand Up @@ -125,4 +127,131 @@ void deleteFirstArgument() {
)
);
}

@Test
void deleteNullArgument() {
rewriteRun(
spec -> spec.recipe(new DeleteMethodArgument("B foo(String)", 0)),
java(
"public class A {{ B.foo(null); }}",
"public class A {{ B.foo(); }}"
)
);
}

@Test
void removeUnusedImportOfGenericType() {
rewriteRun(
spec -> spec.recipes(new DeleteMethodArgument("B foo(java.util.List)", 0)),
java(
"""
import java.util.ArrayList;

class A {{ B.foo(new ArrayList<>()); }}
""",
"""
class A {{ B.foo(); }}
"""
)
);
}

@Test
void removeUnusedImportOfClassOfStaticMethodWithoutAStaticImport() {
rewriteRun(
spec -> spec.recipes(new DeleteMethodArgument("B foo(java.util.List)", 0)),
java(
"""
import java.util.Collections;

class A {{ B.foo(Collections.emptyList()); }}
""",
"""
class A {{ B.foo(); }}
"""
)
);
}

@Test
void removeUnusedStaticMethodImport() {
rewriteRun(
spec -> spec.recipes(new DeleteMethodArgument("B foo(int)", 0)),
java(
"""
import static java.lang.Math.max;

class A {{ B.foo(max(1,2)); }}
""",
"""
class A {{ B.foo(); }}
"""
)
);
}

@Test
void removeUnusedStaticFieldImport() {
rewriteRun(
spec -> spec.recipes(new DeleteMethodArgument("B foo(int)", 0)),
java(
"""
import static java.lang.Integer.MAX_VALUE;

class A {{ B.foo(MAX_VALUE); }}
""",
"""
class A {{ B.foo(); }}
"""
)
);
}


@Test
void removeUnusedImportOfInnerClass() {
rewriteRun(
spec -> spec.recipes(new DeleteMethodArgument("B foo(java.util.List)", 0)),
java(
"""
import java.util.AbstractMap.SimpleEntry;
import java.util.List;

class A {{
B.foo(List.of(new SimpleEntry<>("a", "b")));
}}
""",
"""
class A {{
B.foo();
}}
"""
)
);
}

@Test
void removeUnusedImportWithLambda() {
rewriteRun(
spec -> spec.recipes(new DeleteMethodArgument("B foo(java.util.List)", 0)),
java(
"""
import java.math.BigInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;

class A {{
B.foo(Stream.of("23").map(s -> {
return new BigInteger(s).toString();
}).collect(Collectors.toList()));
}}
""",
"""
class A {{
B.foo();
}}
"""
)
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,18 @@
package org.openrewrite.java;

import lombok.EqualsAndHashCode;
import lombok.RequiredArgsConstructor;
import lombok.Value;
import org.jspecify.annotations.Nullable;
import org.openrewrite.*;
import org.openrewrite.java.search.UsesMethod;
import org.openrewrite.java.tree.*;
import org.openrewrite.marker.Markers;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static java.util.Collections.singletonList;
import static org.openrewrite.Tree.randomId;
Expand Down Expand Up @@ -75,16 +79,14 @@ public Validated<Object> validate() {

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return Preconditions.check(new UsesMethod<>(methodPattern), new DeleteMethodArgumentVisitor(new MethodMatcher(methodPattern)));
MethodMatcher methodMatcher = new MethodMatcher(methodPattern);
return Preconditions.check(new UsesMethod<>(methodMatcher), new DeleteMethodArgumentVisitor(methodMatcher));
}

@RequiredArgsConstructor
private class DeleteMethodArgumentVisitor extends JavaIsoVisitor<ExecutionContext> {
private final MethodMatcher methodMatcher;

public DeleteMethodArgumentVisitor(MethodMatcher methodMatcher) {
this.methodMatcher = methodMatcher;
}

@Override
public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
J.MethodInvocation m = super.visitMethodInvocation(method, ctx);
Expand All @@ -101,8 +103,8 @@ private MethodCall visitMethodCall(MethodCall methodCall) {
MethodCall m = methodCall;
List<Expression> originalArgs = m.getArguments();
if (methodMatcher.matches(m) && originalArgs.stream()
.filter(a -> !(a instanceof J.Empty))
.count() >= argumentIndex + 1) {
.filter(a -> !(a instanceof J.Empty))
.count() >= argumentIndex + 1) {
List<Expression> args = new ArrayList<>(originalArgs);

Expression removed = args.remove(argumentIndex);
Expand All @@ -111,9 +113,38 @@ private MethodCall visitMethodCall(MethodCall methodCall) {
} else if (argumentIndex == 0) {
args.set(0, args.get(0).withPrefix(removed.getPrefix()));
}

m = m.withArguments(args);

// Remove imports of types used in the removed argument
new JavaIsoVisitor<Set<String>>() {
@Override
public @Nullable JavaType visitType(@Nullable JavaType javaType, Set<String> types) {
if (javaType instanceof JavaType.Class) {
JavaType.Class type = (JavaType.Class) javaType;
if (!"java.lang".equals(type.getPackageName())) {
types.add(type.getFullyQualifiedName());
}
} else if (javaType instanceof JavaType.Variable) {
JavaType.Variable variable = (JavaType.Variable) javaType;
if (variable.hasFlags(Flag.Static) && variable.getOwner() instanceof JavaType.Class) {
JavaType.Class owner = (JavaType.Class) variable.getOwner();
types.add(owner.getFullyQualifiedName() + "." + variable.getName());
}
}
return super.visitType(javaType, types);
}

@Override
public J.MethodInvocation visitMethodInvocation(J.MethodInvocation mi, Set<String> strings) {
if (mi.getMethodType() != null && mi.getMethodType().hasFlags(Flag.Static) && mi.getSelect() == null) {
JavaType.FullyQualified receiverType = mi.getMethodType().getDeclaringType();
strings.add(receiverType.getFullyQualifiedName() + "." + mi.getSimpleName());
}
return super.visitMethodInvocation(mi, strings);
}
}.reduce(removed, new HashSet<>()).forEach(this::maybeRemoveImport);

// Update the method types
JavaType.Method methodType = m.getMethodType();
if (methodType != null) {
List<String> parameterNames = new ArrayList<>(methodType.getParameterNames());
Expand Down