-
Notifications
You must be signed in to change notification settings - Fork 350
/
NullnessAnnotatedTypeFactory.java
497 lines (419 loc) · 20.2 KB
/
NullnessAnnotatedTypeFactory.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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
package org.checkerframework.checker.nullness;
import org.checkerframework.checker.initialization.InitializationAnnotatedTypeFactory;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.checker.nullness.qual.PolyNull;
import org.checkerframework.common.basetype.BaseTypeChecker;
import org.checkerframework.framework.flow.CFAbstractAnalysis;
import org.checkerframework.framework.qual.PolyAll;
import org.checkerframework.framework.type.AnnotatedTypeFactory;
import org.checkerframework.framework.type.AnnotatedTypeFormatter;
import org.checkerframework.framework.type.AnnotatedTypeMirror;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedExecutableType;
import org.checkerframework.framework.type.GeneralAnnotatedTypeFactory;
import org.checkerframework.framework.type.QualifierHierarchy;
import org.checkerframework.framework.type.treeannotator.ImplicitsTreeAnnotator;
import org.checkerframework.framework.type.treeannotator.ListTreeAnnotator;
import org.checkerframework.framework.type.treeannotator.PropagationTreeAnnotator;
import org.checkerframework.framework.type.treeannotator.TreeAnnotator;
import org.checkerframework.framework.type.typeannotator.ListTypeAnnotator;
import org.checkerframework.framework.type.typeannotator.TypeAnnotator;
import org.checkerframework.framework.util.DependentTypes;
import org.checkerframework.framework.util.MultiGraphQualifierHierarchy.MultiGraphFactory;
import org.checkerframework.javacutil.AnnotationUtils;
import org.checkerframework.javacutil.ElementUtils;
import org.checkerframework.javacutil.InternalUtils;
import org.checkerframework.javacutil.Pair;
import org.checkerframework.javacutil.TreeUtils;
import org.checkerframework.javacutil.TypesUtils;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.VariableElement;
import javax.lang.model.util.Elements;
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.CompoundAssignmentTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.ReturnTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.UnaryTree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreePath;
/**
* The annotated type factory for the nullness type-system.
*/
public class NullnessAnnotatedTypeFactory
extends InitializationAnnotatedTypeFactory<NullnessValue, NullnessStore, NullnessTransfer, NullnessAnalysis> {
/** Annotation constants */
protected final AnnotationMirror NONNULL, NULLABLE, POLYNULL, MONOTONIC_NONNULL;
/** Dependent types instance. */
protected final DependentTypes dependentTypes;
protected final SystemGetPropertyHandler systemGetPropertyHandler;
protected final CollectionToArrayHeuristics collectionToArrayHeuristics;
/**
* Factory for arbitrary qualifiers, used for declarations and "unused"
* qualifier.
*/
protected final GeneralAnnotatedTypeFactory generalFactory;
// Cache for the nullness annotations
protected final Set<Class<? extends Annotation>> nullnessAnnos;
@SuppressWarnings("deprecation") // aliasing to deprecated annotation
public NullnessAnnotatedTypeFactory(BaseTypeChecker checker, boolean useFbc) {
super(checker, useFbc);
NONNULL = AnnotationUtils.fromClass(elements, NonNull.class);
NULLABLE = AnnotationUtils.fromClass(elements, Nullable.class);
POLYNULL = AnnotationUtils.fromClass(elements, PolyNull.class);
MONOTONIC_NONNULL = AnnotationUtils.fromClass(elements, MonotonicNonNull.class);
Set<Class<? extends Annotation>> tempNullnessAnnos = new HashSet<>();
tempNullnessAnnos.add(NonNull.class);
tempNullnessAnnos.add(MonotonicNonNull.class);
tempNullnessAnnos.add(Nullable.class);
tempNullnessAnnos.add(PolyNull.class);
tempNullnessAnnos.add(PolyAll.class);
nullnessAnnos = Collections.unmodifiableSet(tempNullnessAnnos);
addAliasedAnnotation(org.checkerframework.checker.nullness.qual.LazyNonNull.class, MONOTONIC_NONNULL);
// If you update the following, also update ../../../manual/nullness-checker.tex .
// Aliases for @Nonnull:
addAliasedAnnotation(com.sun.istack.internal.NotNull.class, NONNULL);
addAliasedAnnotation(edu.umd.cs.findbugs.annotations.NonNull.class, NONNULL);
addAliasedAnnotation(javax.annotation.Nonnull.class, NONNULL);
addAliasedAnnotation(javax.validation.constraints.NotNull.class, NONNULL);
addAliasedAnnotation(lombok.NonNull.class, NONNULL);
addAliasedAnnotation(org.eclipse.jdt.annotation.NonNull.class, NONNULL);
addAliasedAnnotation(org.jetbrains.annotations.NotNull.class, NONNULL);
addAliasedAnnotation(org.netbeans.api.annotations.common.NonNull.class, NONNULL);
addAliasedAnnotation(org.jmlspecs.annotation.NonNull.class, NONNULL);
addAliasedAnnotation(android.annotation.NonNull.class, NONNULL);
addAliasedAnnotation(android.support.annotation.NonNull.class, NONNULL);
// Aliases for @Nullable:
addAliasedAnnotation(com.sun.istack.internal.Nullable.class, NULLABLE);
addAliasedAnnotation(edu.umd.cs.findbugs.annotations.CheckForNull.class, NULLABLE);
addAliasedAnnotation(edu.umd.cs.findbugs.annotations.Nullable.class, NULLABLE);
addAliasedAnnotation(edu.umd.cs.findbugs.annotations.UnknownNullness.class, NULLABLE);
addAliasedAnnotation(javax.annotation.CheckForNull.class, NULLABLE);
addAliasedAnnotation(javax.annotation.Nullable.class, NULLABLE);
addAliasedAnnotation(org.eclipse.jdt.annotation.Nullable.class, NULLABLE);
addAliasedAnnotation(org.jetbrains.annotations.Nullable.class, NULLABLE);
addAliasedAnnotation(org.netbeans.api.annotations.common.CheckForNull.class, NULLABLE);
addAliasedAnnotation(org.netbeans.api.annotations.common.NullAllowed.class, NULLABLE);
addAliasedAnnotation(org.netbeans.api.annotations.common.NullUnknown.class, NULLABLE);
addAliasedAnnotation(org.jmlspecs.annotation.Nullable.class, NULLABLE);
addAliasedAnnotation(android.annotation.Nullable.class, NULLABLE);
addAliasedAnnotation(android.support.annotation.Nullable.class, NULLABLE);
// Add compatibility annotations:
addAliasedAnnotation(org.checkerframework.checker.nullness.compatqual.NullableDecl.class, NULLABLE);
addAliasedAnnotation(org.checkerframework.checker.nullness.compatqual.PolyNullDecl.class, POLYNULL);
addAliasedAnnotation(org.checkerframework.checker.nullness.compatqual.NonNullDecl.class, NONNULL);
addAliasedAnnotation(org.checkerframework.checker.nullness.compatqual.MonotonicNonNullDecl.class, MONOTONIC_NONNULL);
addAliasedAnnotation(org.checkerframework.checker.nullness.compatqual.NullableType.class, NULLABLE);
addAliasedAnnotation(org.checkerframework.checker.nullness.compatqual.PolyNullType.class, POLYNULL);
addAliasedAnnotation(org.checkerframework.checker.nullness.compatqual.NonNullType.class, NONNULL);
addAliasedAnnotation(org.checkerframework.checker.nullness.compatqual.MonotonicNonNullType.class, MONOTONIC_NONNULL);
// TODO: These heuristics are just here temporarily. They all either
// need to be replaced, or carefully checked for correctness.
generalFactory = new GeneralAnnotatedTypeFactory(checker);
// Alias the same generalFactory below and ensure that setRoot updates it.
dependentTypes = new DependentTypes(checker, generalFactory);
systemGetPropertyHandler = new SystemGetPropertyHandler(processingEnv, this);
postInit();
// do this last, as it might use the factory again.
this.collectionToArrayHeuristics = new CollectionToArrayHeuristics(
processingEnv, this);
}
@Override
public void setRoot(CompilationUnitTree root) {
generalFactory.setRoot(root);
super.setRoot(root);
}
// handle dependent types
@Override
protected void annotateImplicit(Tree tree, AnnotatedTypeMirror type, boolean useFlow) {
super.annotateImplicit(tree, type, useFlow);
dependentTypes.handle(tree, type);
}
@Override
public AnnotatedTypeMirror getDefaultedAnnotatedType(Tree varTree,
ExpressionTree valueTree) {
AnnotatedTypeMirror result = super.getDefaultedAnnotatedType(varTree, valueTree);
return handlePolyNull(result, valueTree);
}
/**
* Replaces {@link PolyNull} with {@link Nullable} to be more permissive
* (because {@code type} is usually a left-hand side) if the org.checkerframework.dataflow
* analysis has determined that this is allowed soundly.
*/
protected AnnotatedTypeMirror handlePolyNull(AnnotatedTypeMirror type,
Tree context) {
if (type.hasAnnotation(PolyNull.class)
|| type.hasAnnotation(PolyAll.class)) {
NullnessValue inferred = getInferredValueFor(context);
if (inferred != null && inferred.isPolyNullNull) {
type.replaceAnnotation(NULLABLE);
}
}
return type;
}
// handle dependent types
@Override
public Pair<AnnotatedExecutableType, List<AnnotatedTypeMirror>> constructorFromUse(
NewClassTree tree) {
Pair<AnnotatedExecutableType, List<AnnotatedTypeMirror>> fromUse = super.constructorFromUse(tree);
AnnotatedExecutableType constructor = fromUse.first;
dependentTypes.handleConstructor(tree,
generalFactory.getAnnotatedType(tree), constructor);
return fromUse;
}
@Override
public List<VariableTree> getUninitializedInvariantFields(
NullnessStore store, TreePath path, boolean isStatic,
List<? extends AnnotationMirror> receiverAnnotations) {
List<VariableTree> candidates = super.getUninitializedInvariantFields(
store, path, isStatic, receiverAnnotations);
List<VariableTree> result = new ArrayList<>();
for (VariableTree c : candidates) {
AnnotatedTypeMirror type = getAnnotatedType(c);
boolean isPrimitive = TypesUtils.isPrimitive(type.getUnderlyingType());
if (!isPrimitive) {
// primitives do not need to be initialized
result.add(c);
}
}
return result;
}
@Override
protected NullnessAnalysis createFlowAnalysis(List<Pair<VariableElement, NullnessValue>> fieldValues) {
return new NullnessAnalysis(checker, this, fieldValues);
}
@Override
public NullnessTransfer createFlowTransferFunction(CFAbstractAnalysis<NullnessValue, NullnessStore, NullnessTransfer> analysis) {
return new NullnessTransfer((NullnessAnalysis) analysis);
}
/**
* @return an AnnotatedTypeFormatter that does not print the qualifiers on null literals
*/
@Override
protected AnnotatedTypeFormatter createAnnotatedTypeFormatter() {
return new NullnessAnnotatedTypeFormatter(checker.hasOption("printVerboseGenerics"), checker.hasOption("printAllQualifiers"));
}
@Override
public Pair<AnnotatedExecutableType, List<AnnotatedTypeMirror>> methodFromUse(
MethodInvocationTree tree) {
Pair<AnnotatedExecutableType, List<AnnotatedTypeMirror>> mfuPair = super
.methodFromUse(tree);
AnnotatedExecutableType method = mfuPair.first;
systemGetPropertyHandler.handle(tree, method);
collectionToArrayHeuristics.handle(tree, method);
return mfuPair;
}
@Override
public AnnotatedTypeMirror getMethodReturnType(MethodTree m, ReturnTree r) {
return handlePolyNull(super.getMethodReturnType(m, r), r);
}
protected AnnotatedTypeMirror getDeclaredAndDefaultedAnnotatedType(Tree tree) {
HACK_DONT_CALL_POST_AS_MEMBER = true;
shouldCache = false;
AnnotatedTypeMirror type = getAnnotatedType(tree);
shouldCache = true;
HACK_DONT_CALL_POST_AS_MEMBER = false;
return type;
}
@Override
protected TypeAnnotator createTypeAnnotator() {
return new ListTypeAnnotator(
super.createTypeAnnotator(),
new NullnessTypeAnnotator(this)
);
}
@Override
protected TreeAnnotator createTreeAnnotator() {
return new ListTreeAnnotator( // DebugListTreeAnnotator(new Tree.Kind[] {Tree.Kind.CONDITIONAL_EXPRESSION},
new NullnessPropagationAnnotator(this),
new ImplicitsTreeAnnotator(this),
new NullnessTreeAnnotator(this),
new CommitmentTreeAnnotator(this)
);
}
/**
* If the element is {@link NonNull} when used in a static member access,
* modifies the element's type (by adding {@link NonNull}).
*
* @param elt
* the element being accessed
* @param type
* the type of the element {@code elt}
*/
private void annotateIfStatic(Element elt, AnnotatedTypeMirror type) {
if (elt == null)
return;
if (elt.getKind().isClass() || elt.getKind().isInterface()
// Workaround for System.{out,in,err} issue: assume all static
// fields in java.lang.System are nonnull.
|| isSystemField(elt)) {
type.replaceAnnotation(NONNULL);
}
}
private static boolean isSystemField(Element elt) {
if (!elt.getKind().isField())
return false;
if (!ElementUtils.isStatic(elt) || !ElementUtils.isFinal(elt))
return false;
VariableElement var = (VariableElement) elt;
// Heuristic: if we have a static final field in a system package,
// treat it as NonNull (many like Boolean.TYPE and System.out
// have constant value null but are set by the VM).
boolean inJavaPackage = ElementUtils.getQualifiedClassName(var)
.toString().startsWith("java.");
return (var.getConstantValue() != null
|| var.getSimpleName().contentEquals("class") || inJavaPackage);
}
/**
* Nullness doesn't call propagation on binary and unary because
* the result is always @Initialized (the default qualifier).
*
* Would this be valid to move into CommitmentTreeAnnotator.
*/
protected class NullnessPropagationAnnotator extends PropagationTreeAnnotator {
public NullnessPropagationAnnotator(AnnotatedTypeFactory atypeFactory) {
super(atypeFactory);
}
@Override
public Void visitBinary(BinaryTree node, AnnotatedTypeMirror type) {
return null;
}
@Override
public Void visitUnary(UnaryTree node, AnnotatedTypeMirror type) {
return null;
}
}
protected class NullnessTreeAnnotator extends TreeAnnotator
/*extends InitializationAnnotatedTypeFactory<NullnessValue, NullnessStore, NullnessTransfer, NullnessAnalysis>.CommitmentTreeAnnotator*/ {
public NullnessTreeAnnotator(NullnessAnnotatedTypeFactory atypeFactory) {
super(atypeFactory);
}
@Override
public Void visitMemberSelect(MemberSelectTree node,
AnnotatedTypeMirror type) {
Element elt = TreeUtils.elementFromUse(node);
assert elt != null;
// case 8: class in static member access
annotateIfStatic(elt, type);
return null;
}
@Override
public Void visitVariable(VariableTree node,
AnnotatedTypeMirror type) {
Element elt = InternalUtils.symbol(node);
if (elt.getKind() == ElementKind.EXCEPTION_PARAMETER) {
if (!type.isAnnotatedInHierarchy(NONNULL)) {
// case 9. exception parameter
type.addAnnotation(NONNULL);
}
}
return null;
}
@Override
public Void visitIdentifier(IdentifierTree node,
AnnotatedTypeMirror type) {
Element elt = TreeUtils.elementFromUse(node);
assert elt != null;
// case 8. static method access
annotateIfStatic(elt, type);
if (elt.getKind() == ElementKind.EXCEPTION_PARAMETER) {
// TODO: It's surprising that we have to do this in
// both visitVariable and visitIdentifier. This should
// already be handled by applying the defaults anyway.
// case 9. exception parameter
type.replaceAnnotation(NONNULL);
}
return null;
}
// The result of a binary operation is always non-null.
@Override
public Void visitBinary(BinaryTree node, AnnotatedTypeMirror type) {
type.replaceAnnotation(NONNULL);
return null;
}
// The result of a compound operation is always non-null.
@Override
public Void visitCompoundAssignment(CompoundAssignmentTree node,
AnnotatedTypeMirror type) {
type.replaceAnnotation(NONNULL);
// Commitment will run after for initialization defaults
return null;
}
// The result of a unary operation is always non-null.
@Override
public Void visitUnary(UnaryTree node, AnnotatedTypeMirror type) {
type.replaceAnnotation(NONNULL);
return null;
}
// The result of newly allocated structures is always non-null.
@Override
public Void visitNewClass(NewClassTree node, AnnotatedTypeMirror type) {
type.replaceAnnotation(NONNULL);
return null;
}
}
protected class NullnessTypeAnnotator
extends InitializationAnnotatedTypeFactory<NullnessValue, NullnessStore, NullnessTransfer, NullnessAnalysis>.CommitmentTypeAnnotator {
public NullnessTypeAnnotator(InitializationAnnotatedTypeFactory<?, ?, ?, ?> atypeFactory) {
super(atypeFactory);
}
}
/**
* @return The list of annotations of the non-null type system.
*/
public Set<Class<? extends Annotation>> getNullnessAnnotations() {
return nullnessAnnos;
}
@Override
public Set<Class<? extends Annotation>> getInvalidConstructorReturnTypeAnnotations() {
Set<Class<? extends Annotation>> l = new HashSet<>(
super.getInvalidConstructorReturnTypeAnnotations());
l.addAll(getNullnessAnnotations());
return l;
}
@Override
public AnnotationMirror getFieldInvariantAnnotation() {
Elements elements = processingEnv.getElementUtils();
return AnnotationUtils.fromClass(elements, NonNull.class);
}
@Override
public QualifierHierarchy createQualifierHierarchy(MultiGraphFactory factory) {
return new NullnessQualifierHierarchy(factory, (Object[]) null);
}
protected class NullnessQualifierHierarchy extends InitializationQualifierHierarchy {
public NullnessQualifierHierarchy(MultiGraphFactory f, Object[] arg) {
super(f, arg);
}
@Override
public boolean isSubtype(AnnotationMirror rhs, AnnotationMirror lhs) {
if (isInitializationAnnotation(rhs) ||
isInitializationAnnotation(lhs)) {
return this.isSubtypeInitialization(rhs, lhs);
}
return super.isSubtype(rhs, lhs);
}
@Override
public AnnotationMirror leastUpperBound(AnnotationMirror a1, AnnotationMirror a2) {
if (isInitializationAnnotation(a1) ||
isInitializationAnnotation(a2)) {
return this.leastUpperBoundInitialization(a1, a2);
}
return super.leastUpperBound(a1, a2);
}
}
}