-
Notifications
You must be signed in to change notification settings - Fork 730
/
SuggestedFix.java
427 lines (372 loc) · 14.3 KB
/
SuggestedFix.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
/*
* Copyright 2011 The Error Prone Authors.
*
* 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 com.google.errorprone.fixes;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.tree.EndPosTable;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.Nullable;
/**
* @author alexeagle@google.com (Alex Eagle)
*/
public class SuggestedFix implements Fix {
private final String shortDescription;
private final ImmutableList<FixOperation> fixes;
private final ImmutableSet<String> importsToAdd;
private final ImmutableSet<String> importsToRemove;
private SuggestedFix(SuggestedFix.Builder builder) {
this.shortDescription = builder.shortDescription;
this.fixes = ImmutableList.copyOf(builder.fixes);
this.importsToAdd = ImmutableSet.copyOf(builder.importsToAdd);
this.importsToRemove = ImmutableSet.copyOf(builder.importsToRemove);
}
@Override
public boolean isEmpty() {
return fixes.isEmpty() && importsToAdd.isEmpty() && importsToRemove.isEmpty();
}
@Override
public Collection<String> getImportsToAdd() {
return importsToAdd;
}
@Override
public Collection<String> getImportsToRemove() {
return importsToRemove;
}
@Override
public String toString(JCCompilationUnit compilationUnit) {
StringBuilder result = new StringBuilder("replace ");
for (Replacement replacement : getReplacements(compilationUnit.endPositions)) {
result.append(
String.format(
"position %d:%d with \"%s\" ",
replacement.startPosition(), replacement.endPosition(), replacement.replaceWith()));
}
return result.toString();
}
@Override
public String getShortDescription() {
return shortDescription;
}
@Override
public Set<Replacement> getReplacements(EndPosTable endPositions) {
if (endPositions == null) {
throw new IllegalArgumentException(
"Cannot produce correct replacements without endPositions.");
}
Replacements replacements = new Replacements();
for (FixOperation fix : fixes) {
replacements.add(
fix.getReplacement(endPositions), Replacements.CoalescePolicy.EXISTING_FIRST);
}
return replacements.ascending();
}
/** {@link Builder#replace(Tree, String)} */
public static SuggestedFix replace(Tree tree, String replaceWith) {
return builder().replace(tree, replaceWith).build();
}
/**
* Replace the characters from startPos, inclusive, until endPos, exclusive, with the given
* string.
*
* @param startPos The position from which to start replacing, inclusive
* @param endPos The position at which to end replacing, exclusive
* @param replaceWith The string to replace with
*/
public static SuggestedFix replace(int startPos, int endPos, String replaceWith) {
return builder().replace(startPos, endPos, replaceWith).build();
}
/**
* Replace a tree node with a string, but adjust the start and end positions as well. For example,
* if the tree node begins at index 10 and ends at index 30, this call will replace the characters
* at index 15 through 25 with "replacement":
*
* <pre>
* {@code fix.replace(node, "replacement", 5, -5)}
* </pre>
*
* @param node The tree node to replace
* @param replaceWith The string to replace with
* @param startPosAdjustment The adjustment to add to the start position (negative is OK)
* @param endPosAdjustment The adjustment to add to the end position (negative is OK)
*/
public static SuggestedFix replace(
Tree node, String replaceWith, int startPosAdjustment, int endPosAdjustment) {
return builder().replace(node, replaceWith, startPosAdjustment, endPosAdjustment).build();
}
/** {@link Builder#prefixWith(Tree, String)} */
public static SuggestedFix prefixWith(Tree node, String prefix) {
return builder().prefixWith(node, prefix).build();
}
/** {@link Builder#postfixWith(Tree, String)} */
public static SuggestedFix postfixWith(Tree node, String postfix) {
return builder().postfixWith(node, postfix).build();
}
/** {@link Builder#delete(Tree)} */
public static SuggestedFix delete(Tree node) {
return builder().delete(node).build();
}
/** {@link Builder#swap(Tree, Tree)} */
public static SuggestedFix swap(Tree node1, Tree node2) {
return builder().swap(node1, node2).build();
}
private static final SuggestedFix EMPTY = builder().build();
/** Creates an empty {@link SuggestedFix}. */
public static SuggestedFix emptyFix() {
return EMPTY;
}
public static Builder builder() {
return new Builder();
}
/** Builds {@link SuggestedFix}s. */
public static class Builder {
private final List<FixOperation> fixes = new ArrayList<>();
private final Set<String> importsToAdd = new LinkedHashSet<>();
private final Set<String> importsToRemove = new LinkedHashSet<>();
private String shortDescription = "";
protected Builder() {}
public boolean isEmpty() {
return fixes.isEmpty() && importsToAdd.isEmpty() && importsToRemove.isEmpty();
}
public SuggestedFix build() {
return new SuggestedFix(this);
}
@CanIgnoreReturnValue
private Builder with(FixOperation fix) {
fixes.add(fix);
return this;
}
/**
* Sets a custom short description for this fix. This is useful for differentiating multiple
* fixes from the same finding.
*
* <p>Should be limited to one sentence.
*/
@CanIgnoreReturnValue
public Builder setShortDescription(String shortDescription) {
this.shortDescription = shortDescription;
return this;
}
@CanIgnoreReturnValue
public Builder replace(Tree node, String replaceWith) {
checkNotSyntheticConstructor(node);
return with(new ReplacementFix((DiagnosticPosition) node, replaceWith));
}
/**
* Replace the characters from startPos, inclusive, until endPos, exclusive, with the given
* string.
*
* @param startPos The position from which to start replacing, inclusive
* @param endPos The position at which to end replacing, exclusive
* @param replaceWith The string to replace with
*/
@CanIgnoreReturnValue
public Builder replace(int startPos, int endPos, String replaceWith) {
DiagnosticPosition pos = new IndexedPosition(startPos, endPos);
return with(new ReplacementFix(pos, replaceWith));
}
/**
* Replace a tree node with a string, but adjust the start and end positions as well. For
* example, if the tree node begins at index 10 and ends at index 30, this call will replace the
* characters at index 15 through 25 with "replacement":
*
* <pre>
* {@code fix.replace(node, "replacement", 5, -5)}
* </pre>
*
* @param node The tree node to replace
* @param replaceWith The string to replace with
* @param startPosAdjustment The adjustment to add to the start position (negative is OK)
* @param endPosAdjustment The adjustment to add to the end position (negative is OK)
*/
@CanIgnoreReturnValue
public Builder replace(
Tree node, String replaceWith, int startPosAdjustment, int endPosAdjustment) {
checkNotSyntheticConstructor(node);
return with(
new ReplacementFix(
new AdjustedPosition((JCTree) node, startPosAdjustment, endPosAdjustment),
replaceWith));
}
@CanIgnoreReturnValue
public Builder prefixWith(Tree node, String prefix) {
checkNotSyntheticConstructor(node);
return with(new PrefixInsertion((DiagnosticPosition) node, prefix));
}
@CanIgnoreReturnValue
public Builder postfixWith(Tree node, String postfix) {
checkNotSyntheticConstructor(node);
return with(new PostfixInsertion((DiagnosticPosition) node, postfix));
}
@CanIgnoreReturnValue
public Builder delete(Tree node) {
checkNotSyntheticConstructor(node);
return replace(node, "");
}
@CanIgnoreReturnValue
public Builder swap(Tree node1, Tree node2) {
checkNotSyntheticConstructor(node1);
checkNotSyntheticConstructor(node2);
// calling Tree.toString() is kind of cheesy, but we don't currently have a better option
// TODO(cushon): consider an approach that doesn't rewrite the original tokens
fixes.add(new ReplacementFix((DiagnosticPosition) node1, node2.toString()));
fixes.add(new ReplacementFix((DiagnosticPosition) node2, node1.toString()));
return this;
}
/**
* Add an import statement as part of this SuggestedFix. Import string should be of the form
* "foo.bar.baz".
*/
@CanIgnoreReturnValue
public Builder addImport(String importString) {
importsToAdd.add("import " + importString);
return this;
}
/**
* Add a static import statement as part of this SuggestedFix. Import string should be of the
* form "foo.bar.baz".
*/
@CanIgnoreReturnValue
public Builder addStaticImport(String importString) {
importsToAdd.add("import static " + importString);
return this;
}
/**
* Remove an import statement as part of this SuggestedFix. Import string should be of the form
* "foo.bar.baz".
*/
@CanIgnoreReturnValue
public Builder removeImport(String importString) {
importsToRemove.add("import " + importString);
return this;
}
/**
* Remove a static import statement as part of this SuggestedFix. Import string should be of the
* form "foo.bar.baz".
*/
@CanIgnoreReturnValue
public Builder removeStaticImport(String importString) {
importsToRemove.add("import static " + importString);
return this;
}
/**
* Merges all edits from {@code other} into {@code this}. If {@code other} is null, do nothing.
*/
@CanIgnoreReturnValue
public Builder merge(@Nullable Builder other) {
if (other == null) {
return this;
}
if (shortDescription.isEmpty()) {
shortDescription = other.shortDescription;
}
fixes.addAll(other.fixes);
importsToAdd.addAll(other.importsToAdd);
importsToRemove.addAll(other.importsToRemove);
return this;
}
/**
* Merges all edits from {@code other} into {@code this}. If {@code other} is null, do nothing.
*/
@CanIgnoreReturnValue
public Builder merge(@Nullable SuggestedFix other) {
if (other == null) {
return this;
}
if (shortDescription.isEmpty()) {
shortDescription = other.getShortDescription();
}
fixes.addAll(other.fixes);
importsToAdd.addAll(other.importsToAdd);
importsToRemove.addAll(other.importsToRemove);
return this;
}
/**
* Prevent attempts to modify implicit default constructurs, since they are one of the few
* synthetic constructs added to the AST early enough to be visible from Error Prone.
*/
private static void checkNotSyntheticConstructor(Tree tree) {
if (tree instanceof MethodTree && ASTHelpers.isGeneratedConstructor((MethodTree) tree)) {
throw new IllegalArgumentException("Cannot edit synthetic AST nodes");
}
}
}
/** Models a single fix operation. */
private interface FixOperation {
/** Calculate the replacement operation once end positions are available. */
Replacement getReplacement(EndPosTable endPositions);
}
/** Inserts new text at a specific insertion point (e.g. prefix or postfix). */
private abstract static class InsertionFix implements FixOperation {
protected abstract int getInsertionIndex(EndPosTable endPositions);
protected final DiagnosticPosition position;
protected final String insertion;
protected InsertionFix(DiagnosticPosition position, String insertion) {
checkArgument(position.getStartPosition() >= 0, "invalid start position");
this.position = position;
this.insertion = insertion;
}
@Override
public Replacement getReplacement(EndPosTable endPositions) {
int insertionIndex = getInsertionIndex(endPositions);
return Replacement.create(insertionIndex, insertionIndex, insertion);
}
}
private static class PostfixInsertion extends InsertionFix {
public PostfixInsertion(DiagnosticPosition tree, String insertion) {
super(tree, insertion);
}
@Override
protected int getInsertionIndex(EndPosTable endPositions) {
return position.getEndPosition(endPositions);
}
}
private static class PrefixInsertion extends InsertionFix {
public PrefixInsertion(DiagnosticPosition tree, String insertion) {
super(tree, insertion);
}
@Override
protected int getInsertionIndex(EndPosTable endPositions) {
return position.getStartPosition();
}
}
/** Replaces an entire diagnostic position (from start to end) with the given string. */
private static class ReplacementFix implements FixOperation {
private final DiagnosticPosition original;
private final String replacement;
public ReplacementFix(DiagnosticPosition original, String replacement) {
checkArgument(original.getStartPosition() >= 0, "invalid start position");
this.original = original;
this.replacement = replacement;
}
@Override
public Replacement getReplacement(EndPosTable endPositions) {
return Replacement.create(
original.getStartPosition(), original.getEndPosition(endPositions), replacement);
}
}
}