Skip to content

Commit df19197

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

File tree

2 files changed

+851
-0
lines changed

2 files changed

+851
-0
lines changed
Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
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 NormalizeSetter extends ScanningRecipe<NormalizeSetter.MethodAcc> {
39+
40+
@Override
41+
public String getDisplayName() {
42+
//language=markdown
43+
return "Rename setter 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 setter 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 setter 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 parameterType_;
80+
String newMethodName_;
81+
}
82+
83+
84+
@RequiredArgsConstructor
85+
private static class MethodRecorder extends JavaIsoVisitor<ExecutionContext> {
86+
87+
private final static String METHOD_BLACKLIST = "METHOD_BLACKLIST";
88+
89+
private final MethodAcc acc;
90+
91+
@Override
92+
public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext ctx) {
93+
94+
List<String> blackList = classDecl.getBody().getStatements().stream()
95+
.filter(s -> s instanceof J.MethodDeclaration)
96+
.map(s -> (J.MethodDeclaration) s)
97+
.map(J.MethodDeclaration::getSimpleName)
98+
.collect(Collectors.toList());
99+
100+
getCursor().putMessage(METHOD_BLACKLIST, blackList);
101+
102+
super.visitClassDeclaration(classDecl, ctx);
103+
104+
return classDecl;
105+
}
106+
107+
@Override
108+
public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, ExecutionContext ctx) {
109+
assert method.getMethodType() != null;
110+
111+
if (!LombokUtils.isEffectivelySetter(method)) {
112+
return method;
113+
}
114+
115+
//return early if the method overrides another
116+
//if the project defined both the original and the overridden method,
117+
// then the renaming of the "original" in the base class will cover the override
118+
if (method.getLeadingAnnotations().stream().anyMatch(a -> "Override".equals(a.getSimpleName()))) {
119+
return method;
120+
}
121+
122+
J.Assignment assignment_ = (J.Assignment) method.getBody().getStatements().get(0);
123+
J.FieldAccess fieldAccess = (J.FieldAccess) assignment_.getVariable();
124+
JavaType.Variable fieldType = fieldAccess.getName().getFieldType();
125+
126+
String expectedMethodName = LombokUtils.deriveSetterMethodName(fieldType);
127+
String parameterType = fieldType.getType().toString();
128+
String actualMethodName = method.getSimpleName();
129+
130+
//if method already has the name it should have, then nothing to be done
131+
if (expectedMethodName.equals(actualMethodName)) {
132+
return method;
133+
}
134+
135+
//If the desired method name is already taken by an existing method, the current method cannot be renamed
136+
List<String> blackList = getCursor().getNearestMessage(METHOD_BLACKLIST);
137+
assert blackList != null;
138+
if (blackList.contains(expectedMethodName)) {
139+
return method;
140+
}
141+
//WON'T DO: there is a rare edge case, that is not addressed yet.
142+
// If `getFoo()` returns `ba` and `getBa()` returns `foo` then neither will be renamed.
143+
// 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)
144+
// At this point I don't think it's worth the effort.
145+
146+
147+
String pathToClass = method.getMethodType().getDeclaringType().getFullyQualifiedName().replace('$', '.');
148+
//todo write separate recipe for merging effective setters
149+
acc.renameRecords.add(
150+
new RenameRecord(
151+
pathToClass,
152+
actualMethodName,
153+
parameterType,
154+
expectedMethodName
155+
)
156+
);
157+
blackList.remove(actualMethodName);//actual method name becomes available again
158+
blackList.add(expectedMethodName);//expected method name now blocked
159+
return method;
160+
}
161+
}
162+
163+
@Override
164+
public TreeVisitor<?, ExecutionContext> getVisitor(MethodAcc acc) {
165+
166+
return new TreeVisitor<Tree, ExecutionContext>() {
167+
168+
@Override
169+
public @Nullable Tree visit(@Nullable Tree tree, ExecutionContext ctx) {
170+
171+
for (RenameRecord rr : acc.renameRecords) {
172+
String methodPattern = String.format("%s %s(%s)", rr.pathToClass_, rr.methodName_, rr.parameterType_);
173+
tree = new ChangeMethodName(methodPattern, rr.newMethodName_, true, null)
174+
.getVisitor().visit(tree, ctx);
175+
}
176+
return tree;
177+
}
178+
};
179+
}
180+
}

0 commit comments

Comments
 (0)