forked from typetools/checker-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TreeUtils.java
1370 lines (1252 loc) · 51.9 KB
/
TreeUtils.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.javacutil;
import com.sun.source.tree.AnnotatedTypeTree;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ArrayAccessTree;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompoundAssignmentTree;
import com.sun.source.tree.ConditionalExpressionTree;
import com.sun.source.tree.ExpressionStatementTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.LiteralTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.NewArrayTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.ParameterizedTypeTree;
import com.sun.source.tree.ParenthesizedTree;
import com.sun.source.tree.PrimitiveTypeTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.tree.TypeCastTree;
import com.sun.source.tree.TypeParameterTree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreePath;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Types;
import com.sun.tools.javac.processing.JavacProcessingEnvironment;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCAnnotatedType;
import com.sun.tools.javac.tree.JCTree.JCAnnotation;
import com.sun.tools.javac.tree.JCTree.JCExpressionStatement;
import com.sun.tools.javac.tree.JCTree.JCLambda;
import com.sun.tools.javac.tree.JCTree.JCLambda.ParameterKind;
import com.sun.tools.javac.tree.JCTree.JCMemberReference;
import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
import com.sun.tools.javac.tree.JCTree.JCMethodInvocation;
import com.sun.tools.javac.tree.JCTree.JCNewArray;
import com.sun.tools.javac.tree.JCTree.JCNewClass;
import com.sun.tools.javac.tree.JCTree.JCTypeParameter;
import com.sun.tools.javac.tree.TreeInfo;
import com.sun.tools.javac.util.Context;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import javax.annotation.processing.ProcessingEnvironment;
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.Modifier;
import javax.lang.model.element.Name;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
import org.checkerframework.checker.nullness.qual.EnsuresNonNullIf;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.dataflow.qual.Pure;
/** A utility class made for helping to analyze a given {@code Tree}. */
// TODO: This class needs significant restructuring
public final class TreeUtils {
// Class cannot be instantiated.
private TreeUtils() {
throw new AssertionError("Class TreeUtils cannot be instantiated.");
}
/**
* Checks if the provided method is a constructor method or no.
*
* @param tree a tree defining the method
* @return true iff tree describes a constructor
*/
public static boolean isConstructor(final MethodTree tree) {
return tree.getName().contentEquals("<init>");
}
/**
* Checks if the method invocation is a call to super.
*
* @param tree a tree defining a method invocation
* @return true iff tree describes a call to super
*/
public static boolean isSuperConstructorCall(MethodInvocationTree tree) {
return isNamedMethodCall("super", tree);
}
/**
* Checks if the method invocation is a call to "this".
*
* @param tree a tree defining a method invocation
* @return true iff tree describes a call to this
*/
public static boolean isThisConstructorCall(MethodInvocationTree tree) {
return isNamedMethodCall("this", tree);
}
/**
* Checks if the method call is a call to the given method name.
*
* @param name a method name
* @param tree a tree defining a method invocation
* @return true iff tree is a call to the given method
*/
private static boolean isNamedMethodCall(String name, MethodInvocationTree tree) {
return getMethodName(tree.getMethodSelect()).equals(name);
}
/**
* Returns true if the tree is a tree that 'looks like' either an access of a field or an
* invocation of a method that are owned by the same accessing instance.
*
* <p>It would only return true if the access tree is of the form:
*
* <pre>
* field
* this.field
*
* method()
* this.method()
* </pre>
*
* It does not perform any semantical check to differentiate between fields and local variables;
* local methods or imported static methods.
*
* @param tree expression tree representing an access to object member
* @return {@code true} iff the member is a member of {@code this} instance
*/
public static boolean isSelfAccess(final ExpressionTree tree) {
ExpressionTree tr = TreeUtils.withoutParens(tree);
// If method invocation check the method select
if (tr.getKind() == Tree.Kind.ARRAY_ACCESS) {
return false;
}
if (tree.getKind() == Tree.Kind.METHOD_INVOCATION) {
tr = ((MethodInvocationTree) tree).getMethodSelect();
}
tr = TreeUtils.withoutParens(tr);
if (tr.getKind() == Tree.Kind.TYPE_CAST) {
tr = ((TypeCastTree) tr).getExpression();
}
tr = TreeUtils.withoutParens(tr);
if (tr.getKind() == Tree.Kind.IDENTIFIER) {
return true;
}
if (tr.getKind() == Tree.Kind.MEMBER_SELECT) {
tr = ((MemberSelectTree) tr).getExpression();
if (tr.getKind() == Tree.Kind.IDENTIFIER) {
Name ident = ((IdentifierTree) tr).getName();
return ident.contentEquals("this") || ident.contentEquals("super");
}
}
return false;
}
/**
* Gets the first enclosing tree in path, of the specified kind.
*
* @param path the path defining the tree node
* @param kind the kind of the desired tree
* @return the enclosing tree of the given type as given by the path, {@code null} otherwise
*/
public static @Nullable Tree enclosingOfKind(final TreePath path, final Tree.Kind kind) {
return enclosingOfKind(path, EnumSet.of(kind));
}
/**
* Gets the first enclosing tree in path, with any one of the specified kinds.
*
* @param path the path defining the tree node
* @param kinds the set of kinds of the desired tree
* @return the enclosing tree of the given type as given by the path, {@code null} otherwise
*/
public static @Nullable Tree enclosingOfKind(final TreePath path, final Set<Tree.Kind> kinds) {
TreePath p = path;
while (p != null) {
Tree leaf = p.getLeaf();
assert leaf != null; /*nninvariant*/
if (kinds.contains(leaf.getKind())) {
return leaf;
}
p = p.getParentPath();
}
return null;
}
/**
* Gets path to the first enclosing class tree, where class is defined by the classTreeKinds
* method.
*
* @param path the path defining the tree node
* @return the path to the enclosing class tree, {@code null} otherwise
*/
public static @Nullable TreePath pathTillClass(final TreePath path) {
return pathTillOfKind(path, classTreeKinds());
}
/**
* Gets path to the first enclosing tree of the specified kind.
*
* @param path the path defining the tree node
* @param kind the kind of the desired tree
* @return the path to the enclosing tree of the given type, {@code null} otherwise
*/
public static @Nullable TreePath pathTillOfKind(final TreePath path, final Tree.Kind kind) {
return pathTillOfKind(path, EnumSet.of(kind));
}
/**
* Gets path to the first enclosing tree with any one of the specified kinds.
*
* @param path the path defining the tree node
* @param kinds the set of kinds of the desired tree
* @return the path to the enclosing tree of the given type, {@code null} otherwise
*/
public static @Nullable TreePath pathTillOfKind(
final TreePath path, final Set<Tree.Kind> kinds) {
TreePath p = path;
while (p != null) {
Tree leaf = p.getLeaf();
assert leaf != null; /*nninvariant*/
if (kinds.contains(leaf.getKind())) {
return p;
}
p = p.getParentPath();
}
return null;
}
/**
* Gets the first enclosing tree in path, of the specified class.
*
* @param path the path defining the tree node
* @param treeClass the class of the desired tree
* @return the enclosing tree of the given type as given by the path, {@code null} otherwise
*/
public static <T extends Tree> @Nullable T enclosingOfClass(
final TreePath path, final Class<T> treeClass) {
TreePath p = path;
while (p != null) {
Tree leaf = p.getLeaf();
if (treeClass.isInstance(leaf)) {
return treeClass.cast(leaf);
}
p = p.getParentPath();
}
return null;
}
/**
* Gets the enclosing class of the tree node defined by the given {@link TreePath}. It returns a
* {@link Tree}, from which {@code checkers.types.AnnotatedTypeMirror} or {@link Element} can be
* obtained.
*
* @param path the path defining the tree node
* @return the enclosing class (or interface) as given by the path, or {@code null} if one does
* not exist
*/
public static @Nullable ClassTree enclosingClass(final TreePath path) {
return (ClassTree) enclosingOfKind(path, classTreeKinds());
}
/**
* Gets the enclosing variable of a tree node defined by the given {@link TreePath}.
*
* @param path the path defining the tree node
* @return the enclosing variable as given by the path, or {@code null} if one does not exist
*/
public static @Nullable VariableTree enclosingVariable(final TreePath path) {
return (VariableTree) enclosingOfKind(path, Tree.Kind.VARIABLE);
}
/**
* Gets the enclosing method of the tree node defined by the given {@link TreePath}. It returns
* a {@link Tree}, from which an {@code checkers.types.AnnotatedTypeMirror} or {@link Element}
* can be obtained.
*
* @param path the path defining the tree node
* @return the enclosing method as given by the path, or {@code null} if one does not exist
*/
public static @Nullable MethodTree enclosingMethod(final TreePath path) {
return (MethodTree) enclosingOfKind(path, Tree.Kind.METHOD);
}
/**
* Gets the enclosing method or lambda expression of the tree node defined by the given {@link
* TreePath}. It returns a {@link Tree}, from which an {@code
* checkers.types.AnnotatedTypeMirror} or {@link Element} can be obtained.
*
* @param path the path defining the tree node
* @return the enclosing method or lambda as given by the path, or {@code null} if one does not
* exist
*/
public static @Nullable Tree enclosingMethodOrLambda(final TreePath path) {
return enclosingOfKind(path, EnumSet.of(Tree.Kind.METHOD, Kind.LAMBDA_EXPRESSION));
}
public static @Nullable BlockTree enclosingTopLevelBlock(TreePath path) {
TreePath parpath = path.getParentPath();
while (parpath != null && !classTreeKinds.contains(parpath.getLeaf().getKind())) {
path = parpath;
parpath = parpath.getParentPath();
}
if (path.getLeaf().getKind() == Tree.Kind.BLOCK) {
return (BlockTree) path.getLeaf();
}
return null;
}
/**
* If the given tree is a parenthesized tree, return the enclosed non-parenthesized tree.
* Otherwise, return the same tree.
*
* @param tree an expression tree
* @return the outermost non-parenthesized tree enclosed by the given tree
*/
public static ExpressionTree withoutParens(final ExpressionTree tree) {
ExpressionTree t = tree;
while (t.getKind() == Tree.Kind.PARENTHESIZED) {
t = ((ParenthesizedTree) t).getExpression();
}
return t;
}
/**
* Gets the first enclosing tree in path, that is not a parenthesis.
*
* @param path the path defining the tree node
* @return a pair of a non-parenthesis tree that contains the argument, and its child that is
* the argument or is a parenthesized version of it
*/
public static Pair<Tree, Tree> enclosingNonParen(final TreePath path) {
TreePath parentPath = path.getParentPath();
Tree enclosing = parentPath.getLeaf();
Tree enclosingChild = path.getLeaf();
while (enclosing.getKind() == Kind.PARENTHESIZED) {
parentPath = parentPath.getParentPath();
enclosingChild = enclosing;
enclosing = parentPath.getLeaf();
}
return Pair.of(enclosing, enclosingChild);
}
/**
* Returns the tree with the assignment context for the treePath leaf node. (Does not handle
* pseudo-assignment of an argument to a parameter or a receiver expression to a receiver.)
*
* <p>The assignment context for the {@code treePath} is the leaf of its parent, if the parent
* is one of the following trees:
*
* <ul>
* <li>AssignmentTree
* <li>CompoundAssignmentTree
* <li>MethodInvocationTree
* <li>NewArrayTree
* <li>NewClassTree
* <li>ReturnTree
* <li>VariableTree
* </ul>
*
* If the parent is a ConditionalExpressionTree we need to distinguish two cases: If the leaf is
* either the then or else branch of the ConditionalExpressionTree, then recurse on the parent.
* If the leaf is the condition of the ConditionalExpressionTree, then return null to not
* consider this assignment context.
*
* <p>If the leaf is a ParenthesizedTree, then recurse on the parent.
*
* <p>Otherwise, null is returned.
*
* @return the assignment context as described, {@code null} otherwise
*/
public static @Nullable Tree getAssignmentContext(final TreePath treePath) {
TreePath parentPath = treePath.getParentPath();
if (parentPath == null) {
return null;
}
Tree parent = parentPath.getLeaf();
switch (parent.getKind()) {
case PARENTHESIZED:
return getAssignmentContext(parentPath);
case CONDITIONAL_EXPRESSION:
ConditionalExpressionTree cet = (ConditionalExpressionTree) parent;
if (cet.getCondition() == treePath.getLeaf()) {
// The assignment context for the condition is simply boolean.
// No point in going on.
return null;
}
// Otherwise use the context of the ConditionalExpressionTree.
return getAssignmentContext(parentPath);
case ASSIGNMENT:
case METHOD_INVOCATION:
case NEW_ARRAY:
case NEW_CLASS:
case RETURN:
case VARIABLE:
return parent;
default:
// 11 Tree.Kinds are CompoundAssignmentTrees,
// so use instanceof rather than listing all 11.
if (parent instanceof CompoundAssignmentTree) {
return parent;
}
return null;
}
}
/**
* Gets the {@link Element} for the given Tree API node. For an object instantiation returns the
* value of the {@link JCNewClass#constructor} field. Note that this result might differ from
* the result of {@link TreeUtils#constructor(NewClassTree)}.
*
* @param tree the {@link Tree} node to get the symbol for
* @throws IllegalArgumentException if {@code tree} is null or is not a valid javac-internal
* tree (JCTree)
* @return the {@link Symbol} for the given tree, or null if one could not be found
*/
@Pure
public static @Nullable Element elementFromTree(Tree tree) {
if (tree == null) {
throw new BugInCF("InternalUtils.symbol: tree is null");
}
if (!(tree instanceof JCTree)) {
throw new BugInCF("InternalUtils.symbol: tree is not a valid Javac tree");
}
if (isExpressionTree(tree)) {
tree = withoutParens((ExpressionTree) tree);
}
switch (tree.getKind()) {
// symbol() only works on MethodSelects, so we need to get it manually
// for method invocations.
case METHOD_INVOCATION:
return TreeInfo.symbol(((JCMethodInvocation) tree).getMethodSelect());
case ASSIGNMENT:
return TreeInfo.symbol((JCTree) ((AssignmentTree) tree).getVariable());
case ARRAY_ACCESS:
return elementFromTree(((ArrayAccessTree) tree).getExpression());
case NEW_CLASS:
return ((JCNewClass) tree).constructor;
case MEMBER_REFERENCE:
// TreeInfo.symbol, which is used in the default case, didn't handle
// member references until JDK8u20. So handle it here.
return ((JCMemberReference) tree).sym;
default:
if (isTypeDeclaration(tree)
|| tree.getKind() == Tree.Kind.VARIABLE
|| tree.getKind() == Tree.Kind.METHOD) {
return TreeInfo.symbolFor((JCTree) tree);
}
return TreeInfo.symbol((JCTree) tree);
}
}
/**
* Gets the element for a class corresponding to a declaration.
*
* @return the element for the given class
*/
public static TypeElement elementFromDeclaration(ClassTree node) {
TypeElement elt = (TypeElement) TreeUtils.elementFromTree(node);
assert elt != null : "@AssumeAssertion(nullness): tree kind";
return elt;
}
/**
* Gets the element for a method corresponding to a declaration.
*
* @return the element for the given method
*/
public static ExecutableElement elementFromDeclaration(MethodTree node) {
ExecutableElement elt = (ExecutableElement) TreeUtils.elementFromTree(node);
assert elt != null : "@AssumeAssertion(nullness): tree kind";
return elt;
}
/**
* Gets the element for a variable corresponding to its declaration.
*
* @return the element for the given variable
*/
public static VariableElement elementFromDeclaration(VariableTree node) {
VariableElement elt = (VariableElement) TreeUtils.elementFromTree(node);
assert elt != null : "@AssumeAssertion(nullness): tree kind";
return elt;
}
/**
* Gets the element for the declaration corresponding to this use of an element. To get the
* element for a declaration, use {@link #elementFromDeclaration(ClassTree)}, {@link
* #elementFromDeclaration(MethodTree)}, or {@link #elementFromDeclaration(VariableTree)}
* instead.
*
* <p>This method is just a wrapper around {@link TreeUtils#elementFromTree(Tree)}, but this
* class might be the first place someone looks for this functionality.
*
* @param node the tree corresponding to a use of an element
* @return the element for the corresponding declaration, {@code null} otherwise
*/
@Pure
public static @Nullable Element elementFromUse(ExpressionTree node) {
return TreeUtils.elementFromTree(node);
}
/** Specialization for return type. Might return null if element wasn't found. */
public static @Nullable ExecutableElement elementFromUse(MethodInvocationTree node) {
Element el = TreeUtils.elementFromTree(node);
if (el instanceof ExecutableElement) {
return (ExecutableElement) el;
} else {
return null;
}
}
/**
* Specialization for return type. Might return null if element wasn't found.
*
* @see #constructor(NewClassTree)
*/
public static @Nullable ExecutableElement elementFromUse(NewClassTree node) {
Element el = TreeUtils.elementFromTree(node);
if (el instanceof ExecutableElement) {
return (ExecutableElement) el;
} else {
return null;
}
}
/**
* Determines the symbol for a constructor given an invocation via {@code new}.
*
* <p>If the tree is a declaration of an anonymous class, then method returns constructor that
* gets invoked in the extended class, rather than the anonymous constructor implicitly added by
* the constructor (JLS 15.9.5.1)
*
* @see #elementFromUse(NewClassTree)
* @param tree the constructor invocation
* @return the {@link ExecutableElement} corresponding to the constructor call in {@code tree}
*/
public static ExecutableElement constructor(NewClassTree tree) {
if (!(tree instanceof JCTree.JCNewClass)) {
throw new BugInCF("InternalUtils.constructor: not a javac internal tree");
}
JCNewClass newClassTree = (JCNewClass) tree;
if (tree.getClassBody() != null) {
// anonymous constructor bodies should contain exactly one statement
// in the form:
// super(arg1, ...)
// or
// o.super(arg1, ...)
//
// which is a method invocation (!) to the actual constructor
// the method call is guaranteed to return nonnull
JCMethodDecl anonConstructor =
(JCMethodDecl) TreeInfo.declarationFor(newClassTree.constructor, newClassTree);
assert anonConstructor != null;
assert anonConstructor.body.stats.size() == 1;
JCExpressionStatement stmt = (JCExpressionStatement) anonConstructor.body.stats.head;
JCTree.JCMethodInvocation superInvok = (JCMethodInvocation) stmt.expr;
return (ExecutableElement) TreeInfo.symbol(superInvok.meth);
} else {
Element e = newClassTree.constructor;
return (ExecutableElement) e;
}
}
/**
* Determine whether the given ExpressionTree has an underlying element.
*
* @param node the ExpressionTree to test
* @return whether the tree refers to an identifier, member select, or method invocation
*/
@EnsuresNonNullIf(result = true, expression = "elementFromUse(#1)")
@Pure
public static boolean isUseOfElement(ExpressionTree node) {
ExpressionTree realnode = TreeUtils.withoutParens(node);
switch (realnode.getKind()) {
case IDENTIFIER:
case MEMBER_SELECT:
case METHOD_INVOCATION:
case NEW_CLASS:
assert elementFromUse(node) != null : "@AssumeAssertion(nullness): inspection";
return true;
default:
return false;
}
}
/** @return the name of the invoked method */
public static Name methodName(MethodInvocationTree node) {
ExpressionTree expr = node.getMethodSelect();
if (expr.getKind() == Tree.Kind.IDENTIFIER) {
return ((IdentifierTree) expr).getName();
} else if (expr.getKind() == Tree.Kind.MEMBER_SELECT) {
return ((MemberSelectTree) expr).getIdentifier();
}
throw new BugInCF("TreeUtils.methodName: cannot be here: " + node);
}
/**
* @return true if the first statement in the body is a self constructor invocation within a
* constructor
*/
public static boolean containsThisConstructorInvocation(MethodTree node) {
if (!TreeUtils.isConstructor(node) || node.getBody().getStatements().isEmpty()) {
return false;
}
StatementTree st = node.getBody().getStatements().get(0);
if (!(st instanceof ExpressionStatementTree)
|| !(((ExpressionStatementTree) st).getExpression()
instanceof MethodInvocationTree)) {
return false;
}
MethodInvocationTree invocation =
(MethodInvocationTree) ((ExpressionStatementTree) st).getExpression();
return "this".contentEquals(TreeUtils.methodName(invocation));
}
/**
* Returns the first statement of the tree if it is a block. If it is not a block or an empty
* block, tree is returned.
*
* @param tree any kind of tree
* @return the first statement of the tree if it is a block. If it is not a block or an empty
* block, tree is returned.
*/
public static Tree firstStatement(Tree tree) {
Tree first;
if (tree.getKind() == Tree.Kind.BLOCK) {
BlockTree block = (BlockTree) tree;
if (block.getStatements().isEmpty()) {
first = block;
} else {
first = block.getStatements().iterator().next();
}
} else {
first = tree;
}
return first;
}
/**
* Determine whether the given class contains an explicit constructor.
*
* @param node a class tree
* @return true, iff there is an explicit constructor
*/
public static boolean hasExplicitConstructor(ClassTree node) {
TypeElement elem = TreeUtils.elementFromDeclaration(node);
for (ExecutableElement ee : ElementFilter.constructorsIn(elem.getEnclosedElements())) {
MethodSymbol ms = (MethodSymbol) ee;
long mod = ms.flags();
if ((mod & Flags.SYNTHETIC) == 0) {
return true;
}
}
return false;
}
/**
* Returns true if the tree is of a diamond type. In contrast to the implementation in TreeInfo,
* this version works on Trees.
*
* @see com.sun.tools.javac.tree.TreeInfo#isDiamond(JCTree)
*/
public static boolean isDiamondTree(Tree tree) {
switch (tree.getKind()) {
case ANNOTATED_TYPE:
return isDiamondTree(((AnnotatedTypeTree) tree).getUnderlyingType());
case PARAMETERIZED_TYPE:
return ((ParameterizedTypeTree) tree).getTypeArguments().isEmpty();
case NEW_CLASS:
return isDiamondTree(((NewClassTree) tree).getIdentifier());
default:
return false;
}
}
/** Returns true if the tree represents a {@code String} concatenation operation. */
public static boolean isStringConcatenation(Tree tree) {
return (tree.getKind() == Tree.Kind.PLUS && TypesUtils.isString(TreeUtils.typeOf(tree)));
}
/** Returns true if the compound assignment tree is a string concatenation. */
public static boolean isStringCompoundConcatenation(CompoundAssignmentTree tree) {
return (tree.getKind() == Tree.Kind.PLUS_ASSIGNMENT
&& TypesUtils.isString(TreeUtils.typeOf(tree)));
}
/**
* Returns true if the node is a constant-time expression.
*
* <p>A tree is a constant-time expression if it is:
*
* <ol>
* <li>a literal tree
* <li>a reference to a final variable initialized with a compile time constant
* <li>a String concatenation of two compile time constants
* </ol>
*/
public static boolean isCompileTimeString(ExpressionTree node) {
ExpressionTree tree = TreeUtils.withoutParens(node);
if (tree instanceof LiteralTree) {
return true;
}
if (TreeUtils.isUseOfElement(tree)) {
Element elt = TreeUtils.elementFromUse(tree);
return ElementUtils.isCompileTimeConstant(elt);
} else if (TreeUtils.isStringConcatenation(tree)) {
BinaryTree binOp = (BinaryTree) tree;
return isCompileTimeString(binOp.getLeftOperand())
&& isCompileTimeString(binOp.getRightOperand());
} else {
return false;
}
}
/** Returns the receiver tree of a field access or a method invocation. */
public static @Nullable ExpressionTree getReceiverTree(ExpressionTree expression) {
ExpressionTree receiver;
switch (expression.getKind()) {
case METHOD_INVOCATION:
// Trying to handle receiver calls to trees of the form
// ((m).getArray())
// returns the type of 'm' in this case
receiver = ((MethodInvocationTree) expression).getMethodSelect();
if (receiver.getKind() == Tree.Kind.MEMBER_SELECT) {
receiver = ((MemberSelectTree) receiver).getExpression();
} else {
// It's a method call "m(foo)" without an explicit receiver
return null;
}
break;
case NEW_CLASS:
receiver = ((NewClassTree) expression).getEnclosingExpression();
break;
case ARRAY_ACCESS:
receiver = ((ArrayAccessTree) expression).getExpression();
break;
case MEMBER_SELECT:
receiver = ((MemberSelectTree) expression).getExpression();
// Avoid int.class
if (receiver instanceof PrimitiveTypeTree) {
return null;
}
break;
case IDENTIFIER:
// It's a field access on implicit this or a local variable/parameter.
return null;
default:
return null;
}
return TreeUtils.withoutParens(receiver);
}
// TODO: What about anonymous classes?
// Adding Tree.Kind.NEW_CLASS here doesn't work, because then a
// tree gets cast to ClassTree when it is actually a NewClassTree,
// for example in enclosingClass above.
/** The set of kinds that represent classes. */
private static final Set<Tree.Kind> classTreeKinds;
static {
classTreeKinds = EnumSet.noneOf(Tree.Kind.class);
for (Tree.Kind kind : Tree.Kind.values()) {
if (kind.asInterface() == ClassTree.class) {
classTreeKinds.add(kind);
}
}
}
/**
* Return the set of kinds that represent classes.
*
* @return the set of kinds that represent classes
*/
public static Set<Tree.Kind> classTreeKinds() {
return classTreeKinds;
}
/**
* Is the given tree kind a class, i.e. a class, enum, interface, or annotation type.
*
* @param tree the tree to test
* @return true, iff the given kind is a class kind
*/
public static boolean isClassTree(Tree tree) {
return classTreeKinds().contains(tree.getKind());
}
private static final Set<Tree.Kind> typeTreeKinds =
EnumSet.of(
Tree.Kind.PRIMITIVE_TYPE,
Tree.Kind.PARAMETERIZED_TYPE,
Tree.Kind.TYPE_PARAMETER,
Tree.Kind.ARRAY_TYPE,
Tree.Kind.UNBOUNDED_WILDCARD,
Tree.Kind.EXTENDS_WILDCARD,
Tree.Kind.SUPER_WILDCARD,
Tree.Kind.ANNOTATED_TYPE);
public static Set<Tree.Kind> typeTreeKinds() {
return typeTreeKinds;
}
/**
* Is the given tree a type instantiation?
*
* <p>TODO: this is an under-approximation: e.g. an identifier could be either a type use or an
* expression. How can we distinguish.
*
* @param tree the tree to test
* @return true, iff the given tree is a type
*/
public static boolean isTypeTree(Tree tree) {
return typeTreeKinds().contains(tree.getKind());
}
/**
* Returns true if the given element is an invocation of the method, or of any method that
* overrides that one.
*/
public static boolean isMethodInvocation(
Tree tree, ExecutableElement method, ProcessingEnvironment env) {
if (!(tree instanceof MethodInvocationTree)) {
return false;
}
MethodInvocationTree methInvok = (MethodInvocationTree) tree;
ExecutableElement invoked = TreeUtils.elementFromUse(methInvok);
assert invoked != null : "@AssumeAssertion(nullness): assumption";
return ElementUtils.isMethod(invoked, method, env);
}
/**
* Returns true if the argument is an invocation of one of the given methods, or of any method
* that overrides them.
*/
public static boolean isMethodInvocation(
Tree methodTree, List<ExecutableElement> methods, ProcessingEnvironment processingEnv) {
if (!(methodTree instanceof MethodInvocationTree)) {
return false;
}
for (ExecutableElement Method : methods) {
if (isMethodInvocation(methodTree, Method, processingEnv)) {
return true;
}
}
return false;
}
/**
* Returns the ExecutableElement for the method declaration of methodName, in class typeName,
* with params formal parameters. Errs if there is not exactly one matching method. If more than
* one method takes the same number of formal parameters, then use {@link #getMethod(String,
* String, ProcessingEnvironment, String...)}.
*/
public static ExecutableElement getMethod(
String typeName, String methodName, int params, ProcessingEnvironment env) {
List<ExecutableElement> methods = getMethods(typeName, methodName, params, env);
if (methods.size() == 1) {
return methods.get(0);
}
throw new BugInCF(
"TreeUtils.getMethod(%s, %s, %d): expected 1 match, found %d",
typeName, methodName, params, methods.size());
}
/**
* Returns all ExecutableElements for method declarations of methodName, in class typeName, with
* params formal parameters.
*/
public static List<ExecutableElement> getMethods(
String typeName, String methodName, int params, ProcessingEnvironment env) {
List<ExecutableElement> methods = new ArrayList<>(1);
TypeElement typeElt = env.getElementUtils().getTypeElement(typeName);
if (typeElt == null) {
throw new UserError("Configuration problem! Could not load type: " + typeName);
}
for (ExecutableElement exec : ElementFilter.methodsIn(typeElt.getEnclosedElements())) {
if (exec.getSimpleName().contentEquals(methodName)
&& exec.getParameters().size() == params) {
methods.add(exec);
}
}
return methods;
}
/**
* Returns the ExecutableElement for a method declaration of methodName, in class typeName, with
* formal parameters of the given types. Errs if there is no matching method.
*/
public static ExecutableElement getMethod(
String typeName, String methodName, ProcessingEnvironment env, String... paramTypes) {
TypeElement typeElt = env.getElementUtils().getTypeElement(typeName);
for (ExecutableElement exec : ElementFilter.methodsIn(typeElt.getEnclosedElements())) {
if (exec.getSimpleName().contentEquals(methodName)
&& exec.getParameters().size() == paramTypes.length) {
boolean typesMatch = true;
List<? extends VariableElement> params = exec.getParameters();
for (int i = 0; i < paramTypes.length; i++) {
VariableElement ve = params.get(i);
TypeMirror tm = TypeAnnotationUtils.unannotatedType(ve.asType());
if (!tm.toString().equals(paramTypes[i])) {
typesMatch = false;
break;
}
}
if (typesMatch) {
return exec;
}
}
}
throw new BugInCF(
"TreeUtils.getMethod: found no match for "
+ typeName
+ "."
+ methodName
+ "("
+ Arrays.toString(paramTypes)
+ ")");
}
/**
* Determine whether the given expression is either "this" or an outer "C.this".
*
* <p>TODO: Should this also handle "super"?
*/
public static boolean isExplicitThisDereference(ExpressionTree tree) {
if (tree.getKind() == Tree.Kind.IDENTIFIER
&& ((IdentifierTree) tree).getName().contentEquals("this")) {
// Explicit this reference "this"
return true;
}
if (tree.getKind() != Tree.Kind.MEMBER_SELECT) {
return false;
}
MemberSelectTree memSelTree = (MemberSelectTree) tree;
if (memSelTree.getIdentifier().contentEquals("this")) {
// Outer this reference "C.this"
return true;
}
return false;
}
/**
* Determine whether {@code tree} is a class literal, such as.
*
* <pre>
* <em>Object</em> . <em>class</em>
* </pre>
*
* @return true iff if tree is a class literal
*/