Skip to content

Commit

Permalink
fix: Handle ImmutableOf as Select on MethodInvocation (#557)
Browse files Browse the repository at this point in the history
* fix: Handle ImmutableOf as Select on MethodInvocation

* Rename argument for clarity

---------

Co-authored-by: Tim te Beek <tim@moderne.io>
  • Loading branch information
amishra-u and timtebeek authored Sep 18, 2024
1 parent b5ab237 commit 53afa8a
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public TreeVisitor<?, ExecutionContext> getVisitor() {
return Preconditions.check(check, new JavaVisitor<ExecutionContext>() {
@Override
public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
if (IMMUTABLE_MATCHER.matches(method) && isParentTypeDownCast()) {
if (IMMUTABLE_MATCHER.matches(method) && isParentTypeDownCast(method)) {
maybeRemoveImport(guavaType);
maybeAddImport(javaType);

Expand Down Expand Up @@ -115,7 +115,7 @@ public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx)
return super.visitMethodInvocation(method, ctx);
}

private boolean isParentTypeDownCast() {
private boolean isParentTypeDownCast(MethodCall immutableMethod) {
J parent = getCursor().dropParentUntil(J.class::isInstance).getValue();
boolean isParentTypeDownCast = false;
if (parent instanceof J.VariableDeclarations.NamedVariable) {
Expand All @@ -138,14 +138,8 @@ private boolean isParentTypeDownCast() {
}
} else if (parent instanceof J.MethodInvocation) {
J.MethodInvocation m = (J.MethodInvocation) parent;
if (m.getMethodType() != null) {
int index = 0;
for (Expression argument : m.getArguments()) {
if (IMMUTABLE_MATCHER.matches(argument)) {
break;
}
index++;
}
int index = m.getArguments().indexOf(immutableMethod);
if (m.getMethodType() != null && index != -1) {
isParentTypeDownCast = isParentTypeMatched(m.getMethodType().getParameterTypes().get(index));
}
} else if (parent instanceof J.NewClass) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,41 @@ class Test {
);
}

@Test
void doNotChangeMethodInvocationWithSelect() {
//language=java
rewriteRun(
java(
"""
import java.util.List;
public class A {
Object[] list;
public void method(Object[] list ) {
this.list = list;
}
}
"""
),
version(
//language=java
java(
"""
import com.google.common.collect.ImmutableList;
class Test {
void method() {
A a = new A();
a.method(ImmutableList.of().toArray());
}
}
"""
),
11
)
);
}

@Test
void methodInvocationWithListArgument() {
//language=java
Expand Down

0 comments on commit 53afa8a

Please sign in to comment.