/
ImmutableChecker.java
426 lines (386 loc) · 15.7 KB
/
ImmutableChecker.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
/*
* Copyright 2015 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.threadsafety;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.common.collect.Sets.SetView;
import com.google.errorprone.BugPattern;
import com.google.errorprone.ErrorProneFlags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.annotations.Immutable;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MemberReferenceTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher;
import com.google.errorprone.bugpatterns.threadsafety.ImmutableAnalysis.ViolationReporter;
import com.google.errorprone.bugpatterns.threadsafety.ThreadSafety.Violation;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.MemberReferenceTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.TypeParameterTree;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symbol.TypeVariableSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.tree.JCTree.JCMemberReference;
import com.sun.tools.javac.tree.JCTree.JCNewClass;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
name = "Immutable",
summary = "Type declaration annotated with @Immutable is not immutable",
severity = ERROR,
documentSuppression = false)
public class ImmutableChecker extends BugChecker
implements ClassTreeMatcher,
NewClassTreeMatcher,
MethodInvocationTreeMatcher,
MethodTreeMatcher,
MemberReferenceTreeMatcher {
private final WellKnownMutability wellKnownMutability;
private final ImmutableSet<String> immutableAnnotations;
ImmutableChecker(ImmutableSet<String> immutableAnnotations) {
this(ErrorProneFlags.empty(), immutableAnnotations);
}
public ImmutableChecker(ErrorProneFlags flags) {
this(flags, ImmutableSet.of(Immutable.class.getName()));
}
private ImmutableChecker(ErrorProneFlags flags, ImmutableSet<String> immutableAnnotations) {
this.wellKnownMutability = WellKnownMutability.fromFlags(flags);
this.immutableAnnotations = immutableAnnotations;
}
// check instantiations of `@ImmutableTypeParameter`s in method references
@Override
public Description matchMemberReference(MemberReferenceTree tree, VisitorState state) {
checkInvocation(tree, getSymbol(tree), ((JCMemberReference) tree).referentType, state);
return NO_MATCH;
}
// check instantiations of `@ImmutableTypeParameter`s in method invocations
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
checkInvocation(tree, getSymbol(tree), ASTHelpers.getType(tree.getMethodSelect()), state);
return NO_MATCH;
}
@Override
public Description matchNewClass(NewClassTree tree, VisitorState state) {
// check instantiations of `@ImmutableTypeParameter`s in generic constructor invocations
checkInvocation(tree, getSymbol(tree), ((JCNewClass) tree).constructorType, state);
// check instantiations of `@ImmutableTypeParameter`s in class constructor invocations
checkInstantiation(
tree,
state,
getSymbol(tree.getIdentifier()).getTypeParameters(),
ASTHelpers.getType(tree).getTypeArguments());
ClassTree classBody = tree.getClassBody();
// Only anonymous classes have a body next to the new operator.
if (classBody != null) {
// check instantiations of `@ImmutableTypeParameter`s in anonymous class constructor
// invocations
checkClassTreeInstantiation(classBody, state, createImmutableAnalysis(state));
}
return NO_MATCH;
}
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
checkInstantiation(
tree,
state,
getSymbol(tree).getTypeParameters(),
ASTHelpers.getType(tree).getTypeArguments());
return NO_MATCH;
}
private ImmutableAnalysis createImmutableAnalysis(VisitorState state) {
return new ImmutableAnalysis(this, state, wellKnownMutability, immutableAnnotations);
}
private void checkInvocation(
Tree tree, MethodSymbol symbol, Type methodType, VisitorState state) {
ImmutableAnalysis analysis = createImmutableAnalysis(state);
Violation info = analysis.checkInvocation(methodType, symbol);
if (info.isPresent()) {
state.reportMatch(buildDescription(tree).setMessage(info.message()).build());
}
}
private void checkInstantiation(
Tree tree,
VisitorState state,
ImmutableAnalysis analysis,
Collection<TypeVariableSymbol> typeParameters,
Collection<Type> typeArguments) {
Violation info = analysis.checkInstantiation(typeParameters, typeArguments);
if (info.isPresent()) {
state.reportMatch(buildDescription(tree).setMessage(info.message()).build());
}
}
private void checkInstantiation(
Tree tree,
VisitorState state,
Collection<TypeVariableSymbol> typeParameters,
Collection<Type> typeArguments) {
checkInstantiation(tree, state, createImmutableAnalysis(state), typeParameters, typeArguments);
}
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
ImmutableAnalysis analysis = createImmutableAnalysis(state);
checkClassTreeInstantiation(tree, state, analysis);
if (tree.getSimpleName().length() == 0) {
// anonymous classes have empty names
// TODO(cushon): once Java 8 happens, require @Immutable on anonymous classes
return handleAnonymousClass(tree, state, analysis);
}
AnnotationInfo annotation = analysis.getImmutableAnnotation(tree, state);
if (annotation == null) {
// If the type isn't annotated we don't check for immutability, but we do
// report an error if it extends/implements any @Immutable-annotated types.
return checkSubtype(tree, state);
}
// Special-case visiting declarations of known-immutable types; these uses
// of the annotation are "trusted".
if (wellKnownMutability.getKnownImmutableClasses().containsValue(annotation)) {
return NO_MATCH;
}
// Check that the types in containerOf actually exist
Map<String, TypeVariableSymbol> typarams = new HashMap<>();
for (TypeParameterTree typaram : tree.getTypeParameters()) {
typarams.put(typaram.getName().toString(), (TypeVariableSymbol) getSymbol(typaram));
}
SetView<String> difference = Sets.difference(annotation.containerOf(), typarams.keySet());
if (!difference.isEmpty()) {
return buildDescription(tree)
.setMessage(
String.format(
"could not find type(s) referenced by containerOf: %s",
Joiner.on("', '").join(difference)))
.build();
}
ImmutableSet<String> immutableAndContainer =
typarams.entrySet().stream()
.filter(
e ->
annotation.containerOf().contains(e.getKey())
&& analysis.hasThreadSafeTypeParameterAnnotation(e.getValue()))
.map(Map.Entry::getKey)
.collect(toImmutableSet());
if (!immutableAndContainer.isEmpty()) {
return buildDescription(tree)
.setMessage(
String.format(
"using both @ImmutableTypeParameter and containerOf is redundant: %s",
Joiner.on("', '").join(immutableAndContainer)))
.build();
}
// Main path for @Immutable-annotated types:
//
// Check that the fields (including inherited fields) are immutable, and
// validate the type hierarchy superclass.
ClassSymbol sym = getSymbol(tree);
Violation info =
analysis.checkForImmutability(
Optional.of(tree),
immutableTypeParametersInScope(getSymbol(tree), state, analysis),
ASTHelpers.getType(tree),
(Tree matched, Violation violation) ->
describeClass(matched, sym, annotation, violation));
if (!info.isPresent()) {
return NO_MATCH;
}
return describeClass(tree, sym, annotation, info).build();
}
private void checkClassTreeInstantiation(
ClassTree tree, VisitorState state, ImmutableAnalysis analysis) {
for (Tree implementTree : tree.getImplementsClause()) {
checkInstantiation(
tree,
state,
analysis,
getSymbol(implementTree).getTypeParameters(),
ASTHelpers.getType(implementTree).getTypeArguments());
}
Tree extendsClause = tree.getExtendsClause();
if (extendsClause != null) {
checkInstantiation(
tree,
state,
analysis,
getSymbol(extendsClause).getTypeParameters(),
ASTHelpers.getType(extendsClause).getTypeArguments());
}
}
private Description.Builder describeClass(
Tree tree, ClassSymbol sym, AnnotationInfo annotation, Violation info) {
String message;
if (sym.getQualifiedName().contentEquals(annotation.typeName())) {
message = "type annotated with @Immutable could not be proven immutable: " + info.message();
} else {
message =
String.format(
"Class extends @Immutable type %s, but is not immutable: %s",
annotation.typeName(), info.message());
}
return buildDescription(tree).setMessage(message);
}
// Anonymous classes
/** Check anonymous implementations of {@code @Immutable} types. */
private Description handleAnonymousClass(
ClassTree tree, VisitorState state, ImmutableAnalysis analysis) {
ClassSymbol sym = getSymbol(tree);
Type superType = immutableSupertype(sym, state);
if (superType == null) {
return NO_MATCH;
}
// We don't need to check that the superclass has an immutable instantiation.
// The anonymous instance can only be referred to using a superclass type, so
// the type arguments will be validated at any type use site where we care about
// the instance's immutability.
//
// Also, we have no way to express something like:
//
// public static <@Immutable T> ImmutableBox<T> create(T t) {
// return new ImmutableBox<>(t);
// }
ImmutableSet<String> typarams = immutableTypeParametersInScope(sym, state, analysis);
Violation info =
analysis.areFieldsImmutable(
Optional.of(tree),
typarams,
ASTHelpers.getType(tree),
new ViolationReporter() {
@Override
public Description.Builder describe(Tree tree, Violation info) {
return describeAnonymous(tree, superType, info);
}
});
if (!info.isPresent()) {
return NO_MATCH;
}
return describeAnonymous(tree, superType, info).build();
}
private Description.Builder describeAnonymous(Tree tree, Type superType, Violation info) {
String message =
String.format(
"Class extends @Immutable type %s, but is not immutable: %s",
superType, info.message());
return buildDescription(tree).setMessage(message);
}
// Strong behavioural subtyping
/** Check for classes without {@code @Immutable} that have immutable supertypes. */
private Description checkSubtype(ClassTree tree, VisitorState state) {
ClassSymbol sym = getSymbol(tree);
Type superType = immutableSupertype(sym, state);
if (superType == null) {
return NO_MATCH;
}
String message =
String.format(
"Class extends @Immutable type %s, but is not annotated as immutable", superType);
Fix fix =
SuggestedFix.builder()
.prefixWith(tree, "@Immutable ")
.addImport(Immutable.class.getName())
.build();
return buildDescription(tree).setMessage(message).addFix(fix).build();
}
/**
* Returns the type of the first superclass or superinterface in the hierarchy annotated with
* {@code @Immutable}, or {@code null} if no such super type exists.
*/
private Type immutableSupertype(Symbol sym, VisitorState state) {
for (Type superType : state.getTypes().closure(sym.type)) {
if (superType.tsym.equals(sym.type.tsym)) {
continue;
}
// Don't use getImmutableAnnotation here: subtypes of trusted types are
// also trusted, only check for explicitly annotated supertypes.
if (immutableAnnotations.stream()
.anyMatch(annotation -> ASTHelpers.hasAnnotation(superType.tsym, annotation, state))) {
return superType;
}
// We currently trust that @interface annotations are immutable, but don't enforce that
// custom interface implementations are also immutable. That means the check can be
// defeated by writing a custom mutable annotation implementation, and passing it around
// using the superclass type.
//
// TODO(b/25630189): fix this
//
// if (superType.tsym.getKind() == ElementKind.ANNOTATION_TYPE) {
// return superType;
// }
}
return null;
}
/**
* Gets the set of in-scope immutable type parameters from the containerOf specs on
* {@code @Immutable} annotations.
*
* <p>Usually only the immediately enclosing declaration is searched, but it's possible to have
* cases like:
*
* <pre>
* {@code @}Immutable(containerOf="T") class C<T> {
* class Inner extends ImmutableCollection<T> {}
* }
* </pre>
*/
private static ImmutableSet<String> immutableTypeParametersInScope(
Symbol sym, VisitorState state, ImmutableAnalysis analysis) {
if (sym == null) {
return ImmutableSet.of();
}
ImmutableSet.Builder<String> result = ImmutableSet.builder();
OUTER:
for (Symbol s = sym; s.owner != null; s = s.owner) {
switch (s.getKind()) {
case INSTANCE_INIT:
continue;
case PACKAGE:
break OUTER;
default:
break;
}
AnnotationInfo annotation = analysis.getImmutableAnnotation(s, state);
if (annotation == null) {
continue;
}
for (TypeVariableSymbol typaram : s.getTypeParameters()) {
String name = typaram.getSimpleName().toString();
if (annotation.containerOf().contains(name)) {
result.add(name);
}
}
if (s.isStatic()) {
break;
}
}
return result.build();
}
}