-
Notifications
You must be signed in to change notification settings - Fork 364
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
Add AddNullMethodArgument
recipe
#4047
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
0de5ecb
Add `AddNullMethodArgument` recipe
pstreef af9f719
fix test: Method matcher does not match null as Integer
pstreef 768bd77
Apply suggestions from code review
pstreef 7d0296c
fix compilation
pstreef f92811a
add explicit cast
pstreef a99e581
Consistently use ListUtils.insert
timtebeek 3cf3a28
Use `"java.lang.Integer"` instead of `Integer.class.getName()`
timtebeek 6928bf2
Dont try to shorten fully qualified
pstreef File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
89 changes: 89 additions & 0 deletions
89
rewrite-java-test/src/test/java/org/openrewrite/java/AddNullMethodArgumentTest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,89 @@ | ||
/* | ||
* Copyright 2024 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.java; | ||
|
||
import org.junit.jupiter.api.Test; | ||
import org.openrewrite.test.RecipeSpec; | ||
import org.openrewrite.test.RewriteTest; | ||
|
||
import static org.openrewrite.java.Assertions.java; | ||
|
||
class AddNullMethodArgumentTest implements RewriteTest { | ||
|
||
@Override | ||
public void defaults(RecipeSpec spec) { | ||
spec.parser(JavaParser.fromJavaVersion().dependsOn(""" | ||
class B { | ||
static void foo() {} | ||
static void foo(Integer n) {} | ||
static void foo(Integer n1, Integer n2) {} | ||
static void foo(Integer n1, Integer n2, Integer n3) {} | ||
static void foo(Integer n1, Integer n2, Integer n3, Integer n4) {} | ||
static void foo(Integer n1, Integer n2, Integer n3, String n4) {} | ||
B() {} | ||
B(Integer n) {} | ||
} | ||
""")); | ||
} | ||
|
||
@Test | ||
void addToMiddleArgument() { | ||
rewriteRun( | ||
spec -> spec.recipe(new AddNullMethodArgument("B foo(Integer, Integer)", 1, "java.lang.Integer", "n2", false)), | ||
java( | ||
"class A {{ B.foo(0, 1); }}", | ||
"class A {{ B.foo(0, null, 1); }}" | ||
) | ||
); | ||
} | ||
|
||
@Test | ||
void addArgumentsConsecutively() { | ||
rewriteRun( | ||
spec -> spec.recipes( | ||
new AddNullMethodArgument("B foo(Integer)", 1, "java.lang.Integer", "n2", false), | ||
new AddNullMethodArgument("B foo(Integer, Integer)", 1, "java.lang.Integer", "n2", false) | ||
), | ||
java( | ||
"class A {{ B.foo(0); }}", | ||
"class A {{ B.foo(0, null, null); }}" | ||
) | ||
); | ||
} | ||
|
||
@Test | ||
void addToConstructorArgument() { | ||
rewriteRun( | ||
spec -> spec.recipe(new AddNullMethodArgument("B <constructor>()", 0, "java.lang.Integer", "arg", false)), | ||
java( | ||
"class A { B b = new B(); }", | ||
"class A { B b = new B(null); }" | ||
) | ||
); | ||
} | ||
|
||
@Test | ||
void addCastToConflictingArgumentType() { | ||
rewriteRun( | ||
spec -> spec.recipe(new AddNullMethodArgument("B foo(Integer,Integer,Integer)", 3, "java.lang.String", "n2", true)), | ||
java( | ||
"class A {{ B.foo(0, 1, 2); }}", | ||
"class A {{ B.foo(0, 1, 2, (java.lang.String) null); }}" | ||
) | ||
); | ||
} | ||
|
||
} |
149 changes: 149 additions & 0 deletions
149
rewrite-java/src/main/java/org/openrewrite/java/AddNullMethodArgument.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,149 @@ | ||
/* | ||
* Copyright 2024 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.java; | ||
|
||
import lombok.EqualsAndHashCode; | ||
import lombok.Value; | ||
import org.openrewrite.*; | ||
import org.openrewrite.internal.ListUtils; | ||
import org.openrewrite.internal.lang.Nullable; | ||
import org.openrewrite.java.search.UsesMethod; | ||
import org.openrewrite.java.tree.*; | ||
import org.openrewrite.marker.Markers; | ||
|
||
import java.util.ArrayList; | ||
import java.util.List; | ||
|
||
import static org.openrewrite.Tree.randomId; | ||
import static org.openrewrite.java.tree.Space.EMPTY; | ||
|
||
/** | ||
* This recipe finds method invocations matching a method pattern and uses a zero-based argument index to determine | ||
* which argument is added with a null value. | ||
*/ | ||
@Value | ||
@EqualsAndHashCode(callSuper = false) | ||
public class AddNullMethodArgument extends Recipe { | ||
|
||
/** | ||
* A method pattern that is used to find matching method invocations. | ||
* See {@link MethodMatcher} for details on the expression's syntax. | ||
*/ | ||
@Option(displayName = "Method pattern", | ||
description = "A method pattern that is used to find matching method invocations.", | ||
example = "com.yourorg.A foo(int, int)") | ||
String methodPattern; | ||
|
||
/** | ||
* A zero-based index that indicates which argument will be added as null to the method invocation. | ||
*/ | ||
@Option(displayName = "Argument index", | ||
description = "A zero-based index that indicates which argument will be added as null to the method invocation.", | ||
example = "0") | ||
int argumentIndex; | ||
|
||
@Option(displayName = "Parameter type", | ||
description = "The type of the parameter that we add the argument for.", | ||
example = "java.lang.String") | ||
String parameterType; | ||
|
||
@Option(displayName = "Parameter name", | ||
description = "The name of the parameter that we add the argument for.", | ||
required = false, | ||
example = "name") | ||
@Nullable String parameterName; | ||
|
||
@Option(displayName = "Explicit cast", | ||
description = "Explicitly cast the argument to the parameter type. Useful if the method is overridden with another type.", | ||
required = false, | ||
example = "true") | ||
@Nullable Boolean explicitCast; | ||
|
||
@Override | ||
public String getInstanceNameSuffix() { | ||
return String.format("%d in methods `%s`", argumentIndex, methodPattern); | ||
} | ||
|
||
@Override | ||
public String getDisplayName() { | ||
return "Add a `null` method argument"; | ||
} | ||
|
||
@Override | ||
public String getDescription() { | ||
return "Add a `null` argument to method invocations."; | ||
} | ||
|
||
@Override | ||
public TreeVisitor<?, ExecutionContext> getVisitor() { | ||
return Preconditions.check(new UsesMethod<>(methodPattern), new AddNullMethodArgumentVisitor(new MethodMatcher(methodPattern))); | ||
} | ||
|
||
private class AddNullMethodArgumentVisitor extends JavaIsoVisitor<ExecutionContext> { | ||
private final MethodMatcher methodMatcher; | ||
|
||
public AddNullMethodArgumentVisitor(MethodMatcher methodMatcher) { | ||
this.methodMatcher = methodMatcher; | ||
} | ||
|
||
@Override | ||
public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) { | ||
J.MethodInvocation m = super.visitMethodInvocation(method, ctx); | ||
return (J.MethodInvocation) visitMethodCall(m); | ||
} | ||
|
||
@Override | ||
public J.NewClass visitNewClass(J.NewClass newClass, ExecutionContext ctx) { | ||
J.NewClass n = super.visitNewClass(newClass, ctx); | ||
return (J.NewClass) visitMethodCall(n); | ||
} | ||
|
||
private MethodCall visitMethodCall(MethodCall methodCall) { | ||
MethodCall m = methodCall; | ||
List<Expression> originalArgs = m.getArguments(); | ||
if (methodMatcher.matches(m) && (long) originalArgs.size() >= argumentIndex) { | ||
List<Expression> args = new ArrayList<>(originalArgs); | ||
|
||
if (args.size() == 1 && args.get(0) instanceof J.Empty) { | ||
args.remove(0); | ||
} | ||
|
||
Expression nullLiteral = new J.Literal(randomId(), args.isEmpty() ? Space.EMPTY : Space.SINGLE_SPACE, Markers.EMPTY, "null", "null", null, JavaType.Primitive.Null); | ||
if (explicitCast == Boolean.TRUE) { | ||
nullLiteral = new J.TypeCast(randomId(), Space.SINGLE_SPACE, Markers.EMPTY, | ||
new J.ControlParentheses<>(randomId(), EMPTY, Markers.EMPTY, | ||
new JRightPadded<>(TypeTree.build(parameterType), EMPTY, Markers.EMPTY)), | ||
nullLiteral); | ||
} | ||
m = m.withArguments(ListUtils.insert(args, nullLiteral, argumentIndex)); | ||
|
||
JavaType.Method methodType = m.getMethodType(); | ||
if (methodType != null) { | ||
m = m.withMethodType(methodType | ||
.withParameterNames(ListUtils.insert(methodType.getParameterNames(), | ||
parameterName == null ? "arg" + argumentIndex : parameterName, argumentIndex)) | ||
.withParameterTypes(ListUtils.insert(methodType.getParameterTypes(), | ||
JavaType.buildType(parameterType), argumentIndex))); | ||
if (m instanceof J.MethodInvocation && ((J.MethodInvocation) m).getName().getType() != null) { | ||
m = ((J.MethodInvocation) m).withName(((J.MethodInvocation) m).getName().withType(m.getMethodType())); | ||
} | ||
} | ||
} | ||
return m; | ||
} | ||
|
||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I've added this because of possible conflicts. However I'm not sure how to get the cast to only use the not-so-fully qualified name.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think this is fine; should be rare that there's overloads, which require an explicit cast to String.
If you really want to get rid of this you can shorted fully qualified type references as we do here:
https://github.com/openrewrite/rewrite-templating/blob/e69126c2209f4edd1cb8e203d6eaeda26ff744b1/src/main/java/org/openrewrite/java/template/internal/AbstractRefasterJavaVisitor.java#L45
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I tried this but it does not shorten the cast.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
For
java.lang
we indeed don't shorten fully qualified names, as that could be wrong.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Although note that also
java.lang
types would end up as unqualified if the compilation unit already contains unqualified references to that type (which is often the case), so using this visitor is probably still a good idea.