forked from uber/NullAway
/
NullAway.java
2395 lines (2271 loc) · 96 KB
/
NullAway.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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2017 Uber Technologies, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.uber.nullaway;
import static com.google.errorprone.BugPattern.Category.JDK;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.sun.source.tree.Tree.Kind.EXPRESSION_STATEMENT;
import static com.sun.source.tree.Tree.Kind.IDENTIFIER;
import static com.sun.source.tree.Tree.Kind.PARENTHESIZED;
import static com.sun.source.tree.Tree.Kind.TYPE_CAST;
import com.google.auto.service.AutoService;
import com.google.auto.value.AutoValue;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.Sets;
import com.google.errorprone.BugPattern;
import com.google.errorprone.ErrorProneFlags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.Matchers;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ArrayAccessTree;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompoundAssignmentTree;
import com.sun.source.tree.ConditionalExpressionTree;
import com.sun.source.tree.EnhancedForLoopTree;
import com.sun.source.tree.ExpressionStatementTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.ForLoopTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.IfTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.MemberReferenceTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.ModifiersTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.ParenthesizedTree;
import com.sun.source.tree.ReturnTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.TryTree;
import com.sun.source.tree.TypeCastTree;
import com.sun.source.tree.UnaryTree;
import com.sun.source.tree.VariableTree;
import com.sun.source.tree.WhileLoopTree;
import com.sun.source.util.TreePath;
import com.sun.source.util.Trees;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Types;
import com.sun.tools.javac.processing.JavacProcessingEnvironment;
import com.sun.tools.javac.tree.JCTree;
import com.uber.nullaway.ErrorMessage.MessageTypes;
import com.uber.nullaway.dataflow.AccessPathNullnessAnalysis;
import com.uber.nullaway.dataflow.EnclosingEnvironmentNullness;
import com.uber.nullaway.handlers.Handler;
import com.uber.nullaway.handlers.Handlers;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import javax.annotation.Nullable;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.NestingKind;
import javax.lang.model.type.TypeKind;
import org.checkerframework.dataflow.cfg.node.MethodInvocationNode;
import org.checkerframework.javacutil.AnnotationUtils;
/**
* Checker for nullability errors. It assumes that any field, method parameter, or return type that
* may be null is annotated with {@link Nullable}, and then checks the following rules:
*
* <ul>
* <li>no assignment of a nullable expression into a non-null field
* <li>no passing a nullable expression into a non-null parameter
* <li>no returning a nullable expression from a method with non-null return type
* <li>no field access or method invocation on an expression that is nullable
* </ul>
*
* <p>This checker also detects errors related to field initialization. For any @NonNull instance
* field <code>f</code>, this checker ensures that at least one of the following cases holds:
*
* <ol>
* <li><code>f</code> is directly initialized at its declaration
* <li><code>f</code> is always initialized in all constructors
* <li><code>f</code> is always initialized in some method annotated with @Initializer
* </ol>
*
* <p>For any @NonNull static field <code>f</code>, this checker ensures that at least one of the
* following cases holds:
*
* <ol>
* <li><code>f</code> is directly initialized at its declaration
* <li><code>f</code> is always initialized in some static initializer block
* </ol>
*/
@AutoService(BugChecker.class)
@BugPattern(
name = "NullAway",
altNames = {"CheckNullabilityTypes"},
summary = "Nullability type error.",
category = JDK,
severity = WARNING)
public class NullAway extends BugChecker
implements BugChecker.MethodInvocationTreeMatcher,
BugChecker.AssignmentTreeMatcher,
BugChecker.MemberSelectTreeMatcher,
BugChecker.ArrayAccessTreeMatcher,
BugChecker.ReturnTreeMatcher,
BugChecker.ClassTreeMatcher,
BugChecker.MethodTreeMatcher,
BugChecker.VariableTreeMatcher,
BugChecker.NewClassTreeMatcher,
BugChecker.BinaryTreeMatcher,
BugChecker.UnaryTreeMatcher,
BugChecker.ConditionalExpressionTreeMatcher,
BugChecker.IfTreeMatcher,
BugChecker.WhileLoopTreeMatcher,
BugChecker.ForLoopTreeMatcher,
BugChecker.EnhancedForLoopTreeMatcher,
BugChecker.LambdaExpressionTreeMatcher,
BugChecker.IdentifierTreeMatcher,
BugChecker.MemberReferenceTreeMatcher,
BugChecker.CompoundAssignmentTreeMatcher {
private static final String INITIALIZATION_CHECK_NAME = "NullAway.Init";
private static final Matcher<ExpressionTree> THIS_MATCHER =
(expressionTree, state) -> isThisIdentifier(expressionTree);
private final Predicate<MethodInvocationNode> nonAnnotatedMethod;
/** should we match within the current class? */
private boolean matchWithinClass = true;
private final Config config;
/**
* The handler passed to our analysis (usually a {@code CompositeHandler} including handlers for
* various APIs.
*/
private final Handler handler;
/**
* entities relevant to field initialization per class. cached for performance. nulled out in
* {@link #matchClass(ClassTree, VisitorState)}
*/
private final Map<Symbol.ClassSymbol, FieldInitEntities> class2Entities = new LinkedHashMap<>();
/**
* fields not initialized by constructors, per class. cached for performance. nulled out in {@link
* #matchClass(ClassTree, VisitorState)}
*/
private final SetMultimap<Symbol.ClassSymbol, Symbol> class2ConstructorUninit =
LinkedHashMultimap.create();
/**
* maps each top-level initialization member (constructor, init block, field decl with initializer
* expression) to the set of @NonNull fields known to be initialized before that member executes.
*
* <p>cached for performance. nulled out in {@link #matchClass(ClassTree, VisitorState)}
*/
private final Map<Symbol.ClassSymbol, Multimap<Tree, Element>> initTree2PrevFieldInit =
new LinkedHashMap<>();
/**
* dynamically computer/overriden nullness facts for certain expressions, such as specific method
* calls where we can infer a more precise set of facts than those given by the method's
* annotations.
*/
private final Map<ExpressionTree, Nullness> computedNullnessMap = new LinkedHashMap<>();
private final ImmutableSet<Class<? extends Annotation>> customSuppressionAnnotations;
/**
* Error Prone requires us to have an empty constructor for each Plugin, in addition to the
* constructor taking an ErrorProneFlags object. This constructor should not be used anywhere
* else. Checker objects constructed with this constructor will fail with IllegalStateException if
* ever used for analysis.
*/
public NullAway() {
config = new DummyOptionsConfig();
handler = Handlers.buildEmpty();
nonAnnotatedMethod = nonAnnotatedMethodCheck();
customSuppressionAnnotations = ImmutableSet.of();
}
public NullAway(ErrorProneFlags flags) {
config = new ErrorProneCLIFlagsConfig(flags);
handler = Handlers.buildDefault(config);
nonAnnotatedMethod = nonAnnotatedMethodCheck();
customSuppressionAnnotations = initCustomSuppressions();
// workaround for Checker Framework static state bug;
// See https://github.com/typetools/checker-framework/issues/1482
AnnotationUtils.clear();
}
private ImmutableSet<Class<? extends Annotation>> initCustomSuppressions() {
ImmutableSet.Builder<Class<? extends Annotation>> builder = ImmutableSet.builder();
builder.addAll(super.customSuppressionAnnotations());
for (String annotName : config.getExcludedClassAnnotations()) {
try {
builder.add(Class.forName(annotName).asSubclass(Annotation.class));
} catch (ClassNotFoundException e) {
// in this case, the annotation may be a source file currently being compiled,
// in which case we won't be able to resolve the class
}
}
return builder.build();
}
private Predicate<MethodInvocationNode> nonAnnotatedMethodCheck() {
return invocationNode ->
invocationNode == null
|| NullabilityUtil.isUnannotated(
ASTHelpers.getSymbol(invocationNode.getTree()), config);
}
@Override
public String linkUrl() {
// add a space to make it clickable from iTerm
return config.getErrorURL() + " ";
}
@Override
public Set<Class<? extends Annotation>> customSuppressionAnnotations() {
return customSuppressionAnnotations;
}
/**
* We are trying to see if (1) we are in a method guaranteed to return something non-null, and (2)
* this return statement can return something null.
*/
@Override
public Description matchReturn(ReturnTree tree, VisitorState state) {
if (!matchWithinClass) {
return Description.NO_MATCH;
}
handler.onMatchReturn(this, tree, state);
ExpressionTree retExpr = tree.getExpression();
// let's do quick checks on returned expression first
if (retExpr == null) {
return Description.NO_MATCH;
}
// now let's check the enclosing method
TreePath enclosingMethodOrLambda =
NullabilityUtil.findEnclosingMethodOrLambdaOrInitializer(state.getPath());
if (enclosingMethodOrLambda == null) {
throw new RuntimeException("no enclosing method, lambda or initializer!");
}
if (!(enclosingMethodOrLambda.getLeaf() instanceof MethodTree
|| enclosingMethodOrLambda.getLeaf() instanceof LambdaExpressionTree)) {
throw new RuntimeException(
"return statement outside of a method or lambda! (e.g. in an initializer block)");
}
Tree leaf = enclosingMethodOrLambda.getLeaf();
Symbol.MethodSymbol methodSymbol;
if (leaf instanceof MethodTree) {
MethodTree enclosingMethod = (MethodTree) leaf;
methodSymbol = ASTHelpers.getSymbol(enclosingMethod);
} else {
// we have a lambda
methodSymbol =
NullabilityUtil.getFunctionalInterfaceMethod(
(LambdaExpressionTree) leaf, state.getTypes());
}
return checkReturnExpression(tree, retExpr, methodSymbol, state);
}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!matchWithinClass) {
return Description.NO_MATCH;
}
final Symbol.MethodSymbol methodSymbol = ASTHelpers.getSymbol(tree);
if (methodSymbol == null) {
throw new RuntimeException("not expecting unresolved method here");
}
handler.onMatchMethodInvocation(this, tree, state, methodSymbol);
// assuming this list does not include the receiver
List<? extends ExpressionTree> actualParams = tree.getArguments();
return handleInvocation(tree, state, methodSymbol, actualParams);
}
@Override
public Description matchNewClass(NewClassTree tree, VisitorState state) {
if (!matchWithinClass) {
return Description.NO_MATCH;
}
Symbol.MethodSymbol methodSymbol = ASTHelpers.getSymbol(tree);
if (methodSymbol == null) {
throw new RuntimeException("not expecting unresolved method here");
}
List<? extends ExpressionTree> actualParams = tree.getArguments();
if (tree.getClassBody() != null && actualParams.size() > 0) {
// passing parameters to constructor of anonymous class
// this constructor just invokes the constructor of the superclass, and
// in the AST does not have the parameter nullability annotations from the superclass.
// so, treat as if the superclass constructor is being invoked directly
// see https://github.com/uber/NullAway/issues/102
methodSymbol = getSymbolOfSuperConstructor(methodSymbol, state);
}
return handleInvocation(tree, state, methodSymbol, actualParams);
}
/**
* Updates the {@link EnclosingEnvironmentNullness} with an entry for lambda or anonymous class,
* capturing nullability info for locals just before the declaration of the entity
*
* @param tree either a lambda or a local / anonymous class
* @param state visitor state
*/
private void updateEnvironmentMapping(Tree tree, VisitorState state) {
AccessPathNullnessAnalysis analysis = getNullnessAnalysis(state);
// two notes:
// 1. we are free to take local variable information from the program point before
// the lambda / class declaration as only effectively final variables can be accessed
// from the nested scope, so the program point doesn't matter
// 2. we keep info on all locals rather than just effectively final ones for simplicity
EnclosingEnvironmentNullness.instance(state.context)
.addEnvironmentMapping(
tree, analysis.getNullnessInfoBeforeNewContext(state.getPath(), state, handler));
}
private Symbol.MethodSymbol getSymbolOfSuperConstructor(
Symbol.MethodSymbol anonClassConstructorSymbol, VisitorState state) {
// get the statements in the body of the anonymous class constructor
List<? extends StatementTree> statements =
getTreesInstance(state).getTree(anonClassConstructorSymbol).getBody().getStatements();
// there should be exactly one statement, which is an invocation of the super constructor
if (statements.size() == 1) {
StatementTree stmt = statements.get(0);
if (stmt instanceof ExpressionStatementTree) {
ExpressionTree expression = ((ExpressionStatementTree) stmt).getExpression();
if (expression instanceof MethodInvocationTree) {
return ASTHelpers.getSymbol((MethodInvocationTree) expression);
}
}
}
throw new IllegalStateException("unexpected anonymous class constructor body " + statements);
}
@Override
public Description matchAssignment(AssignmentTree tree, VisitorState state) {
if (!matchWithinClass) {
return Description.NO_MATCH;
}
Type lhsType = ASTHelpers.getType(tree.getVariable());
if (lhsType != null && lhsType.isPrimitive()) {
return doUnboxingCheck(state, tree.getExpression());
}
Symbol assigned = ASTHelpers.getSymbol(tree.getVariable());
if (assigned == null || assigned.getKind() != ElementKind.FIELD) {
// not a field of nullable type
return Description.NO_MATCH;
}
if (Nullness.hasNullableAnnotation(assigned)) {
// field already annotated
return Description.NO_MATCH;
}
ExpressionTree expression = tree.getExpression();
if (mayBeNullExpr(state, expression)) {
String message = "assigning @Nullable expression to @NonNull field";
return createErrorDescriptionForNullAssignment(
MessageTypes.ASSIGN_FIELD_NULLABLE, tree, message, expression, state.getPath());
}
return Description.NO_MATCH;
}
@Override
public Description matchCompoundAssignment(CompoundAssignmentTree tree, VisitorState state) {
if (!matchWithinClass) {
return Description.NO_MATCH;
}
Type lhsType = ASTHelpers.getType(tree.getVariable());
Type stringType = state.getTypeFromString("java.lang.String");
if (lhsType != null && !lhsType.equals(stringType)) {
// both LHS and RHS could get unboxed
return doUnboxingCheck(state, tree.getVariable(), tree.getExpression());
}
return Description.NO_MATCH;
}
@Override
public Description matchArrayAccess(ArrayAccessTree tree, VisitorState state) {
if (!matchWithinClass) {
return Description.NO_MATCH;
}
Description description = matchDereference(tree.getExpression(), tree, state);
if (!description.equals(Description.NO_MATCH)) {
return description;
}
// also check for unboxing of array index expression
return doUnboxingCheck(state, tree.getIndex());
}
@Override
public Description matchMemberSelect(MemberSelectTree tree, VisitorState state) {
if (!matchWithinClass) {
return Description.NO_MATCH;
}
Symbol symbol = ASTHelpers.getSymbol(tree);
// some checks for cases where we know it is not
// a null dereference
if (symbol == null || symbol.getSimpleName().toString().equals("class") || symbol.isEnum()) {
return Description.NO_MATCH;
}
Description badDeref = matchDereference(tree.getExpression(), tree, state);
if (!badDeref.equals(Description.NO_MATCH)) {
return badDeref;
}
// if we're accessing a field of this, make sure we're not reading the field before init
if (tree.getExpression() instanceof IdentifierTree
&& ((IdentifierTree) tree.getExpression()).getName().toString().equals("this")) {
return checkForReadBeforeInit(tree, state);
}
return Description.NO_MATCH;
}
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
if (!matchWithinClass) {
return Description.NO_MATCH;
}
// if the method is overriding some other method,
// check that nullability annotations are consistent with
// overridden method (if overridden method is in an annotated
// package)
Symbol.MethodSymbol methodSymbol = ASTHelpers.getSymbol(tree);
handler.onMatchMethod(this, tree, state, methodSymbol);
boolean isOverriding = ASTHelpers.hasAnnotation(methodSymbol, Override.class, state);
boolean exhaustiveOverride = config.exhaustiveOverride();
if (isOverriding || !exhaustiveOverride) {
Symbol.MethodSymbol closestOverriddenMethod =
getClosestOverriddenMethod(methodSymbol, state.getTypes());
if (closestOverriddenMethod == null) {
return Description.NO_MATCH;
}
return checkOverriding(closestOverriddenMethod, methodSymbol, null, state);
}
return Description.NO_MATCH;
}
/**
* checks that an overriding method does not override a {@code @Nullable} parameter with a
* {@code @NonNull} parameter
*
* @param overridingParamSymbols parameters of the overriding method
* @param overriddenMethod method being overridden
* @param lambdaExpressionTree if the overriding method is a lambda, the {@link
* LambdaExpressionTree}; otherwise {@code null}
* @param memberReferenceTree if the overriding method is a member reference (which "overrides" a
* functional interface method), the {@link MemberReferenceTree}; otherwise {@code null}
* @return
*/
private Description checkParamOverriding(
List<VarSymbol> overridingParamSymbols,
Symbol.MethodSymbol overriddenMethod,
@Nullable LambdaExpressionTree lambdaExpressionTree,
@Nullable MemberReferenceTree memberReferenceTree,
VisitorState state) {
com.sun.tools.javac.util.List<VarSymbol> superParamSymbols = overriddenMethod.getParameters();
boolean unboundMemberRef =
(memberReferenceTree != null)
&& ((JCTree.JCMemberReference) memberReferenceTree).kind.isUnbound();
// if we have an unbound method reference, the first parameter of the overridden method must be
// @NonNull, as this parameter will be used as a method receiver inside the generated lambda
if (unboundMemberRef) {
// there must be at least one parameter; otherwise code wouldn't compile
if (Nullness.hasNullableAnnotation(superParamSymbols.get(0))) {
String message =
"unbound instance method reference cannot be used, as first parameter of "
+ "functional interface method "
+ ASTHelpers.enclosingClass(overriddenMethod)
+ "."
+ overriddenMethod.toString()
+ " is @Nullable";
return createErrorDescription(
MessageTypes.WRONG_OVERRIDE_PARAM, memberReferenceTree, message, state.getPath());
}
}
// for unbound member references, we need to adjust parameter indices by 1 when matching with
// overridden method
int startParam = unboundMemberRef ? 1 : 0;
// Collect @Nullable params of overriden method
ImmutableSet<Integer> nullableParamsOfOverriden;
if (NullabilityUtil.isUnannotated(overriddenMethod, config)) {
nullableParamsOfOverriden =
handler.onUnannotatedInvocationGetExplicitlyNullablePositions(
state.context, overriddenMethod, ImmutableSet.of());
} else {
ImmutableSet.Builder<Integer> builder = ImmutableSet.builder();
for (int i = startParam; i < superParamSymbols.size(); i++) {
// we need to call paramHasNullableAnnotation here since overriddenMethod may be defined
// in a class file
if (Nullness.paramHasNullableAnnotation(overriddenMethod, i)) {
builder.add(i);
}
}
nullableParamsOfOverriden = builder.build();
}
for (int i : nullableParamsOfOverriden) {
int methodParamInd = i - startParam;
VarSymbol paramSymbol = overridingParamSymbols.get(methodParamInd);
// in the case where we have a parameter of a lambda expression, we do
// *not* force the parameter to be annotated with @Nullable; instead we "inherit"
// nullability from the corresponding functional interface method.
// So, we report an error if the @Nullable annotation is missing *and*
// we don't have a lambda with implicitly typed parameters
boolean implicitlyTypedLambdaParam =
lambdaExpressionTree != null
&& NullabilityUtil.lambdaParamIsImplicitlyTyped(
lambdaExpressionTree.getParameters().get(methodParamInd));
if (!Nullness.hasNullableAnnotation(paramSymbol) && !implicitlyTypedLambdaParam) {
String message =
"parameter "
+ paramSymbol.name.toString()
+ (memberReferenceTree != null ? " of referenced method" : "")
+ " is @NonNull, but parameter in "
+ ((lambdaExpressionTree != null || memberReferenceTree != null)
? "functional interface "
: "superclass ")
+ "method "
+ ASTHelpers.enclosingClass(overriddenMethod)
+ "."
+ overriddenMethod.toString()
+ " is @Nullable";
Tree errorTree;
if (memberReferenceTree != null) {
errorTree = memberReferenceTree;
} else {
errorTree = getTreesInstance(state).getTree(paramSymbol);
}
return createErrorDescription(
MessageTypes.WRONG_OVERRIDE_PARAM, errorTree, message, state.getPath());
}
}
return Description.NO_MATCH;
}
private static Trees getTreesInstance(VisitorState state) {
return Trees.instance(JavacProcessingEnvironment.instance(state.context));
}
private Description checkReturnExpression(
Tree tree, ExpressionTree retExpr, Symbol.MethodSymbol methodSymbol, VisitorState state) {
Type returnType = methodSymbol.getReturnType();
if (returnType.isPrimitive()) {
// check for unboxing
return doUnboxingCheck(state, retExpr);
}
if (returnType.toString().equals("java.lang.Void")) {
return Description.NO_MATCH;
}
if (NullabilityUtil.isUnannotated(methodSymbol, config)
|| Nullness.hasNullableAnnotation(methodSymbol)) {
return Description.NO_MATCH;
}
if (mayBeNullExpr(state, retExpr)) {
String message = "returning @Nullable expression from method with @NonNull return type";
return createErrorDescriptionForNullAssignment(
MessageTypes.RETURN_NULLABLE, tree, message, retExpr, state.getPath());
}
return Description.NO_MATCH;
}
@Override
public Description matchLambdaExpression(LambdaExpressionTree tree, VisitorState state) {
if (!matchWithinClass) {
return Description.NO_MATCH;
}
Symbol.MethodSymbol funcInterfaceMethod =
NullabilityUtil.getFunctionalInterfaceMethod(tree, state.getTypes());
// we need to update environment mapping before running the handler, as some handlers
// (like Rx nullability) run dataflow analysis
updateEnvironmentMapping(tree, state);
handler.onMatchLambdaExpression(this, tree, state, funcInterfaceMethod);
if (NullabilityUtil.isUnannotated(funcInterfaceMethod, config)) {
return Description.NO_MATCH;
}
Description description =
checkParamOverriding(
tree.getParameters().stream().map(ASTHelpers::getSymbol).collect(Collectors.toList()),
funcInterfaceMethod,
tree,
null,
state);
if (description != Description.NO_MATCH) {
return description;
}
// if the body has a return statement, that gets checked in matchReturn(). We need this code
// for lambdas with expression bodies
if (tree.getBodyKind() == LambdaExpressionTree.BodyKind.EXPRESSION
&& funcInterfaceMethod.getReturnType().getKind() != TypeKind.VOID) {
ExpressionTree resExpr = (ExpressionTree) tree.getBody();
return checkReturnExpression(tree, resExpr, funcInterfaceMethod, state);
}
return Description.NO_MATCH;
}
/**
* for method references, we check that the referenced method correctly overrides the
* corresponding functional interface method
*/
@Override
public Description matchMemberReference(MemberReferenceTree tree, VisitorState state) {
if (!matchWithinClass) {
return Description.NO_MATCH;
}
Symbol.MethodSymbol referencedMethod = ASTHelpers.getSymbol(tree);
Symbol.MethodSymbol funcInterfaceSymbol =
NullabilityUtil.getFunctionalInterfaceMethod(tree, state.getTypes());
handler.onMatchMethodReference(this, tree, state, referencedMethod);
return checkOverriding(funcInterfaceSymbol, referencedMethod, tree, state);
}
/**
* check that nullability annotations of an overriding method are consistent with those in the
* overridden method (both return and parameters)
*
* @param overriddenMethod method being overridden
* @param overridingMethod overriding method
* @param memberReferenceTree if override is via a method reference, the relevant {@link
* MemberReferenceTree}; otherwise {@code null}. If non-null, overridingTree is the AST of the
* referenced method
* @param state
* @return discovered error, or {@link Description#NO_MATCH} if no error
*/
private Description checkOverriding(
Symbol.MethodSymbol overriddenMethod,
Symbol.MethodSymbol overridingMethod,
@Nullable MemberReferenceTree memberReferenceTree,
VisitorState state) {
final boolean isOverridenMethodUnannotated =
NullabilityUtil.isUnannotated(overriddenMethod, config);
final boolean overriddenMethodReturnsNonNull =
((isOverridenMethodUnannotated
&& handler.onUnannotatedInvocationGetExplicitlyNonNullReturn(
overriddenMethod, false))
|| (!isOverridenMethodUnannotated
&& !Nullness.hasNullableAnnotation(overriddenMethod)));
// if the super method returns nonnull,
// overriding method better not return nullable
if (overriddenMethodReturnsNonNull
&& Nullness.hasNullableAnnotation(overridingMethod)
&& getComputedNullness(memberReferenceTree).equals(Nullness.NULLABLE)) {
String message;
if (memberReferenceTree != null) {
message =
"referenced method returns @Nullable, but functional interface method "
+ ASTHelpers.enclosingClass(overriddenMethod)
+ "."
+ overriddenMethod.toString()
+ " returns @NonNull";
} else {
message =
"method returns @Nullable, but superclass method "
+ ASTHelpers.enclosingClass(overriddenMethod)
+ "."
+ overriddenMethod.toString()
+ " returns @NonNull";
}
Tree errorTree =
memberReferenceTree != null
? memberReferenceTree
: getTreesInstance(state).getTree(overridingMethod);
return createErrorDescription(
MessageTypes.WRONG_OVERRIDE_RETURN, errorTree, message, state.getPath());
}
// if any parameter in the super method is annotated @Nullable,
// overriding method cannot assume @Nonnull
return checkParamOverriding(
overridingMethod.getParameters(), overriddenMethod, null, memberReferenceTree, state);
}
@Override
public Description matchIdentifier(IdentifierTree tree, VisitorState state) {
if (!matchWithinClass) {
return Description.NO_MATCH;
}
return checkForReadBeforeInit(tree, state);
}
private Description checkForReadBeforeInit(ExpressionTree tree, VisitorState state) {
// do a bunch of filtering. first, filter out anything outside an initializer
TreePath path = state.getPath();
TreePath enclosingBlockPath = NullabilityUtil.findEnclosingMethodOrLambdaOrInitializer(path);
if (enclosingBlockPath == null) {
// is this possible?
return Description.NO_MATCH;
}
if (!relevantInitializerMethodOrBlock(enclosingBlockPath, state)) {
return Description.NO_MATCH;
}
// now, make sure we have a field read
Symbol symbol = ASTHelpers.getSymbol(tree);
if (symbol == null) {
return Description.NO_MATCH;
}
if (!symbol.getKind().equals(ElementKind.FIELD)) {
return Description.NO_MATCH;
}
// for static fields, make sure the enclosing init is a static method or block
if (symbol.isStatic()) {
Tree enclosing = enclosingBlockPath.getLeaf();
if (enclosing instanceof MethodTree
&& !ASTHelpers.getSymbol((MethodTree) enclosing).isStatic()) {
return Description.NO_MATCH;
} else if (enclosing instanceof BlockTree && !((BlockTree) enclosing).isStatic()) {
return Description.NO_MATCH;
}
}
if (okToReadBeforeInitialized(path)) {
// writing the field, not reading it
return Description.NO_MATCH;
}
// check that the field might actually be problematic to read
FieldInitEntities entities = class2Entities.get(enclosingClassSymbol(enclosingBlockPath));
if (!(entities.nonnullInstanceFields().contains(symbol)
|| entities.nonnullStaticFields().contains(symbol))) {
// field is either nullable or initialized at declaration
return Description.NO_MATCH;
}
if (symbolHasSuppressInitalizationWarningsAnnotation(symbol)) {
// also suppress checking read before init, as we may not find explicit initialization
return Description.NO_MATCH;
}
return checkPossibleUninitFieldRead(tree, state, symbol, path, enclosingBlockPath);
}
private Symbol.ClassSymbol enclosingClassSymbol(TreePath enclosingBlockPath) {
Tree leaf = enclosingBlockPath.getLeaf();
if (leaf instanceof BlockTree) {
// parent must be a ClassTree
Tree parent = enclosingBlockPath.getParentPath().getLeaf();
return ASTHelpers.getSymbol((ClassTree) parent);
} else {
return ASTHelpers.enclosingClass(ASTHelpers.getSymbol(leaf));
}
}
private boolean relevantInitializerMethodOrBlock(
TreePath enclosingBlockPath, VisitorState state) {
Tree methodLambdaOrBlock = enclosingBlockPath.getLeaf();
if (methodLambdaOrBlock instanceof LambdaExpressionTree) {
return false;
} else if (methodLambdaOrBlock instanceof MethodTree) {
MethodTree methodTree = (MethodTree) methodLambdaOrBlock;
if (isConstructor(methodTree) && !constructorInvokesAnother(methodTree, state)) return true;
if (ASTHelpers.getSymbol(methodTree).isStatic()) {
Set<MethodTree> staticInitializerMethods =
class2Entities.get(enclosingClassSymbol(enclosingBlockPath)).staticInitializerMethods();
return staticInitializerMethods.size() == 1
&& staticInitializerMethods.contains(methodTree);
} else {
Set<MethodTree> instanceInitializerMethods =
class2Entities
.get(enclosingClassSymbol(enclosingBlockPath))
.instanceInitializerMethods();
return instanceInitializerMethods.size() == 1
&& instanceInitializerMethods.contains(methodTree);
}
} else {
// initializer or field declaration
return true;
}
}
private Description checkPossibleUninitFieldRead(
ExpressionTree tree,
VisitorState state,
Symbol symbol,
TreePath path,
TreePath enclosingBlockPath) {
if (!fieldInitializedByPreviousInitializer(symbol, enclosingBlockPath, state)
&& !fieldAlwaysInitializedBeforeRead(symbol, path, state, enclosingBlockPath)) {
return createErrorDescription(
MessageTypes.NONNULL_FIELD_READ_BEFORE_INIT,
tree,
"read of @NonNull field " + symbol + " before initialization",
path);
} else {
return Description.NO_MATCH;
}
}
/**
* @param symbol the field being read
* @param pathToRead TreePath to the read operation
* @param state visitor state
* @param enclosingBlockPath TreePath to enclosing initializer block
* @return true if within the initializer, the field is always initialized before the read
* operation, false otherwise
*/
private boolean fieldAlwaysInitializedBeforeRead(
Symbol symbol, TreePath pathToRead, VisitorState state, TreePath enclosingBlockPath) {
AccessPathNullnessAnalysis nullnessAnalysis = getNullnessAnalysis(state);
Set<Element> nonnullFields;
if (symbol.isStatic()) {
nonnullFields = nullnessAnalysis.getNonnullStaticFieldsBefore(pathToRead, state.context);
} else {
nonnullFields = new LinkedHashSet<>();
nonnullFields.addAll(
nullnessAnalysis.getNonnullFieldsOfReceiverBefore(pathToRead, state.context));
nonnullFields.addAll(safeInitByCalleeBefore(pathToRead, state, enclosingBlockPath));
}
return nonnullFields.contains(symbol);
}
/**
* computes those fields always initialized by callee safe init methods before a read operation
* (pathToRead) is invoked. See <a
* href="https://github.com/uber/NullAway/wiki/Error-Messages#initializer-method-does-not-guarantee-nonnull-field-is-initialized--nonnull-field--not-initialized">the
* docs</a> for what is considered a safe initializer method.
*/
private Set<Element> safeInitByCalleeBefore(
TreePath pathToRead, VisitorState state, TreePath enclosingBlockPath) {
Set<Element> result = new LinkedHashSet<>();
Set<Element> safeInitMethods = new LinkedHashSet<>();
Tree enclosingBlockOrMethod = enclosingBlockPath.getLeaf();
if (enclosingBlockOrMethod instanceof VariableTree) {
return Collections.emptySet();
}
BlockTree blockTree =
enclosingBlockOrMethod instanceof BlockTree
? (BlockTree) enclosingBlockOrMethod
: ((MethodTree) enclosingBlockOrMethod).getBody();
List<? extends StatementTree> statements = blockTree.getStatements();
Tree readExprTree = pathToRead.getLeaf();
int readStartPos = getStartPos((JCTree) readExprTree);
TreePath classTreePath = enclosingBlockPath;
// look for the parent ClassTree node, which represents the enclosing class / enum / interface
while (!(classTreePath.getLeaf() instanceof ClassTree)) {
classTreePath = classTreePath.getParentPath();
if (classTreePath == null) {
throw new IllegalStateException(
"could not find enclosing class / enum / interface for "
+ enclosingBlockPath.getLeaf());
}
}
Symbol.ClassSymbol classSymbol = ASTHelpers.getSymbol((ClassTree) classTreePath.getLeaf());
for (int i = 0; i < statements.size(); i++) {
StatementTree curStmt = statements.get(i);
if (getStartPos((JCTree) curStmt) <= readStartPos) {
Element privMethodElem = getInvokeOfSafeInitMethod(curStmt, classSymbol, state);
if (privMethodElem != null) {
safeInitMethods.add(privMethodElem);
}
// Hack: Handling try{...}finally{...} statement, see getSafeInitMethods
if (curStmt.getKind().equals(Tree.Kind.TRY)) {
TryTree tryTree = (TryTree) curStmt;
// ToDo: Should we check initialization inside tryTree.getResources ? What is the scope of
// that initialization?
if (tryTree.getCatches().size() == 0) {
if (tryTree.getBlock() != null) {
result.addAll(
safeInitByCalleeBefore(
pathToRead, state, new TreePath(enclosingBlockPath, tryTree.getBlock())));
}
if (tryTree.getFinallyBlock() != null) {
result.addAll(
safeInitByCalleeBefore(
pathToRead,
state,
new TreePath(enclosingBlockPath, tryTree.getFinallyBlock())));
}
}
}
}
}
addGuaranteedNonNullFromInvokes(
state, getTreesInstance(state), safeInitMethods, getNullnessAnalysis(state), result);
return result;
}
private int getStartPos(JCTree tree) {
return tree.pos().getStartPosition();
}
/**
* @param fieldSymbol the field
* @param initTreePath TreePath to the initializer method / block
* @param state visitor state
* @return true if the field is always initialized (by some other initializer) before the
* initializer corresponding to initTreePath executes
*/
private boolean fieldInitializedByPreviousInitializer(
Symbol fieldSymbol, TreePath initTreePath, VisitorState state) {
TreePath enclosingClassPath = initTreePath.getParentPath();
ClassTree enclosingClass = (ClassTree) enclosingClassPath.getLeaf();
Multimap<Tree, Element> tree2Init =
initTree2PrevFieldInit.get(ASTHelpers.getSymbol(enclosingClass));
if (tree2Init == null) {
tree2Init = computeTree2Init(enclosingClassPath, state);
initTree2PrevFieldInit.put(ASTHelpers.getSymbol(enclosingClass), tree2Init);
}
return tree2Init.containsEntry(initTreePath.getLeaf(), fieldSymbol);
}
/**
* @param enclosingClassPath TreePath to class
* @param state visitor state
* @return a map from each initializer <em>i</em> to the fields known to be initialized before
* <em>i</em> executes
*/
private Multimap<Tree, Element> computeTree2Init(
TreePath enclosingClassPath, VisitorState state) {
ClassTree enclosingClass = (ClassTree) enclosingClassPath.getLeaf();
ImmutableMultimap.Builder<Tree, Element> builder = ImmutableMultimap.builder();
// NOTE: this set includes both instance and static fields
Set<Element> initThusFar = new LinkedHashSet<>();
Set<MethodTree> constructors = new LinkedHashSet<>();
AccessPathNullnessAnalysis nullnessAnalysis = getNullnessAnalysis(state);
// NOTE: we assume the members are returned in their syntactic order. This has held
// true in our testing
for (Tree memberTree : enclosingClass.getMembers()) {
if (memberTree instanceof VariableTree || memberTree instanceof BlockTree) {
// putAll does not keep a reference to initThusFar, so we don't need to make a copy here
builder.putAll(memberTree, initThusFar);
}
if (memberTree instanceof BlockTree) {
BlockTree blockTree = (BlockTree) memberTree;
// add whatever gets initialized here
TreePath memberPath = new TreePath(enclosingClassPath, memberTree);
if (blockTree.isStatic()) {
initThusFar.addAll(
nullnessAnalysis.getNonnullStaticFieldsAtExit(memberPath, state.context));
} else {
initThusFar.addAll(
nullnessAnalysis.getNonnullFieldsOfReceiverAtExit(memberPath, state.context));
}
}
if (memberTree instanceof MethodTree) {
MethodTree methodTree = (MethodTree) memberTree;
if (isConstructor(methodTree)) {
constructors.add(methodTree);
}
}
}
// all the initializer blocks have run before any code inside a constructor
constructors.stream().forEach((c) -> builder.putAll(c, initThusFar));
Symbol.ClassSymbol classSymbol = ASTHelpers.getSymbol(enclosingClass);
FieldInitEntities entities = class2Entities.get(classSymbol);
if (entities.instanceInitializerMethods().size() == 1) {
MethodTree initMethod = entities.instanceInitializerMethods().iterator().next();
// collect the fields that may not be initialized by *some* constructor NC
Set<Symbol> constructorUninitSymbols = class2ConstructorUninit.get(classSymbol);