Skip to content

Commit b4898ef

Browse files
committed
migrate recipes as-is
1 parent bb00d0a commit b4898ef

File tree

3 files changed

+819
-0
lines changed

3 files changed

+819
-0
lines changed

src/main/java/org/openrewrite/java/migrate/lombok/LombokUtils.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,24 @@ private static boolean hasMatchingTypeAndGetterName(J.MethodDeclaration method,
7070
return false;
7171
}
7272

73+
public static boolean isEffectivelyGetter(J.MethodDeclaration method) {
74+
boolean takesNoParameters = method.getParameters().get(0) instanceof J.Empty;
75+
boolean singularReturn = method.getBody() != null //abstract methods can be null
76+
&& method.getBody().getStatements().size() == 1 //
77+
&& method.getBody().getStatements().get(0) instanceof J.Return;
78+
79+
if (takesNoParameters && singularReturn) {
80+
Expression returnExpression = ((J.Return) method.getBody().getStatements().get(0)).getExpression();
81+
//returns just an identifier
82+
if (returnExpression instanceof J.Identifier) {
83+
J.Identifier identifier = (J.Identifier) returnExpression;
84+
JavaType.Variable fieldType = identifier.getFieldType();
85+
return method.getType().equals(fieldType.getType()); //type match
86+
}
87+
}
88+
return false;
89+
}
90+
7391
private static String deriveGetterMethodName(@Nullable JavaType type, String fieldName) {
7492
if (type == JavaType.Primitive.Boolean) {
7593
boolean alreadyStartsWithIs = fieldName.length() >= 3 &&
@@ -83,6 +101,22 @@ private static String deriveGetterMethodName(@Nullable JavaType type, String fie
83101
return "get" + StringUtils.capitalize(fieldName);
84102
}
85103

104+
public static String deriveGetterMethodName(JavaType.Variable fieldType) {
105+
boolean isPrimitiveBoolean = JavaType.Variable.Primitive.Boolean.equals(fieldType.getType());
106+
107+
final String fieldName = fieldType.getName();
108+
109+
boolean alreadyStartsWithIs = fieldName.length() >= 3 && fieldName.substring(0, 3).matches("is[A-Z]");
110+
111+
if (isPrimitiveBoolean)
112+
if (alreadyStartsWithIs)
113+
return fieldName;
114+
else
115+
return "is" + StringUtils.capitalize(fieldName);
116+
117+
return "get" + StringUtils.capitalize(fieldName);
118+
}
119+
86120
static boolean isSetter(J.MethodDeclaration method) {
87121
// Check return type: void
88122
if (method.getType() != JavaType.Primitive.Void) {
Lines changed: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
1+
/*
2+
* Copyright 2021 the original author or authors.
3+
* <p>
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
* <p>
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
* <p>
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package org.openrewrite.java.migrate.lombok;
17+
18+
import lombok.EqualsAndHashCode;
19+
import lombok.RequiredArgsConstructor;
20+
import lombok.Value;
21+
import org.jspecify.annotations.Nullable;
22+
import org.openrewrite.ExecutionContext;
23+
import org.openrewrite.ScanningRecipe;
24+
import org.openrewrite.Tree;
25+
import org.openrewrite.TreeVisitor;
26+
import org.openrewrite.java.ChangeMethodName;
27+
import org.openrewrite.java.JavaIsoVisitor;
28+
import org.openrewrite.java.tree.J;
29+
import org.openrewrite.java.tree.JavaType;
30+
31+
import java.util.ArrayList;
32+
import java.util.List;
33+
import java.util.StringJoiner;
34+
import java.util.stream.Collectors;
35+
36+
@Value
37+
@EqualsAndHashCode(callSuper = false)
38+
public class NormalizeGetter extends ScanningRecipe<NormalizeGetter.MethodAcc> {
39+
40+
@Override
41+
public String getDisplayName() {
42+
//language=markdown
43+
return "Rename getter methods to fit lombok";
44+
}
45+
46+
@Override
47+
public String getDescription() {
48+
//language=markdown
49+
return new StringJoiner("\n")
50+
.add("Rename methods that are effectively getter to the name lombok would give them.")
51+
.add("")
52+
.add("Limitations:")
53+
.add("")
54+
.add(" - If two methods in a class are effectively the same getter then one's name will be corrected and the others name will be left as it is.")
55+
.add(" - If the correct name for a method is already taken by another method then the name will not be corrected.")
56+
.add(" - Method name swaps or circular renaming within a class cannot be performed because the names block each other. ")
57+
.add("E.g. `int getFoo() { return ba; } int getBa() { return foo; }` stays as it is.")
58+
.toString();
59+
}
60+
61+
public static class MethodAcc {
62+
List<RenameRecord> renameRecords = new ArrayList<>();
63+
}
64+
65+
@Override
66+
public MethodAcc getInitialValue(ExecutionContext ctx) {
67+
return new MethodAcc();
68+
}
69+
70+
@Override
71+
public TreeVisitor<?, ExecutionContext> getScanner(MethodAcc acc) {
72+
return new MethodRecorder(acc);
73+
}
74+
75+
@Value
76+
private static class RenameRecord {
77+
String pathToClass_;
78+
String methodName_;
79+
String newMethodName_;
80+
}
81+
82+
83+
@RequiredArgsConstructor
84+
private static class MethodRecorder extends JavaIsoVisitor<ExecutionContext> {
85+
86+
private final static String METHOD_BLACKLIST = "METHOD_BLACKLIST";
87+
88+
private final MethodAcc acc;
89+
90+
@Override
91+
public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext ctx) {
92+
93+
List<String> blackList = classDecl.getBody().getStatements().stream()
94+
.filter(s -> s instanceof J.MethodDeclaration)
95+
.map(s -> (J.MethodDeclaration) s)
96+
.map(J.MethodDeclaration::getSimpleName)
97+
.collect(Collectors.toList());
98+
99+
getCursor().putMessage(METHOD_BLACKLIST, blackList);
100+
101+
super.visitClassDeclaration(classDecl, ctx);
102+
103+
return classDecl;
104+
}
105+
106+
@Override
107+
public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, ExecutionContext ctx) {
108+
assert method.getMethodType() != null;
109+
110+
if (!LombokUtils.isEffectivelyGetter(method)) {
111+
return method;
112+
}
113+
114+
//return early if the method overrides another
115+
//if the project defined both the original and the overridden method,
116+
// then the renaming of the "original" in the base class will cover the override
117+
if (method.getLeadingAnnotations().stream().anyMatch(a -> "Override".equals(a.getSimpleName()))) {
118+
return method;
119+
}
120+
121+
J.Return return_ = (J.Return) method.getBody().getStatements().get(0);
122+
JavaType.Variable fieldType = ((J.Identifier) return_.getExpression()).getFieldType();
123+
124+
String expectedMethodName = LombokUtils.deriveGetterMethodName(fieldType);
125+
String actualMethodName = method.getSimpleName();
126+
127+
//if method already has the name it should have, then nothing to be done
128+
if (expectedMethodName.equals(actualMethodName)) {
129+
return method;
130+
}
131+
132+
//If the desired method name is already taken by an existing method, the current method cannot be renamed
133+
List<String> blackList = getCursor().getNearestMessage(METHOD_BLACKLIST);
134+
assert blackList != null;
135+
if (blackList.contains(expectedMethodName)) {
136+
return method;
137+
}
138+
//WON'T DO: there is a rare edge case, that is not addressed yet.
139+
// If `getFoo()` returns `ba` and `getBa()` returns `foo` then neither will be renamed.
140+
// This could be fixed by compiling a list of planned changes and doing a soundness check (and not renaming sequentially, or rather introducing temporary method names)
141+
// At this point I don't think it's worth the effort.
142+
143+
144+
String pathToClass = method.getMethodType().getDeclaringType().getFullyQualifiedName().replace('$', '.');
145+
//todo write separate recipe for merging effective getters
146+
acc.renameRecords.add(
147+
new RenameRecord(
148+
pathToClass,
149+
actualMethodName,
150+
expectedMethodName
151+
)
152+
);
153+
blackList.remove(actualMethodName);//actual method name becomes available again
154+
blackList.add(expectedMethodName);//expected method name now blocked
155+
return method;
156+
}
157+
}
158+
159+
@Override
160+
public TreeVisitor<?, ExecutionContext> getVisitor(MethodAcc acc) {
161+
162+
return new TreeVisitor<Tree, ExecutionContext>() {
163+
164+
@Override
165+
public @Nullable Tree visit(@Nullable Tree tree, ExecutionContext ctx) {
166+
167+
for (RenameRecord rr : acc.renameRecords) {
168+
String methodPattern = String.format("%s %s()", rr.pathToClass_, rr.methodName_);
169+
tree = new ChangeMethodName(methodPattern, rr.newMethodName_, true, null)
170+
.getVisitor().visit(tree, ctx);
171+
}
172+
return tree;
173+
}
174+
};
175+
}
176+
}

0 commit comments

Comments
 (0)