-
Notifications
You must be signed in to change notification settings - Fork 821
/
NPECheck.java
1569 lines (1252 loc) · 62.1 KB
/
NPECheck.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
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.netbeans.modules.java.hints.bugs;
import com.sun.source.tree.*;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.util.TreePath;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
import org.netbeans.api.annotations.common.CheckForNull;
import org.netbeans.api.java.source.CompilationInfo;
import org.netbeans.api.java.source.support.CancellableTreePathScanner;
import org.netbeans.spi.editor.hints.ErrorDescription;
import org.openide.util.NbBundle;
import static org.netbeans.modules.java.hints.bugs.NPECheck.State.*;
import org.netbeans.modules.java.hints.errors.Utilities;
import org.netbeans.spi.java.hints.*;
import org.netbeans.spi.java.hints.Hint.Options;
import org.openide.util.Lookup;
/**
*
* @author lahvac
*/
@Hint(displayName="#DN_NPECheck",
description="#DESC_NPECheck",
category="bugs", options=Options.QUERY, suppressWarnings = {"null", "", "NullableProblems"}
)
public class NPECheck {
static final boolean DEF_ENABLE_FOR_FIELDS = false;
@BooleanOption(displayName = "#LBL_NPECheck.ENABLE_FOR_FIELDS", tooltip = "#TP_NPECheck.ENABLE_FOR_FIELDS", defaultValue=DEF_ENABLE_FOR_FIELDS)
static final String KEY_ENABLE_FOR_FIELDS = "enable-for-fields"; // NOI18N
static final boolean DEF_UNBOXING_UNKNOWN_VALUES = true;
@BooleanOption(displayName = "#LBL_NPECheck.UNBOXING_UNKNOWN_VALUES", tooltip = "#TP_NPECheck.UNBOXING_UNKNOWN_VALUES", defaultValue=DEF_UNBOXING_UNKNOWN_VALUES)
static final String KEY_UNBOXING_UNKNOWN_VALUES = "unboxing-unknown"; // NOI18N
@TriggerPatterns({
@TriggerPattern("$mods$ $type $var = $expr;"),
@TriggerPattern("$var = $expr")
})
public static ErrorDescription assignment(HintContext ctx) {
Element e = ctx.getInfo().getTrees().getElement(ctx.getVariables().get("$var"));
if (!isVariableElement(ctx, e)) {
return null;
}
TreePath expr = ctx.getVariables().get("$expr");
State r = computeExpressionsState(ctx).get(expr.getLeaf());
State elementState = getStateFromAnnotations(ctx.getInfo(), e);
if (elementState != null && elementState.isNotNull()) {
String key = null;
if (r == NULL || r == NULL_HYPOTHETICAL) {
key = "ERR_AssigningNullToNotNull";
}
if (r == POSSIBLE_NULL_REPORT) {
key = "ERR_PossibleAssigingNullToNotNull";
}
if (key != null) {
return ErrorDescriptionFactory.forTree(ctx, ctx.getPath(), NbBundle.getMessage(NPECheck.class, key));
}
}
return null;
}
@TriggerPatterns({
@TriggerPattern(value = "$expr ? $trueExpr : $falseExpr", constraints = {
@ConstraintVariableType(variable = "$trueExpr", type = "double"),
@ConstraintVariableType(variable = "$falseExpr", type = "java.lang.Number")
}),
@TriggerPattern(value = "$expr ? $trueExpr : $falseExpr", constraints = {
@ConstraintVariableType(variable = "$falseExpr", type = "double"),
@ConstraintVariableType(variable = "$trueExpr", type = "java.lang.Number")
}),
@TriggerPattern(value = "$expr ? $trueExpr : $falseExpr", constraints = {
@ConstraintVariableType(variable = "$trueExpr", type = "boolean"),
@ConstraintVariableType(variable = "$falseExpr", type = "java.lang.Boolean")
}),
@TriggerPattern(value = "$expr ? $trueExpr : $falseExpr", constraints = {
@ConstraintVariableType(variable = "$falseExpr", type = "boolean"),
@ConstraintVariableType(variable = "$trueExpr", type = "java.lang.Boolean")
}),
@TriggerPattern(value = "$expr ? $trueExpr : $falseExpr", constraints = {
@ConstraintVariableType(variable = "$trueExpr", type = "char"),
@ConstraintVariableType(variable = "$falseExpr", type = "java.lang.Character")
}),
@TriggerPattern(value = "$expr ? $trueExpr : $falseExpr", constraints = {
@ConstraintVariableType(variable = "$falseExpr", type = "char"),
@ConstraintVariableType(variable = "$trueExpr", type = "java.lang.Character")
}),
})
public static ErrorDescription unboxingConditional(HintContext ctx) {
CompilationInfo ci = ctx.getInfo();
TypeMirror leftType = ci.getTrees().getTypeMirror(ctx.getVariables().get("$trueExpr")); // NOI18N
TypeMirror rightType = ci.getTrees().getTypeMirror(ctx.getVariables().get("$falseExpr")); // NOI18N
TypeMirror resType = ci.getTrees().getTypeMirror(ctx.getPath()); // NOI18N
if (!Utilities.isValidType(leftType) || !Utilities.isValidType(rightType) || !Utilities.isValidType(resType)) {
return null;
}
if (!resType.getKind().isPrimitive()) {
return null;
}
TreePath npPath;
TypeMirror np;
if (leftType.getKind().isPrimitive()) {
if (rightType.getKind().isPrimitive()) {
npPath = null;
np = null;
} else {
np = rightType;
npPath = ctx.getVariables().get("$falseExpr"); // NOI18N
}
} else if (!rightType.getKind().isPrimitive()) {
// one more check: if BOTh are declared and BOTH are primitive wrappers and they
// are not SAME, then unboxing still occurs.
if (!Utilities.isPrimitiveWrapperType(leftType) ||
!Utilities.isPrimitiveWrapperType(rightType) ||
ci.getTypes().isSameType(leftType, rightType)) {
return null;
}
Object o = ci.getCachedValue(KEY_CONDITIONAL_PARAMETER);
if (o == null) {
np = leftType;
npPath = ctx.getVariables().get("$trueExpr"); // NOI18N
ci.putCachedValue(KEY_CONDITIONAL_PARAMETER, Boolean.TRUE, CompilationInfo.CacheClearPolicy.ON_TASK_END);
} else {
np = rightType;
npPath = ctx.getVariables().get("$falseExpr"); // NOI18N
}
} else {
np = leftType;
npPath = ctx.getVariables().get("$trueExpr"); // NOI18N
}
if (np == null || !ci.getTypes().isAssignable(np, resType)) {
return null;
}
assert npPath != null;
Map<Tree, State> expressionsState = computeExpressionsState(ctx);
State s = expressionsState.get(npPath.getLeaf());
String k;
if (s == null || s == POSSIBLE_NULL) {
boolean report = ctx.getPreferences().getBoolean(KEY_UNBOXING_UNKNOWN_VALUES, DEF_UNBOXING_UNKNOWN_VALUES);
if (!report) {
return null;
}
k = "ERR_UnboxingPotentialNullValue"; // NOI18N
} else switch (s) {
case NULL:
case NULL_HYPOTHETICAL:
k = "ERR_UnboxingNullValue"; // NOI18N
break;
case POSSIBLE_NULL_REPORT:
case POSSIBLE_NULL:
case INSTANCE_OF_FALSE:
k = "ERR_UnboxingPotentialNullValue"; // NOI18N
break;
case NOT_NULL_BE_NPE:
case NOT_NULL:
case NOT_NULL_HYPOTHETICAL:
case INSTANCE_OF_TRUE:
return null;
default:
throw new AssertionError(s.name());
}
return ErrorDescriptionFactory.forTree(ctx, npPath,
NbBundle.getMessage(NPECheck.class, k));
}
@TriggerPattern("switch ($select) { case $cases$; }")
public static ErrorDescription switchExpression(HintContext ctx) {
TreePath select = ctx.getVariables().get("$select");
TypeMirror m = ctx.getInfo().getTrees().getTypeMirror(select);
if (m == null || m.getKind() != TypeKind.DECLARED) {
return null;
}
State r = computeExpressionsState(ctx).get(select.getLeaf());
if (r == NULL || r == NULL_HYPOTHETICAL) {
String displayName = NbBundle.getMessage(NPECheck.class, "ERR_DereferencingNull");
return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), displayName);
}
if (r == State.POSSIBLE_NULL_REPORT || r == INSTANCE_OF_FALSE) {
String displayName = NbBundle.getMessage(NPECheck.class, "ERR_PossiblyDereferencingNull");
return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), displayName);
}
return null;
}
@TriggerPattern("for ($type $var : $expr) $stmts$")
public static ErrorDescription enhancedFor(HintContext ctx) {
TreePath colExpr = ctx.getVariables().get("$expr");
if (colExpr == null) {
return null;
}
State r = computeExpressionsState(ctx).get(colExpr.getLeaf());
if (r == NULL || r == NULL_HYPOTHETICAL) {
String displayName = NbBundle.getMessage(NPECheck.class, "ERR_DereferencingNull");
return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), displayName);
}
if (r == State.POSSIBLE_NULL_REPORT || r == State.INSTANCE_OF_FALSE) {
String displayName = NbBundle.getMessage(NPECheck.class, "ERR_PossiblyDereferencingNull");
return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), displayName);
}
return null;
}
@TriggerPattern("$select.$variable")
public static ErrorDescription memberSelect(HintContext ctx) {
TreePath select = ctx.getVariables().get("$select");
State r = computeExpressionsState(ctx).get(select.getLeaf());
if (r == NULL || r == NULL_HYPOTHETICAL) {
String displayName = NbBundle.getMessage(NPECheck.class, "ERR_DereferencingNull");
return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), displayName);
}
if (r == State.POSSIBLE_NULL_REPORT || r == State.INSTANCE_OF_FALSE) {
String displayName = NbBundle.getMessage(NPECheck.class, "ERR_PossiblyDereferencingNull");
return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), displayName);
}
return null;
}
/**
* Checks for a possible null dereference - if the path denotes a possibly
* null expression.
*
*/
public static boolean isSafeToDereference(CompilationInfo info, TreePath path) {
State r = computeExpressionsState(info, null).get(path.getLeaf());
// copied from warning issued on redundant != null.
return r != null && r.isNotNull();
}
@TriggerTreeKind(Kind.METHOD_INVOCATION)
public static List<ErrorDescription> methodInvocation(HintContext ctx) {
MethodInvocationTree mit = (MethodInvocationTree) ctx.getPath().getLeaf();
List<State> paramStates = new ArrayList<>(mit.getArguments().size());
Map<Tree, State> expressionsState = computeExpressionsState(ctx);
for (Tree param : mit.getArguments()) {
State r = expressionsState.get(param);
paramStates.add(r != null ? r : State.POSSIBLE_NULL);
}
Element e = ctx.getInfo().getTrees().getElement(ctx.getPath());
if (e == null || e.getKind() != ElementKind.METHOD) {
return null;
}
ExecutableElement ee = (ExecutableElement) e;
int index = 0;
List<ErrorDescription> result = new ArrayList<>();
List<? extends VariableElement> params = ee.getParameters();
for (VariableElement param : params) {
if (getStateFromAnnotations(ctx.getInfo(), param) == NOT_NULL && (!ee.isVarArgs() || param != params.get(params.size() - 1))) {
switch (paramStates.get(index)) {
case NULL: case NULL_HYPOTHETICAL:
result.add(ErrorDescriptionFactory.forTree(ctx, mit.getArguments().get(index), NbBundle.getMessage(NPECheck.class, "ERR_NULL_TO_NON_NULL_ARG")));
break;
case POSSIBLE_NULL_REPORT:
case INSTANCE_OF_FALSE:
result.add(ErrorDescriptionFactory.forTree(ctx, mit.getArguments().get(index), NbBundle.getMessage(NPECheck.class, "ERR_POSSIBLENULL_TO_NON_NULL_ARG")));
break;
}
}
index++;
}
return result;
}
@TriggerPatterns({
@TriggerPattern("$variable != null"),
@TriggerPattern("null != $variable"),
})
public static ErrorDescription notNullTest(HintContext ctx) {
TreePath variable = ctx.getVariables().get("$variable");
State r = computeExpressionsState(ctx).get(variable.getLeaf());
if (r != null && r.isNotNull() && !ignore(ctx, false)) {
String displayName = NbBundle.getMessage(NPECheck.class, r == State.NOT_NULL_BE_NPE ? "ERR_NotNullWouldBeNPE" : "ERR_NotNull");
return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), displayName);
}
return null;
}
@TriggerPatterns({
@TriggerPattern("$variable == null"),
@TriggerPattern("null == $variable")
})
public static ErrorDescription nullTest(HintContext ctx) {
TreePath variable = ctx.getVariables().get("$variable");
State r = computeExpressionsState(ctx).get(variable.getLeaf());
if (r != null && r.isNotNull() && !ignore(ctx, true)) {
String displayName = NbBundle.getMessage(NPECheck.class, r == State.NOT_NULL_BE_NPE ? "ERR_NotNullWouldBeNPE" : "ERR_NotNull");
return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), displayName);
}
return null;
}
private static boolean ignore(HintContext ctx, boolean equalsToNull) {
TreePath test = ctx.getPath().getParentPath();
while (test != null && !StatementTree.class.isAssignableFrom(test.getLeaf().getKind().asInterface())) {
test = test.getParentPath();
}
if (test == null) return false;
if (test.getLeaf().getKind() == Kind.ASSERT && !equalsToNull) {
return verifyConditions(ctx, ((AssertTree) test.getLeaf()).getCondition(), equalsToNull);
} else if (test.getLeaf().getKind() == Kind.IF && equalsToNull) {
StatementTree last;
IfTree it = (IfTree) test.getLeaf();
switch (it.getThenStatement().getKind()) {
case BLOCK:
List<? extends StatementTree> statements = ((BlockTree) it.getThenStatement()).getStatements();
last = !statements.isEmpty() ? statements.get(statements.size() - 1) : null;
break;
default:
last = it.getThenStatement();
break;
}
return last != null && last.getKind() == Kind.THROW && verifyConditions(ctx, ((IfTree) test.getLeaf()).getCondition(), equalsToNull);
}
return false;
}
private static boolean verifyConditions(HintContext ctx, ExpressionTree cond, boolean equalsToNull) {
switch (cond.getKind()) {
case PARENTHESIZED: return verifyConditions(ctx, ((ParenthesizedTree) cond).getExpression(), equalsToNull);
case NOT_EQUAL_TO: return !equalsToNull && hasNull(ctx, (BinaryTree) cond);
case EQUAL_TO: return equalsToNull && hasNull(ctx, (BinaryTree) cond);
case CONDITIONAL_OR: case OR:
return equalsToNull && verifyConditions(ctx, ((BinaryTree) cond).getLeftOperand(), equalsToNull) && verifyConditions(ctx, ((BinaryTree) cond).getRightOperand(), equalsToNull);
case CONDITIONAL_AND: case AND:
return !equalsToNull && verifyConditions(ctx, ((BinaryTree) cond).getLeftOperand(), equalsToNull) && verifyConditions(ctx, ((BinaryTree) cond).getRightOperand(), equalsToNull);
}
return false;
}
private static boolean hasNull(HintContext ctx, BinaryTree bt) {
return bt.getLeftOperand().getKind() == Kind.NULL_LITERAL
|| bt.getRightOperand().getKind() == Kind.NULL_LITERAL;
}
@TriggerPattern("return $expression;")
public static ErrorDescription returnNull(HintContext ctx) {
TreePath expression = ctx.getVariables().get("$expression");
State returnState = computeExpressionsState(ctx).get(expression.getLeaf());
if (returnState == null) return null;
TreePath method = Utilities.findOwningExecutable(ctx, ctx.getPath(), true);
if (method == null) return null;
CompilationInfo info = ctx.getInfo();
Element el = null;
switch (method.getLeaf().getKind()) {
case LAMBDA_EXPRESSION:
TypeMirror functionalType = info.getTrees().getTypeMirror(method);
if (!Utilities.isValidType(functionalType) || functionalType.getKind() != TypeKind.DECLARED) return null;
el = info.getElementUtilities().getDescriptorElement((TypeElement) ((DeclaredType) functionalType).asElement());
break;
case METHOD:
el = info.getTrees().getElement(method);
break;
}
if (el == null || el.getKind() != ElementKind.METHOD) return null;
State expected = getStateFromAnnotations(info, el);
String key = null;
switch (returnState) {
case NULL: case NULL_HYPOTHETICAL:
if (expected.isNotNull()) key = "ERR_ReturningNullFromNonNull";
break;
case POSSIBLE_NULL_REPORT:
case INSTANCE_OF_FALSE:
if (expected.isNotNull()) key = "ERR_ReturningPossibleNullFromNonNull";
break;
}
if (key != null) {
String displayName = NbBundle.getMessage(NPECheck.class, key);
return ErrorDescriptionFactory.forName(ctx, expression, displayName);
}
return null;
}
private static final Object KEY_EXPRESSION_STATE = new Object();
private static final Object KEY_CONDITIONAL_PARAMETER = new Object();
private static Map<Tree, State> computeExpressionsState(CompilationInfo info, HintContext ctx) {
Map<Tree, State> result = (Map<Tree, State>) info.getCachedValue(KEY_EXPRESSION_STATE);
if (result != null) {
return result;
}
VisitorImpl v = new VisitorImpl(ctx, info, null);
v.scan(info.getCompilationUnit(), null);
result = v.expressionState;
info.putCachedValue(KEY_EXPRESSION_STATE, result, CompilationInfo.CacheClearPolicy.ON_TASK_END);
return result;
}
//Cancelling:
private static Map<Tree, State> computeExpressionsState(HintContext ctx) {
Map<Tree, State> result = (Map<Tree, State>) ctx.getInfo().getCachedValue(KEY_EXPRESSION_STATE);
if (result != null) {
return result;
}
VisitorImpl v = new VisitorImpl(ctx);
v.scan(ctx.getInfo().getCompilationUnit(), null);
result = v.expressionState;
ctx.getInfo().putCachedValue(KEY_EXPRESSION_STATE, result, CompilationInfo.CacheClearPolicy.ON_TASK_END);
return result;
}
private static State getStateFromAnnotations(CompilationInfo info, Element e) {
return getStateFromAnnotations(info, e, State.POSSIBLE_NULL);
}
private static final AnnotationMirrorGetter OVERRIDE_ANNOTATIONS = Lookup.getDefault().lookup(AnnotationMirrorGetter.class);
private static State getStateFromAnnotations(CompilationInfo info, Element e, State def) {
if (e == null) return def;
Iterable<? extends AnnotationMirror> mirrors = OVERRIDE_ANNOTATIONS != null ? OVERRIDE_ANNOTATIONS.getAnnotationMirrors(info, e) : null;
if (mirrors == null) mirrors = e.getAnnotationMirrors();
for (AnnotationMirror am : mirrors) {
String simpleName = ((TypeElement) am.getAnnotationType().asElement()).getSimpleName().toString();
if ("Nullable".equals(simpleName) || "NullAllowed".equals(simpleName)) {
return State.POSSIBLE_NULL_REPORT;
}
if ("CheckForNull".equals(simpleName)) {
return State.POSSIBLE_NULL_REPORT;
}
if ("NotNull".equals(simpleName) || "NonNull".equals(simpleName) || "Nonnull".equals(simpleName)) {
return State.NOT_NULL;
}
}
return def;
}
public interface AnnotationMirrorGetter {
public Iterable<? extends AnnotationMirror> getAnnotationMirrors(CompilationInfo info, Element el);
}
private static final class VisitorImpl extends CancellableTreePathScanner<State, Void> {
private final HintContext ctx;
private final CompilationInfo info;
private final AtomicBoolean cancelFlag;
/**
* Tracks variables which are in scope. When a variable goes out of scope, its state (if any) moves
* to {@link #variable2StateFinal}.
*/
private Map<VariableElement, State> variable2State = new HashMap<>();
/**
* Finalized state of variables. Records for variables, which go out of scope is collected here.
*/
private final Map<VariableElement, State> variable2StateFinal = new HashMap<>();
private final Map<Tree, Collection<Map<VariableElement, State>>> resumeBefore = new IdentityHashMap<>();
private final Map<Tree, Collection<Map<VariableElement, State>>> resumeAfter = new IdentityHashMap<>();
private Map<TypeMirror, Map<VariableElement, State>> resumeOnExceptionHandler = new IdentityHashMap<>();
private final Map<Tree, State> expressionState = new IdentityHashMap<>();
private final List<TreePath> pendingFinally = new LinkedList<>();
private boolean not;
private boolean doNotRecord;
private final TypeElement throwableEl;
private final TypeMirror runtimeExceptionType;
private final TypeMirror errorType;
/**
* For a Tree, collects variables scoped into that tree. The Map is used
* when the traversal exits the tree, to clean up variables that go out of scope from
* variable2State, so state cloning takes less memory
*/
private final Map<Tree, Collection<VariableElement>> scopedVariables = new IdentityHashMap<>();
public VisitorImpl(HintContext ctx, CompilationInfo aInfo, AtomicBoolean cancel) {
this.ctx = ctx;
if (ctx != null) {
this.info = ctx.getInfo();
this.cancelFlag = null;
} else {
this.info = aInfo;
this.cancelFlag = cancel != null ? cancel : new AtomicBoolean(false);
}
this.throwableEl = this.info.getElements().getTypeElement("java.lang.Throwable"); // NOI18N
TypeElement tel = this.info.getElements().getTypeElement("java.lang.RuntimeException"); // NOI18N
if (tel != null) {
runtimeExceptionType = tel.asType();
} else {
runtimeExceptionType = null;
}
tel = this.info.getElements().getTypeElement("java.lang.Error"); // NOI18N
if (tel != null) {
errorType = tel.asType();
} else {
errorType = null;
}
}
public VisitorImpl(HintContext ctx) {
this(ctx, null, null);
}
@Override
protected boolean isCanceled() {
if (ctx != null) {
return ctx.isCanceled();
} else {
return cancelFlag.get();
}
}
@Override
public State scan(Tree tree, Void p) {
resume(tree, resumeBefore);
State r = super.scan(tree, p);
TypeMirror currentType = tree != null ? info.getTrees().getTypeMirror(new TreePath(getCurrentPath(), tree)) : null;
if (currentType != null && currentType.getKind().isPrimitive()) {
r = State.NOT_NULL;
}
if (r != null && !doNotRecord) {
// expressionState.put(tree, r);
expressionState.put(tree, mergeIn(expressionState, tree, r));
}
resume(tree, resumeAfter);
Collection<VariableElement> varsOutScope = scopedVariables.get(tree);
if (varsOutScope != null) {
for (VariableElement ve : varsOutScope) {
State s = variable2State.get(ve);
if (s != null) {
variable2StateFinal.put(ve, s);
}
}
variable2State.keySet().removeAll(varsOutScope);
}
return r;
}
private void resume(Tree tree, Map<Tree, Collection<Map<VariableElement, State>>> resume) {
Collection<Map<VariableElement, State>> toResume = resume.remove(tree);
if (toResume != null) {
for (Map<VariableElement, State> s : toResume) {
mergeIntoVariable2State(s);
}
}
}
@Override
public State visitAssignment(AssignmentTree node, Void p) {
Element e = info.getTrees().getElement(new TreePath(getCurrentPath(), node.getVariable()));
Map<VariableElement, State> orig = new HashMap<>(variable2State);
State r = scan(node.getExpression(), p);
scan(node.getVariable(), p);
mergeHypotheticalVariable2State(orig);
if (isVariableElement(e)) {
variable2State.put((VariableElement) e, r);
}
return r;
}
@Override
public State visitCompoundAssignment(CompoundAssignmentTree node, Void p) {
Map<VariableElement, State> orig = new HashMap<>(variable2State);
scan(node.getExpression(), p);
scan(node.getVariable(), p);
mergeHypotheticalVariable2State(orig);
return null;
}
private void addScopedVariable(Tree t, VariableElement ve) {
Collection<VariableElement> c = scopedVariables.get(t);
if (c == null) {
c = new ArrayList<>(3);
scopedVariables.put(t, c);
}
c.add(ve);
}
@Override
public State visitVariable(VariableTree node, Void p) {
Element e = info.getTrees().getElement(getCurrentPath());
Map<VariableElement, State> orig = new HashMap<>(variable2State);
State r = scan(node.getInitializer(), p);
mergeHypotheticalVariable2State(orig);
if (e != null) {
variable2State.put((VariableElement) e, r);
TreePath pp = getCurrentPath().getParentPath();
if (pp != null) {
addScopedVariable(pp.getLeaf(), (VariableElement)e);
}
}
return r;
}
@Override
public State visitMemberSelect(MemberSelectTree node, Void p) {
State expr = scan(node.getExpression(), p);
boolean wasNPE = false;
if (expr == State.NULL || expr == State.NULL_HYPOTHETICAL || expr == State.POSSIBLE_NULL || expr == State.POSSIBLE_NULL_REPORT || expr == State.INSTANCE_OF_FALSE) {
wasNPE = true;
}
Element site = info.getTrees().getElement(new TreePath(getCurrentPath(), node.getExpression()));
if (isVariableElement(site) && wasNPE && (variable2State.get((VariableElement) site) == null || !variable2State.get((VariableElement) site).isNotNull())) {
variable2State.put((VariableElement) site, NOT_NULL_BE_NPE);
}
// special case: if the memberSelect selects enum field = constant, it is never null.
if (site != null && site.getKind() == ElementKind.ENUM) {
Element enumConst = info.getTrees().getElement(getCurrentPath());
if (enumConst != null && enumConst.getKind() == ElementKind.ENUM_CONSTANT) {
return State.NOT_NULL;
}
}
return getStateFromAnnotations(info, info.getTrees().getElement(getCurrentPath()));
}
@Override
public State visitLiteral(LiteralTree node, Void p) {
if (node.getValue() == null) {
return State.NULL;
} else {
return State.NOT_NULL;
}
}
@Override
public State visitIf(IfTree node, Void p) {
Map<VariableElement, State> oldVariable2StateBeforeCondition = new HashMap<>(variable2State);
State condition = scan(node.getCondition(), p);
scan(node.getThenStatement(), null);
Map<VariableElement, State> variableStatesAfterThen = new HashMap<>(variable2State);
variable2State = new HashMap<>(oldVariable2StateBeforeCondition);
not = true;
doNotRecord = true;
scan(node.getCondition(), p);
not = false;
doNotRecord = false;
scan(node.getElseStatement(), null);
boolean thenExitsFromAllBranches = Utilities.exitsFromAllBranchers(info, new TreePath(getCurrentPath(), node.getThenStatement()));
boolean elseExitsFromAllBranches = node.getElseStatement() != null && Utilities.exitsFromAllBranchers(info, new TreePath(getCurrentPath(), node.getElseStatement()));
if (thenExitsFromAllBranches && !elseExitsFromAllBranches) {
//already set
} else if (!thenExitsFromAllBranches && elseExitsFromAllBranches) {
variable2State = variableStatesAfterThen;
} else {
mergeIntoVariable2State(variableStatesAfterThen);
}
return null;
}
@Override
public State visitBinary(BinaryTree node, Void p) {
Kind kind = node.getKind();
if (not) {
switch (kind) {
case CONDITIONAL_AND: kind = Kind.CONDITIONAL_OR; break;
case CONDITIONAL_OR: kind = Kind.CONDITIONAL_AND; break;
case EQUAL_TO: kind = Kind.NOT_EQUAL_TO; break;
case NOT_EQUAL_TO: kind = Kind.EQUAL_TO; break;
}
}
State left = null;
State right = null;
switch (kind) {
case CONDITIONAL_AND:
case AND: case OR: case XOR:
scan(node.getLeftOperand(), p);
scan(node.getRightOperand(), p);
break;
case CONDITIONAL_OR: {
HashMap<VariableElement, State> orig = new HashMap<>(variable2State);
scan(node.getLeftOperand(), p);
Map<VariableElement, State> afterLeft = variable2State;
variable2State = orig;
boolean oldNot = not;
boolean oldDoNotRecord = doNotRecord;
not ^= true;
doNotRecord = true;
scan(node.getLeftOperand(), p);
not = oldNot;
doNotRecord = oldDoNotRecord;
scan(node.getRightOperand(), p);
mergeIntoVariable2State(afterLeft);
break;
}
default: {
boolean oldNot = not;
not = false;
left = scan(node.getLeftOperand(), p);
right = scan(node.getRightOperand(), p);
not = oldNot;
}
}
if (kind == Kind.EQUAL_TO) {
if (right == State.NULL) {
Element e = info.getTrees().getElement(new TreePath(getCurrentPath(), node.getLeftOperand()));
if (isVariableElement(e) && !hasDefiniteValue((VariableElement) e)) {
variable2State.put((VariableElement) e, State.NULL_HYPOTHETICAL);
return null;
}
}
if (left == State.NULL) {
Element e = info.getTrees().getElement(new TreePath(getCurrentPath(), node.getRightOperand()));
if (isVariableElement(e) && !hasDefiniteValue((VariableElement) e)) {
variable2State.put((VariableElement) e, State.NULL_HYPOTHETICAL);
return null;
}
}
}
if (kind == Kind.NOT_EQUAL_TO) {
if (right == State.NULL) {
Element e = info.getTrees().getElement(new TreePath(getCurrentPath(), node.getLeftOperand()));
if (isVariableElement(e) && !hasDefiniteValue((VariableElement) e)) {
variable2State.put((VariableElement) e, State.NOT_NULL_HYPOTHETICAL);
return null;
}
}
if (left == State.NULL) {
Element e = info.getTrees().getElement(new TreePath(getCurrentPath(), node.getRightOperand()));
if (isVariableElement(e) && !hasDefiniteValue((VariableElement) e)) {
variable2State.put((VariableElement) e, State.NOT_NULL_HYPOTHETICAL);
return null;
}
}
}
return null;
}
@Override
public State visitInstanceOf(InstanceOfTree node, Void p) {
super.visitInstanceOf(node, p);
Element e = info.getTrees().getElement(new TreePath(getCurrentPath(), node.getExpression()));
if (isVariableElement(e)) {
boolean setState = false;
State currentState = variable2State.get((VariableElement) e);
if (currentState == null) {
setState = !getStateFromAnnotations(info, e).isNotNull();
} else {
setState = !variable2State.get((VariableElement) e).isNotNull();
}
if (setState) {
variable2State.put((VariableElement) e, not ? State.INSTANCE_OF_FALSE : State.INSTANCE_OF_TRUE);
}
}
return null;
}
@Override
public State visitConditionalExpression(ConditionalExpressionTree node, Void p) {
//TODO: handle the condition similarly to visitIf
Map<VariableElement, State> oldVariable2State = new HashMap<>(variable2State);
scan(node.getCondition(), p);
State thenSection = scan(node.getTrueExpression(), p);
Map<VariableElement, State> variableStatesAfterThen = variable2State;
variable2State = oldVariable2State;
not = true;
doNotRecord = true;
scan(node.getCondition(), p);
not = false;
doNotRecord = false;
State elseSection = scan(node.getFalseExpression(), p);
State result = State.collect(thenSection, elseSection);
mergeIntoVariable2State(variableStatesAfterThen);
return result;
}
@Override
public State visitNewClass(NewClassTree node, Void p) {
scan(node.getEnclosingExpression(), p);
scan(node.getIdentifier(), p);
scan(node.getTypeArguments(), p);
for (Tree param : node.getArguments()) {
Map<VariableElement, State> origVariable2State = variable2State;
variable2State = new HashMap<>(variable2State);
scan(param, p);
mergeNonHypotheticalVariable2State(origVariable2State);
}
scan(node.getClassBody(), p);
Element invoked = info.getTrees().getElement(getCurrentPath());
if (invoked != null && invoked.getKind() == ElementKind.CONSTRUCTOR) {
recordResumeOnExceptionHandler((ExecutableElement) invoked);
}
return State.NOT_NULL;
}
@Override
public State visitMethodInvocation(MethodInvocationTree node, Void p) {
scan(node.getTypeArguments(), p);
scan(node.getMethodSelect(), p);
for (Tree param : node.getArguments()) {
Map<VariableElement, State> origVariable2State = variable2State;
variable2State = new HashMap<>(variable2State);
scan(param, p);
mergeNonHypotheticalVariable2State(origVariable2State);
}
Element e = info.getTrees().getElement(getCurrentPath());
if (e == null || e.getKind() != ElementKind.METHOD) {
return State.POSSIBLE_NULL;
} else {
recordResumeOnExceptionHandler((ExecutableElement) e);
visitAssertMethods(node, e);
State s = visitPrimitiveWrapperMethods(node, e);
if (s != null) {
return s;
}
}
return getStateFromAnnotations(info, e);
}
private State visitPrimitiveWrapperMethods(MethodInvocationTree node, Element e) {
if (!Utilities.isPrimitiveWrapperType(e.getEnclosingElement().asType())) {
return null;
}
switch (e.getSimpleName().toString()) {
case "toString": // NOI18N
case "toUnsignedString":// NOI18N
case "toHexString":case "toOctalString": case "toBinaryString": // NOI18N
case "valueOf":// NOI18N
case "decode":// NOI18N
return NOT_NULL;