forked from google/error-prone
-
Notifications
You must be signed in to change notification settings - Fork 2
/
ASTHelpers.java
2484 lines (2270 loc) · 88.9 KB
/
ASTHelpers.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
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.util;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Verify.verify;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Streams.stream;
import static com.google.errorprone.matchers.JUnitMatchers.JUNIT4_RUN_WITH_ANNOTATION;
import static com.google.errorprone.matchers.Matchers.isSubtypeOf;
import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toCollection;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.google.auto.value.AutoValue;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.CharMatcher;
import com.google.common.collect.AbstractIterator;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.Sets;
import com.google.common.collect.Streams;
import com.google.errorprone.VisitorState;
import com.google.errorprone.annotations.InlineMe;
import com.google.errorprone.dataflow.nullnesspropagation.Nullness;
import com.google.errorprone.dataflow.nullnesspropagation.NullnessAnalysis;
import com.google.errorprone.matchers.JUnitMatchers;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.TestNgMatchers;
import com.google.errorprone.suppliers.Supplier;
import com.google.errorprone.suppliers.Suppliers;
import com.sun.source.tree.AnnotatedTypeTree;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ArrayAccessTree;
import com.sun.source.tree.AssertTree;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.CaseTree;
import com.sun.source.tree.CatchTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.CompoundAssignmentTree;
import com.sun.source.tree.ConditionalExpressionTree;
import com.sun.source.tree.DoWhileLoopTree;
import com.sun.source.tree.EnhancedForLoopTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.ForLoopTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.IfTree;
import com.sun.source.tree.InstanceOfTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.LiteralTree;
import com.sun.source.tree.MemberReferenceTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.ModifiersTree;
import com.sun.source.tree.ModuleTree;
import com.sun.source.tree.NewArrayTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.PackageTree;
import com.sun.source.tree.ParameterizedTypeTree;
import com.sun.source.tree.ParenthesizedTree;
import com.sun.source.tree.ReturnTree;
import com.sun.source.tree.SwitchTree;
import com.sun.source.tree.SynchronizedTree;
import com.sun.source.tree.ThrowTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.tree.TryTree;
import com.sun.source.tree.TypeCastTree;
import com.sun.source.tree.TypeParameterTree;
import com.sun.source.tree.UnaryTree;
import com.sun.source.tree.VariableTree;
import com.sun.source.tree.WhileLoopTree;
import com.sun.source.util.SimpleTreeVisitor;
import com.sun.source.util.TreePath;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.api.JavacTrees;
import com.sun.tools.javac.code.Attribute;
import com.sun.tools.javac.code.Attribute.Compound;
import com.sun.tools.javac.code.Attribute.TypeCompound;
import com.sun.tools.javac.code.BoundKind;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Scope;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.CompletionFailure;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symbol.PackageSymbol;
import com.sun.tools.javac.code.Symbol.TypeSymbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.Symtab;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Type.ClassType;
import com.sun.tools.javac.code.Type.TypeVar;
import com.sun.tools.javac.code.Type.UnionClassType;
import com.sun.tools.javac.code.Type.WildcardType;
import com.sun.tools.javac.code.TypeAnnotations;
import com.sun.tools.javac.code.TypeAnnotations.AnnotationType;
import com.sun.tools.javac.code.TypeTag;
import com.sun.tools.javac.code.Types;
import com.sun.tools.javac.comp.Enter;
import com.sun.tools.javac.comp.Resolve;
import com.sun.tools.javac.parser.JavaTokenizer;
import com.sun.tools.javac.parser.ScannerFactory;
import com.sun.tools.javac.parser.Tokens.Token;
import com.sun.tools.javac.parser.Tokens.TokenKind;
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.JCClassDecl;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import com.sun.tools.javac.tree.JCTree.JCFieldAccess;
import com.sun.tools.javac.tree.JCTree.JCIdent;
import com.sun.tools.javac.tree.JCTree.JCLiteral;
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.JCNewClass;
import com.sun.tools.javac.tree.JCTree.JCPackageDecl;
import com.sun.tools.javac.tree.JCTree.JCTypeParameter;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.FatalError;
import com.sun.tools.javac.util.Log;
import com.sun.tools.javac.util.Log.DeferredDiagnosticHandler;
import com.sun.tools.javac.util.Name;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.net.JarURLConnection;
import java.net.URI;
import java.nio.CharBuffer;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Deque;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.type.TypeKind;
/** This class contains utility methods to work with the javac AST. */
public class ASTHelpers {
/**
* Determines whether two expressions refer to the same variable. Note that returning false
* doesn't necessarily mean the expressions do *not* refer to the same field. We don't attempt to
* do any complex analysis here, just catch the obvious cases.
*/
public static boolean sameVariable(ExpressionTree expr1, ExpressionTree expr2) {
requireNonNull(expr1);
requireNonNull(expr2);
// Throw up our hands if we're not comparing identifiers and/or field accesses.
if ((expr1.getKind() != Kind.IDENTIFIER && expr1.getKind() != Kind.MEMBER_SELECT)
|| (expr2.getKind() != Kind.IDENTIFIER && expr2.getKind() != Kind.MEMBER_SELECT)) {
return false;
}
Symbol sym1 = getSymbol(expr1);
Symbol sym2 = getSymbol(expr2);
if (sym1 == null) {
throw new IllegalStateException("Couldn't get symbol for " + expr1);
} else if (sym2 == null) {
throw new IllegalStateException("Couldn't get symbol for " + expr2);
}
if (expr1.getKind() == Kind.IDENTIFIER && expr2.getKind() == Kind.IDENTIFIER) {
// foo == foo?
return sym1.equals(sym2);
} else if (expr1.getKind() == Kind.MEMBER_SELECT && expr2.getKind() == Kind.MEMBER_SELECT) {
// foo.baz.bar == foo.baz.bar?
return sym1.equals(sym2)
&& sameVariable(((JCFieldAccess) expr1).selected, ((JCFieldAccess) expr2).selected);
} else {
// this.foo == foo?
ExpressionTree selected;
if (expr1.getKind() == Kind.IDENTIFIER) {
selected = ((JCFieldAccess) expr2).selected;
} else {
selected = ((JCFieldAccess) expr1).selected;
}
// TODO(eaftan): really shouldn't be relying on .toString()
return selected.toString().equals("this") && sym1.equals(sym2);
}
}
/**
* Gets the symbol declared by a tree. Returns null if {@code tree} does not declare a symbol or
* is null.
*/
@Nullable
public static Symbol getDeclaredSymbol(Tree tree) {
if (tree instanceof PackageTree) {
return getSymbol((PackageTree) tree);
}
if (tree instanceof TypeParameterTree) {
Type type = ((JCTypeParameter) tree).type;
return type == null ? null : type.tsym;
}
if (tree instanceof ClassTree) {
return getSymbol((ClassTree) tree);
}
if (tree instanceof MethodTree) {
return getSymbol((MethodTree) tree);
}
if (tree instanceof VariableTree) {
return getSymbol((VariableTree) tree);
}
return null;
}
/**
* Gets the symbol for a tree. Returns null if this tree does not have a symbol because it is of
* the wrong type, if {@code tree} is null, or if the symbol cannot be found due to a compilation
* error.
*/
// TODO(eaftan): refactor other code that accesses symbols to use this method
public static Symbol getSymbol(Tree tree) {
if (tree instanceof AnnotationTree) {
return getSymbol(((AnnotationTree) tree).getAnnotationType());
}
if (tree instanceof JCFieldAccess) {
return ((JCFieldAccess) tree).sym;
}
if (tree instanceof JCIdent) {
return ((JCIdent) tree).sym;
}
if (tree instanceof JCMethodInvocation) {
return ASTHelpers.getSymbol((MethodInvocationTree) tree);
}
if (tree instanceof JCNewClass) {
return ASTHelpers.getSymbol((NewClassTree) tree);
}
if (tree instanceof MemberReferenceTree) {
return ((JCMemberReference) tree).sym;
}
if (tree instanceof JCAnnotatedType) {
return getSymbol(((JCAnnotatedType) tree).underlyingType);
}
if (tree instanceof ParameterizedTypeTree) {
return getSymbol(((ParameterizedTypeTree) tree).getType());
}
if (tree instanceof ClassTree) {
return getSymbol((ClassTree) tree);
}
return getDeclaredSymbol(tree);
}
/** Gets the symbol for a class. */
public static ClassSymbol getSymbol(ClassTree tree) {
return checkNotNull(((JCClassDecl) tree).sym, "%s had a null ClassSymbol", tree);
}
/** Gets the symbol for a package. */
public static PackageSymbol getSymbol(PackageTree tree) {
return checkNotNull(((JCPackageDecl) tree).packge, "%s had a null PackageSymbol", tree);
}
/** Gets the symbol for a method. */
public static MethodSymbol getSymbol(MethodTree tree) {
return checkNotNull(((JCMethodDecl) tree).sym, "%s had a null MethodSymbol", tree);
}
/** Gets the method symbol for a new class. */
public static MethodSymbol getSymbol(NewClassTree tree) {
Symbol sym = ((JCNewClass) tree).constructor;
if (!(sym instanceof MethodSymbol)) {
// Defensive. Would only occur if there are errors in the AST.
throw new IllegalArgumentException(tree.toString());
}
return (MethodSymbol) sym;
}
/** Gets the symbol for a variable. */
public static VarSymbol getSymbol(VariableTree tree) {
return checkNotNull(((JCVariableDecl) tree).sym, "%s had a null VariableTree", tree);
}
/** Gets the symbol for a method invocation. */
public static MethodSymbol getSymbol(MethodInvocationTree tree) {
Symbol sym = ASTHelpers.getSymbol(tree.getMethodSelect());
if (!(sym instanceof MethodSymbol)) {
// Defensive. Would only occur if there are errors in the AST.
throw new IllegalArgumentException(tree.toString());
}
return (MethodSymbol) sym;
}
/** Gets the symbol for a member reference. */
public static MethodSymbol getSymbol(MemberReferenceTree tree) {
Symbol sym = ((JCMemberReference) tree).sym;
if (!(sym instanceof MethodSymbol)) {
// Defensive. Would only occur if there are errors in the AST.
throw new IllegalArgumentException(tree.toString());
}
return (MethodSymbol) sym;
}
/**
* Returns whether this symbol is safe to remove. That is, if it cannot be accessed from outside
* its own compilation unit.
*
* <p>For variables this just means that one of the enclosing elements is private; for methods, it
* also means that this symbol is not an override.
*/
public static boolean canBeRemoved(Symbol symbol, VisitorState state) {
if (symbol instanceof MethodSymbol
&& !findSuperMethods((MethodSymbol) symbol, state.getTypes()).isEmpty()) {
return false;
}
return isEffectivelyPrivate(symbol);
}
/** See {@link #canBeRemoved(Symbol, VisitorState)}. */
public static boolean canBeRemoved(VarSymbol symbol) {
return isEffectivelyPrivate(symbol);
}
/** See {@link #canBeRemoved(Symbol, VisitorState)}. */
public static boolean canBeRemoved(ClassSymbol symbol) {
return isEffectivelyPrivate(symbol);
}
/** Returns whether this symbol or any of its owners are private. */
private static boolean isEffectivelyPrivate(Symbol symbol) {
return enclosingElements(symbol).anyMatch(Symbol::isPrivate);
}
/** Checks whether an expression requires parentheses. */
public static boolean requiresParentheses(ExpressionTree expression, VisitorState state) {
switch (expression.getKind()) {
case IDENTIFIER:
case MEMBER_SELECT:
case METHOD_INVOCATION:
case ARRAY_ACCESS:
case PARENTHESIZED:
case NEW_CLASS:
case MEMBER_REFERENCE:
return false;
case LAMBDA_EXPRESSION:
// Parenthesizing e.g. `x -> (y -> z)` is unnecessary but helpful
Tree parent = state.getPath().getParentPath().getLeaf();
return parent.getKind().equals(Kind.LAMBDA_EXPRESSION)
&& stripParentheses(((LambdaExpressionTree) parent).getBody()).equals(expression);
default: // continue below
}
if (expression instanceof LiteralTree) {
if (!isSameType(getType(expression), state.getSymtab().stringType, state)) {
return false;
}
// TODO(b/112139121): work around for javac's too-early constant string folding
return state.getOffsetTokensForNode(expression).stream()
.anyMatch(t -> t.kind() == TokenKind.PLUS);
}
if (expression instanceof UnaryTree) {
Tree parent = state.getPath().getParentPath().getLeaf();
if (!(parent instanceof MemberSelectTree)) {
return false;
}
// eg. (i++).toString();
return stripParentheses(((MemberSelectTree) parent).getExpression()).equals(expression);
}
return true;
}
/** Removes any enclosing parentheses from the tree. */
public static Tree stripParentheses(Tree tree) {
return tree instanceof ExpressionTree ? stripParentheses((ExpressionTree) tree) : tree;
}
/** Given an ExpressionTree, removes any enclosing parentheses. */
public static ExpressionTree stripParentheses(ExpressionTree tree) {
while (tree instanceof ParenthesizedTree) {
tree = ((ParenthesizedTree) tree).getExpression();
}
return tree;
}
/**
* Given a TreePath, finds the first enclosing node of the given type and returns the path from
* the enclosing node to the top-level {@code CompilationUnitTree}.
*/
public static <T> TreePath findPathFromEnclosingNodeToTopLevel(TreePath path, Class<T> klass) {
if (path != null) {
do {
path = path.getParentPath();
} while (path != null && !klass.isInstance(path.getLeaf()));
}
return path;
}
/**
* Returns a stream of the owner hierarchy starting from {@code sym}, as described by {@link
* Symbol#owner}. Returns {@code sym} itself first, followed by its owners, closest first, up to
* the owning package and possibly module.
*/
public static Stream<Symbol> enclosingElements(Symbol sym) {
return Stream.iterate(sym, Symbol::getEnclosingElement).takeWhile(s -> s != null);
}
/**
* Given a TreePath, walks up the tree until it finds a node of the given type. Returns null if no
* such node is found.
*/
@Nullable
public static <T> T findEnclosingNode(TreePath path, Class<T> klass) {
path = findPathFromEnclosingNodeToTopLevel(path, klass);
return (path == null) ? null : klass.cast(path.getLeaf());
}
/** Finds the enclosing {@link MethodTree}. Returns {@code null} if no such node found. */
@Nullable
public static MethodTree findEnclosingMethod(VisitorState state) {
for (Tree parent : state.getPath()) {
switch (parent.getKind()) {
case METHOD:
return (MethodTree) parent;
case CLASS:
case LAMBDA_EXPRESSION:
return null;
default: // fall out
}
}
return null;
}
/**
* Find the root assignable expression of a chain of field accesses. If there is no root (i.e, a
* bare method call or a static method call), return null.
*
* <p>Examples:
*
* <pre>{@code
* a.trim().intern() ==> a
* a.b.trim().intern() ==> a.b
* this.intValue.foo() ==> this.intValue
* this.foo() ==> this
* intern() ==> null
* String.format() ==> null
* java.lang.String.format() ==> null
* }</pre>
*/
@Nullable
public static ExpressionTree getRootAssignable(MethodInvocationTree methodInvocationTree) {
if (!(methodInvocationTree instanceof JCMethodInvocation)) {
throw new IllegalArgumentException(
"Expected type to be JCMethodInvocation, but was " + methodInvocationTree.getClass());
}
// Check for bare method call, e.g. intern().
if (((JCMethodInvocation) methodInvocationTree).getMethodSelect() instanceof JCIdent) {
return null;
}
// Unwrap the field accesses until you get to an identifier.
ExpressionTree expr = methodInvocationTree;
while (expr instanceof JCMethodInvocation) {
expr = ((JCMethodInvocation) expr).getMethodSelect();
if (expr instanceof JCFieldAccess) {
expr = ((JCFieldAccess) expr).getExpression();
}
}
// We only want assignable identifiers.
Symbol sym = getSymbol(expr);
if (sym instanceof VarSymbol) {
return expr;
}
return null;
}
/**
* Gives the return type of an ExpressionTree that represents a method select.
*
* <p>TODO(eaftan): Are there other places this could be used?
*/
public static Type getReturnType(ExpressionTree expressionTree) {
if (expressionTree instanceof JCFieldAccess) {
JCFieldAccess methodCall = (JCFieldAccess) expressionTree;
return methodCall.type.getReturnType();
} else if (expressionTree instanceof JCIdent) {
JCIdent methodCall = (JCIdent) expressionTree;
return methodCall.type.getReturnType();
} else if (expressionTree instanceof JCMethodInvocation) {
return getReturnType(((JCMethodInvocation) expressionTree).getMethodSelect());
} else if (expressionTree instanceof JCMemberReference) {
return ((JCMemberReference) expressionTree).sym.type.getReturnType();
}
throw new IllegalArgumentException("Expected a JCFieldAccess or JCIdent");
}
/**
* Returns the type that this expression tree will evaluate to. If it's a literal, an identifier,
* or a member select this is the actual type, if it's a method invocation then it's the return
* type of the method (after instantiating generic types), if it's a constructor then it's the
* type of the returned class.
*
* <p>TODO(andrewrice) consider replacing {@code getReturnType} with this method
*
* @param expressionTree the tree to evaluate
* @return the result type of this tree or null if unable to resolve it
*/
@Nullable
public static Type getResultType(ExpressionTree expressionTree) {
Type type = ASTHelpers.getType(expressionTree);
return type == null ? null : Optional.ofNullable(type.getReturnType()).orElse(type);
}
/**
* Returns the type of a receiver of a method call expression. Precondition: the expressionTree
* corresponds to a method call.
*
* <p>Examples:
*
* <pre>{@code
* a.b.foo() ==> type of a.b
* a.bar().foo() ==> type of a.bar()
* this.foo() ==> type of this
* foo() ==> type of this
* TheClass.aStaticMethod() ==> TheClass
* aStaticMethod() ==> type of class in which method is defined
* }</pre>
*/
public static Type getReceiverType(ExpressionTree expressionTree) {
if (expressionTree instanceof JCFieldAccess) {
JCFieldAccess methodSelectFieldAccess = (JCFieldAccess) expressionTree;
return methodSelectFieldAccess.selected.type;
} else if (expressionTree instanceof JCIdent) {
JCIdent methodCall = (JCIdent) expressionTree;
return methodCall.sym.owner.type;
} else if (expressionTree instanceof JCMethodInvocation) {
return getReceiverType(((JCMethodInvocation) expressionTree).getMethodSelect());
} else if (expressionTree instanceof JCMemberReference) {
return ((JCMemberReference) expressionTree).getQualifierExpression().type;
}
throw new IllegalArgumentException(
"Expected a JCFieldAccess or JCIdent from expression " + expressionTree);
}
/**
* Returns the receiver of an expression.
*
* <p>Examples:
*
* <pre>{@code
* a.foo() ==> a
* a.b.foo() ==> a.b
* a.bar().foo() ==> a.bar()
* a.b.c ==> a.b
* a.b().c ==> a.b()
* this.foo() ==> this
* foo() ==> null
* TheClass.aStaticMethod() ==> TheClass
* aStaticMethod() ==> null
* aStaticallyImportedMethod() ==> null
* }</pre>
*/
@Nullable
public static ExpressionTree getReceiver(ExpressionTree expressionTree) {
if (expressionTree instanceof MethodInvocationTree) {
ExpressionTree methodSelect = ((MethodInvocationTree) expressionTree).getMethodSelect();
if (methodSelect instanceof IdentifierTree) {
return null;
}
return getReceiver(methodSelect);
} else if (expressionTree instanceof MemberSelectTree) {
return ((MemberSelectTree) expressionTree).getExpression();
} else if (expressionTree instanceof MemberReferenceTree) {
return ((MemberReferenceTree) expressionTree).getQualifierExpression();
} else {
throw new IllegalStateException(
String.format(
"Expected expression '%s' to be a method invocation or field access, but was %s",
expressionTree, expressionTree.getKind()));
}
}
/**
* Returns a {@link Stream} of {@link ExpressionTree}s resulting from calling {@link
* #getReceiver(ExpressionTree)} repeatedly until no receiver exists.
*
* <p>For example, give {@code foo().bar().baz()}, returns a stream of {@code [foo().bar(),
* foo()]}.
*
* <p>This can be more convenient than manually traversing up a tree, as it handles the
* termination condition automatically. Typical uses cases would include traversing fluent call
* chains.
*/
public static Stream<ExpressionTree> streamReceivers(ExpressionTree tree) {
return stream(
new AbstractIterator<ExpressionTree>() {
private ExpressionTree current = tree;
@Override
protected ExpressionTree computeNext() {
if (current instanceof MethodInvocationTree
|| current instanceof MemberSelectTree
|| current instanceof MemberReferenceTree) {
current = getReceiver(current);
return current == null ? endOfData() : current;
}
return endOfData();
}
});
}
/**
* Given a BinaryTree to match against and a list of two matchers, applies the matchers to the
* operands in both orders. If both matchers match, returns a list with the operand that matched
* each matcher in the corresponding position.
*
* @param tree a BinaryTree AST node
* @param matchers a list of matchers
* @param state the VisitorState
* @return a list of matched operands, or null if at least one did not match
*/
@Nullable
public static List<ExpressionTree> matchBinaryTree(
BinaryTree tree, List<Matcher<ExpressionTree>> matchers, VisitorState state) {
ExpressionTree leftOperand = tree.getLeftOperand();
ExpressionTree rightOperand = tree.getRightOperand();
if (matchers.get(0).matches(leftOperand, state)
&& matchers.get(1).matches(rightOperand, state)) {
return Arrays.asList(leftOperand, rightOperand);
} else if (matchers.get(0).matches(rightOperand, state)
&& matchers.get(1).matches(leftOperand, state)) {
return Arrays.asList(rightOperand, leftOperand);
}
return null;
}
/**
* Returns the method tree that matches the given symbol within the compilation unit, or null if
* none was found.
*/
@Nullable
public static MethodTree findMethod(MethodSymbol symbol, VisitorState state) {
return JavacTrees.instance(state.context).getTree(symbol);
}
/**
* Returns the class tree that matches the given symbol within the compilation unit, or null if
* none was found.
*/
@Nullable
public static ClassTree findClass(ClassSymbol symbol, VisitorState state) {
return JavacTrees.instance(state.context).getTree(symbol);
}
// TODO(ghm): Using a comparison of tsym here appears to be a behaviour change.
@SuppressWarnings("TypeEquals")
@Nullable
public static MethodSymbol findSuperMethodInType(
MethodSymbol methodSymbol, Type superType, Types types) {
if (methodSymbol.isStatic() || superType.equals(methodSymbol.owner.type)) {
return null;
}
Scope scope = superType.tsym.members();
for (Symbol sym : scope.getSymbolsByName(methodSymbol.name)) {
if (sym != null
&& !sym.isStatic()
&& ((sym.flags() & Flags.SYNTHETIC) == 0)
&& methodSymbol.overrides(
sym, (TypeSymbol) methodSymbol.owner, types, /* checkResult= */ true)) {
return (MethodSymbol) sym;
}
}
return null;
}
public static Set<MethodSymbol> findSuperMethods(MethodSymbol methodSymbol, Types types) {
return findSuperMethods(methodSymbol, types, /* skipInterfaces= */ false)
.collect(toCollection(LinkedHashSet::new));
}
private static Stream<MethodSymbol> findSuperMethods(
MethodSymbol methodSymbol, Types types, boolean skipInterfaces) {
TypeSymbol owner = (TypeSymbol) methodSymbol.owner;
Stream<Type> typeStream = types.closure(owner.type).stream();
if (skipInterfaces) {
typeStream = typeStream.filter(type -> !type.isInterface());
}
return typeStream
.map(type -> findSuperMethodInType(methodSymbol, type, types))
.filter(Objects::nonNull);
}
/**
* Finds (if it exists) first (in the class hierarchy) non-interface super method of given {@code
* method}.
*/
public static Optional<MethodSymbol> findSuperMethod(MethodSymbol methodSymbol, Types types) {
return findSuperMethods(methodSymbol, types, /* skipInterfaces= */ true).findFirst();
}
/**
* Finds all methods in any superclass of {@code startClass} with a certain {@code name} that
* match the given {@code predicate}.
*
* @return The (possibly empty) list of methods in any superclass that match {@code predicate} and
* have the given {@code name}. Results are returned least-abstract first, i.e., starting in
* the {@code startClass} itself, progressing through its superclasses, and finally interfaces
* in an unspecified order.
*/
public static Stream<MethodSymbol> matchingMethods(
Name name, Predicate<MethodSymbol> predicate, Type startClass, Types types) {
Predicate<Symbol> matchesMethodPredicate =
sym -> sym instanceof MethodSymbol && predicate.test((MethodSymbol) sym);
// Iterate over all classes and interfaces that startClass inherits from.
return types.closure(startClass).stream()
.flatMap(
(Type superClass) -> {
// Iterate over all the methods declared in superClass.
TypeSymbol superClassSymbol = superClass.tsym;
Scope superClassSymbols = superClassSymbol.members();
if (superClassSymbols == null) { // Can be null if superClass is a type variable
return Stream.empty();
}
return stream(
scope(superClassSymbols)
.getSymbolsByName(name, matchesMethodPredicate, NON_RECURSIVE))
// By definition of the filter, we know that the symbol is a MethodSymbol.
.map(symbol -> (MethodSymbol) symbol);
});
}
/**
* Finds all methods in any superclass of {@code startClass} with a certain {@code name} that
* match the given {@code predicate}.
*
* @return The (possibly empty) set of methods in any superclass that match {@code predicate} and
* have the given {@code name}. The set's iteration order will be the same as the order
* documented in {@link #matchingMethods(Name, java.util.function.Predicate, Type, Types)}.
*/
public static ImmutableSet<MethodSymbol> findMatchingMethods(
Name name, Predicate<MethodSymbol> predicate, Type startClass, Types types) {
return matchingMethods(name, predicate, startClass, types).collect(toImmutableSet());
}
/**
* Determines whether a method can be overridden.
*
* @return true if the method can be overridden.
*/
public static boolean methodCanBeOverridden(MethodSymbol methodSymbol) {
if (methodSymbol.getModifiers().contains(Modifier.ABSTRACT)) {
return true;
}
if (methodSymbol.isStatic()
|| methodSymbol.isPrivate()
|| isFinal(methodSymbol)
|| methodSymbol.isConstructor()) {
return false;
}
ClassSymbol classSymbol = (ClassSymbol) methodSymbol.owner;
return !isFinal(classSymbol) && !classSymbol.isAnonymous();
}
private static boolean isFinal(Symbol symbol) {
return (symbol.flags() & Flags.FINAL) == Flags.FINAL;
}
/**
* Flag for record types, canonical record constructors and type members that are part of a
* record's state vector. Can be replaced by {@code com.sun.tools.javac.code.Flags.RECORD} once
* the minimum JDK version is 14.
*/
private static final long RECORD_FLAG = 1L << 61;
/**
* Returns true if the given {@link Tree} is a record, a record's canonical constructor or a
* member that is part of a record's state vector.
*/
public static boolean isRecord(Tree tree) {
return isRecord(getSymbol(tree));
}
/**
* Returns true if the given {@link Symbol} is a record, a record's canonical constructor or a
* member that is part of a record's state vector.
*/
public static boolean isRecord(Symbol symbol) {
return symbol != null && (symbol.flags() & RECORD_FLAG) == RECORD_FLAG;
}
/**
* Determines whether a symbol has an annotation of the given type. This includes annotations
* inherited from superclasses due to {@code @Inherited}.
*
* @param annotationClass the binary class name of the annotation (e.g.
* "javax.annotation.Nullable", or "some.package.OuterClassName$InnerClassName")
* @return true if the symbol is annotated with given type.
*/
public static boolean hasAnnotation(Symbol sym, String annotationClass, VisitorState state) {
if (sym == null) {
return false;
}
// TODO(amalloy): unify with hasAnnotation(Symbol, Name, VisitorState)
// normalize to non-binary names
annotationClass = annotationClass.replace('$', '.');
Name annotationName = state.getName(annotationClass);
if (hasAttribute(sym, annotationName)) {
return true;
}
if (sym instanceof ClassSymbol && isInherited(state, annotationClass)) {
do {
if (hasAttribute(sym, annotationName)) {
return true;
}
sym = ((ClassSymbol) sym).getSuperclass().tsym;
} while (sym instanceof ClassSymbol);
}
return false;
}
/**
* Check for the presence of an annotation, considering annotation inheritance.
*
* @return true if the symbol is annotated with given type.
*/
public static boolean hasAnnotation(
Symbol sym, Class<? extends Annotation> annotationClass, VisitorState state) {
return hasAnnotation(sym, annotationClass.getName(), state);
}
/**
* Check for the presence of an annotation, considering annotation inheritance.
*
* @param annotationClass the binary class name of the annotation (e.g.
* "javax.annotation.Nullable", or "some.package.OuterClassName$InnerClassName")
* @return true if the tree is annotated with given type.
*/
public static boolean hasAnnotation(Tree tree, String annotationClass, VisitorState state) {
Symbol sym = getDeclaredSymbol(tree);
return hasAnnotation(sym, annotationClass, state);
}
/**
* Check for the presence of an annotation, considering annotation inheritance.
*
* @return true if the tree is annotated with given type.
*/
public static boolean hasAnnotation(
Tree tree, Class<? extends Annotation> annotationClass, VisitorState state) {
return hasAnnotation(tree, annotationClass.getName(), state);
}
private static final Supplier<Cache<Name, Boolean>> inheritedAnnotationCache =
VisitorState.memoize(unusedState -> Caffeine.newBuilder().maximumSize(1000).build());
@SuppressWarnings("ConstantConditions") // IntelliJ worries unboxing our Boolean may throw NPE.
private static boolean isInherited(VisitorState state, Name annotationName) {
return inheritedAnnotationCache
.get(state)
.get(
annotationName,
name -> {
Symbol annotationSym = state.getSymbolFromName(annotationName);
if (annotationSym == null) {
return false;
}
try {
annotationSym.complete();
} catch (CompletionFailure e) {
/* @Inherited won't work if the annotation isn't on the classpath, but we can still
check if it's present directly */
}
Symbol inheritedSym = state.getSymtab().inheritedType.tsym;
return annotationSym.attribute(inheritedSym) != null;
});
}
private static boolean isInherited(VisitorState state, String annotationName) {
return isInherited(state, state.binaryNameFromClassname(annotationName));
}
private static boolean hasAttribute(Symbol sym, Name annotationName) {
for (Compound a : sym.getRawAttributes()) {
if (a.type.tsym.getQualifiedName().equals(annotationName)) {
return true;
}
}
return false;
}
/**
* Determines which of a set of annotations are present on a symbol.
*
* @param sym The symbol to inspect for annotations
* @param annotationClasses The annotations of interest to look for, Each name must be in binary
* form, e.g. "com.google.Foo$Bar", not "com.google.Foo.Bar".
* @return A possibly-empty set of annotations present on the queried element.
*/
public static Set<Name> annotationsAmong(
Symbol sym, Set<? extends Name> annotationClasses, VisitorState state) {
if (sym == null) {
return ImmutableSet.of();
}
Set<Name> result = directAnnotationsAmong(sym, annotationClasses);
if (!(sym instanceof ClassSymbol)) {
return result;
}
Set<Name> possibleInherited = new HashSet<>();
for (Name a : annotationClasses) {
if (!result.contains(a) && isInherited(state, a)) {
possibleInherited.add(a);
}
}
sym = ((ClassSymbol) sym).getSuperclass().tsym;
while (sym instanceof ClassSymbol && !possibleInherited.isEmpty()) {
for (Name local : directAnnotationsAmong(sym, possibleInherited)) {
result.add(local);
possibleInherited.remove(local);
}
sym = ((ClassSymbol) sym).getSuperclass().tsym;
}
return result;
}
/**
* Explicitly returns a modifiable {@code Set<Name>}, so that annotationsAmong can futz with it to
* add inherited annotations.
*/
private static Set<Name> directAnnotationsAmong(
Symbol sym, Set<? extends Name> binaryAnnotationNames) {
Set<Name> result = new HashSet<>();
for (Compound a : sym.getRawAttributes()) {
Name annoName = a.type.tsym.flatName();
if (binaryAnnotationNames.contains(annoName)) {
result.add(annoName);
}
}
return result;
}
/**
* Check for the presence of an annotation with a specific simple name directly on this symbol.
* Does *not* consider annotation inheritance.
*
* @param sym the symbol to check for the presence of the annotation
* @param simpleName the simple name of the annotation to look for, e.g. "Nullable" or
* "CheckReturnValue"
*/
public static boolean hasDirectAnnotationWithSimpleName(Symbol sym, String simpleName) {
for (AnnotationMirror annotation : sym.getAnnotationMirrors()) {
if (annotation.getAnnotationType().asElement().getSimpleName().contentEquals(simpleName)) {
return true;
}
}
return false;
}
/**
* Check for the presence of an annotation with a specific simple name directly on this symbol.
* Does *not* consider annotation inheritance.
*
* @param tree the tree to check for the presence of the annotation
* @param simpleName the simple name of the annotation to look for, e.g. "Nullable" or
* "CheckReturnValue"
*/