/
GenericAnnotatedTypeFactory.java
2803 lines (2570 loc) · 110 KB
/
GenericAnnotatedTypeFactory.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
package org.checkerframework.framework.type;
import com.google.common.collect.Ordering;
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.MemberReferenceTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.UnaryTree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreePath;
import java.lang.annotation.Annotation;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.StringJoiner;
import java.util.regex.Pattern;
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.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.type.TypeVariable;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import org.checkerframework.afu.scenelib.el.AField;
import org.checkerframework.afu.scenelib.el.AMethod;
import org.checkerframework.checker.formatter.qual.FormatMethod;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.common.basetype.BaseTypeChecker;
import org.checkerframework.common.wholeprograminference.WholeProgramInferenceImplementation;
import org.checkerframework.common.wholeprograminference.WholeProgramInferenceJavaParserStorage;
import org.checkerframework.common.wholeprograminference.WholeProgramInferenceScenesStorage;
import org.checkerframework.dataflow.analysis.Analysis;
import org.checkerframework.dataflow.analysis.Analysis.BeforeOrAfter;
import org.checkerframework.dataflow.analysis.AnalysisResult;
import org.checkerframework.dataflow.analysis.TransferInput;
import org.checkerframework.dataflow.analysis.TransferResult;
import org.checkerframework.dataflow.cfg.ControlFlowGraph;
import org.checkerframework.dataflow.cfg.UnderlyingAST;
import org.checkerframework.dataflow.cfg.UnderlyingAST.CFGLambda;
import org.checkerframework.dataflow.cfg.UnderlyingAST.CFGMethod;
import org.checkerframework.dataflow.cfg.UnderlyingAST.CFGStatement;
import org.checkerframework.dataflow.cfg.node.MethodInvocationNode;
import org.checkerframework.dataflow.cfg.node.Node;
import org.checkerframework.dataflow.cfg.node.ObjectCreationNode;
import org.checkerframework.dataflow.cfg.node.ReturnNode;
import org.checkerframework.dataflow.cfg.visualize.CFGVisualizer;
import org.checkerframework.dataflow.cfg.visualize.DOTCFGVisualizer;
import org.checkerframework.dataflow.expression.FieldAccess;
import org.checkerframework.dataflow.expression.JavaExpression;
import org.checkerframework.dataflow.expression.LocalVariable;
import org.checkerframework.framework.flow.CFAbstractAnalysis;
import org.checkerframework.framework.flow.CFAbstractAnalysis.FieldInitialValue;
import org.checkerframework.framework.flow.CFAbstractStore;
import org.checkerframework.framework.flow.CFAbstractTransfer;
import org.checkerframework.framework.flow.CFAbstractValue;
import org.checkerframework.framework.flow.CFAnalysis;
import org.checkerframework.framework.flow.CFCFGBuilder;
import org.checkerframework.framework.flow.CFStore;
import org.checkerframework.framework.flow.CFTransfer;
import org.checkerframework.framework.flow.CFValue;
import org.checkerframework.framework.qual.DefaultFor;
import org.checkerframework.framework.qual.DefaultQualifier;
import org.checkerframework.framework.qual.DefaultQualifierInHierarchy;
import org.checkerframework.framework.qual.EnsuresQualifier;
import org.checkerframework.framework.qual.EnsuresQualifierIf;
import org.checkerframework.framework.qual.MonotonicQualifier;
import org.checkerframework.framework.qual.QualifierForLiterals;
import org.checkerframework.framework.qual.RelevantJavaTypes;
import org.checkerframework.framework.qual.RequiresQualifier;
import org.checkerframework.framework.qual.TypeUseLocation;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedDeclaredType;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedExecutableType;
import org.checkerframework.framework.type.poly.DefaultQualifierPolymorphism;
import org.checkerframework.framework.type.poly.QualifierPolymorphism;
import org.checkerframework.framework.type.treeannotator.ListTreeAnnotator;
import org.checkerframework.framework.type.treeannotator.LiteralTreeAnnotator;
import org.checkerframework.framework.type.treeannotator.PropagationTreeAnnotator;
import org.checkerframework.framework.type.treeannotator.TreeAnnotator;
import org.checkerframework.framework.type.typeannotator.DefaultForTypeAnnotator;
import org.checkerframework.framework.type.typeannotator.DefaultQualifierForUseTypeAnnotator;
import org.checkerframework.framework.type.typeannotator.IrrelevantTypeAnnotator;
import org.checkerframework.framework.type.typeannotator.ListTypeAnnotator;
import org.checkerframework.framework.type.typeannotator.PropagationTypeAnnotator;
import org.checkerframework.framework.type.typeannotator.TypeAnnotator;
import org.checkerframework.framework.util.AnnotatedTypes;
import org.checkerframework.framework.util.Contract;
import org.checkerframework.framework.util.ContractsFromMethod;
import org.checkerframework.framework.util.JavaExpressionParseUtil.JavaExpressionParseException;
import org.checkerframework.framework.util.StringToJavaExpression;
import org.checkerframework.framework.util.defaults.QualifierDefaults;
import org.checkerframework.framework.util.dependenttypes.DependentTypesHelper;
import org.checkerframework.framework.util.dependenttypes.DependentTypesTreeAnnotator;
import org.checkerframework.framework.util.typeinference.TypeArgInferenceUtil;
import org.checkerframework.javacutil.AnnotationBuilder;
import org.checkerframework.javacutil.AnnotationUtils;
import org.checkerframework.javacutil.BugInCF;
import org.checkerframework.javacutil.CollectionUtils;
import org.checkerframework.javacutil.ElementUtils;
import org.checkerframework.javacutil.Pair;
import org.checkerframework.javacutil.TreePathUtil;
import org.checkerframework.javacutil.TreeUtils;
import org.checkerframework.javacutil.TypeSystemError;
import org.checkerframework.javacutil.TypesUtils;
import org.checkerframework.javacutil.UserError;
import org.plumelib.reflection.Signatures;
import org.plumelib.util.CollectionsPlume;
import org.plumelib.util.SystemPlume;
/**
* A factory that extends {@link AnnotatedTypeFactory} to optionally use flow-sensitive qualifier
* inference.
*
* <p>It also adds other features: qualifier polymorphism, default annotations via {@link
* DefaultFor}, user-specified defaults via {@link DefaultQualifier}, standardization via {@link
* DependentTypesHelper}, etc. Those features, and {@link #addComputedTypeAnnotations} (other than
* the part related to flow-sensitivity), could and should be in the superclass {@link
* AnnotatedTypeFactory}; it is not clear why they are defined in this class.
*/
public abstract class GenericAnnotatedTypeFactory<
Value extends CFAbstractValue<Value>,
Store extends CFAbstractStore<Value, Store>,
TransferFunction extends CFAbstractTransfer<Value, Store, TransferFunction>,
FlowAnalysis extends CFAbstractAnalysis<Value, Store, TransferFunction>>
extends AnnotatedTypeFactory {
/** Should use flow by default. */
protected static boolean flowByDefault = true;
/** To cache the supported monotonic type qualifiers. */
private Set<Class<? extends Annotation>> supportedMonotonicQuals;
/** to annotate types based on the given tree */
protected TypeAnnotator typeAnnotator;
/** for use in addAnnotationsFromDefaultForType */
private DefaultQualifierForUseTypeAnnotator defaultQualifierForUseTypeAnnotator;
/** for use in addAnnotationsFromDefaultForType */
private DefaultForTypeAnnotator defaultForTypeAnnotator;
/** to annotate types based on the given un-annotated types */
protected TreeAnnotator treeAnnotator;
/** to handle any polymorphic types */
protected QualifierPolymorphism poly;
/** to handle defaults specified by the user */
protected QualifierDefaults defaults;
/** To handle dependent type annotations and contract expressions. */
protected DependentTypesHelper dependentTypesHelper;
/** to handle method pre- and postconditions */
protected ContractsFromMethod contractsUtils;
/**
* The Java types on which users may write this type system's type annotations. null means no
* restrictions. Arrays are handled by separate field {@code #arraysAreRelevant}.
*
* <p>If the relevant type is generic, this contains its erasure.
*
* <p>Although a {@code Class<?>} object exists for every element, this does not contain those
* {@code Class<?>} objects because the elements will be compared to TypeMirrors for which Class
* objects may not exist (they might not be on the classpath).
*/
public @Nullable Set<TypeMirror> relevantJavaTypes;
/**
* Whether users may write type annotations on arrays. Ignored unless {@link #relevantJavaTypes}
* is non-null.
*/
boolean arraysAreRelevant = false;
// Flow related fields
/**
* Should use flow-sensitive type refinement analysis? This value can be changed when an
* AnnotatedTypeMirror without annotations from data flow is required.
*
* @see #getAnnotatedTypeLhs(Tree)
*/
private boolean useFlow;
/** Is this type factory configured to use flow-sensitive type refinement? */
private final boolean everUseFlow;
/**
* Should the local variable default annotation be applied to type variables?
*
* <p>It is initialized to true if data flow is used by the checker. It is set to false when
* getting the assignment context for type argument inference.
*
* @see GenericAnnotatedTypeFactory#getAnnotatedTypeLhsNoTypeVarDefault
*/
private boolean shouldDefaultTypeVarLocals;
/**
* Elements representing variables for which the type of the initializer is being determined in
* order to apply qualifier parameter defaults.
*
* <p>Local variables with a qualifier parameter get their declared type from the type of their
* initializer. Sometimes the initializer's type depends on the type of the variable, such as
* during type variable inference or when a variable is used in its own initializer as in "Object
* o = (o = null)". This creates a circular dependency resulting in infinite recursion. To prevent
* this, variables in this set should not be typed based on their initializer, but by using normal
* defaults.
*
* <p>This set should only be modified in
* GenericAnnotatedTypeFactory#applyLocalVariableQualifierParameterDefaults which clears variables
* after computing their initializer types.
*
* @see GenericAnnotatedTypeFactory#applyLocalVariableQualifierParameterDefaults
*/
private Set<VariableElement> variablesUnderInitialization;
/**
* Caches types of initializers for local variables with a qualifier parameter, so that they
* aren't computed each time the type of a variable is looked up.
*
* @see GenericAnnotatedTypeFactory#applyLocalVariableQualifierParameterDefaults
*/
private Map<Tree, AnnotatedTypeMirror> initializerCache;
/**
* Should the analysis assume that side effects to a value can change the type of aliased
* references?
*
* <p>For many type systems, once a local variable's type is refined, side effects to the
* variable's value do not change the variable's type annotations. For some type systems, a side
* effect to the value could change them; set this field to true.
*/
// Not final so that subclasses can set it.
public boolean sideEffectsUnrefineAliases = false;
/**
* True if this checker either has one or more subcheckers, or if this checker is a subchecker.
* False otherwise. All uses of the methods {@link #addSharedCFGForTree(Tree, ControlFlowGraph)}
* and {@link #getSharedCFGForTree(Tree)} should be guarded by a check that this is true.
*/
public final boolean hasOrIsSubchecker;
/** An empty store. */
// Set in postInit only
protected Store emptyStore;
// Set in postInit only
protected FlowAnalysis analysis;
// Set in postInit only
protected TransferFunction transfer;
// Maintain for every class the store that is used when we analyze initialization code
protected Store initializationStore;
// Maintain for every class the store that is used when we analyze static initialization code
protected Store initializationStaticStore;
/**
* Caches for {@link AnalysisResult#runAnalysisFor(Node, Analysis.BeforeOrAfter, TransferInput,
* IdentityHashMap, Map)}. This cache is enabled if {@link #shouldCache} is true. The cache size
* is derived from {@link #getCacheSize()}.
*
* @see AnalysisResult#runAnalysisFor(Node, Analysis.BeforeOrAfter, TransferInput,
* IdentityHashMap, Map)
*/
protected final Map<
TransferInput<Value, Store>, IdentityHashMap<Node, TransferResult<Value, Store>>>
flowResultAnalysisCaches;
/**
* Subcheckers share the same ControlFlowGraph for each analyzed code statement. This maps from
* code statements to the shared control flow graphs. This map is null in all subcheckers (i.e.
* any checker for which getParentChecker() returns non-null). This map is also unused (and
* therefore null) for a checker with no subcheckers with which it can share CFGs.
*
* <p>The initial capacity of the map is set by {@link #getCacheSize()}.
*/
protected @Nullable Map<Tree, ControlFlowGraph> subcheckerSharedCFG;
/**
* If true, {@link #setRoot(CompilationUnitTree)} should clear the {@link #subcheckerSharedCFG}
* map, freeing memory.
*
* <p>For each compilation unit, all the subcheckers run first and finally the ultimate parent
* checker runs. The ultimate parent checker's {@link #setRoot(CompilationUnitTree)} (the last to
* run) sets this field to true.
*
* <p>In first subchecker to run for the next compilation unit, {@link
* #setRoot(CompilationUnitTree)} observes the true value, clears the {@link #subcheckerSharedCFG}
* map, and sets this field back to false. That first subchecker will create a CFG and re-populate
* the map, and subsequent subcheckers will use the map.
*/
protected boolean shouldClearSubcheckerSharedCFGs = true;
/**
* Creates a type factory. Its compilation unit is not yet set.
*
* @param checker the checker to which this type factory belongs
* @param useFlow whether flow analysis should be performed
*/
protected GenericAnnotatedTypeFactory(BaseTypeChecker checker, boolean useFlow) {
super(checker);
this.everUseFlow = useFlow;
this.shouldDefaultTypeVarLocals = useFlow;
this.useFlow = useFlow;
this.variablesUnderInitialization = new HashSet<>();
this.scannedClasses = new HashMap<>();
this.flowResult = null;
this.regularExitStores = null;
this.exceptionalExitStores = null;
this.methodInvocationStores = null;
this.returnStatementStores = null;
this.initializationStore = null;
this.initializationStaticStore = null;
this.cfgVisualizer = createCFGVisualizer();
if (shouldCache) {
int cacheSize = getCacheSize();
flowResultAnalysisCaches = CollectionUtils.createLRUCache(cacheSize);
initializerCache = CollectionUtils.createLRUCache(cacheSize);
} else {
flowResultAnalysisCaches = null;
initializerCache = null;
}
RelevantJavaTypes relevantJavaTypesAnno =
checker.getClass().getAnnotation(RelevantJavaTypes.class);
if (relevantJavaTypesAnno == null) {
this.relevantJavaTypes = null;
this.arraysAreRelevant = true;
} else {
Types types = getChecker().getTypeUtils();
Elements elements = getElementUtils();
Class<?>[] classes = relevantJavaTypesAnno.value();
this.relevantJavaTypes = new HashSet<>(CollectionsPlume.mapCapacity(classes.length));
this.arraysAreRelevant = false;
for (Class<?> clazz : classes) {
if (clazz == Object[].class) {
arraysAreRelevant = true;
} else if (clazz.isArray()) {
throw new TypeSystemError(
"Don't use arrays other than Object[] in @RelevantJavaTypes on "
+ this.getClass().getSimpleName());
} else {
TypeMirror relevantType = TypesUtils.typeFromClass(clazz, types, elements);
relevantJavaTypes.add(types.erasure(relevantType));
}
}
}
contractsUtils = createContractsFromMethod();
hasOrIsSubchecker =
!this.getChecker().getSubcheckers().isEmpty()
|| this.getChecker().getParentChecker() != null;
// Every subclass must call postInit, but it must be called after
// all other initialization is finished.
}
@Override
protected void postInit() {
super.postInit();
this.dependentTypesHelper = createDependentTypesHelper();
this.defaults = createAndInitQualifierDefaults();
this.treeAnnotator = createTreeAnnotator();
this.typeAnnotator = createTypeAnnotator();
this.defaultQualifierForUseTypeAnnotator = createDefaultForUseTypeAnnotator();
this.defaultForTypeAnnotator = createDefaultForTypeAnnotator();
this.poly = createQualifierPolymorphism();
this.analysis = createFlowAnalysis();
this.transfer = analysis.getTransferFunction();
this.emptyStore = analysis.createEmptyStore(transfer.usesSequentialSemantics());
this.parseAnnotationFiles();
}
/**
* Performs flow-sensitive type refinement on {@code classTree} if this type factory is configured
* to do so.
*
* @param classTree tree on which to perform flow-sensitive type refinement
*/
@Override
public void preProcessClassTree(ClassTree classTree) {
if (this.everUseFlow) {
checkAndPerformFlowAnalysis(classTree);
}
}
/**
* Creates a type factory. Its compilation unit is not yet set.
*
* @param checker the checker to which this type factory belongs
*/
protected GenericAnnotatedTypeFactory(BaseTypeChecker checker) {
this(checker, flowByDefault);
}
@Override
public void setRoot(@Nullable CompilationUnitTree root) {
super.setRoot(root);
this.scannedClasses.clear();
this.flowResult = null;
this.regularExitStores = null;
this.exceptionalExitStores = null;
this.methodInvocationStores = null;
this.returnStatementStores = null;
this.initializationStore = null;
this.initializationStaticStore = null;
if (shouldCache) {
this.flowResultAnalysisCaches.clear();
this.initializerCache.clear();
this.defaultQualifierForUseTypeAnnotator.clearCache();
if (this.checker.getParentChecker() == null) {
// This is an ultimate parent checker, so after it runs the shared CFG it is using
// will no longer be needed, and can be cleared.
this.shouldClearSubcheckerSharedCFGs = true;
if (this.checker.getSubcheckers().isEmpty()) {
// If this checker has no subcheckers, then any maps that are currently
// being maintained should be cleared right away.
clearSharedCFG(this);
}
} else {
GenericAnnotatedTypeFactory<?, ?, ?, ?> ultimateParentATF =
this.checker.getUltimateParentChecker().getTypeFactory();
clearSharedCFG(ultimateParentATF);
}
}
}
/**
* Clears the caches associated with the shared CFG for the given type factory, if it is safe to
* do so.
*
* @param factory a type factory
*/
private void clearSharedCFG(GenericAnnotatedTypeFactory<?, ?, ?, ?> factory) {
if (factory.shouldClearSubcheckerSharedCFGs) {
// This is the first subchecker running in a group that share CFGs, so it must clear its
// ultimate parent's shared CFG before adding a new shared CFG.
factory.shouldClearSubcheckerSharedCFGs = false;
if (factory.subcheckerSharedCFG != null) {
factory.subcheckerSharedCFG.clear();
}
// The same applies to this map.
factory.artificialTreeToEnclosingElementMap.clear();
}
}
// **********************************************************************
// Factory Methods for the appropriate annotator classes
// **********************************************************************
/**
* Returns an immutable set of the <em>monotonic</em> type qualifiers supported by this checker.
*
* @return the monotonic type qualifiers supported this processor, or an empty set if none
* @see MonotonicQualifier
*/
public final Set<Class<? extends Annotation>> getSupportedMonotonicTypeQualifiers() {
if (supportedMonotonicQuals == null) {
supportedMonotonicQuals = new HashSet<>();
for (Class<? extends Annotation> anno : getSupportedTypeQualifiers()) {
MonotonicQualifier mono = anno.getAnnotation(MonotonicQualifier.class);
if (mono != null) {
supportedMonotonicQuals.add(anno);
}
}
}
return supportedMonotonicQuals;
}
/**
* Returns a {@link TreeAnnotator} that adds annotations to a type based on the contents of a
* tree.
*
* <p>The default tree annotator is a {@link ListTreeAnnotator} of the following:
*
* <ol>
* <li>{@link PropagationTreeAnnotator}: Propagates annotations from subtrees
* <li>{@link LiteralTreeAnnotator}: Adds annotations based on {@link QualifierForLiterals}
* meta-annotations
* <li>{@link DependentTypesTreeAnnotator}: Adapts dependent annotations based on context
* </ol>
*
* <p>Subclasses may override this method to specify additional tree annotators, for example:
*
* <pre>
* new ListTreeAnnotator(super.createTreeAnnotator(), new KeyLookupTreeAnnotator(this));
* </pre>
*
* @return a tree annotator
*/
protected TreeAnnotator createTreeAnnotator() {
List<TreeAnnotator> treeAnnotators = new ArrayList<>(2);
treeAnnotators.add(new PropagationTreeAnnotator(this));
treeAnnotators.add(new LiteralTreeAnnotator(this).addStandardLiteralQualifiers());
if (dependentTypesHelper.hasDependentAnnotations()) {
treeAnnotators.add(dependentTypesHelper.createDependentTypesTreeAnnotator());
}
return new ListTreeAnnotator(treeAnnotators);
}
/**
* Returns a {@link DefaultForTypeAnnotator} that adds annotations to a type based on the content
* of the type itself.
*
* <p>Subclass may override this method. The default type annotator is a {@link ListTypeAnnotator}
* of the following:
*
* <ol>
* <li>{@link IrrelevantTypeAnnotator}: Adds top to types not listed in the {@code @}{@link
* RelevantJavaTypes} annotation on the checker.
* <li>{@link PropagationTypeAnnotator}: Propagates annotation onto wildcards.
* </ol>
*
* @return a type annotator
*/
protected TypeAnnotator createTypeAnnotator() {
List<TypeAnnotator> typeAnnotators = new ArrayList<>(1);
if (relevantJavaTypes != null) {
typeAnnotators.add(
new IrrelevantTypeAnnotator(this, getQualifierHierarchy().getTopAnnotations()));
}
typeAnnotators.add(new PropagationTypeAnnotator(this));
return new ListTypeAnnotator(typeAnnotators);
}
/**
* Creates an {@link DefaultQualifierForUseTypeAnnotator}.
*
* @return a new {@link DefaultQualifierForUseTypeAnnotator}
*/
protected DefaultQualifierForUseTypeAnnotator createDefaultForUseTypeAnnotator() {
return new DefaultQualifierForUseTypeAnnotator(this);
}
/**
* Creates an {@link DefaultForTypeAnnotator}.
*
* @return a new {@link DefaultForTypeAnnotator}
*/
protected DefaultForTypeAnnotator createDefaultForTypeAnnotator() {
return new DefaultForTypeAnnotator(this);
}
/**
* Returns the {@link DefaultForTypeAnnotator}.
*
* @return the {@link DefaultForTypeAnnotator}
*/
public DefaultForTypeAnnotator getDefaultForTypeAnnotator() {
return defaultForTypeAnnotator;
}
/**
* Returns the appropriate flow analysis class that is used for the org.checkerframework.dataflow
* analysis.
*
* <p>This implementation uses the checker naming convention to create the appropriate analysis.
* If no transfer function is found, it returns an instance of {@link CFAnalysis}.
*
* <p>Subclasses have to override this method to create the appropriate analysis if they do not
* follow the checker naming convention.
*
* @return the appropriate flow analysis class that is used for the org.checkerframework.dataflow
* analysis
*/
@SuppressWarnings({"unchecked", "rawtypes"})
protected FlowAnalysis createFlowAnalysis() {
// Try to reflectively load the visitor.
Class<?> checkerClass = checker.getClass();
while (checkerClass != BaseTypeChecker.class) {
FlowAnalysis result =
BaseTypeChecker.invokeConstructorFor(
BaseTypeChecker.getRelatedClassName(checkerClass, "Analysis"),
new Class<?>[] {BaseTypeChecker.class, this.getClass(), List.class},
new Object[] {checker, this});
if (result != null) {
return result;
}
checkerClass = checkerClass.getSuperclass();
}
// If an analysis couldn't be loaded reflectively, return the default.
return (FlowAnalysis) new CFAnalysis(checker, (GenericAnnotatedTypeFactory) this);
}
/**
* Returns the appropriate transfer function that is used for the org.checkerframework.dataflow
* analysis.
*
* <p>This implementation uses the checker naming convention to create the appropriate transfer
* function. If no transfer function is found, it returns an instance of {@link CFTransfer}.
*
* <p>Subclasses have to override this method to create the appropriate transfer function if they
* do not follow the checker naming convention.
*/
// A more precise type for the parameter would be FlowAnalysis, which
// is the type parameter bounded by the current parameter type CFAbstractAnalysis<Value, Store,
// TransferFunction>.
// However, we ran into issues in callers of the method if we used that type.
public TransferFunction createFlowTransferFunction(
CFAbstractAnalysis<Value, Store, TransferFunction> analysis) {
// Try to reflectively load the visitor.
Class<?> checkerClass = checker.getClass();
while (checkerClass != BaseTypeChecker.class) {
TransferFunction result =
BaseTypeChecker.invokeConstructorFor(
BaseTypeChecker.getRelatedClassName(checkerClass, "Transfer"),
new Class<?>[] {analysis.getClass()},
new Object[] {analysis});
if (result != null) {
return result;
}
checkerClass = checkerClass.getSuperclass();
}
// If a transfer function couldn't be loaded reflectively, return the default.
@SuppressWarnings("unchecked")
TransferFunction ret =
(TransferFunction)
new CFTransfer((CFAbstractAnalysis<CFValue, CFStore, CFTransfer>) analysis);
return ret;
}
/**
* Creates a {@link DependentTypesHelper} and returns it. Use {@link #getDependentTypesHelper} to
* access the value.
*
* @return a new {@link DependentTypesHelper}
*/
protected DependentTypesHelper createDependentTypesHelper() {
return new DependentTypesHelper(this);
}
/**
* Returns the DependentTypesHelper.
*
* @return the DependentTypesHelper
*/
public DependentTypesHelper getDependentTypesHelper() {
return dependentTypesHelper;
}
/**
* Creates an {@link ContractsFromMethod} and returns it.
*
* @return a new {@link ContractsFromMethod}
*/
protected ContractsFromMethod createContractsFromMethod() {
return new ContractsFromMethod(this);
}
/**
* Returns the helper for method pre- and postconditions.
*
* @return the helper for method pre- and postconditions
*/
public ContractsFromMethod getContractsFromMethod() {
return contractsUtils;
}
@Override
protected List<AnnotatedTypeMirror> getExplicitNewClassClassTypeArgs(NewClassTree newClassTree) {
List<AnnotatedTypeMirror> superResult = super.getExplicitNewClassClassTypeArgs(newClassTree);
for (AnnotatedTypeMirror superR : superResult) {
dependentTypesHelper.atExpression(superR, newClassTree);
}
return superResult;
}
@Override
public Set<AnnotationMirror> getExplicitNewClassAnnos(NewClassTree newClassTree) {
Set<AnnotationMirror> superResult = super.getExplicitNewClassAnnos(newClassTree);
AnnotatedTypeMirror dummy = getAnnotatedNullType(superResult);
dependentTypesHelper.atExpression(dummy, newClassTree);
return dummy.getAnnotations();
}
/**
* Create {@link QualifierDefaults} which handles checker specified defaults, and initialize the
* created {@link QualifierDefaults}. Subclasses should override {@link
* GenericAnnotatedTypeFactory#addCheckedCodeDefaults(QualifierDefaults defs)} to add more
* defaults or use different defaults.
*
* @return the QualifierDefaults object
*/
// TODO: When changing this method, also look into
// {@link
// org.checkerframework.common.wholeprograminference.WholeProgramInferenceScenesHelper#shouldIgnore}.
// Both methods should have some functionality merged into a single location.
// See Issue 683
// https://github.com/typetools/checker-framework/issues/683
protected final QualifierDefaults createAndInitQualifierDefaults() {
QualifierDefaults defs = createQualifierDefaults();
addCheckedCodeDefaults(defs);
addCheckedStandardDefaults(defs);
addUncheckedStandardDefaults(defs);
checkForDefaultQualifierInHierarchy(defs);
return defs;
}
/**
* Create {@link QualifierDefaults} which handles checker specified defaults. Sub-classes override
* this method to provide a different {@code QualifierDefault} implementation.
*/
protected QualifierDefaults createQualifierDefaults() {
return new QualifierDefaults(elements, this);
}
/**
* Creates and returns a string containing the number of qualifiers and the canonical class names
* of each qualifier that has been added to this checker's supported qualifier set. The names are
* alphabetically sorted.
*
* @return a string containing the number of qualifiers and canonical names of each qualifier
*/
protected final String getSortedQualifierNames() {
Set<Class<? extends Annotation>> stq = getSupportedTypeQualifiers();
if (stq.isEmpty()) {
return "No qualifiers examined";
}
if (stq.size() == 1) {
return "1 qualifier examined: " + stq.iterator().next().getCanonicalName();
}
// Create a list of the supported qualifiers and sort the list alphabetically
List<Class<? extends Annotation>> sortedSupportedQuals = new ArrayList<>(stq);
sortedSupportedQuals.sort(Comparator.comparing(Class::getCanonicalName));
// display the number of qualifiers as well as the names of each qualifier.
StringJoiner sj =
new StringJoiner(", ", sortedSupportedQuals.size() + " qualifiers examined: ", "");
for (Class<? extends Annotation> qual : sortedSupportedQuals) {
sj.add(qual.getCanonicalName());
}
return sj.toString();
}
/**
* Adds default qualifiers for type-checked code by reading {@link DefaultFor} and {@link
* DefaultQualifierInHierarchy} meta-annotations. Subclasses may override this method to add
* defaults that cannot be specified with a {@link DefaultFor} or {@link
* DefaultQualifierInHierarchy} meta-annotations.
*
* @param defs QualifierDefault object to which defaults are added
*/
protected void addCheckedCodeDefaults(QualifierDefaults defs) {
// Add defaults from @DefaultFor and @DefaultQualifierInHierarchy
for (Class<? extends Annotation> qual : getSupportedTypeQualifiers()) {
DefaultFor defaultFor = qual.getAnnotation(DefaultFor.class);
if (defaultFor != null) {
final TypeUseLocation[] locations = defaultFor.value();
defs.addCheckedCodeDefaults(AnnotationBuilder.fromClass(elements, qual), locations);
}
if (qual.getAnnotation(DefaultQualifierInHierarchy.class) != null) {
defs.addCheckedCodeDefault(
AnnotationBuilder.fromClass(elements, qual), TypeUseLocation.OTHERWISE);
}
}
}
/**
* Adds the standard CLIMB defaults that do not conflict with previously added defaults.
*
* @param defs {@link QualifierDefaults} object to which defaults are added
*/
protected void addCheckedStandardDefaults(QualifierDefaults defs) {
if (this.everUseFlow) {
defs.addClimbStandardDefaults();
}
}
/**
* Adds standard unchecked defaults that do not conflict with previously added defaults.
*
* @param defs {@link QualifierDefaults} object to which defaults are added
*/
protected void addUncheckedStandardDefaults(QualifierDefaults defs) {
defs.addUncheckedStandardDefaults();
}
/**
* Check that a default qualifier (in at least one hierarchy) has been set and issue an error if
* not.
*
* @param defs {@link QualifierDefaults} object to which defaults are added
*/
protected void checkForDefaultQualifierInHierarchy(QualifierDefaults defs) {
if (!defs.hasDefaultsForCheckedCode()) {
throw new BugInCF(
"GenericAnnotatedTypeFactory.createQualifierDefaults: "
+ "@DefaultQualifierInHierarchy or @DefaultFor(TypeUseLocation.OTHERWISE) not found. "
+ "Every checker must specify a default qualifier. "
+ getSortedQualifierNames());
}
// If a default unchecked code qualifier isn't specified, the defaults
// for checked code will be used.
}
/**
* Creates the {@link QualifierPolymorphism} instance which supports the QualifierPolymorphism
* mechanism.
*
* @return the QualifierPolymorphism instance to use
*/
protected QualifierPolymorphism createQualifierPolymorphism() {
return new DefaultQualifierPolymorphism(processingEnv, this);
}
/**
* Gives the current {@link QualifierPolymorphism} instance which supports the
* QualifierPolymorphism mechanism.
*
* @return the QualifierPolymorphism instance to use
*/
public QualifierPolymorphism getQualifierPolymorphism() {
return this.poly;
}
// **********************************************************************
// Factory Methods for the appropriate annotator classes
// **********************************************************************
@Override
protected void postDirectSuperTypes(
AnnotatedTypeMirror type, List<? extends AnnotatedTypeMirror> supertypes) {
super.postDirectSuperTypes(type, supertypes);
if (type.getKind() == TypeKind.DECLARED) {
for (AnnotatedTypeMirror supertype : supertypes) {
Element elt = ((DeclaredType) supertype.getUnderlyingType()).asElement();
addComputedTypeAnnotations(elt, supertype);
}
}
}
/**
* Gets the type of the resulting constructor call of a MemberReferenceTree.
*
* @param memberReferenceTree MemberReferenceTree where the member is a constructor
* @param constructorType AnnotatedExecutableType of the declaration of the constructor
* @return AnnotatedTypeMirror of the resulting type of the constructor
*/
public AnnotatedTypeMirror getResultingTypeOfConstructorMemberReference(
MemberReferenceTree memberReferenceTree, AnnotatedExecutableType constructorType) {
assert memberReferenceTree.getMode() == MemberReferenceTree.ReferenceMode.NEW;
// The return type for constructors should only have explicit annotations from the
// constructor. Recreate some of the logic from TypeFromTree.visitNewClass here.
// The return type of the constructor will be the type of the expression of the member
// reference tree.
AnnotatedDeclaredType constructorReturnType =
(AnnotatedDeclaredType) fromTypeTree(memberReferenceTree.getQualifierExpression());
// Keep only explicit annotations and those from @Poly
AnnotatedTypes.copyOnlyExplicitConstructorAnnotations(
this, constructorReturnType, constructorType);
// Now add back defaulting.
addComputedTypeAnnotations(memberReferenceTree.getQualifierExpression(), constructorReturnType);
return constructorReturnType;
}
/**
* Returns the primary annotation on expression if it were evaluated at path.
*
* @param expression a Java expression
* @param tree current tree
* @param path location at which expression is evaluated
* @param clazz class of the annotation
* @return the annotation on expression or null if one does not exist
* @throws JavaExpressionParseException thrown if the expression cannot be parsed
*/
public AnnotationMirror getAnnotationFromJavaExpressionString(
String expression, Tree tree, TreePath path, Class<? extends Annotation> clazz)
throws JavaExpressionParseException {
JavaExpression expressionObj = parseJavaExpressionString(expression, path);
return getAnnotationFromJavaExpression(expressionObj, tree, clazz);
}
/**
* Returns the primary annotation on an expression, at a particular location.
*
* @param expr the expression for which the annotation is returned
* @param tree current tree
* @param clazz the Class of the annotation
* @return the annotation on expression or null if one does not exist
*/
public AnnotationMirror getAnnotationFromJavaExpression(
JavaExpression expr, Tree tree, Class<? extends Annotation> clazz) {
return getAnnotationByClass(getAnnotationsFromJavaExpression(expr, tree), clazz);
}
/**
* Returns the primary annotations on an expression, at a particular location.
*
* @param expr the expression for which the annotation is returned
* @param tree current tree
* @return the annotation on expression or null if one does not exist
*/
public Set<AnnotationMirror> getAnnotationsFromJavaExpression(JavaExpression expr, Tree tree) {
// Look in the store
if (CFAbstractStore.canInsertJavaExpression(expr)) {
Store store = getStoreBefore(tree);
// `store` can be null if the tree is in a field initializer.
if (store != null) {
Value value = store.getValue(expr);
if (value != null) {
// Is it possible that this lacks some annotations that appear in the type factory?
return value.getAnnotations();
}
}
}
// Look in the type factory, if not found in the store.
if (expr instanceof LocalVariable) {
Element ele = ((LocalVariable) expr).getElement();
// Because of
// https://github.com/eisop/checker-framework/issues/14
// and the workaround in
// org.checkerframework.framework.type.ElementAnnotationApplier.applyInternal
// The annotationMirror may not contain all explicitly written annotations.
return getAnnotatedType(ele).getAnnotations();
} else if (expr instanceof FieldAccess) {
Element ele = ((FieldAccess) expr).getField();
return getAnnotatedType(ele).getAnnotations();
} else {
return Collections.emptySet();
}
}
/**
* Produces the JavaExpression as if {@code expression} were written at {@code currentPath}.
*
* @param expression a Java expression
* @param currentPath the current path
* @return the JavaExpression associated with expression on currentPath
* @throws JavaExpressionParseException thrown if the expression cannot be parsed
*/
public JavaExpression parseJavaExpressionString(String expression, TreePath currentPath)
throws JavaExpressionParseException {
return StringToJavaExpression.atPath(expression, currentPath, checker);
}
/**
* Produces the JavaExpression and offset associated with an expression. For instance, "n+1" has
* no associated JavaExpression, but this method produces a pair of a JavaExpression (for "n") and
* an offset ("1").
*
* @param expression a Java expression, possibly with a constant offset
* @param currentPath location at which expression is evaluated
* @return the JavaExpression and offset for the given expression
* @throws JavaExpressionParseException thrown if the expression cannot be parsed
*/
public Pair<JavaExpression, String> getExpressionAndOffsetFromJavaExpressionString(
String expression, TreePath currentPath) throws JavaExpressionParseException {
Pair<String, String> p = getExpressionAndOffset(expression);
JavaExpression r = parseJavaExpressionString(p.first, currentPath);