-
Notifications
You must be signed in to change notification settings - Fork 78
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
236 var for methods #249
Merged
Merged
236 var for methods #249
Changes from 9 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
0927622
fix missing imports in VarBaseTest
MBoegers 17d7eef
add Tests to prove issue #236 us already covered (except generics)
MBoegers ff62c14
add new Recipe to cover var for generics add test harness
MBoegers f44eaf3
add missing licences
MBoegers 5a58c68
Implement var for generic constructor invocations and move general me…
MBoegers 98d5020
Merge branch 'openrewrite:main' into 236-var_for_methods
MBoegers bd82510
Update UseVarKeywordTest to be compliant with child test UseVarForGen…
MBoegers 274dbb3
Modify Generic Method Invocations
MBoegers 42b3c96
Merge branch 'main' into 236-var_for_methods
MBoegers 400f836
Apply suggestions from code review
MBoegers 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
116 changes: 116 additions & 0 deletions
116
src/main/java/org/openrewrite/java/migrate/lang/var/UseVarForGenericMethodInvocations.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,116 @@ | ||
/* | ||
* 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.java.migrate.lang.var; | ||
|
||
import java.util.ArrayList; | ||
import java.util.List; | ||
import java.util.stream.Collectors; | ||
|
||
import org.openrewrite.*; | ||
import org.openrewrite.java.JavaIsoVisitor; | ||
import org.openrewrite.java.JavaParser; | ||
import org.openrewrite.java.JavaTemplate; | ||
import org.openrewrite.java.search.UsesJavaVersion; | ||
import org.openrewrite.java.tree.*; | ||
import org.openrewrite.marker.Markers; | ||
|
||
public class UseVarForGenericMethodInvocations extends Recipe { | ||
@Override | ||
public String getDisplayName() { | ||
//language=markdown | ||
return "Apply `var` to Generic Method Invocations"; | ||
} | ||
|
||
@Override | ||
public String getDescription() { | ||
//language=markdown | ||
return "Apply `var` to variables initialized by invocations of Generic Methods. " + | ||
"This recipe ignores generic factory methods without parameters, because open rewrite cannot handle them correctly ATM."; | ||
} | ||
|
||
@Override | ||
public TreeVisitor<?, ExecutionContext> getVisitor() { | ||
return Preconditions.check( | ||
new UsesJavaVersion<>(10), | ||
new UseVarForGenericMethodInvocations.UseVarForGenericsVisitor()); | ||
} | ||
|
||
static final class UseVarForGenericsVisitor extends JavaIsoVisitor<ExecutionContext> { | ||
private final JavaTemplate template = JavaTemplate.builder("var #{} = #{any()}") | ||
.javaParser(JavaParser.fromJavaVersion()).build(); | ||
|
||
@Override | ||
public J.VariableDeclarations visitVariableDeclarations(J.VariableDeclarations vd, ExecutionContext ctx) { | ||
vd = super.visitVariableDeclarations(vd, ctx); | ||
|
||
boolean isGeneralApplicable = DeclarationCheck.isVarApplicable(this.getCursor(), vd); | ||
if (!isGeneralApplicable) return vd; | ||
|
||
// recipe specific | ||
boolean isPrimitive = DeclarationCheck.isPrimitive(vd); | ||
boolean usesNoGenerics = !DeclarationCheck.useGenerics(vd); | ||
boolean usesTernary = DeclarationCheck.initializedByTernary(vd); | ||
if (isPrimitive || usesTernary || usesNoGenerics) return vd; | ||
|
||
//now we deal with generics, check for method invocations | ||
Expression initializer = vd.getVariables().get(0).getInitializer(); | ||
boolean isMethodInvocation = initializer != null && initializer.unwrap() instanceof J.MethodInvocation; | ||
if (!isMethodInvocation) return vd; | ||
|
||
//if no type paramters are present and no arguments we assume the type is hard to determine a needs manual action | ||
boolean hasNoTypeParams = ((J.MethodInvocation) initializer).getTypeParameters() == null; | ||
boolean argumentsEmpty = ((J.MethodInvocation) initializer).getArguments().stream().allMatch(p -> p instanceof J.Empty); | ||
if (hasNoTypeParams && argumentsEmpty) return vd; | ||
|
||
return transformToVar(vd, new ArrayList<>(), new ArrayList<>()); | ||
} | ||
|
||
private J.VariableDeclarations transformToVar(J.VariableDeclarations vd, List<JavaType> leftTypes, List<JavaType> rightTypes) { | ||
Expression initializer = vd.getVariables().get(0).getInitializer(); | ||
String simpleName = vd.getVariables().get(0).getSimpleName(); | ||
|
||
// if left is defined but not right, copy types to initializer | ||
if(rightTypes.isEmpty() && !leftTypes.isEmpty()) { | ||
// we need to switch type infos from left to right here | ||
List<Expression> typeArgument = leftTypes.stream() | ||
.map(t -> | ||
new J.Identifier(Tree.randomId(), Space.EMPTY, Markers.EMPTY, ((JavaType.Class)t).getClassName(), t, null)) | ||
.collect(Collectors.toList()); | ||
J.ParameterizedType typedInitializerClazz = ((J.ParameterizedType) ((J.NewClass) initializer).getClazz()).withTypeParameters(typeArgument); | ||
initializer = ((J.NewClass) initializer).withClazz(typedInitializerClazz); | ||
} | ||
|
||
J.VariableDeclarations result = template.<J.VariableDeclarations>apply(getCursor(), vd.getCoordinates().replace(), simpleName, initializer) | ||
.withPrefix(vd.getPrefix()); | ||
|
||
// apply modifiers like final | ||
List<J.Modifier> modifiers = vd.getModifiers(); | ||
boolean hasModifiers = !modifiers.isEmpty(); | ||
if (hasModifiers) { | ||
result = result.withModifiers(modifiers); | ||
} | ||
|
||
// apply prefix to type expression | ||
TypeTree resultingTypeExpression = result.getTypeExpression(); | ||
boolean resultHasTypeExpression = resultingTypeExpression != null; | ||
if (resultHasTypeExpression) { | ||
result = result.withTypeExpression(resultingTypeExpression.withPrefix(vd.getTypeExpression().getPrefix())); | ||
} | ||
|
||
return result; | ||
} | ||
} | ||
} |
147 changes: 147 additions & 0 deletions
147
src/main/java/org/openrewrite/java/migrate/lang/var/UseVarForGenericsConstructors.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,147 @@ | ||
/* | ||
* 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.java.migrate.lang.var; | ||
|
||
import java.util.ArrayList; | ||
import java.util.List; | ||
import java.util.Objects; | ||
import java.util.stream.Collectors; | ||
|
||
import org.openrewrite.*; | ||
import org.openrewrite.internal.lang.Nullable; | ||
import org.openrewrite.java.JavaIsoVisitor; | ||
import org.openrewrite.java.JavaParser; | ||
import org.openrewrite.java.JavaTemplate; | ||
import org.openrewrite.java.search.UsesJavaVersion; | ||
import org.openrewrite.java.tree.*; | ||
import org.openrewrite.marker.Markers; | ||
|
||
public class UseVarForGenericsConstructors extends Recipe { | ||
@Override | ||
public String getDisplayName() { | ||
//language=markdown | ||
return "Apply `var` to Generic Constructors"; | ||
} | ||
|
||
@Override | ||
public String getDescription() { | ||
//language=markdown | ||
return "Apply `var` to generics variables initialized by constructor calls."; | ||
} | ||
|
||
@Override | ||
public TreeVisitor<?, ExecutionContext> getVisitor() { | ||
return Preconditions.check( | ||
new UsesJavaVersion<>(10), | ||
new UseVarForGenericsConstructors.UseVarForGenericsVisitor()); | ||
} | ||
|
||
static final class UseVarForGenericsVisitor extends JavaIsoVisitor<ExecutionContext> { | ||
private final JavaTemplate template = JavaTemplate.builder("var #{} = #{any()}") | ||
.javaParser(JavaParser.fromJavaVersion()).build(); | ||
|
||
@Override | ||
public J.VariableDeclarations visitVariableDeclarations(J.VariableDeclarations vd, ExecutionContext ctx) { | ||
vd = super.visitVariableDeclarations(vd, ctx); | ||
|
||
boolean isGeneralApplicable = DeclarationCheck.isVarApplicable(this.getCursor(), vd); | ||
if (!isGeneralApplicable) return vd; | ||
|
||
// recipe specific | ||
boolean isPrimitive = DeclarationCheck.isPrimitive(vd); | ||
boolean usesNoGenerics = !DeclarationCheck.useGenerics(vd); | ||
boolean usesTernary = DeclarationCheck.initializedByTernary(vd); | ||
if (isPrimitive || usesTernary || usesNoGenerics) return vd; | ||
|
||
//now we deal with generics | ||
J.VariableDeclarations.NamedVariable variable = vd.getVariables().get(0); | ||
List<JavaType> leftTypes = extractParameters(variable.getVariableType()); | ||
List<JavaType> rightTypes = extractParameters(variable.getInitializer()); | ||
if (rightTypes == null || (leftTypes.isEmpty() && rightTypes.isEmpty())) return vd; | ||
|
||
return transformToVar(vd, leftTypes, rightTypes); | ||
} | ||
|
||
/** | ||
* Tries to extract the genric parameters from the expression, | ||
* if the Initializer is no new class or not of a parameterized type, returns null to signale "no info". | ||
* if the initializer uses empty diamonds use an empty list to signale no type information | ||
* @param initializer to extract parameters from | ||
* @return null or list of type parameters in diamond | ||
*/ | ||
private @Nullable List<JavaType> extractParameters(@Nullable Expression initializer) { | ||
if (initializer instanceof J.NewClass) { | ||
TypeTree clazz = ((J.NewClass) initializer).getClazz(); | ||
if (clazz instanceof J.ParameterizedType) { | ||
List<Expression> typeParameters = ((J.ParameterizedType) clazz).getTypeParameters(); | ||
if (typeParameters != null) { | ||
return typeParameters | ||
.stream() | ||
.map(Expression::getType) | ||
.filter(Objects::nonNull) | ||
.collect(Collectors.toList()); | ||
} else { | ||
return new ArrayList<>(); | ||
} | ||
} | ||
} | ||
return null; | ||
} | ||
|
||
private List<JavaType> extractParameters(@Nullable JavaType.Variable variableType) { | ||
if (variableType != null && variableType.getType() instanceof JavaType.Parameterized) { | ||
return ((JavaType.Parameterized) variableType.getType()).getTypeParameters(); | ||
} else { | ||
return new ArrayList<>(); | ||
} | ||
} | ||
|
||
private J.VariableDeclarations transformToVar(J.VariableDeclarations vd, List<JavaType> leftTypes, List<JavaType> rightTypes) { | ||
Expression initializer = vd.getVariables().get(0).getInitializer(); | ||
String simpleName = vd.getVariables().get(0).getSimpleName(); | ||
|
||
// if left is defined but not right, copy types to initializer | ||
if(rightTypes.isEmpty() && !leftTypes.isEmpty()) { | ||
// we need to switch type infos from left to right here | ||
List<Expression> typeArgument = leftTypes.stream() | ||
.map(t -> | ||
new J.Identifier(Tree.randomId(), Space.EMPTY, Markers.EMPTY, ((JavaType.Class)t).getClassName(), t, null)) | ||
.collect(Collectors.toList()); | ||
J.ParameterizedType typedInitializerClazz = ((J.ParameterizedType) ((J.NewClass) initializer).getClazz()).withTypeParameters(typeArgument); | ||
initializer = ((J.NewClass) initializer).withClazz(typedInitializerClazz); | ||
} | ||
|
||
J.VariableDeclarations result = template.<J.VariableDeclarations>apply(getCursor(), vd.getCoordinates().replace(), simpleName, initializer) | ||
.withPrefix(vd.getPrefix()); | ||
|
||
// apply modifiers like final | ||
List<J.Modifier> modifiers = vd.getModifiers(); | ||
boolean hasModifiers = !modifiers.isEmpty(); | ||
if (hasModifiers) { | ||
result = result.withModifiers(modifiers); | ||
} | ||
|
||
// apply prefix to type expression | ||
TypeTree resultingTypeExpression = result.getTypeExpression(); | ||
boolean resultHasTypeExpression = resultingTypeExpression != null; | ||
if (resultHasTypeExpression) { | ||
result = result.withTypeExpression(resultingTypeExpression.withPrefix(vd.getTypeExpression().getPrefix())); | ||
} | ||
|
||
return result; | ||
} | ||
} | ||
} |
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
Oops, something went wrong.
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.
👍