/
InstanceOfPatternMatch.java
430 lines (388 loc) · 19.3 KB
/
InstanceOfPatternMatch.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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
/*
* 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.Data;
import lombok.EqualsAndHashCode;
import lombok.Value;
import org.openrewrite.*;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.java.JavaVisitor;
import org.openrewrite.java.VariableNameUtils;
import org.openrewrite.java.search.SemanticallyEqual;
import org.openrewrite.java.search.UsesJavaVersion;
import org.openrewrite.java.tree.*;
import org.openrewrite.marker.Markers;
import org.openrewrite.staticanalysis.groovy.GroovyFileChecker;
import org.openrewrite.staticanalysis.kotlin.KotlinFileChecker;
import java.time.Duration;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.Collections.emptyList;
import static org.openrewrite.Tree.randomId;
import static org.openrewrite.java.VariableNameUtils.GenerationStrategy.INCREMENT_NUMBER;
@Incubating(since = "7.36.0")
@Value
@EqualsAndHashCode(callSuper = false)
public class InstanceOfPatternMatch extends Recipe {
@Override
public String getDisplayName() {
return "Changes code to use Java 17's `instanceof` pattern matching";
}
@Override
public String getDescription() {
return "Adds pattern variables to `instanceof` expressions wherever the same (side effect free) expression is referenced in a corresponding type cast expression within the flow scope of the `instanceof`."
+ " Currently, this recipe supports `if` statements and ternary operator expressions.";
}
@Override
public Duration getEstimatedEffortPerOccurrence() {
return Duration.ofMinutes(1);
}
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
TreeVisitor<?, ExecutionContext> preconditions = Preconditions.and(
new UsesJavaVersion<>(17),
Preconditions.not(new KotlinFileChecker<>()),
Preconditions.not(new GroovyFileChecker<>())
);
return Preconditions.check(preconditions, new JavaVisitor<ExecutionContext>() {
@Override
public @Nullable J postVisit(J tree, ExecutionContext ctx) {
J result = super.postVisit(tree, ctx);
InstanceOfPatternReplacements original = getCursor().getMessage("flowTypeScope");
if (original != null && !original.isEmpty()) {
return UseInstanceOfPatternMatching.refactor(result, original, getCursor().getParentOrThrow());
}
return result;
}
@Override
public J.InstanceOf visitInstanceOf(J.InstanceOf instanceOf, ExecutionContext ctx) {
instanceOf = (J.InstanceOf) super.visitInstanceOf(instanceOf, ctx);
if (instanceOf.getPattern() != null || !instanceOf.getSideEffects().isEmpty()) {
return instanceOf;
}
Cursor maybeReplacementRoot = null;
J additionalContext = null;
boolean flowScopeBreakEncountered = false;
for (Iterator<Cursor> it = getCursor().getPathAsCursors(); it.hasNext(); ) {
Cursor next = it.next();
Object value = next.getValue();
if (value instanceof J.Binary) {
J.Binary binary = (J.Binary) value;
if (!flowScopeBreakEncountered && binary.getOperator() == J.Binary.Type.And) {
additionalContext = binary;
} else {
flowScopeBreakEncountered = true;
}
} else if (value instanceof J.Unary && ((J.Unary) value).getOperator() == J.Unary.Type.Not) {
// TODO this could be improved (the pattern variable may be applicable in the else case
// or even in subsequent statements (due to the flow scope semantics)
flowScopeBreakEncountered = true;
} else if (value instanceof Statement) {
maybeReplacementRoot = next;
break;
}
}
if (maybeReplacementRoot != null) {
J root = maybeReplacementRoot.getValue();
Set<J> contexts = new HashSet<>();
if (!flowScopeBreakEncountered) {
if (root instanceof J.If) {
contexts.add(((J.If) root).getThenPart());
} else if (root instanceof J.Ternary) {
contexts.add(((J.Ternary) root).getTruePart());
}
}
if (additionalContext != null) {
contexts.add(additionalContext);
}
if (!contexts.isEmpty()) {
InstanceOfPatternReplacements replacements = maybeReplacementRoot
.computeMessageIfAbsent("flowTypeScope", k -> new InstanceOfPatternReplacements(root));
replacements.registerInstanceOf(instanceOf, contexts);
}
}
return instanceOf;
}
@Override
public J visitTypeCast(J.TypeCast typeCast, ExecutionContext ctx) {
J result = super.visitTypeCast(typeCast, ctx);
if (result instanceof J.TypeCast) {
InstanceOfPatternReplacements replacements = getCursor().getNearestMessage("flowTypeScope");
if (replacements != null) {
replacements.registerTypeCast((J.TypeCast) result, getCursor());
}
}
return result;
}
});
}
@Data
private static class ExpressionAndType {
private final Expression expression;
private final JavaType type;
}
@Data
private static class InstanceOfPatternReplacements {
private final J root;
private final Map<ExpressionAndType, J.InstanceOf> instanceOfs = new HashMap<>();
private final Map<J.InstanceOf, Set<J>> contexts = new HashMap<>();
private final Map<J.InstanceOf, Set<Cursor>> contextScopes = new HashMap<>();
private final Map<J.TypeCast, J.InstanceOf> replacements = new HashMap<>();
private final Map<J.InstanceOf, J.VariableDeclarations.NamedVariable> variablesToDelete = new HashMap<>();
public void registerInstanceOf(J.InstanceOf instanceOf, Set<J> contexts) {
Expression expression = instanceOf.getExpression();
JavaType type = ((TypedTree) instanceOf.getClazz()).getType();
Optional<ExpressionAndType> existing = instanceOfs.keySet().stream()
.filter(k -> TypeUtils.isAssignableTo(type, k.getType())
&& SemanticallyEqual.areEqual(k.getExpression(), expression))
.findAny();
if (!existing.isPresent()) {
instanceOfs.put(new ExpressionAndType(expression, type), instanceOf);
this.contexts.put(instanceOf, contexts);
}
}
@SuppressWarnings("SuspiciousMethodCalls")
public void registerTypeCast(J.TypeCast typeCast, Cursor cursor) {
Expression expression = typeCast.getExpression();
JavaType type = typeCast.getClazz().getTree().getType();
Optional<ExpressionAndType> match = instanceOfs.keySet().stream()
.filter(k -> TypeUtils.isAssignableTo(type, k.getType())
&& SemanticallyEqual.areEqual(k.getExpression(), expression))
.findAny();
if (match.isPresent()) {
Cursor parent = cursor.getParentTreeCursor();
J.InstanceOf instanceOf = instanceOfs.get(match.get());
Set<J> validContexts = contexts.get(instanceOf);
for (Iterator<?> it = cursor.getPath(); it.hasNext(); ) {
Object next = it.next();
if (validContexts.contains(next)) {
if (parent.getValue() instanceof J.VariableDeclarations.NamedVariable
&& !variablesToDelete.containsKey(instanceOf)) {
variablesToDelete.put(instanceOf, parent.getValue());
} else {
replacements.put(typeCast, instanceOf);
}
contextScopes.computeIfAbsent(instanceOf, k -> new HashSet<>()).add(cursor);
break;
} else if (root == next) {
break;
}
}
}
}
public boolean isEmpty() {
return replacements.isEmpty() && variablesToDelete.isEmpty();
}
public J.InstanceOf processInstanceOf(J.InstanceOf instanceOf, Cursor cursor) {
if (!contextScopes.containsKey(instanceOf)) {
return instanceOf;
}
@Nullable JavaType type = ((TypedTree) instanceOf.getClazz()).getType();
String name = patternVariableName(instanceOf, cursor);
J.InstanceOf result = instanceOf.withPattern(new J.Identifier(
randomId(),
Space.build(" ", emptyList()),
Markers.EMPTY,
emptyList(),
name,
type,
null));
// update entry in replacements to share the pattern variable name
for (Map.Entry<J.TypeCast, J.InstanceOf> entry : replacements.entrySet()) {
if (entry.getValue() == instanceOf) {
entry.setValue(result);
}
}
return result;
}
private String patternVariableName(J.InstanceOf instanceOf, Cursor cursor) {
VariableNameStrategy strategy;
if (root instanceof J.If) {
J.VariableDeclarations.NamedVariable variable = variablesToDelete.get(instanceOf);
strategy = variable != null
? VariableNameStrategy.exact(variable.getSimpleName())
: VariableNameStrategy.normal(contextScopes.get(instanceOf));
} else {
strategy = VariableNameStrategy.short_();
}
String baseName = variableBaseName((TypeTree) instanceOf.getClazz(), strategy);
return VariableNameUtils.generateVariableName(baseName, cursor, INCREMENT_NUMBER);
}
@Nullable
public J processTypeCast(J.TypeCast typeCast, Cursor cursor) {
J.InstanceOf instanceOf = replacements.get(typeCast);
if (instanceOf != null && instanceOf.getPattern() != null) {
String name = ((J.Identifier) instanceOf.getPattern()).getSimpleName();
TypedTree owner = cursor.firstEnclosing(J.MethodDeclaration.class);
owner = owner != null ? owner : cursor.firstEnclosingOrThrow(J.ClassDeclaration.class);
JavaType.Variable fieldType = new JavaType.Variable(null, Flag.Default.getBitMask(), name, owner.getType(), typeCast.getType(), emptyList());
return new J.Identifier(
randomId(),
typeCast.getPrefix(),
Markers.EMPTY,
emptyList(),
name,
typeCast.getType(),
fieldType);
}
return null;
}
@Nullable
public J processVariableDeclarations(J.VariableDeclarations multiVariable) {
return multiVariable.getVariables().stream().anyMatch(variablesToDelete::containsValue) ? null : multiVariable;
}
}
private static String variableBaseName(TypeTree typeTree, VariableNameStrategy nameStrategy) {
return nameStrategy.variableName(typeTree.getType());
}
private static class UseInstanceOfPatternMatching extends JavaVisitor<Integer> {
private final InstanceOfPatternReplacements replacements;
public UseInstanceOfPatternMatching(InstanceOfPatternReplacements replacements) {
this.replacements = replacements;
}
@Nullable
static J refactor(@Nullable J tree, InstanceOfPatternReplacements replacements, Cursor cursor) {
return new UseInstanceOfPatternMatching(replacements).visit(tree, 0, cursor);
}
@Override
public J.InstanceOf visitInstanceOf(J.InstanceOf instanceOf, Integer executionContext) {
instanceOf = (J.InstanceOf) super.visitInstanceOf(instanceOf, executionContext);
instanceOf = replacements.processInstanceOf(instanceOf, getCursor());
return instanceOf;
}
@Override
public <T extends J> J visitParentheses(J.Parentheses<T> parens, Integer executionContext) {
if (parens.getTree() instanceof J.TypeCast) {
J replacement = replacements.processTypeCast((J.TypeCast) parens.getTree(), getCursor());
if (replacement != null) {
return replacement;
}
}
return super.visitParentheses(parens, executionContext);
}
@Override
public J visitTypeCast(J.TypeCast typeCast, Integer executionContext) {
typeCast = (J.TypeCast) super.visitTypeCast(typeCast, executionContext);
J replacement = replacements.processTypeCast(typeCast, getCursor());
if (replacement != null) {
return replacement;
}
return typeCast;
}
@SuppressWarnings("NullableProblems")
@Override
@Nullable
public J visitVariableDeclarations(J.VariableDeclarations multiVariable, Integer integer) {
multiVariable = (J.VariableDeclarations) super.visitVariableDeclarations(multiVariable, integer);
return replacements.processVariableDeclarations(multiVariable);
}
}
private static class VariableNameStrategy {
public static final Pattern NAME_SPLIT_PATTERN = Pattern.compile("[$._]*(?=\\p{Upper}+[\\p{Lower}\\p{Digit}]*)");
private final Style style;
@Nullable
private final String name;
private final Set<Cursor> contextScopes;
enum Style {
SHORT, NORMAL, EXACT
}
private VariableNameStrategy(Style style, @Nullable String exactName, Set<Cursor> contextScopes) {
this.style = style;
this.name = exactName;
this.contextScopes = contextScopes;
}
static VariableNameStrategy short_() {
return new VariableNameStrategy(Style.SHORT, null, Collections.emptySet());
}
static VariableNameStrategy normal(Set<Cursor> contextScopes) {
return new VariableNameStrategy(Style.NORMAL, null, contextScopes);
}
static VariableNameStrategy exact(String name) {
return new VariableNameStrategy(Style.EXACT, name, Collections.emptySet());
}
public String variableName(@Nullable JavaType type) {
// the instanceof operator only accepts classes (without generics) and arrays
if (style == Style.EXACT) {
//noinspection DataFlowIssue
return name;
} else if (type instanceof JavaType.FullyQualified) {
String className = ((JavaType.FullyQualified) type).getClassName();
className = className.substring(className.lastIndexOf('.') + 1);
String baseName = null;
switch (style) {
case SHORT:
StringBuilder builder = new StringBuilder();
for (int i = 0; i < className.length(); i++) {
char c = className.charAt(i);
if (Character.isUpperCase(c)) {
builder.append(Character.toLowerCase(c));
}
}
baseName = builder.length() > 0 ? builder.toString() : "o";
break;
case NORMAL:
Set<String> namesInScope = contextScopes.stream()
.flatMap(c -> VariableNameUtils.findNamesInScope(c).stream())
.collect(Collectors.toSet());
List<String> nameSegments = Stream.of(NAME_SPLIT_PATTERN.split(className))
.filter(s -> !s.isEmpty()).collect(Collectors.toList());
for (int i = nameSegments.size() - 1; i >= 0; i--) {
String name = String.join("", nameSegments.subList(i, nameSegments.size()));
if (name.length() < 2) {
continue;
}
name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
if (!namesInScope.contains(name)) {
baseName = name;
break;
}
}
if (baseName == null) {
baseName = Character.toLowerCase(className.charAt(0)) + className.substring(1);
}
break;
default:
baseName = "obj";
}
String candidate = baseName;
OUTER:
while (true) {
for (Cursor scope : contextScopes) {
String newCandidate = VariableNameUtils.generateVariableName(candidate, scope, VariableNameUtils.GenerationStrategy.INCREMENT_NUMBER);
if (!newCandidate.equals(candidate)) {
candidate = newCandidate;
continue OUTER;
}
}
break;
}
return candidate;
} else if (type instanceof JavaType.Primitive) {
String keyword = ((JavaType.Primitive) type).getKeyword();
return style == Style.SHORT ? keyword.substring(0, 1) : keyword;
} else if (type instanceof JavaType.Array) {
JavaType elemType = ((JavaType.Array) type).getElemType();
while (elemType instanceof JavaType.Array) {
elemType = ((JavaType.Array) elemType).getElemType();
}
return variableName(elemType) + 's';
}
return style == Style.SHORT ? "o" : "obj";
}
}
}