forked from typetools/checker-framework-inference
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathInferenceVisitor.java
More file actions
1147 lines (1035 loc) · 49.4 KB
/
InferenceVisitor.java
File metadata and controls
1147 lines (1035 loc) · 49.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.CatchTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.ThrowTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreePath;
import org.checkerframework.checker.compilermsgs.qual.CompilerMessageKey;
import org.checkerframework.common.basetype.BaseAnnotatedTypeFactory;
import org.checkerframework.common.basetype.BaseTypeVisitor;
import org.checkerframework.common.subtyping.qual.Unqualified;
import org.checkerframework.framework.qual.TargetLocations;
import org.checkerframework.framework.qual.TypeUseLocation;
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.AnnotatedTypeVariable;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedUnionType;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedWildcardType;
import org.checkerframework.framework.type.AnnotatedTypeParameterBounds;
import org.checkerframework.framework.util.AnnotatedTypes;
import org.checkerframework.javacutil.*;
import org.checkerframework.javacutil.TreeUtils;
import org.plumelib.util.ArraysPlume;
import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
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.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import checkers.inference.model.ConstantSlot;
import checkers.inference.model.ConstraintManager;
import checkers.inference.model.RefinementVariableSlot;
import checkers.inference.model.Slot;
import checkers.inference.model.VariableSlot;
import checkers.inference.qual.VarAnnot;
import checkers.inference.util.InferenceUtil;
/**
* InferenceVisitor visits trees in each compilation unit both in typecheck/inference mode. In
* typecheck mode, it functions nearly identically to BaseTypeVisitor, i.e. it enforces common
* assignment and other checks. However, it also defines a new API that may be more intuitive for
* checker writers (see mainIsNot).
*
* <p>InferneceVisitor has an "infer" flag which indicates whether or not it is in typecheck or in
* inference mode. When true, this class replaces type checks with constraint generation.
*
* <p>InferneceVisitor is intended to replace BaseTypeVisitor. That is, the methods from
* BaseTypeVisiotr should be migrated here and InferenceVisitor should replace it in the Visitor
* hierarchy.
*/
// TODO(Zhiping): new logics from BaseTypeVisitor should be migrated here
public class InferenceVisitor<
Checker extends InferenceChecker, Factory extends BaseAnnotatedTypeFactory>
extends BaseTypeVisitor<Factory> {
private static final Logger logger = Logger.getLogger(InferenceVisitor.class.getName());
/* One design alternative would have been to use two separate subclasses instead of the boolean.
* However, this separates the inference and checking implementation of a method.
* Using the boolean, the two implementations are closer together.
*
*/
protected final boolean infer;
protected final Checker realChecker;
/*
* Map from type-use location to a list of qualifiers which cannot be used on that location.
* This is used to create the inequality constraint in inference.
*/
protected final Map<TypeUseLocation, AnnotationMirrorSet> locationToIllegalQuals;
public InferenceVisitor(
Checker checker, InferenceChecker ichecker, Factory factory, boolean infer) {
super((infer) ? ichecker : checker, factory);
this.realChecker = checker;
this.infer = infer;
((InferenceValidator) typeValidator).setInfer(infer);
locationToIllegalQuals = createMapForIllegalQuals();
}
@SuppressWarnings("unchecked")
@Override
protected Factory createTypeFactory() {
return (Factory) ((BaseInferrableChecker) checker).getTypeFactory();
}
@Override
public void visit(TreePath path) {
if (infer) {
final SlotManager slotManager = InferenceMain.getInstance().getSlotManager();
slotManager.setTopLevelClass((ClassTree) path.getLeaf());
}
super.visit(path);
}
public void doesNotContain(
AnnotatedTypeMirror ty, AnnotationMirror mod, String msgkey, Tree node) {
doesNotContain(ty, new AnnotationMirror[] {mod}, msgkey, node);
}
public void doesNotContain(
AnnotatedTypeMirror ty, AnnotationMirror[] mods, String msgkey, Tree node) {
if (infer) {
doesNotContainInfer(ty, mods, node);
} else {
for (AnnotationMirror mod : mods) {
if (AnnotatedTypes.containsModifier(ty, mod)) {
checker.reportError(
node,
msgkey,
ty.getAnnotations().toString(),
ty.toString(),
node.toString());
}
}
}
}
private void doesNotContainInfer(AnnotatedTypeMirror ty, AnnotationMirror[] mods, Tree node) {
doesNotContainInferImpl(ty, mods, new java.util.LinkedList<AnnotatedTypeMirror>(), node);
}
private void doesNotContainInferImpl(
AnnotatedTypeMirror ty,
AnnotationMirror[] mods,
java.util.List<AnnotatedTypeMirror> visited,
Tree node) {
if (visited.contains(ty)) {
return;
}
visited.add(ty);
final SlotManager slotManager = InferenceMain.getInstance().getSlotManager();
Slot el = slotManager.getSlot(ty);
if (el == null) {
// TODO: prims not annotated in UTS, others might
logger.warning("InferenceVisitor::doesNotContain: no annotation in type: " + ty);
} else {
if (!InferenceMain.getInstance().isPerformingFlow()) {
logger.fine(
"InferenceVisitor::doesNotContain: Inequality constraint constructor invocation(s).");
}
ConstraintManager cm = InferenceMain.getInstance().getConstraintManager();
for (AnnotationMirror mod : mods) {
// TODO: are Constants compared correctly???
cm.addInequalityConstraint(el, slotManager.getSlot(mod));
}
}
if (ty.getKind() == TypeKind.DECLARED) {
AnnotatedDeclaredType declaredType = (AnnotatedDeclaredType) ty;
for (AnnotatedTypeMirror typearg : declaredType.getTypeArguments()) {
doesNotContainInferImpl(typearg, mods, visited, node);
}
} else if (ty.getKind() == TypeKind.ARRAY) {
AnnotatedArrayType arrayType = (AnnotatedArrayType) ty;
doesNotContainInferImpl(arrayType.getComponentType(), mods, visited, node);
} else if (ty.getKind() == TypeKind.TYPEVAR) {
AnnotatedTypeVariable atv = (AnnotatedTypeVariable) ty;
if (atv.getUpperBound() != null) {
doesNotContainInferImpl(atv.getUpperBound(), mods, visited, node);
}
if (atv.getLowerBound() != null) {
doesNotContainInferImpl(atv.getLowerBound(), mods, visited, node);
}
}
}
private AnnotationMirror findEffectiveAnnotation(
AnnotatedTypeMirror type, AnnotationMirror target) {
if (infer) {
AnnotationMirror varAnnot =
((InferenceAnnotatedTypeFactory) atypeFactory).getVarAnnot();
return AnnotatedTypes.findEffectiveAnnotationInHierarchy(
atypeFactory.getQualifierHierarchy(),
type,
varAnnot,
InferenceMain.isHackMode());
}
return AnnotatedTypes.findEffectiveAnnotationInHierarchy(
atypeFactory.getQualifierHierarchy(), type, target, InferenceMain.isHackMode());
}
private AnnotationMirror findMainAnnotation(AnnotatedTypeMirror type, AnnotationMirror target) {
if (infer) {
AnnotationMirror varAnnot =
((InferenceAnnotatedTypeFactory) atypeFactory).getVarAnnot();
return type.getAnnotationInHierarchy(varAnnot);
}
return type.getAnnotationInHierarchy(target);
}
public void effectiveIs(
AnnotatedTypeMirror ty, AnnotationMirror mod, String msgkey, Tree node) {
AnnotationMirror effective = findEffectiveAnnotation(ty, mod);
if (InferenceMain.isHackMode(effective == null)) {
return;
}
annoIs(ty, effective, mod, msgkey, node);
}
public void effectiveIsNot(
AnnotatedTypeMirror ty, AnnotationMirror mod, String msgkey, Tree node) {
AnnotationMirror effective = findEffectiveAnnotation(ty, mod);
annoIsNot(ty, effective, mod, msgkey, node);
}
public void mainIs(AnnotatedTypeMirror ty, AnnotationMirror mod, String msgkey, Tree node) {
AnnotationMirror main = findMainAnnotation(ty, mod);
if (InferenceMain.isHackMode(main == null)) {
return;
}
annoIs(ty, main, mod, msgkey, node);
}
public void mainIsSubtype(
AnnotatedTypeMirror ty, AnnotationMirror mod, String msgkey, Tree node) {
if (infer) {
final SlotManager slotManager = InferenceMain.getInstance().getSlotManager();
Slot el = slotManager.getSlot(ty);
if (el == null) {
// TODO: prims not annotated in UTS, others might
logger.warning("InferenceVisitor::mainIs: no annotation in type: " + ty);
} else {
if (!InferenceMain.getInstance().isPerformingFlow()) {
logger.fine(
"InferenceVisitor::mainIs: Subtype constraint constructor invocation(s).");
InferenceMain.getInstance()
.getConstraintManager()
.addSubtypeConstraint(el, slotManager.getSlot(mod));
}
}
} else {
if (!ty.hasEffectiveAnnotation(mod)) {
checker.reportError(
node,
msgkey,
ty.getAnnotations().toString(),
ty.toString(),
node.toString());
}
}
}
public void mainIsNot(AnnotatedTypeMirror ty, AnnotationMirror mod, String msgkey, Tree node) {
mainIsNoneOf(ty, new AnnotationMirror[] {mod}, msgkey, node);
}
public void mainIsNoneOf(
AnnotatedTypeMirror ty, AnnotationMirror[] mods, String msgkey, Tree node) {
if (infer) {
final SlotManager slotManager = InferenceMain.getInstance().getSlotManager();
Slot el = slotManager.getSlot(ty);
if (el == null) {
// TODO: prims not annotated in UTS, others might
logger.warning("InferenceVisitor::isNoneOf: no annotation in type: " + ty);
} else {
if (!InferenceMain.getInstance().isPerformingFlow()) {
logger.fine(
"InferenceVisitor::mainIsNoneOf: Inequality constraint constructor invocation(s).");
for (AnnotationMirror mod : mods) {
InferenceMain.getInstance()
.getConstraintManager()
.addInequalityConstraint(el, slotManager.getSlot(mod));
}
}
}
} else {
for (AnnotationMirror mod : mods) {
if (ty.hasEffectiveAnnotation(mod)) {
checker.reportError(
node,
msgkey,
ty.getAnnotations().toString(),
ty.toString(),
node.toString());
}
}
}
}
private void addDeepPreferenceImpl(
AnnotatedTypeMirror ty,
AnnotationMirror goal,
int weight,
java.util.List<AnnotatedTypeMirror> visited,
Tree node) {
if (infer) {
if (visited.contains(ty)) {
return;
}
visited.add(ty);
final SlotManager slotManager = InferenceMain.getInstance().getSlotManager();
Slot el = slotManager.getSlot(ty);
if (el == null) {
logger.warning(
"InferenceVisitor::addDeepPreferenceImpl: no annotation in type: " + ty);
} else {
addPreference(ty, goal, weight);
}
if (ty.getKind() == TypeKind.DECLARED) {
AnnotatedDeclaredType declaredType = (AnnotatedDeclaredType) ty;
for (AnnotatedTypeMirror typearg : declaredType.getTypeArguments()) {
addDeepPreferenceImpl(typearg, goal, weight, visited, node);
}
} else if (ty.getKind() == TypeKind.ARRAY) {
AnnotatedArrayType arrayType = (AnnotatedArrayType) ty;
addDeepPreferenceImpl(arrayType.getComponentType(), goal, weight, visited, node);
} else if (ty.getKind() == TypeKind.TYPEVAR) {
AnnotatedTypeVariable atv = (AnnotatedTypeVariable) ty;
addDeepPreferenceImpl(atv.getUpperBound(), goal, weight, visited, node);
addDeepPreferenceImpl(atv.getLowerBound(), goal, weight, visited, node);
}
}
// Else, do nothing
}
public void addDeepPreference(
AnnotatedTypeMirror ty, AnnotationMirror goal, int weight, Tree node) {
addDeepPreferenceImpl(ty, goal, weight, new LinkedList<>(), node);
}
public void addPreference(AnnotatedTypeMirror type, AnnotationMirror anno, int weight) {
if (infer) {
ConstraintManager cManager = InferenceMain.getInstance().getConstraintManager();
SlotManager sManager = InferenceMain.getInstance().getSlotManager();
Slot vSlot = sManager.getSlot(type);
if (vSlot instanceof ConstantSlot) {
throw new BugInCF("Trying to add Preference to a constant target: " + vSlot);
}
ConstantSlot cSlot =
InferenceMain.getInstance().getSlotManager().createConstantSlot(anno);
cManager.addPreferenceConstraint((VariableSlot) vSlot, cSlot, weight);
}
// Nothing to do in type check mode.
}
protected void annoIs(
AnnotatedTypeMirror sourceType,
AnnotationMirror effectiveAnno,
AnnotationMirror target,
String msgKey,
Tree node) {
if (infer) {
final SlotManager slotManager = InferenceMain.getInstance().getSlotManager();
Slot el = slotManager.getSlot(effectiveAnno);
if (el == null) {
// TODO: prims not annotated in UTS, others might
logger.warning("InferenceVisitor::mainIs: no annotation in type: " + sourceType);
} else {
if (!InferenceMain.getInstance().isPerformingFlow()) {
logger.fine(
"InferenceVisitor::mainIs: Equality constraint constructor invocation(s).");
InferenceMain.getInstance()
.getConstraintManager()
.addEqualityConstraint(el, slotManager.getSlot(target));
}
}
} else {
if (!AnnotationUtils.areSame(effectiveAnno, target)) {
checker.reportError(
node, msgKey, effectiveAnno, sourceType.toString(), node.toString());
}
}
}
protected void annoIsNot(
AnnotatedTypeMirror sourceType,
AnnotationMirror effectiveAnno,
AnnotationMirror target,
String msgKey,
Tree node) {
annoIsNoneOf(sourceType, effectiveAnno, new AnnotationMirror[] {target}, msgKey, node);
}
public void annoIsNoneOf(
AnnotatedTypeMirror sourceType,
AnnotationMirror effectiveAnno,
AnnotationMirror[] targets,
String msgKey,
Tree node) {
if (infer) {
final SlotManager slotManager = InferenceMain.getInstance().getSlotManager();
Slot el = slotManager.getSlot(effectiveAnno);
if (el == null) {
// TODO: prims not annotated in UTS, others might
logger.warning(
"InferenceVisitor::isNoneOf: no annotation in type: "
+ Arrays.toString(targets));
} else {
if (!InferenceMain.getInstance().isPerformingFlow()) {
logger.fine(
"InferenceVisitor::mainIsNoneOf: Inequality constraint constructor invocation(s).");
for (AnnotationMirror mod : targets) {
InferenceMain.getInstance()
.getConstraintManager()
.addInequalityConstraint(el, slotManager.getSlot(mod));
}
}
}
} else {
for (AnnotationMirror target : targets) {
if (AnnotationUtils.areSame(target, effectiveAnno)) {
checker.reportError(
node, msgKey, effectiveAnno, sourceType.toString(), node.toString());
}
}
}
}
public void areComparable(
AnnotatedTypeMirror ty1, AnnotatedTypeMirror ty2, String msgkey, Tree node) {
if (infer) {
final SlotManager slotManager = InferenceMain.getInstance().getSlotManager();
Slot el1 = slotManager.getSlot(ty1);
Slot el2 = slotManager.getSlot(ty2);
if (el1 == null || el2 == null) {
// TODO: prims not annotated in UTS, others might
logger.warning(
"InferenceVisitor::areComparable: no annotation on type: "
+ ty1
+ " or "
+ ty2);
} else {
if (!InferenceMain.getInstance().isPerformingFlow()) {
logger.fine(
"InferenceVisitor::areComparable: Comparable constraint constructor invocation.");
InferenceMain.getInstance()
.getConstraintManager()
.addComparableConstraint(el1, el2);
}
}
} else {
if (!(atypeFactory.getTypeHierarchy().isSubtype(ty1, ty2)
|| atypeFactory.getTypeHierarchy().isSubtype(ty2, ty1))) {
checker.reportError(node, msgkey, ty1.toString(), ty2.toString(), node.toString());
}
}
}
public void areEqual(
AnnotatedTypeMirror ty1, AnnotatedTypeMirror ty2, String msgkey, Tree node) {
if (infer) {
final SlotManager slotManager = InferenceMain.getInstance().getSlotManager();
Slot el1 = slotManager.getSlot(ty1);
Slot el2 = slotManager.getSlot(ty2);
if (el1 == null || el2 == null) {
// TODO: prims not annotated in UTS, others might
logger.warning(
"InferenceVisitor::areEqual: no annotation on type: " + ty1 + " or " + ty2);
} else {
if (!InferenceMain.getInstance().isPerformingFlow()) {
logger.fine(
"InferenceVisitor::areEqual: Equality constraint constructor invocation.");
InferenceMain.getInstance()
.getConstraintManager()
.addEqualityConstraint(el1, el2);
}
}
} else {
if (!ty1.equals(ty2)) {
checker.reportError(node, msgkey, ty1.toString(), ty2.toString(), node.toString());
}
}
}
@Override
protected void checkTypeArguments(
Tree toptree,
List<? extends AnnotatedTypeParameterBounds> paramBounds,
List<? extends AnnotatedTypeMirror> typeargs,
List<? extends Tree> typeargTrees,
CharSequence typeOrMethodName,
List<?> paramNames) {
// System.out.printf("BaseTypeVisitor.checkTypeArguments: %s, TVs: %s, TAs: %s, TATs: %s\n",
// toptree, paramBounds, typeargs, typeargTrees);
// If there are no type variables, do nothing.
if (paramBounds.isEmpty()) {
return;
}
int size = paramBounds.size();
assert size == typeargs.size()
: "BaseTypeVisitor.checkTypeArguments: mismatch between type arguments: "
+ typeargs
+ " and type parameter bounds"
+ paramBounds;
for (int i = 0; i < size; i++) {
AnnotatedTypeParameterBounds bounds = paramBounds.get(i);
AnnotatedTypeMirror typeArg = typeargs.get(i);
Object curParamName = paramNames.get(i);
AnnotatedTypeMirror varUpperBound = bounds.getUpperBound();
final AnnotatedTypeMirror typeArgForUpperBoundCheck = typeArg;
if (typeArg.getKind() == TypeKind.WILDCARD) {
if (bounds.getUpperBound().getKind() == TypeKind.WILDCARD) {
// TODO: When capture conversion is implemented, this special case should be
// removed.
// TODO: This may not occur only in places where capture conversion occurs but
// in those cases
// TODO: The containment check provided by this method should be enough
continue;
}
// If we have a declaration:
// class MyClass<T extends String> ...
//
// the javac compiler allows wildcard type arguments that have Java types OUTSIDE of
// the
// bounds of T, i.e:
// MyClass<? extends Object>
//
// This is sound because every NON-WILDCARD reference to MyClass MUST obey those
// bounds
// This leads to cases where varUpperBound is actually a subtype of
// typeArgForUpperBoundCheck
final TypeMirror varUnderlyingUb = varUpperBound.getUnderlyingType();
final TypeMirror argUnderlyingUb =
((AnnotatedWildcardType) typeArg).getExtendsBound().getUnderlyingType();
if (!types.isSubtype(argUnderlyingUb, varUnderlyingUb)
&& types.isSubtype(varUnderlyingUb, argUnderlyingUb)) {
varUpperBound =
AnnotatedTypes.asSuper(
atypeFactory, varUpperBound, typeArgForUpperBoundCheck);
}
}
if (typeargTrees == null || typeargTrees.isEmpty()) {
// The type arguments were inferred and we mark the whole method.
// The inference fails if we provide invalid arguments,
// therefore issue an error for the arguments.
// I hope this is less confusing for users.
commonAssignmentCheck(
varUpperBound,
typeArg,
toptree,
"type.argument.type.incompatible",
curParamName,
typeOrMethodName);
} else {
commonAssignmentCheck(
varUpperBound,
typeArg,
typeargTrees.get(typeargs.indexOf(typeArg)),
"type.argument.type.incompatible",
curParamName,
typeOrMethodName);
}
if (!atypeFactory.getTypeHierarchy().isSubtype(bounds.getLowerBound(), typeArg)) {
if (typeargTrees == null || typeargTrees.isEmpty()) {
// The type arguments were inferred and we mark the whole method.
checker.reportError(
toptree,
"type.argument.type.incompatible",
curParamName,
typeOrMethodName,
typeArg,
bounds);
} else {
checker.reportError(
typeargTrees.get(typeargs.indexOf(typeArg)),
"type.argument.type.incompatible",
curParamName,
typeOrMethodName,
typeArg,
bounds);
}
}
}
}
/**
* Checks the validity of an assignment (or pseudo-assignment) from a value to a variable and
* emits an error message (through the compiler's messaging interface) if it is not valid.
*
* @param varTree the AST node for the variable
* @param valueExp the AST node for the value
* @param errorKey the error message to use if the check fails (must be a compiler message key,
* see {@link org.checkerframework.checker.compilermsgs.qual.CompilerMessageKey})
* @param extraArgs arguments to the error message key, before "found" and "expected" types
*/
@Override
protected boolean commonAssignmentCheck(
Tree varTree,
ExpressionTree valueExp,
@CompilerMessageKey String errorKey,
Object... extraArgs) {
if (!validateTypeOf(varTree)) {
return true;
}
AnnotatedTypeMirror var;
if (infer && varTree.getKind() == Kind.TYPE_PARAMETER) {
// When the lhs is a type variable, due to the partially resolved issue
// https://github.com/opprop/checker-framework-inference/issues/316,
// currently it is still "commonAssignmentCheck" who creates the refinement constraint.
// We need this constraint to be between the refinement variable and the rhs value.
// Since refinement variables come from flow inference, we must call "getAnnotatedType"
// instead of "getAnnotatedTypeLhs".
// TODO: use "getAnnotatedTypeLhs" uniformly when issue 316 is completely resolved.
// (In that way, the refinement constraints are uniformly created during dataflow
// analysis, so
// "commonAssignmentCheck" only needs to enforce the general type rule regarding
// assignment.)
var = atypeFactory.getAnnotatedType(varTree);
} else {
var = atypeFactory.getAnnotatedTypeLhs(varTree);
}
assert var != null : "no variable found for tree: " + varTree;
return commonAssignmentCheck(var, valueExp, errorKey, extraArgs);
}
@Override
protected boolean commonAssignmentCheck(
AnnotatedTypeMirror varType,
AnnotatedTypeMirror valueType,
Tree valueTree,
@CompilerMessageKey String errorKey,
Object... extraArgs) {
// ####### Copied Code ########
String valueTypeString = valueType.toString();
String varTypeString = varType.toString();
// If both types as strings are the same, try outputting
// the type including also invisible qualifiers.
// This usually means there is a mistake in type defaulting.
// This code is therefore not covered by a test.
if (valueTypeString.equals(varTypeString)) {
valueTypeString = valueType.toString(true);
varTypeString = varType.toString(true);
}
if (checker.hasOption("showchecks")) {
long valuePos = positions.getStartPosition(root, valueTree);
System.out.printf(
" %s (line %3d): %s %s%n actual: %s %s%n expected: %s %s%n",
"About to test whether actual is a subtype of expected",
(root.getLineMap() != null ? root.getLineMap().getLineNumber(valuePos) : -1),
valueTree.getKind(),
valueTree,
valueType.getKind(),
valueTypeString,
varType.getKind(),
varTypeString);
}
// ####### End Copied Code ########
// Handle refinement variables.
// If this is the result of an assignment,
// instead of a subtype relationship we know the refinement variable
// on the LHS must be equal to the variable on the RHS.
if (infer) {
maybeAddRefinementVariableConstraints(varType, valueType);
}
// this will also add a subtyping constraint between any refinement variables added and
// the RHS of this comparison. Those variables will already have an equality constraint
// from the above maybeAddRefinementVariableConstraints this will at most bias solvers
// towards breaking these constraints fewer times when solving
// We keep the subtype check anyway for the sake of component types that should be compared
// using this method
// TODO: We should get rid of this if, but for now type variables will have their bounds
// TODO: incorrectly inferred if we do not have it
boolean success = true;
if (!infer
|| (varType.getKind() != TypeKind.TYPEVAR
&& valueType.getKind() != TypeKind.TYPEVAR)) {
success = atypeFactory.getTypeHierarchy().isSubtype(valueType, varType);
}
// ####### Copied Code ########
// TODO: integrate with subtype test.
if (success) {
for (Class<? extends Annotation> mono :
atypeFactory.getSupportedMonotonicTypeQualifiers()) {
if (valueType.hasAnnotation(mono) && varType.hasAnnotation(mono)) {
checker.reportError(
valueTree,
"monotonic.type.incompatible",
mono.getCanonicalName(),
mono.getCanonicalName(),
valueType.toString());
// Assign success to false to report the error.
success = false;
}
}
}
if (checker.hasOption("showchecks")) {
long valuePos = positions.getStartPosition(root, valueTree);
System.out.printf(
" %s (line %3d): %s %s%n actual: %s %s%n expected: %s %s%n",
(success
? "success: actual is subtype of expected"
: "FAILURE: actual is not subtype of expected"),
(root.getLineMap() != null ? root.getLineMap().getLineNumber(valuePos) : -1),
valueTree.getKind(),
valueTree,
valueType.getKind(),
valueTypeString,
varType.getKind(),
varTypeString);
}
// Use an error key only if it's overridden by a checker.
if (!success) {
checker.reportError(
valueTree,
errorKey,
ArraysPlume.concatenate(extraArgs, valueTypeString, varTypeString));
}
return success;
// ####### End Copied Code ########
}
private void addRefinementVariableConstraints(
final AnnotatedTypeMirror varType,
final AnnotatedTypeMirror valueType,
final SlotManager slotManager,
final ConstraintManager constraintManager) {
Slot sup = slotManager.getSlot(varType);
Slot sub = slotManager.getSlot(valueType);
logger.fine(
"InferenceVisitor::commonAssignmentCheck: Equality constraint for qualifiers sub: "
+ sub
+ " sup: "
+ sup);
// Equality between the refvar and the value
constraintManager.addEqualityConstraint(sup, sub);
// Refinement variable still needs to be a subtype of its declared type value
constraintManager.addSubtypeConstraint(sup, ((RefinementVariableSlot) sup).getRefined());
}
/**
* A refinement variable generally has two constraints that must be enforce. It must be a
* subtype of the declared type it refines and it must be equal to the type on the right-hand
* side of the assignment or pseudo-assignment that created it.
*
* <p>This method detects the assignments that cause refinements and generates the above
* constraints.
*
* <p>For declared type, we create the refinement constraint once the refinement variable is
* created in {@link checkers.inference.dataflow.InferenceTransfer#createRefinementVar} during
* dataflow analysis. Therefore nothing needs to be done here. TODO: handle type variables and
* wildcards the same way as declared types, so that finally all refinement-related constraints
* are created in the dataflow analysis, and this method is removed.
*/
public boolean maybeAddRefinementVariableConstraints(
final AnnotatedTypeMirror varType, final AnnotatedTypeMirror valueType) {
boolean inferenceRefinementVariable = false;
final SlotManager slotManager = InferenceMain.getInstance().getSlotManager();
final ConstraintManager constraintManager =
InferenceMain.getInstance().getConstraintManager();
// type variables have two refinement variables (one on the upper bound and one on the lower
// bound)
if (varType.getKind() == TypeKind.TYPEVAR) {
if (valueType.getKind() == TypeKind.TYPEVAR) {
final AnnotatedTypeVariable varTypeTv = (AnnotatedTypeVariable) varType;
final AnnotatedTypeMirror varUpperBoundAtm;
final AnnotatedTypeMirror varLowerBoundAtm;
try {
varUpperBoundAtm = InferenceUtil.findUpperBoundType(varTypeTv);
varLowerBoundAtm = InferenceUtil.findLowerBoundType(varTypeTv);
} catch (Throwable exc) {
if (InferenceMain.isHackMode()) {
return false;
} else {
throw exc;
}
}
final Slot upperBoundSlot = slotManager.getSlot(varUpperBoundAtm);
final Slot lowerBoundSlot = slotManager.getSlot(varLowerBoundAtm);
if (upperBoundSlot instanceof RefinementVariableSlot
&& lowerBoundSlot instanceof RefinementVariableSlot) {
final AnnotatedTypeVariable valueTypeTv = (AnnotatedTypeVariable) valueType;
final AnnotatedTypeMirror valUpperBoundAtm;
final AnnotatedTypeMirror valLowerBoundAtm;
try {
valUpperBoundAtm = InferenceUtil.findUpperBoundType(valueTypeTv);
valLowerBoundAtm = InferenceUtil.findLowerBoundType(valueTypeTv);
} catch (Throwable exc) {
if (InferenceMain.isHackMode()) {
return false;
} else {
throw exc;
}
}
addRefinementVariableConstraints(
varUpperBoundAtm, valUpperBoundAtm, slotManager, constraintManager);
constraintManager.addEqualityConstraint(
lowerBoundSlot, slotManager.getSlot(valLowerBoundAtm));
constraintManager.addSubtypeConstraint(lowerBoundSlot, upperBoundSlot);
inferenceRefinementVariable = true;
}
} else if (valueType.getKind() == TypeKind.NULL) {
// TODO: For now do nothing but we should be doing some refinement
} else {
if (!InferenceMain.isHackMode()) {
throw new BugInCF(
"Unexpected assignment to type variable"); // TODO: Either more detail,
// or remove because of type
// args?
// TODO: OR A DIFFERENT SET OF CONSTRAINTS?
}
}
}
return inferenceRefinementVariable;
}
protected Set<AnnotationMirror> filterThrowCatchBounds(
Set<? extends AnnotationMirror> originals) {
Set<AnnotationMirror> throwBounds = new HashSet<>();
for (AnnotationMirror throwBound : originals) {
if (atypeFactory.areSameByClass(throwBound, VarAnnot.class)) {
if (throwBound.getElementValues().size() != 0) {
throwBounds.add(throwBound);
}
} else if (!atypeFactory.areSameByClass(throwBound, Unqualified.class)) {
// throwBound represents the qualifier which all thrown types must be subtypes of
// there is not point in enforcing thrownType <: TOP, since it will always be true
AnnotationMirror top =
atypeFactory.getQualifierHierarchy().getTopAnnotation(throwBound);
if (!AnnotationUtils.areSame(top, throwBound)) {
throwBounds.add(throwBound);
}
}
}
return throwBounds;
}
@Override
protected void checkThrownExpression(ThrowTree node) {
if (infer) {
// TODO: We probably want to unify this code with BaseTypeVisitor
AnnotatedTypeMirror throwType = atypeFactory.getAnnotatedType(node.getExpression());
Set<AnnotationMirror> throwBounds =
filterThrowCatchBounds(getThrowUpperBoundAnnotations());
final AnnotationMirror varAnnot =
new AnnotationBuilder(atypeFactory.getProcessingEnv(), VarAnnot.class).build();
final SlotManager slotManager = InferenceMain.getInstance().getSlotManager();
final ConstraintManager constraintManager =
InferenceMain.getInstance().getConstraintManager();
for (AnnotationMirror throwBound : throwBounds) {
switch (throwType.getKind()) {
case NULL:
case DECLARED:
constraintManager.addSubtypeConstraint(
slotManager.getSlot(throwType), slotManager.getSlot(throwBound));
break;
case TYPEVAR:
case WILDCARD:
AnnotationMirror foundEffective =
AnnotatedTypes.findEffectiveAnnotationInHierarchy(
atypeFactory.getQualifierHierarchy(), throwType, varAnnot);
constraintManager.addSubtypeConstraint(
slotManager.getSlot(foundEffective),
slotManager.getSlot(throwBound));
break;
case UNION:
AnnotatedUnionType unionType = (AnnotatedUnionType) throwType;
AnnotationMirror primary = unionType.getAnnotationInHierarchy(varAnnot);
if (primary != null) {
constraintManager.addSubtypeConstraint(
slotManager.getSlot(primary), slotManager.getSlot(throwBound));
}
for (AnnotatedTypeMirror altern : unionType.getAlternatives()) {
AnnotationMirror alternAnno = altern.getAnnotationInHierarchy(varAnnot);
if (alternAnno != null) {
constraintManager.addSubtypeConstraint(
slotManager.getSlot(alternAnno),
slotManager.getSlot(throwBound));
}
}
break;
default:
throw new BugInCF(
"Unexpected throw expression type: " + throwType.getKind());
}
}
} else {
super.checkThrownExpression(node);
}
}
// TODO: TEMPORARY HACK UNTIL WE SUPPORT UNIONS
private boolean isUnion(Tree tree) {
if (tree.getKind() == Kind.VARIABLE) {
return ((VariableTree) tree).getType().getKind() == Kind.UNION_TYPE;
}
return tree.getKind() == Kind.UNION_TYPE;
}
@Override
protected void checkExceptionParameter(CatchTree node) {
if (infer) {
// TODO: Unify with BaseTypeVisitor implementation
Set<AnnotationMirror> requiredAnnotations =
filterThrowCatchBounds(getExceptionParameterLowerBoundAnnotations());
AnnotatedTypeMirror exPar = atypeFactory.getAnnotatedType(node.getParameter());
for (AnnotationMirror required : requiredAnnotations) {
AnnotationMirror found = exPar.getAnnotationInHierarchy(required);
assert found != null;
if (exPar.getKind() != TypeKind.UNION) {
if (!atypeFactory
.getQualifierHierarchy()
.isSubtypeQualifiersOnly(required, found)) {
checker.reportError(
node.getParameter(),
"exception.parameter.invalid",
found,
required);
}
} else {
AnnotatedUnionType aut = (AnnotatedUnionType) exPar;
for (AnnotatedTypeMirror alterntive : aut.getAlternatives()) {
AnnotationMirror foundAltern =
alterntive.getAnnotationInHierarchy(required);
if (!atypeFactory
.getQualifierHierarchy()
.isSubtypeQualifiersOnly(required, foundAltern)) {
checker.reportError(
node.getParameter(),
"exception.parameter.invalid",
foundAltern,
required);
}
}
}
}
} else {
super.checkExceptionParameter(node);