forked from typetools/checker-framework-inference
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathVariableAnnotator.java
More file actions
1868 lines (1619 loc) · 80.4 KB
/
VariableAnnotator.java
File metadata and controls
1868 lines (1619 loc) · 80.4 KB
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 checkers.inference;
import com.sun.source.tree.AnnotatedTypeTree;
import com.sun.source.tree.ArrayTypeTree;
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IntersectionTypeTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.NewArrayTree;
import com.sun.source.tree.ParameterizedTypeTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.tree.TypeParameterTree;
import com.sun.source.tree.UnionTypeTree;
import com.sun.source.tree.VariableTree;
import com.sun.source.tree.WildcardTree;
import com.sun.source.util.TreePath;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.tree.JCTree;
import org.checkerframework.afu.scenelib.io.ASTIndex;
import org.checkerframework.afu.scenelib.io.ASTPath;
import org.checkerframework.afu.scenelib.io.ASTRecord;
import org.checkerframework.framework.type.AnnotatedTypeFactory;
import org.checkerframework.framework.type.AnnotatedTypeMirror;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedArrayType;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedDeclaredType;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedExecutableType;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedIntersectionType;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedNullType;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedPrimitiveType;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedTypeVariable;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedUnionType;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedWildcardType;
import org.checkerframework.framework.type.visitor.AnnotatedTypeScanner;
import org.checkerframework.javacutil.AnnotationBuilder;
import org.checkerframework.javacutil.AnnotationMirrorSet;
import org.checkerframework.javacutil.BugInCF;
import org.checkerframework.javacutil.ElementUtils;
import org.checkerframework.javacutil.TreePathUtil;
import org.checkerframework.javacutil.TreeUtils;
import org.checkerframework.javacutil.TypesUtils;
import org.plumelib.util.IPair;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Logger;
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.TypeParameterElement;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import checkers.inference.model.AnnotationLocation;
import checkers.inference.model.AnnotationLocation.AstPathLocation;
import checkers.inference.model.AnnotationLocation.ClassDeclLocation;
import checkers.inference.model.ConstantSlot;
import checkers.inference.model.ConstraintManager;
import checkers.inference.model.ExistentialVariableSlot;
import checkers.inference.model.Slot;
import checkers.inference.model.SourceVariableSlot;
import checkers.inference.model.VariableSlot;
import checkers.inference.model.tree.ArtificialExtendsBoundTree;
import checkers.inference.qual.VarAnnot;
import checkers.inference.util.ASTPathUtil;
import checkers.inference.util.CopyUtil;
import checkers.inference.util.InferenceUtil;
/**
* VariableAnnotator takes a type and the tree that the type represents. It determines what
* locations on the tree should contain a slot (i.e. locations over which we are doing inference).
* For each one of these locations it: 1. Checks to see if that tree has been given a VariableSlot
* previously, if so skip to 3 2. Creates the appropriate VariableSlot or ConstantSlot for the
* location 3. Adds an annotation representing that slot to the AnnotatedTypeMirror that corresponds
* to the given tree 4. Stores a mapping of tree -> VariableSlot for the given tree if it contains a
* VariableSlot
*/
public class VariableAnnotator extends AnnotatedTypeScanner<Void, Tree> {
private static final Logger logger = Logger.getLogger(VariableAnnotator.class.getName());
protected final InferenceAnnotatedTypeFactory inferenceTypeFactory;
protected final SlotManager slotManager;
// Variable Annotator needs this to create equality constraints for pre-annotated and
// implicit code
protected final ConstraintManager constraintManager;
/**
* Store the corresponding slot and annotation mirrors for each tree. The second parameter of
* pair is needed because sometimes the annotation mirror for a tree is calculated (i.e least
* upper bound for binary tree), and the calculated result is cached in the set.
*/
protected final Map<Tree, IPair<Slot, Set<? extends AnnotationMirror>>> treeToVarAnnoPair;
/** Store elements that have already been annotated * */
private final Map<Element, AnnotatedTypeMirror> elementToAtm;
private final Map<IPair<Integer, Integer>, ExistentialVariableSlot> idsToExistentialSlots;
private final AnnotatedTypeFactory realTypeFactory;
private final InferrableChecker realChecker;
// Keep a different store for each of the types of missing trees
// that we may need to find.
// The key is the most specific identifiable object.
/** Element is that class Element that we are storing. */
private final Map<Element, SourceVariableSlot> extendsMissingTrees;
/** Element is the method for the implicit receiver we are storing. */
private final Map<Element, AnnotatedTypeMirror> receiverMissingTrees;
/** Key is the NewArray Tree */
private final Map<Tree, AnnotatedArrayType> newArrayMissingTrees;
/** Class declarations may (or may not) have annotations that act as bound. */
private final Map<Element, Slot> classDeclAnnos;
/**
* When inferring the type of polymorphic qualifiers we create one new Variable to represent the
* call-site value of that qualifier. This map keeps track of methodCall -> variable created to
* represent Poly qualifiers See InferenceQualifierPolymorphism.
*/
private final Map<Tree, VariableSlot> treeToPolyVar;
// An instance of @VarAnnot
private final AnnotationMirror varAnnot;
// A single top in the target type system
private final AnnotationMirror realTop;
private final ExistentialVariableInserter existentialInserter;
private final ImpliedTypeAnnotator impliedTypeAnnotator;
public VariableAnnotator(
final InferenceAnnotatedTypeFactory typeFactory,
final AnnotatedTypeFactory realTypeFactory,
final InferrableChecker realChecker,
final SlotManager slotManager,
ConstraintManager constraintManager) {
this.realTypeFactory = realTypeFactory;
this.inferenceTypeFactory = typeFactory;
this.slotManager = slotManager;
this.treeToVarAnnoPair = new HashMap<>();
this.elementToAtm = new HashMap<>();
this.extendsMissingTrees = new HashMap<>();
this.receiverMissingTrees = new HashMap<>();
this.newArrayMissingTrees = new HashMap<>();
this.treeToPolyVar = new HashMap<>();
this.idsToExistentialSlots = new HashMap<>();
this.classDeclAnnos = new HashMap<>();
this.realChecker = realChecker;
this.constraintManager = constraintManager;
this.varAnnot =
new AnnotationBuilder(typeFactory.getProcessingEnv(), VarAnnot.class).build();
this.realTop =
realTypeFactory.getQualifierHierarchy().getTopAnnotations().iterator().next();
this.existentialInserter =
new ExistentialVariableInserter(
slotManager, constraintManager, this.realTop, varAnnot, this);
this.impliedTypeAnnotator =
new ImpliedTypeAnnotator(inferenceTypeFactory, slotManager, existentialInserter);
}
public static AnnotationLocation treeToLocation(AnnotatedTypeFactory typeFactory, Tree tree) {
final TreePath path = typeFactory.getPath(tree);
if (path == null) {
return AnnotationLocation.MISSING_LOCATION;
} // else
ASTPathUtil.getASTRecordForPath(typeFactory, path);
if (tree.getKind() == Kind.CLASS
|| tree.getKind() == Kind.INTERFACE
|| tree.getKind() == Kind.ENUM
|| tree.getKind() == Kind.ANNOTATION_TYPE) {
TypeElement typeElement = TreeUtils.elementFromDeclaration((ClassTree) tree);
return new ClassDeclLocation(((ClassSymbol) typeElement).flatName().toString());
} // else
ASTRecord record = ASTPathUtil.getASTRecordForPath(typeFactory, path);
if (record == null) {
return AnnotationLocation.MISSING_LOCATION;
}
return new AstPathLocation(record);
}
protected AnnotationLocation treeToLocation(Tree tree) {
return treeToLocation(inferenceTypeFactory, tree);
}
/**
* For each method call that uses a method with a polymorphic qualifier, we replace all uses of
* that polymorphic qualifier with a Variable. Sometimes we might have to later retrieve that
* qualifier for a given invocation tree. This method will return a previously created variable
* for a given invocation tree OR create a new one and return it, if we haven't created one for
* the given tree. see InferenceQualifierPolymorphism
*
* @return The Variable representing PolymorphicQualifier for the given tree
*/
public VariableSlot getOrCreatePolyVar(Tree tree) {
VariableSlot polyVar = treeToPolyVar.get(tree);
if (polyVar == null) {
polyVar =
slotManager.createPolymorphicInstanceSlot(
treeToLocation(tree), TreeUtils.typeOf(tree));
treeToPolyVar.put(tree, polyVar);
}
return polyVar;
}
/**
* Creates a variable for the given tree, adds it to the slotManager, and returns it. The only
* variables not created by this method should be those that are attached to an "implied tree",
* (e.g. the "extends Object" that is implied in the declaration class MyClass {}). In those
* cases the ASTPath should be created in the calling method and the createVariable(ASTPath
* astPat) method should be used.
*
* @param tree The tree to create a variable for. Tree will be converted to an ASTPath that will
* be passed to the created variable
* @return A new VariableSlot corresponding to tree
*/
private SourceVariableSlot createVariable(final Tree tree) {
final SourceVariableSlot varSlot =
createVariable(treeToLocation(tree), TreeUtils.typeOf(tree));
// if (path != null) {
// Element element = inferenceTypeFactory.getTreeUtils().getElement(path);
// if ( (!element.getKind().isClass() && element.getKind().isInterface() &&
// element.getKind().isField())) {
//
// }
// }
final IPair<Slot, Set<? extends AnnotationMirror>> varATMPair =
IPair.<Slot, Set<? extends AnnotationMirror>>of(varSlot, new AnnotationMirrorSet());
treeToVarAnnoPair.put(tree, varATMPair);
logger.fine("Created variable for tree:\n" + varSlot.getId() + " => " + tree);
return varSlot;
}
/**
* Creates a variable with the given ASTPath, adds it to the slotManager, and returns it. This
* method should be used ONLY for "implied trees". That is, locations that don't exist in the
* source code but are implied by other trees. The created variable is also added to the
* SlotManager (e.g. the "extends Object" bound that is implied by <T> in the declaration class
* MyClass<T> extends List<T>{}).
*
* @param location The path to the "missing tree". That is, the path to the parent tree with the
* path to the actual implied tree appended to it.
* @return A new VariableSlot corresponding to tree
*/
private SourceVariableSlot createVariable(final AnnotationLocation location, TypeMirror type) {
final SourceVariableSlot variableSlot =
slotManager.createSourceVariableSlot(location, type);
return variableSlot;
}
public ConstantSlot createConstant(final AnnotationMirror value, final Tree tree) {
final ConstantSlot constantSlot = slotManager.createConstantSlot(value);
// if (path != null) {
// Element element = inferenceTypeFactory.getTreeUtils().getElement(path);
// if ( (!element.getKind().isClass() && element.getKind().isInterface() &&
// element.getKind().isField())) {
//
// }
// }
Set<AnnotationMirror> annotations = new AnnotationMirrorSet();
annotations.add(constantSlot.getValue());
final IPair<Slot, Set<? extends AnnotationMirror>> varATMPair =
IPair.<Slot, Set<? extends AnnotationMirror>>of(constantSlot, annotations);
treeToVarAnnoPair.put(tree, varATMPair);
logger.fine("Created constant for tree:\n" + constantSlot.getId() + " => " + tree);
return constantSlot;
}
/**
* ExistentialVariableSlot are used when a constraint should appear in an ExistentialConstraint.
* Between two variable slots (a potential and alternative) we only ever need to create 1
* existential variable slot which we can then reuse.
*
* <p>If one does not already exist, this method creates an existential variable slot between
* potentialVariable and alternative and stores it. Otherwise, it returns the previously stored
* ExistentialVariableSlot
*
* <p>This method then applies the existential variable as a primary annotation on atm
*/
ExistentialVariableSlot getOrCreateExistentialVariable(
final AnnotatedTypeMirror atm,
final Slot potentialVariable,
final Slot alternativeSlot) {
ExistentialVariableSlot existentialVariable =
getOrCreateExistentialVariable(potentialVariable, alternativeSlot);
atm.replaceAnnotation(slotManager.getAnnotation(existentialVariable));
return existentialVariable;
}
/**
* ExistentialVariableSlot are used when a constraint should appear in an ExistentialConstraint.
* Between two variable slots (a potential and alternative) we only ever need to create 1
* existential variable slot which we can then reuse.
*
* <p>If one does not already exist, this method creates an existential variable slot between
* potentialVariable and alternative and stores it. Otherwise, it returns the previously stored
* ExistentialVariableSlot
*/
ExistentialVariableSlot getOrCreateExistentialVariable(
final Slot potentialVariable, final Slot alternativeSlot) {
final IPair<Integer, Integer> idPair =
IPair.of(potentialVariable.getId(), alternativeSlot.getId());
ExistentialVariableSlot existentialVariable = idsToExistentialSlots.get(idPair);
if (existentialVariable == null) {
existentialVariable =
slotManager.createExistentialVariableSlot(potentialVariable, alternativeSlot);
idsToExistentialSlots.put(idPair, existentialVariable);
} // else
return existentialVariable;
}
/**
* When getting trees to annotate types we sometimes need them from other compilation units
* (this occurs in calls to directSupertypes for instance). TypeFactory.getPath will NOT find
* these trees instead use getPath. Note, this call should not be made often since we do not
* cache any of the tree lookups and we re-traverse from the root everytime.
*/
public static TreePath expensiveBackupGetPath(
final Element element,
final Tree tree,
final InferenceAnnotatedTypeFactory inferenceTypeFactory) {
TypeElement typeElement = ElementUtils.enclosingTypeElement(element);
CompilationUnitTree compilationUnitTree =
inferenceTypeFactory.getTreeUtils().getPath(typeElement).getCompilationUnit();
return inferenceTypeFactory.getTreeUtils().getPath(compilationUnitTree, tree);
}
/**
* Adds existential variables to a USE of a type parameter. Note: See ExistentialVariableSlot
* for a key to the shorthand used below.
*
* <p>E.g. if we have a type parameter: {@code <@0 T extends @1 Object> } And we have a use of
* T: {@code T t; } Then the type of t should be: {@code <(@2 (@3 | @0)) T extends (@4 (@3
* | @1)) Object }
*
* @param typeVar A use of a type parameter
* @param tree The tree corresponding to the use of the type parameter
*/
private void addExistentialVariable(
final AnnotatedTypeVariable typeVar, final Tree tree, boolean isUpperBoundOfTypeParam) {
// TODO: THINK THROUGH POLY QUALS
// Leave polymorphic qualifiers on the type. They will be replaced during
// methodFromUse/constructorFromUse.
// if (typeVar.getAnnotations().size() > 0) {
// for (AnnotationMirror aa :
// typeVar.getAnnotations().iterator().next().getAnnotationType().asElement().getAnnotationMirrors()) {
// if
// (aa.getAnnotationType().toString().equals(PolymorphicQualifier.class.getCanonicalName()))
// {
// return;
// }
// }
// }
final Slot potentialVariable;
final Element varElem;
final Tree typeTree;
if (tree.getKind() == Kind.VARIABLE) {
varElem = TreeUtils.elementFromDeclaration((VariableTree) tree);
typeTree = ((VariableTree) tree).getType();
} else {
varElem = TreeUtils.elementFromUse((ExpressionTree) tree);
typeTree = tree;
}
final boolean isReturn;
if (tree.getKind() == Kind.IDENTIFIER) {
// so this can happen when we call direct supertypes on a type for which we have the
// class's source
// file. The tree here is a type variable in that file and therefore cannot be found
// from
// the root of the current compilation unit via the type factory.
TreePath pathToTree = inferenceTypeFactory.getPath(tree);
if (pathToTree == null) {
pathToTree =
expensiveBackupGetPath(varElem, tree, inferenceTypeFactory).getParentPath();
if (pathToTree == null) {
throw new BugInCF(
"Could not find path to tree: "
+ tree
+ "\n"
+ "typeVar="
+ typeVar
+ "\n"
+ "tree="
+ tree
+ "\n"
+ "isUpperBoundOfTypeParam="
+ isUpperBoundOfTypeParam);
}
}
// TODO: What if parent is ANNOTATED_TYPE
Tree parent = pathToTree.getParentPath().getLeaf();
isUpperBoundOfTypeParam |= isInUpperBound(pathToTree);
if (parent.getKind() == Tree.Kind.METHOD) {
isReturn = true;
} else {
isReturn = false;
}
} else {
isReturn = false;
}
// TODO: I think this was to guard against declarations getting here but I think
// TODO: we might want to remove this check and just always add them (because declarations
// shouldn't get here?)
if (elementToAtm.containsKey(varElem) && !isUpperBoundOfTypeParam && !isReturn) {
typeVar.clearAnnotations();
annotateElementFromStore(varElem, typeVar);
return;
}
AnnotationMirror explicitPrimary = null;
if (treeToVarAnnoPair.containsKey(typeTree)) {
potentialVariable = treeToVarAnnoPair.get(typeTree).first;
// might have a primary annotation lingering around
// (that would removed in the else clause)
typeVar.clearAnnotations();
} else {
// element from use and see if we already have this as a local var or field?
// if(tree.getKind() == ) // TODO: GOTTA FIGURE OUT IDENTIFIER STUFF
if (!typeVar.getAnnotations().isEmpty()) {
if (typeVar.getAnnotations().size() > 2) {
throw new BugInCF(
"There should be only 1 or 2 primary annotation on the typevar: \n"
+ "typeVar="
+ typeVar
+ "\n"
+ "tree="
+ tree
+ "\n");
}
typeVar.clearAnnotations();
}
potentialVariable = createVariable(typeTree);
final IPair<Slot, Set<? extends AnnotationMirror>> varATMPair =
IPair.<Slot, Set<? extends AnnotationMirror>>of(
potentialVariable, typeVar.getAnnotations());
treeToVarAnnoPair.put(typeTree, varATMPair);
// TODO: explicitPrimary is null at this point! Someone needs to set it.
if (explicitPrimary != null) {
constraintManager.addEqualityConstraint(
potentialVariable, slotManager.getSlot(explicitPrimary));
}
}
final Element typeVarDeclElem = typeVar.getUnderlyingType().asElement();
final AnnotatedTypeMirror typeVarDecl;
if (!elementToAtm.containsKey(typeVarDeclElem)) {
// e.g. <T extends E, E extends Object>
// TODO: THIS CRASHES ON RECURSIVE TYPES
typeVarDecl = inferenceTypeFactory.getAnnotatedType(typeVarDeclElem);
} else {
typeVarDecl = elementToAtm.get(typeVarDeclElem);
// TODO: I THINK THIS IS UNNECESSARY DUE TO InferenceVisitor.visitVariable
// if(tree instanceof VariableTree && !treeToVariable.containsKey(tree)) { //
// if it's a declaration of a variable, store it
// final Element varElement =
// TreeUtils.elementFromDeclaration((VariableTree) tree);
// storeElementType(varElement, typeVar);
// treeToVariable.put(tree, potentialVariable);
// }
}
existentialInserter.insert(potentialVariable, typeVar, typeVarDecl);
}
// TODO JB: I think this means we don't need the isUpperBoundOfTypeParam parameter above
private boolean isInUpperBound(TreePath path) {
TreePath parentPath = path;
Tree parent;
do {
parentPath = parentPath.getParentPath();
parent = parentPath.getLeaf();
if (parent.getKind() == Kind.TYPE_PARAMETER) {
return true;
}
} while (parent.getKind() == Kind.PARAMETERIZED_TYPE
|| parent.getKind() == Kind.ANNOTATED_TYPE);
return false;
}
/**
* If treeToVariable contains tree, add the stored variable as a primary annotation to atm If
* treeToVariable does not contain tree, create a new variable as a primary annotation to atm
*
* <p>If any annotation exist on Atm already create an EqualityConstraint between that
* annotation and the one added to atm. The original annotation is cleared from atm
*
* @param atm Annotation mirror representing tree, atm will have a VarAnnot as its primary
* annotation after this method completes
* @param tree Tree for which we want to create variables
*/
private Slot addPrimaryVariable(AnnotatedTypeMirror atm, final Tree tree) {
final Slot variable;
if (treeToVarAnnoPair.containsKey(tree)) {
variable = treeToVarAnnoPair.get(tree).first;
// The record will be null if we created a variable for a tree in a different
// compilation unit.
// When that compilation unit is visited we will be able to get the record.
if ((variable instanceof VariableSlot)
&& ((VariableSlot) variable).getLocation() == null) {
((VariableSlot) variable).setLocation(treeToLocation(tree));
}
} else {
AnnotationLocation location = treeToLocation(tree);
variable = replaceOrCreateEquivalentVarAnno(atm, tree, location);
MethodTree enclosingMethod =
TreePathUtil.enclosingMethod(inferenceTypeFactory.getPath(tree));
if (enclosingMethod != null && TreeUtils.isAnonymousConstructor(enclosingMethod)) {
// Slots created for anonymous constructors should not be inserted to source code
((SourceVariableSlot) variable).setInsertable(false);
}
final IPair<Slot, Set<? extends AnnotationMirror>> varATMPair =
IPair.of(variable, new AnnotationMirrorSet());
treeToVarAnnoPair.put(tree, varATMPair);
}
atm.removeAnnotationInHierarchy(realTop);
atm.replaceAnnotation(slotManager.getAnnotation(variable));
return variable;
}
/**
* If we have a tree to a type use that is implied, such as:{@code extends String } Create a
* variable for the primary annotation on the type. For the above example, the record argument
* would be an ASTRecord that points to the annotation @1 below: {@code extends @1 String }
*
* <p>We create a variable annotation for @1 and place it in the primary annotation position of
* the type.
*/
public SourceVariableSlot addImpliedPrimaryVariable(
AnnotatedTypeMirror atm, final AnnotationLocation location) {
SourceVariableSlot variable =
slotManager.createSourceVariableSlot(location, atm.getUnderlyingType());
atm.addAnnotation(slotManager.getAnnotation(variable));
AnnotationMirror realAnno = atm.getAnnotationInHierarchy(realTop);
if (realAnno != null) {
constraintManager.addEqualityConstraint(slotManager.getSlot(realAnno), variable);
}
logger.fine("Created implied variable for type:\n" + atm + " => " + location);
return variable;
}
/**
* Given an atm, replace its real annotation from pre-annotated code and implicit from the
* underlying type system by the equivalent varAnnotation, or creating a new VarAnnotation for
* it if doesn't have any existing annotations.
*/
private Slot replaceOrCreateEquivalentVarAnno(
AnnotatedTypeMirror atm, Tree tree, final AnnotationLocation location) {
Slot varSlot = null;
AnnotationMirror realQualifier = null;
AnnotationMirror existinVar = atm.getAnnotationInHierarchy(varAnnot);
if (existinVar != null) {
varSlot = slotManager.getSlot(atm);
} else if (!atm.getAnnotations().isEmpty()) {
realQualifier = atm.getAnnotationInHierarchy(realTop);
if (realQualifier == null) {
throw new BugInCF(
"The annotation(s) on the given type is neither VarAnno nor real qualifier!"
+ "Atm is: "
+ atm
+ " annotations: "
+ atm.getAnnotations());
}
varSlot = slotManager.createConstantSlot(realQualifier);
} else if (tree != null && realChecker.isConstant(tree)) {
// Considered constant by real type system
realQualifier =
realTypeFactory.getAnnotatedType(tree).getAnnotationInHierarchy(realTop);
varSlot = slotManager.createConstantSlot(realQualifier);
} else {
varSlot = createVariable(location, atm.getUnderlyingType());
}
if (realQualifier != null) {
// Remove the real qualifier in the atm, to make sure the source code
// is only annotated with @VarAnnot
atm.removeAnnotation(realQualifier);
}
atm.replaceAnnotation(slotManager.getAnnotation(varSlot));
return varSlot;
}
public ConstantSlot getTopConstant() {
return slotManager.createConstantSlot(realTop);
}
/**
* Stores the given AnnotatedTypeMirror with element as a key.
*
* @see checkers.inference.VariableAnnotator#annotateElementFromStore
*/
public void storeElementType(final Element element, final AnnotatedTypeMirror atm) {
elementToAtm.put(element, atm);
}
/**
* For the given tree, create or retrieve variable or constant annotations and place them on the
* AnnotatedDeclaredType. Note, often AnnotatedDeclaredTypes are associated with VariableTrees
* but they should NOT be passed as a tree here. Instead pass their identifier.
*
* @param adt A type to annotate
* @param tree A tree of kind: ANNOTATION_TYPE, CLASS, INTERFACE, ENUM, STRING_LITERAL,
* IDENTIFIER, ANNOTATED_TYPE, TYPE_PARAMETER, MEMBER_SELECT, PARAMETERIZED_TYPE
* @return null
*/
@Override
public Void visitDeclared(final AnnotatedDeclaredType adt, final Tree tree) {
if (tree instanceof BinaryTree) {
// Since there are so many kinds of binary trees
// handle these with an if instead of in the switch.
handleBinaryTree(adt, (BinaryTree) tree);
return null;
}
// TODO: For class declarations, create a map of classDecl -> ExistentialVariableAnnotator
// TODO: and make a constraint between it
switch (tree.getKind()) {
case ANNOTATION_TYPE:
case CLASS:
case INTERFACE:
case ENUM: // TODO: MORE TO DO HERE?
handleClassDeclaration(adt, (ClassTree) tree);
break;
case ANNOTATED_TYPE: // We need to do this for Identifiers that are
// already annotated.
case STRING_LITERAL:
case IDENTIFIER:
Slot primary = addPrimaryVariable(adt, tree);
handleWasRawDeclaredTypes(adt);
addDeclarationConstraints(getOrCreateDeclBound(adt), primary);
break;
case VARIABLE:
final Element varElement = TreeUtils.elementFromDeclaration((VariableTree) tree);
if (varElement.getKind() == ElementKind.ENUM_CONSTANT) {
AnnotatedTypeMirror realType = realTypeFactory.getAnnotatedType(tree);
CopyUtil.copyAnnotations(realType, adt);
inferenceTypeFactory.getConstantToVariableAnnotator().visit(adt);
} else {
// calls this method again but with a ParameterizedTypeTree
visitDeclared(adt, ((VariableTree) tree).getType());
}
break;
case TYPE_PARAMETER:
// TODO: I assume that the only way a TypeParameterTree is going to
// have an ADT as its
// TODO: AnnotatedTypeMirror is through either a
// getEffectiveAnnotation call or some other
// TODO: call that will treat the type parameter as it's upper bound
// but we should probably
// TODO: inspect this in order to have an idea of when this happens
final TypeParameterTree typeParamTree = (TypeParameterTree) tree;
if (typeParamTree.getBounds().isEmpty()) {
primary = addPrimaryVariable(adt, tree);
addDeclarationConstraints(getOrCreateDeclBound(adt), primary);
// TODO: HANDLE MISSING EXTENDS BOUND?
} else {
visit(adt, typeParamTree.getBounds().get(0));
}
break;
case MEMBER_SELECT:
primary = addPrimaryVariable(adt, tree);
// We only need to dive into the expression if it is not an
// identifier.
// Otherwise we may try to annotate the outer class for a
// Outer.Inner static class.
if (adt.getEnclosingType() != null
&& ((MemberSelectTree) tree).getExpression().getKind()
!= Tree.Kind.IDENTIFIER) {
visit(adt.getEnclosingType(), ((MemberSelectTree) tree).getExpression());
}
addDeclarationConstraints(getOrCreateDeclBound(adt), primary);
break;
case PARAMETERIZED_TYPE:
final ParameterizedTypeTree parameterizedTypeTree = (ParameterizedTypeTree) tree;
primary = addPrimaryVariable(adt, parameterizedTypeTree.getType());
// visit(adt, parameterizedTypeTree.getType());
AnnotatedDeclaredType newAdt = adt;
if (!handleWasRawDeclaredTypes(newAdt)
&& !parameterizedTypeTree.getTypeArguments().isEmpty()) {
if (TypesUtils.isAnonymous(newAdt.getUnderlyingType())) {
// There are multiple super classes for an anonymous class
// if the name following new keyword specifies an interface,
// and the anonymous class implements that interface and
// extends Object. In this case, we need the following for
// loop to find out the AnnotatedTypeMirror for the
// interface.
for (AnnotatedDeclaredType adtSuper : newAdt.directSupertypes()) {
if (TreeUtils.typeOf(parameterizedTypeTree)
.equals(adtSuper.getUnderlyingType())) {
newAdt = adtSuper;
}
}
}
final List<? extends Tree> treeArgs = parameterizedTypeTree.getTypeArguments();
final List<AnnotatedTypeMirror> typeArgs = newAdt.getTypeArguments();
if (treeArgs.size() != typeArgs.size()) {
throw new BugInCF(
"Raw type? Tree("
+ parameterizedTypeTree
+ "), Atm("
+ newAdt
+ ")");
}
for (int i = 0; i < typeArgs.size(); i++) {
final AnnotatedTypeMirror typeArg = typeArgs.get(i);
visit(typeArg, treeArgs.get(i));
}
}
addDeclarationConstraints(getOrCreateDeclBound(newAdt), primary);
break;
default:
throw new IllegalArgumentException(
"Unexpected tree type ( kind="
+ tree.getKind()
+ " tree= "
+ tree
+ " ) when visiting "
+ "AnnotatedDeclaredType( "
+ adt
+ " )");
}
return null;
}
protected boolean handleWasRawDeclaredTypes(AnnotatedDeclaredType adt) {
if (adt.isUnderlyingTypeRaw() && adt.getTypeArguments().size() != 0) {
// the type arguments should be wildcards AND if I get the real type of "tree"
// it corresponds to the declaration of adt.getUnderlyingType
Element declarationEle = adt.getUnderlyingType().asElement();
final AnnotatedDeclaredType declaration =
(AnnotatedDeclaredType) inferenceTypeFactory.getAnnotatedType(declarationEle);
final List<AnnotatedTypeMirror> declarationTypeArgs = declaration.getTypeArguments();
final List<AnnotatedTypeMirror> rawTypeArgs = adt.getTypeArguments();
for (int i = 0; i < declarationTypeArgs.size(); i++) {
final AnnotatedTypeVariable declArg =
(AnnotatedTypeVariable) declarationTypeArgs.get(i);
if (InferenceMain.isHackMode(rawTypeArgs.get(i).getKind() != TypeKind.WILDCARD)) {
return false;
}
final AnnotatedWildcardType rawArg = (AnnotatedWildcardType) rawTypeArgs.get(i);
rawArg.getExtendsBound()
.replaceAnnotation(
declArg.getUpperBound().getAnnotationInHierarchy(varAnnot));
rawArg.getSuperBound()
.replaceAnnotation(
declArg.getLowerBound().getAnnotationInHierarchy(varAnnot));
}
return true;
} else {
return false;
}
}
/**
* Handle implicit extends clauses and type parameters of the given class type and tree.
* Explicit extends and implements clauses are handled by {@link
* checkers.inference.InferenceAnnotatedTypeFactory#getTypeOfExtendsImplements}
*/
private void handleClassDeclaration(AnnotatedDeclaredType classType, ClassTree classTree) {
final Tree extendsTree = classTree.getExtendsClause();
if (extendsTree == null) {
// Annotated the implicit extends.
Element classElement = classType.getUnderlyingType().asElement();
SourceVariableSlot extendsSlot;
if (!extendsMissingTrees.containsKey(classElement)) {
// TODO: SEE COMMENT ON createImpliedExtendsLocation
AnnotationLocation location = createImpliedExtendsLocation(classTree);
extendsSlot = createVariable(location, classType.getUnderlyingType());
extendsMissingTrees.put(classElement, extendsSlot);
logger.fine(
"Created variable for implicit extends on class:\n"
+ extendsSlot.getId()
+ " => "
+ classElement
+ " (extends Object)");
} else {
// Add annotation
extendsSlot = extendsMissingTrees.get(classElement);
}
List<AnnotatedDeclaredType> superTypes = classType.directSupertypes();
superTypes.get(0).replaceAnnotation(slotManager.getAnnotation(extendsSlot));
}
if (InferenceMain.isHackMode(
(classType.getTypeArguments().size() != classTree.getTypeParameters().size()))) {
return;
}
visitTogether(classType.getTypeArguments(), classTree.getTypeParameters());
Slot varSlot = getOrCreateDeclBound(classType);
classType.removeAnnotationInHierarchy(realTop);
classType.replaceAnnotation(slotManager.getAnnotation(varSlot));
// before we were relying on trees but the ClassTree has it's type args erased
// when the compiler moves on to the next class
Element classElement = classType.getUnderlyingType().asElement();
storeElementType(classElement, classType);
}
/**
* I BELIEVE THIS METHOD IS NO LONGER NEEDED BECAUSE WE DON'T HAVE SEMANTICS FOR the extends
* LOCATION ON A CLASS IN THE CHECKER FRAMEWORK. Mike Ernst, Javier Thaine, Werner Deitl, and
* Suzanne Millstein have an email entitled "Annotation on Class Name" that covers this. But the
* gist is, Werner does not see the need for an annotation on the extends bound and we currently
* have no semantics for it.
*
* <p>Note, if we have on on the extends bound, you can also have one on every implemented
* interface. Which are other locations we don't have sematnics for.
*/
private AnnotationLocation createImpliedExtendsLocation(ClassTree classTree) {
// TODO: THIS CAN BE CREATED ONCE THIS IS FIXED:
// https://github.com/typetools/annotation-tools/issues/100
InferenceMain.getInstance()
.logger
.warning(
"Hack:VariableAnnotator::createImpliedExtendsLocation(classTree) not implemented");
return AnnotationLocation.MISSING_LOCATION;
}
/**
* Creates an AnnotationLocation that represents the implied (missing bound) on a type parameter
* that extends object. E.g. {@code <T> } the "extends Object" on T is implied but not written.
*/
private AnnotationLocation createImpliedExtendsLocation(TypeParameterTree typeParamTree) {
AnnotationLocation parentLoc = treeToLocation(typeParamTree);
AnnotationLocation result;
switch (parentLoc.getKind()) {
case AST_PATH:
ASTRecord parent = ((AstPathLocation) parentLoc).getAstRecord();
result = new AstPathLocation(parent.extend(Kind.TYPE_PARAMETER, "bound", 0));
break;
case MISSING:
result = AnnotationLocation.MISSING_LOCATION;
break;
default:
throw new RuntimeException(
"Unexpected location "
+ parentLoc.getKind()
+ " location kind for tree:\n"
+ typeParamTree);
}
return result;
}
/**
* Visit each bound on the intersection type
*
* @param intersectionType type to annotate
* @param tree An AnnotatedIntersectionTypeTree, an IllegalArgumentException will be thrown
* otherwise
* @return null
*/
@Override
public Void visitIntersection(AnnotatedIntersectionType intersectionType, Tree tree) {
if (InferenceMain.isHackMode(!(tree instanceof IntersectionTypeTree))) {
return null;
}
// TODO: THERE ARE PROBABLY INSTANCES OF THIS THAT I DON'T KNOW ABOUT, CONSULT WERNER
// TODO: AND DO GENERAL TESTING/THINKING ABOUT WHAT WE WANT TO DO WITH INTERSECTIONS
switch (tree.getKind()) {
case INTERSECTION_TYPE:
assert ((IntersectionTypeTree) tree).getBounds().size()
== intersectionType.directSupertypes().size();
visitTogether(
intersectionType.directSupertypes(),
((IntersectionTypeTree) tree).getBounds());
break;
case TYPE_PARAMETER:
assert ((TypeParameterTree) tree).getBounds().size()
== intersectionType.directSupertypes().size();
visitTogether(
intersectionType.directSupertypes(),
((TypeParameterTree) tree).getBounds());
break;
// TODO: IN JAVA 8, LAMBDAS CAN HAVE INTERSECTION ARGUMENTS
default:
InferenceUtil.testArgument(
false,
"Unexpected tree type ( "
+ tree
+ " ) when visiting AnnotatedIntersectionType( "
+ intersectionType
+ " )");
}
// TODO: So in Java 8 the Ast the "A & B" tree in T extends A & B is an IntersectionTypeTree
// TODO: but there are also casts of type (A & B) I believe
// visitTogether(intersectionType.directSuperTypes(), ((IntersectionTypeTree)
// tree).getBounds());
return null;
}
/**
* Visit each alternative in the union type
*
* @param unionType type to be annotated
* @param tree must be a UnionTypeTree
* @return null
*/
@Override
public Void visitUnion(final AnnotatedUnionType unionType, final Tree tree) {
InferenceUtil.testArgument(
tree instanceof UnionTypeTree || tree instanceof VariableTree,
"Unexpected tree type ( " + tree + " ) for AnnotatedUnionType (" + unionType + ")");
UnionTypeTree unionTree;
if (tree instanceof VariableTree) {
VariableTree varTree = (VariableTree) tree;
Tree typeTree = varTree.getType();
InferenceUtil.testArgument(