/
RedundantSetterCall.java
384 lines (338 loc) · 14 KB
/
RedundantSetterCall.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
/*
* Copyright 2018 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.bugpatterns;
import static com.google.common.base.CaseFormat.UPPER_CAMEL;
import static com.google.common.base.CaseFormat.UPPER_UNDERSCORE;
import static com.google.common.collect.Streams.stream;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.VisitorState.memoize;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import static com.google.errorprone.predicates.TypePredicates.isDescendantOf;
import static com.google.errorprone.util.ASTHelpers.enumValues;
import static com.google.errorprone.util.ASTHelpers.getEnclosedElements;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.getUpperBound;
import static com.google.errorprone.util.ASTHelpers.hasAnnotation;
import static com.google.errorprone.util.ASTHelpers.isAbstract;
import static com.google.errorprone.util.ASTHelpers.isSameType;
import static com.google.errorprone.util.ASTHelpers.isSubtype;
import static java.util.stream.Collectors.joining;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.ListMultimap;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.ErrorProneFlags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.predicates.TypePredicate;
import com.google.errorprone.suppliers.Supplier;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Type;
import java.util.Collection;
import java.util.Map;
import java.util.regex.Pattern;
import javax.inject.Inject;
import org.checkerframework.checker.nullness.qual.Nullable;
/** A BugPattern; see the summary. */
@BugPattern(
summary = "A field was set twice in the same chained expression.",
severity = ERROR,
altNames = "ProtoRedundantSet",
tags = StandardTags.FRAGILE_CODE)
public final class RedundantSetterCall extends BugChecker implements MethodInvocationTreeMatcher {
/** Matches a fluent setter method. */
private static final Matcher<ExpressionTree> FLUENT_SETTER =
anyOf(
instanceMethod()
.onDescendantOfAny(
"com.google.protobuf.GeneratedMessage.Builder",
"com.google.protobuf.GeneratedMessageLite.Builder")
.withNameMatching(Pattern.compile("^(set|add|clear|put).+")),
(tree, state) -> {
if (!(tree instanceof MethodInvocationTree)) {
return false;
}
var symbol = getSymbol((MethodInvocationTree) tree);
return isAbstract(symbol)
&& isWithinAutoValueBuilder(symbol, state)
&& isSameType(symbol.owner.type, symbol.getReturnType(), state);
});
private static final TypePredicate ONE_OF_ENUM =
isDescendantOf("com.google.protobuf.AbstractMessageLite.InternalOneOfEnum");
/**
* Matches a terminal setter. That is, a fluent builder method which is either not followed by
* another method invocation, or by a method invocation which is not a {@link #FLUENT_SETTER}.
*/
private static final Matcher<ExpressionTree> TERMINAL_FLUENT_SETTER =
allOf(
FLUENT_SETTER,
(tree, state) ->
!(state.getPath().getParentPath().getLeaf() instanceof MemberSelectTree
&& FLUENT_SETTER.matches(
(ExpressionTree) state.getPath().getParentPath().getParentPath().getLeaf(),
state)));
private final boolean matchOneOfs;
@Inject
RedundantSetterCall(ErrorProneFlags flags) {
this.matchOneOfs = flags.getBoolean("RedundantSetterCall:MatchOneOfs").orElse(true);
}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!TERMINAL_FLUENT_SETTER.matches(tree, state)) {
return Description.NO_MATCH;
}
ListMultimap<Field, FieldWithValue> setters = ArrayListMultimap.create();
ImmutableMap<String, OneOfField> oneOfSetters =
matchOneOfs ? scanForOneOfSetters(getType(tree), state) : ImmutableMap.of();
Type type = ASTHelpers.getReturnType(tree);
for (ExpressionTree current = tree;
FLUENT_SETTER.matches(current, state);
current = ASTHelpers.getReceiver(current)) {
MethodInvocationTree method = (MethodInvocationTree) current;
if (!ASTHelpers.isSameType(type, ASTHelpers.getReturnType(current), state)) {
break;
}
Symbol symbol = getSymbol(current);
if (!(symbol instanceof MethodSymbol)) {
break;
}
String methodName = symbol.getSimpleName().toString();
// Break on methods like "addFooBuilder", otherwise we might be building a nested proto of the
// same type.
if (methodName.endsWith("Builder")) {
break;
}
for (FieldType fieldType : FieldType.values()) {
FieldWithValue match = fieldType.match(methodName, method, state);
if (match != null) {
setters.put(match.getField(), match);
if (oneOfSetters.containsKey(methodName)) {
setters.put(oneOfSetters.get(methodName), match);
}
}
}
}
setters.asMap().entrySet().removeIf(entry -> entry.getValue().size() <= 1);
if (setters.isEmpty()) {
return Description.NO_MATCH;
}
for (Map.Entry<Field, Collection<FieldWithValue>> entry : setters.asMap().entrySet()) {
Field field = entry.getKey();
Collection<FieldWithValue> values = entry.getValue();
state.reportMatch(describe(field, values, state));
}
return Description.NO_MATCH;
}
private ImmutableMap<String, OneOfField> scanForOneOfSetters(Type type, VisitorState state) {
var owner = getUpperBound(type, state.getTypes()).tsym.owner;
if (owner == null || isSubtype(owner.type, GENERATED_MESSAGE_LITE.get(state), state)) {
return ImmutableMap.of();
}
var builder = ImmutableMap.<String, OneOfField>builder();
for (Symbol element : getEnclosedElements(owner)) {
if (!ONE_OF_ENUM.apply(element.type, state)) {
continue;
}
var oneOfField = OneOfField.of(element.getSimpleName().toString().replaceFirst("Case$", ""));
for (String enumName : enumValues(element.type.tsym)) {
if (enumName.equals("ONEOF_NOT_SET")) {
continue;
}
builder.put("set" + UPPER_UNDERSCORE.to(UPPER_CAMEL, enumName), oneOfField);
}
}
return builder.buildOrThrow();
}
private static final Supplier<Type> GENERATED_MESSAGE_LITE =
memoize(state -> state.getTypeFromString("com.google.protobuf.GeneratedMessageLite"));
private Description describe(
Field field, Collection<FieldWithValue> locations, VisitorState state) {
// We flag up all duplicate sets, but only suggest a fix if the setter is given the same
// argument (based on source code). This is to avoid the temptation to apply the fix in
// cases like,
// MyProto.newBuilder().setFoo(copy.getFoo()).setFoo(copy.getBar())
// where the correct fix is probably to replace the second 'setFoo' with 'setBar'.
SuggestedFix.Builder fix = SuggestedFix.builder();
long values =
locations.stream().map(l -> state.getSourceForNode(l.getArgument())).distinct().count();
if (field.identicalValuesShouldBeRemoved() && values == 1) {
for (FieldWithValue fieldWithValue : Iterables.skip(locations, 1)) {
MethodInvocationTree method = fieldWithValue.getMethodInvocation();
int startPos = state.getEndPosition(ASTHelpers.getReceiver(method));
int endPos = state.getEndPosition(method);
fix.replace(startPos, endPos, "");
}
}
return buildDescription(locations.iterator().next().getArgument())
.setMessage(
String.format(
"%s was called %s with %s. Setting the same field multiple times is redundant, and "
+ "could mask a bug.",
field.toString(locations),
nTimes(locations.size()),
field.identicalValuesShouldBeRemoved()
? (values == 1 ? " with the same argument" : " with different arguments")
: ""))
.addFix(fix.build())
.build();
}
private static String nTimes(int n) {
return n == 2 ? "twice" : String.format("%d times", n);
}
enum FieldType {
SINGLE {
@Override
@Nullable FieldWithValue match(String name, MethodInvocationTree tree, VisitorState state) {
if ((name.startsWith("set") || isWithinAutoValueBuilder(getSymbol(tree), state))
&& tree.getArguments().size() == 1) {
return FieldWithValue.of(SingleField.of(name), tree, tree.getArguments().get(0));
}
return null;
}
},
REPEATED {
@Override
@Nullable FieldWithValue match(String name, MethodInvocationTree tree, VisitorState state) {
if (name.startsWith("set") && tree.getArguments().size() == 2) {
Integer index = ASTHelpers.constValue(tree.getArguments().get(0), Integer.class);
if (index != null) {
return FieldWithValue.of(
RepeatedField.of(name, index), tree, tree.getArguments().get(1));
}
}
return null;
}
},
MAP {
@Override
@Nullable FieldWithValue match(String name, MethodInvocationTree tree, VisitorState state) {
if (name.startsWith("put") && tree.getArguments().size() == 2) {
Object key = ASTHelpers.constValue(tree.getArguments().get(0), Object.class);
if (key != null) {
return FieldWithValue.of(MapField.of(name, key), tree, tree.getArguments().get(1));
}
}
return null;
}
};
abstract FieldWithValue match(String name, MethodInvocationTree tree, VisitorState state);
}
private static boolean isWithinAutoValueBuilder(MethodSymbol symbol, VisitorState state) {
return hasAnnotation(symbol.owner, "com.google.auto.value.AutoValue.Builder", state);
}
interface Field {
@Override
boolean equals(@Nullable Object other);
@Override
int hashCode();
boolean identicalValuesShouldBeRemoved();
String toString(Iterable<FieldWithValue> locations);
}
@AutoValue
abstract static class SingleField implements Field {
abstract String getName();
static SingleField of(String name) {
return new AutoValue_RedundantSetterCall_SingleField(name);
}
@Override
public final String toString(Iterable<FieldWithValue> locations) {
return String.format("%s(..)", getName());
}
@Override
public boolean identicalValuesShouldBeRemoved() {
return true;
}
}
@AutoValue
abstract static class RepeatedField implements Field {
abstract String getName();
abstract int getIndex();
static RepeatedField of(String name, int index) {
return new AutoValue_RedundantSetterCall_RepeatedField(name, index);
}
@Override
public final String toString(Iterable<FieldWithValue> locations) {
return String.format("%s(%s, ..)", getName(), getIndex());
}
@Override
public boolean identicalValuesShouldBeRemoved() {
return true;
}
}
@AutoValue
abstract static class MapField implements Field {
abstract String getName();
abstract Object getKey();
static MapField of(String name, Object key) {
return new AutoValue_RedundantSetterCall_MapField(name, key);
}
@Override
public final String toString(Iterable<FieldWithValue> locations) {
return String.format("%s(%s, ..)", getName(), getKey());
}
@Override
public boolean identicalValuesShouldBeRemoved() {
return true;
}
}
@AutoValue
abstract static class OneOfField implements Field {
abstract String oneOfName();
static OneOfField of(String oneOfName) {
return new AutoValue_RedundantSetterCall_OneOfField(oneOfName);
}
@Override
public final String toString(Iterable<FieldWithValue> locations) {
return String.format(
"The oneof `%s` (set via %s)",
oneOfName(),
stream(locations)
.map(l -> getSymbol(l.getMethodInvocation()).getSimpleName().toString())
.distinct()
.sorted()
.collect(joining(", ")));
}
@Override
public boolean identicalValuesShouldBeRemoved() {
return false;
}
}
@AutoValue
abstract static class FieldWithValue {
abstract Field getField();
abstract MethodInvocationTree getMethodInvocation();
abstract ExpressionTree getArgument();
static FieldWithValue of(
Field field, MethodInvocationTree methodInvocationTree, ExpressionTree argumentTree) {
return new AutoValue_RedundantSetterCall_FieldWithValue(
field, methodInvocationTree, argumentTree);
}
}
}