-
Notifications
You must be signed in to change notification settings - Fork 56
/
RemoveUnusedLocalVariables.java
358 lines (320 loc) · 15.8 KB
/
RemoveUnusedLocalVariables.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
/*
* 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.staticanalysis;
import lombok.EqualsAndHashCode;
import lombok.Value;
import org.jspecify.annotations.Nullable;
import org.openrewrite.*;
import org.openrewrite.internal.ListUtils;
import org.openrewrite.java.DeleteStatement;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.JavaVisitor;
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.service.AnnotationService;
import org.openrewrite.java.tree.*;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Predicate;
@Value
@EqualsAndHashCode(callSuper = false)
@SuppressWarnings("ConstantConditions")
public class RemoveUnusedLocalVariables extends Recipe {
@Incubating(since = "7.17.2")
@Option(displayName = "Ignore matching variable names",
description = "An array of variable identifier names for local variables to ignore, even if the local variable is unused.",
required = false,
example = "[unused, notUsed, IGNORE_ME]")
String @Nullable [] ignoreVariablesNamed;
@Override
public String getDisplayName() {
return "Remove unused local variables";
}
@Override
public String getDescription() {
return "If a local variable is declared but not used, it is dead code and should be removed.";
}
@Override
public Set<String> getTags() {
return Collections.singleton("RSPEC-S1481");
}
@Override
public Duration getEstimatedEffortPerOccurrence() {
return Duration.ofMinutes(5);
}
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
// All methods that start with 'get' matching this InvocationMatcher will be considered non-side effecting.
MethodMatcher SAFE_GETTER_METHODS = new MethodMatcher("java.io.File get*(..)");
Set<String> ignoreVariableNames;
if (ignoreVariablesNamed == null) {
ignoreVariableNames = null;
} else {
ignoreVariableNames = new HashSet<>(ignoreVariablesNamed.length);
ignoreVariableNames.addAll(Arrays.asList(ignoreVariablesNamed));
}
return new JavaIsoVisitor<ExecutionContext>() {
private Cursor getCursorToParentScope(Cursor cursor) {
return cursor.dropParentUntil(is ->
is instanceof J.ClassDeclaration ||
is instanceof J.Block ||
is instanceof J.MethodDeclaration ||
is instanceof J.ForLoop ||
is instanceof J.ForEachLoop ||
is instanceof J.ForLoop.Control ||
is instanceof J.ForEachLoop.Control ||
is instanceof J.Case ||
is instanceof J.Try ||
is instanceof J.Try.Resource ||
is instanceof J.Try.Catch ||
is instanceof J.MultiCatch ||
is instanceof J.Lambda ||
is instanceof JavaSourceFile
);
}
@Override
public J.VariableDeclarations.NamedVariable visitVariable(J.VariableDeclarations.NamedVariable variable, ExecutionContext ctx) {
// skip matching ignored variable names right away
if (ignoreVariableNames != null && ignoreVariableNames.contains(variable.getSimpleName())) {
return variable;
}
Cursor parentScope = getCursorToParentScope(getCursor());
J parent = parentScope.getValue();
if (parentScope.getParent() == null ||
// skip class instance variables. parentScope.getValue() covers java records.
parentScope.getParent().getValue() instanceof J.ClassDeclaration || parentScope.getValue() instanceof J.ClassDeclaration ||
// skip anonymous class instance variables
parentScope.getParent().getValue() instanceof J.NewClass ||
// skip if method declaration parameter
parent instanceof J.MethodDeclaration ||
// skip if defined in an enhanced or standard for loop, since there isn't much we can do about the semantics at that point
parent instanceof J.ForLoop.Control || parent instanceof J.ForEachLoop.Control ||
// skip if defined in a switch case
parent instanceof J.Case ||
// skip if defined in a try's catch clause as an Exception variable declaration
parent instanceof J.Try.Resource || parent instanceof J.Try.Catch || parent instanceof J.MultiCatch ||
// skip if defined as a parameter to a lambda expression
parent instanceof J.Lambda ||
// skip if the initializer may have a side effect
initializerMightSideEffect(variable)
) {
return variable;
}
List<J> readReferences = References.findRhsReferences(parentScope.getValue(), variable.getName());
if (readReferences.isEmpty()) {
List<Statement> assignmentReferences = References.findLhsReferences(parentScope.getValue(), variable.getName());
for (Statement ref : assignmentReferences) {
if (ref instanceof J.Assignment) {
doAfterVisit(new PruneAssignmentExpression((J.Assignment) ref));
}
doAfterVisit(new DeleteStatement<>(ref));
}
return null;
}
return super.visitVariable(variable, ctx);
}
@Override
public Statement visitStatement(Statement statement, ExecutionContext ctx) {
List<Comment> comments = getCursor().pollNearestMessage("COMMENTS_KEY");
if (comments != null) {
statement = statement.withComments(ListUtils.concatAll(statement.getComments(), comments));
}
return super.visitStatement(statement, ctx);
}
@Override
public J.VariableDeclarations visitVariableDeclarations(J.VariableDeclarations multiVariable, ExecutionContext ctx) {
if (!service(AnnotationService.class).getAllAnnotations(getCursor()).isEmpty()) {
return multiVariable;
}
J.VariableDeclarations mv = super.visitVariableDeclarations(multiVariable, ctx);
if (mv.getVariables().isEmpty()) {
if (!mv.getPrefix().getComments().isEmpty()) {
getCursor().dropParentUntil(J.ClassDeclaration.class::isInstance).putMessage("COMMENTS_KEY", mv.getPrefix().getComments());
}
doAfterVisit(new DeleteStatement<>(mv));
}
return mv;
}
private boolean initializerMightSideEffect(J.VariableDeclarations.NamedVariable variable) {
if (variable.getInitializer() == null) {
return false;
}
AtomicBoolean mightSideEffect = new AtomicBoolean(false);
new JavaIsoVisitor<AtomicBoolean>() {
@Override
public J.MethodInvocation visitMethodInvocation(J.MethodInvocation methodInvocation, AtomicBoolean result) {
if (SAFE_GETTER_METHODS.matches(methodInvocation)) {
return methodInvocation;
}
result.set(true);
return methodInvocation;
}
@Override
public J.NewClass visitNewClass(J.NewClass newClass, AtomicBoolean result) {
result.set(true);
return newClass;
}
@Override
public J.Assignment visitAssignment(J.Assignment assignment, AtomicBoolean result) {
result.set(true);
return assignment;
}
}.visit(variable.getInitializer(), mightSideEffect);
return mightSideEffect.get();
}
};
}
/**
* Take an assignment in a context other than a variable declaration, such as the arguments of a function invocation or if condition,
* and remove the assignment, leaving behind the value being assigned.
*/
@Value
@EqualsAndHashCode(callSuper = false)
private static class PruneAssignmentExpression extends JavaIsoVisitor<ExecutionContext> {
J.Assignment assignment;
@Override
public <T extends J> J.ControlParentheses<T> visitControlParentheses(J.ControlParentheses<T> c, ExecutionContext ctx) {
//noinspection unchecked
c = (J.ControlParentheses<T>) new AssignmentToLiteral(assignment)
.visitNonNull(c, ctx, getCursor().getParentOrThrow());
return c;
}
@Override
public J.MethodInvocation visitMethodInvocation(J.MethodInvocation m, ExecutionContext ctx) {
AssignmentToLiteral atl = new AssignmentToLiteral(assignment);
m = m.withArguments(ListUtils.map(m.getArguments(), it -> (Expression) atl.visitNonNull(it, ctx, getCursor().getParentOrThrow())));
return m;
}
}
@Value
@EqualsAndHashCode(callSuper = false)
private static class AssignmentToLiteral extends JavaVisitor<ExecutionContext> {
J.Assignment assignment;
@Override
public J visitAssignment(J.Assignment a, ExecutionContext ctx) {
if (assignment.isScope(a)) {
return a.getAssignment().withPrefix(a.getPrefix());
}
return a;
}
}
private static class References {
private static boolean isIncrementKind(Cursor tree) {
return tree.getValue() instanceof J.Unary && ((J.Unary) tree.getValue()).getOperator().isModifying();
}
private static @Nullable Cursor dropParentWhile(Predicate<Object> valuePredicate, Cursor cursor) {
while (cursor != null && valuePredicate.test(cursor.getValue())) {
cursor = cursor.getParent();
}
return cursor;
}
private static @Nullable Cursor dropParentUntil(Predicate<Object> valuePredicate, Cursor cursor) {
while (cursor != null && !valuePredicate.test(cursor.getValue())) {
cursor = cursor.getParent();
}
return cursor;
}
private static boolean isRhsValue(Cursor tree) {
if (!(tree.getValue() instanceof J.Identifier)) {
return false;
}
Cursor parent = dropParentWhile(J.Parentheses.class::isInstance, tree.getParent());
assert parent != null;
if (parent.getValue() instanceof J.Assignment) {
if (dropParentUntil(J.ControlParentheses.class::isInstance, parent) != null) {
return true;
}
J.Assignment assignment = parent.getValue();
return assignment.getVariable() != tree.getValue();
}
if (parent.getValue() instanceof J.VariableDeclarations.NamedVariable) {
J.VariableDeclarations.NamedVariable namedVariable = parent.getValue();
return namedVariable.getName() != tree.getValue();
}
if (parent.getValue() instanceof J.AssignmentOperation) {
J.AssignmentOperation assignmentOperation = parent.getValue();
if (assignmentOperation.getVariable() == tree.getValue()) {
Tree grandParent = parent.getParentTreeCursor().getValue();
return (grandParent instanceof Expression || grandParent instanceof J.Return);
}
}
return !(isIncrementKind(parent) && parent.getParentTreeCursor().getValue() instanceof J.Block);
}
/**
* An identifier is considered a right-hand side ("rhs") read operation if it is not used as the left operand
* of an assignment, nor as the operand of a stand-alone increment.
*
* @param j The subtree to search.
* @param target A {@link J.Identifier} to check for usages.
* @return found {@link J} locations of "right-hand" read calls.
*/
private static List<J> findRhsReferences(J j, J.Identifier target) {
final List<J> refs = new ArrayList<>();
new JavaIsoVisitor<List<J>>() {
@Override
public J.Identifier visitIdentifier(J.Identifier identifier, List<J> ctx) {
if (identifier.getSimpleName().equals(target.getSimpleName()) && isRhsValue(getCursor())) {
ctx.add(identifier);
}
return super.visitIdentifier(identifier, ctx);
}
}.visit(j, refs);
return refs;
}
/**
* @param j The subtree to search.
* @param target A {@link J.Identifier} to check for usages.
* @return found {@link Statement} locations of "left-hand" assignment write calls.
*/
private static List<Statement> findLhsReferences(J j, J.Identifier target) {
JavaIsoVisitor<List<Statement>> visitor = new JavaIsoVisitor<List<Statement>>() {
@Override
public J.Assignment visitAssignment(J.Assignment assignment, List<Statement> ctx) {
if (assignment.getVariable() instanceof J.Identifier) {
J.Identifier i = (J.Identifier) assignment.getVariable();
if (i.getSimpleName().equals(target.getSimpleName())) {
ctx.add(assignment);
}
}
return super.visitAssignment(assignment, ctx);
}
@Override
public J.AssignmentOperation visitAssignmentOperation(J.AssignmentOperation assignOp, List<Statement> ctx) {
if (assignOp.getVariable() instanceof J.Identifier) {
J.Identifier i = (J.Identifier) assignOp.getVariable();
if (i.getSimpleName().equals(target.getSimpleName())) {
ctx.add(assignOp);
}
}
return super.visitAssignmentOperation(assignOp, ctx);
}
@Override
public J.Unary visitUnary(J.Unary unary, List<Statement> ctx) {
if (unary.getExpression() instanceof J.Identifier) {
J.Identifier i = (J.Identifier) unary.getExpression();
if (i.getSimpleName().equals(target.getSimpleName())) {
ctx.add(unary);
}
}
return super.visitUnary(unary, ctx);
}
};
List<Statement> refs = new ArrayList<>();
visitor.visit(j, refs);
return refs;
}
}
}