Class ASTHelpers
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic final class
Scanner for determining what types are thrown by a tree.static class
An expression's target type, seetargetType(VisitorState)
. -
Field Summary
Fields -
Method Summary
Modifier and TypeMethodDescriptionstatic Set
<com.sun.tools.javac.util.Name> annotationsAmong
(com.sun.tools.javac.code.Symbol sym, Set<? extends com.sun.tools.javac.util.Name> annotationClasses, VisitorState state) Determines which of a set of annotations are present on a symbol.static EnumSet
<com.sun.tools.javac.code.Flags.Flag> asFlagSet
(long flags) static boolean
canBeRemoved
(com.sun.tools.javac.code.Symbol.ClassSymbol symbol) static boolean
canBeRemoved
(com.sun.tools.javac.code.Symbol.VarSymbol symbol) static boolean
canBeRemoved
(com.sun.tools.javac.code.Symbol symbol, VisitorState state) Returns whether this symbol is safe to remove.static com.sun.tools.javac.code.Symbol.MethodSymbol
canonicalConstructor
(com.sun.tools.javac.code.Symbol.ClassSymbol record, VisitorState state) Finds the canonical constructor on a record.static @Nullable Object
constValue
(Tree tree) Returns the compile-time constant value of a tree if it has one, ornull
.static <T> @Nullable T
constValue
(Tree tree, Class<? extends T> clazz) Returns the compile-time constant value of a tree if it is of type clazz, ornull
.static boolean
containsComments
(Tree tree, VisitorState state) Returns whether the giventree
contains any comments in its source.static String
createPrivateConstructor
(ClassTree classTree) Returns a no arg private constructor for theClassTree
.static @Nullable com.sun.tools.javac.code.Symbol.ClassSymbol
enclosingClass
(com.sun.tools.javac.code.Symbol sym) Return the enclosingClassSymbol
of the given symbol, ornull
.static Stream
<com.sun.tools.javac.code.Symbol> enclosingElements
(com.sun.tools.javac.code.Symbol sym) Returns a stream of the owner hierarchy starting fromsym
, as described bySymbol.owner
.static @Nullable com.sun.tools.javac.code.Symbol.PackageSymbol
enclosingPackage
(com.sun.tools.javac.code.Symbol sym) Return the enclosingPackageSymbol
of the given symbol, ornull
.static LinkedHashSet
<String> enumValues
(com.sun.tools.javac.code.Symbol.TypeSymbol enumType) static @Nullable ClassTree
findClass
(com.sun.tools.javac.code.Symbol.ClassSymbol symbol, VisitorState state) Returns the class tree that matches the given symbol within the compilation unit, or null if none was found.static @Nullable MethodTree
findEnclosingMethod
(VisitorState state) Finds the enclosingMethodTree
.static <T> @Nullable T
findEnclosingNode
(TreePath path, Class<T> klass) Given a TreePath, walks up the tree until it finds a node of the given type.static com.google.common.collect.ImmutableSet
<com.sun.tools.javac.code.Symbol.MethodSymbol> findMatchingMethods
(com.sun.tools.javac.util.Name name, Predicate<com.sun.tools.javac.code.Symbol.MethodSymbol> predicate, com.sun.tools.javac.code.Type startClass, com.sun.tools.javac.code.Types types) Finds all methods in any superclass ofstartClass
with a certainname
that match the givenpredicate
.static @Nullable MethodTree
findMethod
(com.sun.tools.javac.code.Symbol.MethodSymbol symbol, VisitorState state) Returns the method tree that matches the given symbol within the compilation unit, or null if none was found.static <T> @Nullable TreePath
findPathFromEnclosingNodeToTopLevel
(TreePath path, Class<T> klass) Given a TreePath, finds the first enclosing node of the given type and returns the path from the enclosing node to the top-levelCompilationUnitTree
.static Optional
<com.sun.tools.javac.code.Symbol.MethodSymbol> findSuperMethod
(com.sun.tools.javac.code.Symbol.MethodSymbol methodSymbol, com.sun.tools.javac.code.Types types) Finds (if it exists) first (in the class hierarchy) non-interface super method of givenmethod
.static @Nullable com.sun.tools.javac.code.Symbol.MethodSymbol
findSuperMethodInType
(com.sun.tools.javac.code.Symbol.MethodSymbol methodSymbol, com.sun.tools.javac.code.Type superType, com.sun.tools.javac.code.Types types) static Set
<com.sun.tools.javac.code.Symbol.MethodSymbol> findSuperMethods
(com.sun.tools.javac.code.Symbol.MethodSymbol methodSymbol, com.sun.tools.javac.code.Types types) Finds supermethods ofmethodSymbol
, not includingmethodSymbol
itself, and including interfaces.static <T extends Annotation>
@Nullable TgetAnnotation
(Tree tree, Class<T> annotationClass) Deprecated.static <T extends Annotation>
@Nullable TgetAnnotation
(com.sun.tools.javac.code.Symbol sym, Class<T> annotationClass) Deprecated.IfannotationClass
contains a member that is aClass
or an array of them, attempting to access that member from the Error Prone checker code will result in a runtime exception.static AnnotationMirror
getAnnotationMirror
(AnnotationTree annotationTree) Return a mirror of this annotation.static @Nullable String
static List
<? extends AnnotationTree> getAnnotations
(Tree tree) Returns the annotations of the given tree, or an empty list.static List
<AnnotationTree> getAnnotationsWithSimpleName
(List<? extends AnnotationTree> annotations, String name) Returns a list ofAnnotationTree
with the given simple name.static @Nullable com.sun.tools.javac.code.TypeAnnotations.AnnotationType
getAnnotationType
(AnnotationTree anno, @Nullable com.sun.tools.javac.code.Symbol target, VisitorState state) Returns whetheranno
corresponds to a type annotation, ornull
if it could not be determined.static @Nullable AnnotationTree
getAnnotationWithSimpleName
(List<? extends AnnotationTree> annotations, String name) Returns anAnnotationTree
with the given simple name, ornull
.static List
<MethodTree> getConstructors
(ClassTree classTree) Returns the list of all constructors defined in the class (including generated ones).static com.google.common.collect.ImmutableList
<com.sun.tools.javac.code.Symbol.MethodSymbol> getConstructors
(com.sun.tools.javac.code.Symbol.ClassSymbol classSymbol) Returns the list of all constructors defined in the class.static Stream
<com.sun.tools.javac.code.Attribute.Compound> getDeclarationAndTypeAttributes
(com.sun.tools.javac.code.Symbol sym) Returns declaration annotations of the given symbol, as well as 'top-level' type annotations, including : Type annotations of the return type of a method.static @Nullable com.sun.tools.javac.code.Symbol
getDeclaredSymbol
(Tree tree) Gets the symbol declared by a tree.static List
<com.sun.tools.javac.code.Symbol> getEnclosedElements
(com.sun.tools.javac.code.Symbol symbol) A wrapper forSymbol.getEnclosedElements()
to avoid binary compatibility issues for covariant overrides in subtypes ofSymbol
.static Tree
getErasedTypeTree
(Tree tree) Returns the erasure of the given type tree, i.e.static @Nullable String
Extract the filename from aCompilationUnitTree
, with special handling for jar files.static @Nullable String
getFileNameFromUri
(URI uri) Extract the filename from the URI, with special handling for jar files.static com.google.common.collect.ImmutableSet
<String> getGeneratedBy
(VisitorState state) Returns the value of the@Generated
annotation on enclosing classes, if present.static com.google.common.collect.ImmutableSet
<String> getGeneratedBy
(com.sun.tools.javac.code.Symbol symbol, VisitorState state) Returns the values of the given symbol'sGenerated
annotations, if present.static @Nullable ModifiersTree
getModifiers
(Tree tree) Returns the modifiers tree of the given class, method, or variable declaration.static Nullness
getNullnessValue
(ExpressionTree expr, VisitorState state, NullnessAnalysis nullnessAnalysis) Returns theNullness
for an expression as determined by the nullness dataflow analysis.static @Nullable ExpressionTree
getReceiver
(ExpressionTree expressionTree) Returns the receiver of an expression.static com.sun.tools.javac.code.Type
getReceiverType
(ExpressionTree expressionTree) Returns the type of a receiver of a method call expression.static @Nullable com.sun.tools.javac.code.Type
getResultType
(ExpressionTree expressionTree) Returns the type that this expression tree will evaluate to.static com.sun.tools.javac.code.Type
getReturnType
(ExpressionTree expressionTree) Gives the return type of an ExpressionTree that represents a method select.static @Nullable ExpressionTree
getRootAssignable
(MethodInvocationTree methodInvocationTree) Find the root assignable expression of a chain of field accesses.static int
getStartPosition
(Tree tree) Returns the start position of the node.getSwitchDefault
(SwitchTree switchTree) static com.sun.tools.javac.code.Symbol.ClassSymbol
Gets the symbol for a class.static com.sun.tools.javac.code.Symbol.MethodSymbol
getSymbol
(MemberReferenceTree tree) Gets the symbol for a member reference.static com.sun.tools.javac.code.Symbol.MethodSymbol
Gets the symbol for a method invocation.static com.sun.tools.javac.code.Symbol.MethodSymbol
getSymbol
(MethodTree tree) Gets the symbol for a method.static com.sun.tools.javac.code.Symbol.MethodSymbol
getSymbol
(NewClassTree tree) Gets the method symbol for a new class.static com.sun.tools.javac.code.Symbol.PackageSymbol
getSymbol
(PackageTree tree) Gets the symbol for a package.static @Nullable com.sun.tools.javac.code.Symbol
Gets the symbol for a tree.static com.sun.tools.javac.code.Symbol.VarSymbol
getSymbol
(VariableTree tree) Gets the symbol for a variable.static com.google.common.collect.ImmutableSet
<com.sun.tools.javac.code.Type> getThrownExceptions
(Tree tree, VisitorState state) Returns the exceptions thrown bytree
.static @Nullable com.sun.tools.javac.code.Type.ClassType
Returns theClassType
for the given typeClassTree
ornull
if the type could not be determined.static @Nullable com.sun.tools.javac.code.Type
Returns theType
of the given tree, ornull
if the type could not be determined.static com.google.common.collect.ImmutableListMultimap
<com.sun.tools.javac.code.Symbol.TypeVariableSymbol, com.sun.tools.javac.code.Type> getTypeSubstitution
(com.sun.tools.javac.code.Type type, com.sun.tools.javac.code.Symbol sym) Returns the mapping between type variables and their instantiations in the given type.static com.sun.tools.javac.code.Type
getUpperBound
(com.sun.tools.javac.code.Type type, com.sun.tools.javac.code.Types types) Returns the upper bound of a type if it has one, or the type itself if not.static boolean
hasAnnotation
(Tree tree, Class<? extends Annotation> annotationClass, VisitorState state) Deprecated.preferhasAnnotation(Symbol, String, VisitorState)
to avoid needing a runtime dependency on the annotation class, and to prevent issues if there is skew between the definition of the annotation on the runtime and compile-time classpathsstatic boolean
hasAnnotation
(Tree tree, String annotationClass, VisitorState state) Check for the presence of an annotation, considering annotation inheritance.static boolean
hasAnnotation
(com.sun.tools.javac.code.Symbol sym, Class<? extends Annotation> annotationClass, VisitorState state) Deprecated.preferhasAnnotation(Symbol, String, VisitorState)
to avoid needing a runtime dependency on the annotation class, and to prevent issues if there is skew between the definition of the annotation on the runtime and compile-time classpathsstatic boolean
hasAnnotation
(com.sun.tools.javac.code.Symbol sym, String annotationClass, VisitorState state) Determines whether a symbol has an annotation of the given type.static boolean
hasDirectAnnotationWithSimpleName
(Tree tree, String simpleName) Check for the presence of an annotation with a specific simple name directly on this symbol.static boolean
hasDirectAnnotationWithSimpleName
(com.sun.tools.javac.code.Symbol.MethodSymbol sym, String simpleName) static boolean
hasDirectAnnotationWithSimpleName
(com.sun.tools.javac.code.Symbol.VarSymbol sym, String simpleName) static boolean
hasDirectAnnotationWithSimpleName
(com.sun.tools.javac.code.Symbol sym, String simpleName) Check for the presence of an annotation with the given simple name directly on this symbol or its type.static boolean
hasExplicitSource
(Tree tree, VisitorState state) Returns whether the given tree has an explicit source code representation.static boolean
hasImplicitType
(VariableTree tree, VisitorState state) Returns whether this is avar
or a lambda parameter that has no explicit type.static boolean
hasOverloadWithOnlyOneParameter
(com.sun.tools.javac.code.Symbol.MethodSymbol existingMethod, com.sun.tools.javac.util.Name targetMethodName, com.sun.tools.javac.code.Type onlyParameterType, VisitorState state) Returns whetherexistingMethod
has an overload (or "nearly" an overload) with the giventargetMethodName
, and only a single parameter of typeonlyParameterType
.static boolean
inSamePackage
(com.sun.tools.javac.code.Symbol targetSymbol, VisitorState state) Return true if the given symbol is defined in the current package.static boolean
isAbstract
(com.sun.tools.javac.code.Symbol.MethodSymbol method) Returns true if the given method symbol is abstract.static boolean
isBugCheckerCode
(VisitorState state) Returnstrue
if the code is in a BugChecker class.static boolean
isCastable
(com.sun.tools.javac.code.Type s, com.sun.tools.javac.code.Type t, VisitorState state) Returns true iferasure(s)
is castable toerasure(t)
.static boolean
isCheckedExceptionType
(com.sun.tools.javac.code.Type t, VisitorState state) Returns true ift
is a subtype of Throwable but not a subtype of RuntimeException or Error.static boolean
isConsideredFinal
(com.sun.tools.javac.code.Symbol symbol) Returns whethersymbol
is final or effectively final.static boolean
isEffectivelyPrivate
(com.sun.tools.javac.code.Symbol symbol) Returns whether this symbol or any of its owners are private.static boolean
Returns true if the given tree is a generated constructor.static boolean
Attempts to detect whether we're in a static-initializer-like context: that includes direct assignments to static fields, assignments to enum fields, being contained within an expression which is ultimately assigned to a static field.static boolean
isJUnitTestCode
(VisitorState state) Returns true if the leaf node in theTreePath
fromstate
sits somewhere underneath a class or method that is marked as JUnit 3 or 4 test code.static boolean
isKotlin
(com.sun.tools.javac.code.Symbol symbol, VisitorState state) Returnstrue
if this symbol was declared in Kotlin source.static boolean
isRecord
(com.sun.tools.javac.code.Symbol symbol) Returns whether the givenSymbol
is a record, a record's canonical constructor or a member that is part of a record's state vector.static boolean
isSameType
(com.sun.tools.javac.code.Type s, com.sun.tools.javac.code.Type t, VisitorState state) Returns true iferasure(s) == erasure(t)
.static boolean
isStatic
(com.sun.tools.javac.code.Symbol symbol) Returns true if the symbol is static.static boolean
isSubtype
(com.sun.tools.javac.code.Type s, com.sun.tools.javac.code.Type t, VisitorState state) Returns true iferasure(s) <: erasure(t)
.static boolean
static boolean
isSwitchDefault
(CaseTree caseTree) Returns whethercaseTree
is the default case of a switch statement.static boolean
isTestNgTestCode
(VisitorState state) Returns true if the leaf node in theTreePath
fromstate
sits somewhere underneath a class or method that is marked as TestNG test code.static boolean
isVoidType
(com.sun.tools.javac.code.Type type, VisitorState state) Return true if the given type is 'void' or 'Void'.static @Nullable List
<ExpressionTree> matchBinaryTree
(BinaryTree tree, List<Matcher<ExpressionTree>> matchers, VisitorState state) Given a BinaryTree to match against and a list of two matchers, applies the matchers to the operands in both orders.static Stream
<com.sun.tools.javac.code.Symbol.MethodSymbol> matchingMethods
(com.sun.tools.javac.util.Name name, Predicate<com.sun.tools.javac.code.Symbol.MethodSymbol> predicate, com.sun.tools.javac.code.Type startClass, com.sun.tools.javac.code.Types types) Finds all methods in any superclass ofstartClass
with a certainname
that match the givenpredicate
.static boolean
methodCanBeOverridden
(com.sun.tools.javac.code.Symbol.MethodSymbol methodSymbol) Determines whether a method can be overridden.static boolean
methodIsPublicAndNotAnOverride
(com.sun.tools.javac.code.Symbol.MethodSymbol method, VisitorState state) Returns true if the given method symbol is public (both the method and the enclosing class) and does not have a super-method (i.e., it is not an@Override
).static @Nullable com.sun.tools.javac.code.Symbol.ClassSymbol
outermostClass
(com.sun.tools.javac.code.Symbol symbol) Returns the outermost enclosing owning class, ornull
.static boolean
requiresParentheses
(ExpressionTree expression, VisitorState state) Checks whether an expression requires parentheses.static @Nullable com.sun.tools.javac.code.Symbol.MethodSymbol
resolveExistingMethod
(VisitorState state, com.sun.tools.javac.code.Symbol.TypeSymbol base, com.sun.tools.javac.util.Name name, Iterable<com.sun.tools.javac.code.Type> argTypes, Iterable<com.sun.tools.javac.code.Type> tyargTypes) Given a Type (base
), find the method namedname
, with the appropriateargTypes
andtyargTypes
and return its MethodSymbol.static boolean
sameVariable
(ExpressionTree expr1, ExpressionTree expr2) Determines whether two expressions refer to the same variable.static boolean
shouldKeep
(Tree tree) Returns true if any of the given tree is a declaration annotated with an annotation with the simple name@UsedReflectively
or@Keep
, or any annotations meta-annotated with an annotation with that simple name.static Stream
<ExpressionTree> Returns aStream
ofExpressionTree
s resulting from callinggetReceiver(ExpressionTree)
repeatedly until no receiver exists.static Stream
<com.sun.tools.javac.code.Symbol.MethodSymbol> streamSuperMethods
(com.sun.tools.javac.code.Symbol.MethodSymbol methodSymbol, com.sun.tools.javac.code.Types types) static boolean
stringContainsComments
(CharSequence source, com.sun.tools.javac.util.Context context) Returns true if the given source code contains comments.static ExpressionTree
Given an ExpressionTree, removes any enclosing parentheses.static Tree
stripParentheses
(Tree tree) Removes any enclosing parentheses from the tree.static @Nullable ASTHelpers.TargetType
targetType
(VisitorState state) Returns the target type of the tree at the givenVisitorState
's path, or elsenull
.static boolean
variableIsStaticFinal
(com.sun.tools.javac.code.Symbol.VarSymbol var) Whether the variable is (or should be regarded as) static final.
-
Field Details
-
POTENTIALLY_AMBIGUOUS
public static final long POTENTIALLY_AMBIGUOUS- See Also:
-
-
Method Details
-
sameVariable
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. -
getDeclaredSymbol
Gets the symbol declared by a tree. Returns null iftree
does not declare a symbol or is null. -
getSymbol
Gets the symbol for a tree. Returns null if this tree does not have a symbol because it is of the wrong type, iftree
is null, or if the symbol cannot be found due to a compilation error. -
getSymbol
Gets the symbol for a class. -
getSymbol
Gets the symbol for a package. -
getSymbol
Gets the symbol for a method. -
getSymbol
Gets the method symbol for a new class. -
getSymbol
Gets the symbol for a variable. -
getSymbol
Gets the symbol for a method invocation. -
getSymbol
Gets the symbol for a member reference. -
canBeRemoved
Returns whether this symbol is safe to remove. That is, if it cannot be accessed from outside its own compilation unit.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.
-
canBeRemoved
public static boolean canBeRemoved(com.sun.tools.javac.code.Symbol.VarSymbol symbol) -
canBeRemoved
public static boolean canBeRemoved(com.sun.tools.javac.code.Symbol.ClassSymbol symbol) -
isEffectivelyPrivate
public static boolean isEffectivelyPrivate(com.sun.tools.javac.code.Symbol symbol) Returns whether this symbol or any of its owners are private. -
requiresParentheses
Checks whether an expression requires parentheses. -
stripParentheses
-
stripParentheses
Given an ExpressionTree, removes any enclosing parentheses. -
findPathFromEnclosingNodeToTopLevel
-
enclosingElements
public static Stream<com.sun.tools.javac.code.Symbol> enclosingElements(com.sun.tools.javac.code.Symbol sym) Returns a stream of the owner hierarchy starting fromsym
, as described bySymbol.owner
. Returnssym
itself first, followed by its owners, closest first, up to the owning package and possibly module. -
findEnclosingNode
-
findEnclosingMethod
Finds the enclosingMethodTree
. Returnsnull
if no such node found. -
getRootAssignable
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.Examples:
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
-
getReturnType
Gives the return type of an ExpressionTree that represents a method select.TODO(eaftan): Are there other places this could be used?
-
getResultType
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.TODO(andrewrice) consider replacing
getReturnType
with this method- Parameters:
expressionTree
- the tree to evaluate- Returns:
- the result type of this tree or null if unable to resolve it
-
getReceiverType
Returns the type of a receiver of a method call expression. Precondition: the expressionTree corresponds to a method call.Examples:
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
-
getReceiver
Returns the receiver of an expression.Examples:
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
-
streamReceivers
Returns aStream
ofExpressionTree
s resulting from callinggetReceiver(ExpressionTree)
repeatedly until no receiver exists.For example, give
foo().bar().baz()
, returns a stream of[foo().bar(), foo()]
.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.
-
matchBinaryTree
public static @Nullable List<ExpressionTree> matchBinaryTree(BinaryTree tree, List<Matcher<ExpressionTree>> matchers, VisitorState state) 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.- Parameters:
tree
- a BinaryTree AST nodematchers
- a list of matchersstate
- the VisitorState- Returns:
- a list of matched operands, or null if at least one did not match
-
findMethod
public static @Nullable MethodTree findMethod(com.sun.tools.javac.code.Symbol.MethodSymbol symbol, VisitorState state) Returns the method tree that matches the given symbol within the compilation unit, or null if none was found. -
findClass
public static @Nullable ClassTree findClass(com.sun.tools.javac.code.Symbol.ClassSymbol symbol, VisitorState state) Returns the class tree that matches the given symbol within the compilation unit, or null if none was found. -
findSuperMethodInType
public static @Nullable com.sun.tools.javac.code.Symbol.MethodSymbol findSuperMethodInType(com.sun.tools.javac.code.Symbol.MethodSymbol methodSymbol, com.sun.tools.javac.code.Type superType, com.sun.tools.javac.code.Types types) -
findSuperMethods
public static Set<com.sun.tools.javac.code.Symbol.MethodSymbol> findSuperMethods(com.sun.tools.javac.code.Symbol.MethodSymbol methodSymbol, com.sun.tools.javac.code.Types types) Finds supermethods ofmethodSymbol
, not includingmethodSymbol
itself, and including interfaces. -
streamSuperMethods
public static Stream<com.sun.tools.javac.code.Symbol.MethodSymbol> streamSuperMethods(com.sun.tools.javac.code.Symbol.MethodSymbol methodSymbol, com.sun.tools.javac.code.Types types) -
findSuperMethod
public static Optional<com.sun.tools.javac.code.Symbol.MethodSymbol> findSuperMethod(com.sun.tools.javac.code.Symbol.MethodSymbol methodSymbol, com.sun.tools.javac.code.Types types) Finds (if it exists) first (in the class hierarchy) non-interface super method of givenmethod
. -
matchingMethods
public static Stream<com.sun.tools.javac.code.Symbol.MethodSymbol> matchingMethods(com.sun.tools.javac.util.Name name, Predicate<com.sun.tools.javac.code.Symbol.MethodSymbol> predicate, com.sun.tools.javac.code.Type startClass, com.sun.tools.javac.code.Types types) Finds all methods in any superclass ofstartClass
with a certainname
that match the givenpredicate
.- Returns:
- The (possibly empty) list of methods in any superclass that match
predicate
and have the givenname
. Results are returned least-abstract first, i.e., starting in thestartClass
itself, progressing through its superclasses, and finally interfaces in an unspecified order.
-
findMatchingMethods
public static com.google.common.collect.ImmutableSet<com.sun.tools.javac.code.Symbol.MethodSymbol> findMatchingMethods(com.sun.tools.javac.util.Name name, Predicate<com.sun.tools.javac.code.Symbol.MethodSymbol> predicate, com.sun.tools.javac.code.Type startClass, com.sun.tools.javac.code.Types types) Finds all methods in any superclass ofstartClass
with a certainname
that match the givenpredicate
.- Returns:
- The (possibly empty) set of methods in any superclass that match
predicate
and have the givenname
. The set's iteration order will be the same as the order documented inmatchingMethods(Name, java.util.function.Predicate, Type, Types)
.
-
methodCanBeOverridden
public static boolean methodCanBeOverridden(com.sun.tools.javac.code.Symbol.MethodSymbol methodSymbol) Determines whether a method can be overridden.- Returns:
- true if the method can be overridden.
-
isRecord
public static boolean isRecord(com.sun.tools.javac.code.Symbol symbol) Returns whether the givenSymbol
is a record, a record's canonical constructor or a member that is part of a record's state vector.Health warning: some things are flagged within a compilation, but won't be flagged across compilation boundaries, like canonical constructors.
-
canonicalConstructor
public static com.sun.tools.javac.code.Symbol.MethodSymbol canonicalConstructor(com.sun.tools.javac.code.Symbol.ClassSymbol record, VisitorState state) Finds the canonical constructor on a record. -
hasAnnotation
public static boolean hasAnnotation(com.sun.tools.javac.code.Symbol sym, String annotationClass, VisitorState state) Determines whether a symbol has an annotation of the given type. This includes annotations inherited from superclasses due to@Inherited
.- Parameters:
annotationClass
- the binary class name of the annotation (e.g. "org.jspecify.annotations.Nullable", or "some.package.OuterClassName$InnerClassName")- Returns:
- true if the symbol is annotated with given type.
-
hasAnnotation
@InlineMe(replacement="ASTHelpers.hasAnnotation(sym, annotationClass.getName(), state)", imports="com.google.errorprone.util.ASTHelpers") @Deprecated public static boolean hasAnnotation(com.sun.tools.javac.code.Symbol sym, Class<? extends Annotation> annotationClass, VisitorState state) Deprecated.preferhasAnnotation(Symbol, String, VisitorState)
to avoid needing a runtime dependency on the annotation class, and to prevent issues if there is skew between the definition of the annotation on the runtime and compile-time classpathsCheck for the presence of an annotation, considering annotation inheritance.- Returns:
- true if the symbol is annotated with given type.
-
hasAnnotation
Check for the presence of an annotation, considering annotation inheritance.- Parameters:
annotationClass
- the binary class name of the annotation (e.g. "org.jspecify.annotations.Nullable", or "some.package.OuterClassName$InnerClassName")- Returns:
- true if the tree is annotated with given type.
-
hasAnnotation
@InlineMe(replacement="ASTHelpers.hasAnnotation(tree, annotationClass.getName(), state)", imports="com.google.errorprone.util.ASTHelpers") @Deprecated public static boolean hasAnnotation(Tree tree, Class<? extends Annotation> annotationClass, VisitorState state) Deprecated.preferhasAnnotation(Symbol, String, VisitorState)
to avoid needing a runtime dependency on the annotation class, and to prevent issues if there is skew between the definition of the annotation on the runtime and compile-time classpathsCheck for the presence of an annotation, considering annotation inheritance.- Returns:
- true if the tree is annotated with given type.
-
annotationsAmong
public static Set<com.sun.tools.javac.util.Name> annotationsAmong(com.sun.tools.javac.code.Symbol sym, Set<? extends com.sun.tools.javac.util.Name> annotationClasses, VisitorState state) Determines which of a set of annotations are present on a symbol.- Parameters:
sym
- The symbol to inspect for annotationsannotationClasses
- 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".- Returns:
- A possibly-empty set of annotations present on the queried element.
-
hasDirectAnnotationWithSimpleName
public static boolean hasDirectAnnotationWithSimpleName(com.sun.tools.javac.code.Symbol sym, String simpleName) Check for the presence of an annotation with the given simple name directly on this symbol or its type. (If the given symbol is a method symbol, the type searched for annotations is its return type.)This method looks only a annotations that are directly present. It does not consider annotation inheritance (see JLS 9.6.4.3).
-
hasDirectAnnotationWithSimpleName
public static boolean hasDirectAnnotationWithSimpleName(com.sun.tools.javac.code.Symbol.MethodSymbol sym, String simpleName) -
hasDirectAnnotationWithSimpleName
public static boolean hasDirectAnnotationWithSimpleName(com.sun.tools.javac.code.Symbol.VarSymbol sym, String simpleName) -
hasDirectAnnotationWithSimpleName
Check for the presence of an annotation with a specific simple name directly on this symbol. Does *not* consider annotation inheritance.- Parameters:
tree
- the tree to check for the presence of the annotationsimpleName
- the simple name of the annotation to look for, e.g. "Nullable" or "CheckReturnValue"
-
shouldKeep
Returns true if any of the given tree is a declaration annotated with an annotation with the simple name@UsedReflectively
or@Keep
, or any annotations meta-annotated with an annotation with that simple name.This indicates the annotated element is used (e.g. by reflection, or referenced by generated code) and should not be removed.
-
getAnnotation
@Deprecated public static <T extends Annotation> @Nullable T getAnnotation(Tree tree, Class<T> annotationClass) Deprecated.IfannotationClass
contains a member that is aClass
or an array of them, attempting to access that member from the Error Prone checker code will result in a runtime exception. Instead, operate ongetSymbol(tree).getAnnotationMirrors()
to meta-syntactically inspect the annotation. Note that this method (and thegetSymbol
-based replacement suggested above) looks for annotations not just on the given tree (such as aMethodTree
) but also on the symbol referred to by the given tree (such as on theSymbol.MethodSymbol
that is being called by the givenMethodInvocationTree
). If you want to examine annotations only on the given tree, then usegetAnnotations(Tree)
(or a direct call to agetAnnotations
method declared on a specificTree
subclass) instead.Retrieves an annotation, considering annotation inheritance. -
getAnnotation
@Deprecated public static <T extends Annotation> @Nullable T getAnnotation(com.sun.tools.javac.code.Symbol sym, Class<T> annotationClass) Deprecated.IfannotationClass
contains a member that is aClass
or an array of them, attempting to access that member from the Error Prone checker code will result in a runtime exception. Instead, operate onsym.getAnnotationMirrors()
to meta-syntactically inspect the annotation.Retrieves an annotation, considering annotation inheritance. -
enumValues
- Returns:
- all values of the given enum type, in declaration order.
-
isGeneratedConstructor
Returns true if the given tree is a generated constructor. -
getConstructors
Returns the list of all constructors defined in the class (including generated ones). -
getEnclosedElements
public static List<com.sun.tools.javac.code.Symbol> getEnclosedElements(com.sun.tools.javac.code.Symbol symbol) A wrapper forSymbol.getEnclosedElements()
to avoid binary compatibility issues for covariant overrides in subtypes ofSymbol
. -
getConstructors
public static com.google.common.collect.ImmutableList<com.sun.tools.javac.code.Symbol.MethodSymbol> getConstructors(com.sun.tools.javac.code.Symbol.ClassSymbol classSymbol) Returns the list of all constructors defined in the class. -
getType
Returns theType
of the given tree, ornull
if the type could not be determined. -
getType
Returns theClassType
for the given typeClassTree
ornull
if the type could not be determined. -
getAnnotationName
-
getErasedTypeTree
-
enclosingClass
public static @Nullable com.sun.tools.javac.code.Symbol.ClassSymbol enclosingClass(com.sun.tools.javac.code.Symbol sym) Return the enclosingClassSymbol
of the given symbol, ornull
. -
enclosingPackage
public static @Nullable com.sun.tools.javac.code.Symbol.PackageSymbol enclosingPackage(com.sun.tools.javac.code.Symbol sym) Return the enclosingPackageSymbol
of the given symbol, ornull
.Prefer this to
Symbol.packge()
, which throws aNullPointerException
for symbols that are not contained by a package: https://bugs.openjdk.java.net/browse/JDK-8231911 -
inSamePackage
public static boolean inSamePackage(com.sun.tools.javac.code.Symbol targetSymbol, VisitorState state) Return true if the given symbol is defined in the current package. -
getNullnessValue
public static Nullness getNullnessValue(ExpressionTree expr, VisitorState state, NullnessAnalysis nullnessAnalysis) Returns theNullness
for an expression as determined by the nullness dataflow analysis. -
constValue
-
constValue
-
isVoidType
Return true if the given type is 'void' or 'Void'. -
isSubtype
public static boolean isSubtype(com.sun.tools.javac.code.Type s, com.sun.tools.javac.code.Type t, VisitorState state) Returns true iferasure(s) <: erasure(t)
. -
isCheckedExceptionType
Returns true ift
is a subtype of Throwable but not a subtype of RuntimeException or Error. -
isCastable
public static boolean isCastable(com.sun.tools.javac.code.Type s, com.sun.tools.javac.code.Type t, VisitorState state) Returns true iferasure(s)
is castable toerasure(t)
. -
isSameType
public static boolean isSameType(com.sun.tools.javac.code.Type s, com.sun.tools.javac.code.Type t, VisitorState state) Returns true iferasure(s) == erasure(t)
. -
getModifiers
Returns the modifiers tree of the given class, method, or variable declaration. -
getAnnotations
Returns the annotations of the given tree, or an empty list. -
getUpperBound
public static com.sun.tools.javac.code.Type getUpperBound(com.sun.tools.javac.code.Type type, com.sun.tools.javac.code.Types types) Returns the upper bound of a type if it has one, or the type itself if not. Correctly handles wildcards and capture variables. -
isJUnitTestCode
Returns true if the leaf node in theTreePath
fromstate
sits somewhere underneath a class or method that is marked as JUnit 3 or 4 test code. -
isTestNgTestCode
Returns true if the leaf node in theTreePath
fromstate
sits somewhere underneath a class or method that is marked as TestNG test code. -
getAnnotationWithSimpleName
public static @Nullable AnnotationTree getAnnotationWithSimpleName(List<? extends AnnotationTree> annotations, String name) Returns anAnnotationTree
with the given simple name, ornull
. -
getAnnotationsWithSimpleName
public static List<AnnotationTree> getAnnotationsWithSimpleName(List<? extends AnnotationTree> annotations, String name) Returns a list ofAnnotationTree
with the given simple name. This is useful forRepeatable
annotations -
getAnnotationType
public static @Nullable com.sun.tools.javac.code.TypeAnnotations.AnnotationType getAnnotationType(AnnotationTree anno, @Nullable com.sun.tools.javac.code.Symbol target, VisitorState state) Returns whetheranno
corresponds to a type annotation, ornull
if it could not be determined. -
getFileName
Extract the filename from aCompilationUnitTree
, with special handling for jar files. The return value is normalized to always use '/' to separate elements of the path and to always have a leading '/'. -
getFileNameFromUri
-
resolveExistingMethod
public static @Nullable com.sun.tools.javac.code.Symbol.MethodSymbol resolveExistingMethod(VisitorState state, com.sun.tools.javac.code.Symbol.TypeSymbol base, com.sun.tools.javac.util.Name name, Iterable<com.sun.tools.javac.code.Type> argTypes, Iterable<com.sun.tools.javac.code.Type> tyargTypes) Given a Type (base
), find the method namedname
, with the appropriateargTypes
andtyargTypes
and return its MethodSymbol.Ex:
..... class A {} class B { public int hashCode() { return 42; } } ..... MethodSymbol meth = ASTHelpers.resolveExistingMethod( state, symbol, state.getName("hashCode"), ImmutableList.<Type>of(), ImmutableList.<Type>of());
meth
could be different MethodSymbol's depending on whethersymbol
representedB
orA
. (B's hashCode method or Object#hashCode).- Returns:
- a MethodSymbol representing the method symbol resolved from the context of this type,
or
null
if the method could not be resolved.
-
getGeneratedBy
Returns the value of the@Generated
annotation on enclosing classes, if present.Although
@Generated
can be applied to non-class program elements, there are no known cases of that happening, so it isn't supported here. -
getGeneratedBy
public static com.google.common.collect.ImmutableSet<String> getGeneratedBy(com.sun.tools.javac.code.Symbol symbol, VisitorState state) Returns the values of the given symbol'sGenerated
annotations, if present. If the annotation doesn't havevalues
set, returns the string name of the annotation itself. -
isSuper
-
isInStaticInitializer
Attempts to detect whether we're in a static-initializer-like context: that includes direct assignments to static fields, assignments to enum fields, being contained within an expression which is ultimately assigned to a static field.This is very much a heuristic, and not fool-proof.
-
variableIsStaticFinal
public static boolean variableIsStaticFinal(com.sun.tools.javac.code.Symbol.VarSymbol var) Whether the variable is (or should be regarded as) static final.We regard instance fields within enums as "static final", as they will only have a finite number of instances tied to an (effectively) static final enum value.
-
targetType
Returns the target type of the tree at the givenVisitorState
's path, or elsenull
.For example, the target type of an assignment expression is the variable's type, and the target type of a return statement is the enclosing method's type.
-
getDeclarationAndTypeAttributes
public static Stream<com.sun.tools.javac.code.Attribute.Compound> getDeclarationAndTypeAttributes(com.sun.tools.javac.code.Symbol sym) Returns declaration annotations of the given symbol, as well as 'top-level' type annotations, including :- Type annotations of the return type of a method.
- Type annotations on the type of a formal parameter or field.
One might expect this to be equivalent to information returned by
Type.getAnnotationMirrors()
, but javac doesn't associate type annotation information with types for symbols completed from class files, so that approach doesn't work across compilation boundaries. -
getAnnotationMirror
Return a mirror of this annotation.- Returns:
- an
AnnotationMirror
for the annotation represented byannotationTree
.
-
containsComments
Returns whether the giventree
contains any comments in its source. -
outermostClass
public static @Nullable com.sun.tools.javac.code.Symbol.ClassSymbol outermostClass(com.sun.tools.javac.code.Symbol symbol) Returns the outermost enclosing owning class, ornull
. Doesn't crash on symbols that aren't containing in a package, unlikeSymbol.outermostClass()
(see b/123431414). -
isConsideredFinal
public static boolean isConsideredFinal(com.sun.tools.javac.code.Symbol symbol) Returns whethersymbol
is final or effectively final. -
getThrownExceptions
public static com.google.common.collect.ImmutableSet<com.sun.tools.javac.code.Type> getThrownExceptions(Tree tree, VisitorState state) Returns the exceptions thrown bytree
. -
getStartPosition
Returns the start position of the node. -
createPrivateConstructor
-
isBugCheckerCode
Returnstrue
if the code is in a BugChecker class. -
isStatic
public static boolean isStatic(com.sun.tools.javac.code.Symbol symbol) Returns true if the symbol is static. Returnsfalse
for module symbols. -
methodIsPublicAndNotAnOverride
public static boolean methodIsPublicAndNotAnOverride(com.sun.tools.javac.code.Symbol.MethodSymbol method, VisitorState state) Returns true if the given method symbol is public (both the method and the enclosing class) and does not have a super-method (i.e., it is not an@Override
).This method is useful (in part) for determining whether to suggest API improvements or not.
-
isAbstract
public static boolean isAbstract(com.sun.tools.javac.code.Symbol.MethodSymbol method) Returns true if the given method symbol is abstract.Note: this API does not consider interface
default
methods to be abstract. -
asFlagSet
-
stringContainsComments
public static boolean stringContainsComments(CharSequence source, com.sun.tools.javac.util.Context context) Returns true if the given source code contains comments. -
getTypeSubstitution
public static com.google.common.collect.ImmutableListMultimap<com.sun.tools.javac.code.Symbol.TypeVariableSymbol, com.sun.tools.javac.code.Type> getTypeSubstitution(com.sun.tools.javac.code.Type type, com.sun.tools.javac.code.Symbol sym) Returns the mapping between type variables and their instantiations in the given type. For example, the instantiation ofMap<K, V>
asMap<String, Integer>
would be represented as aTypeSubstitution
from[K, V]
to[String, Integer]
. -
hasImplicitType
Returns whether this is avar
or a lambda parameter that has no explicit type. -
hasExplicitSource
Returns whether the given tree has an explicit source code representation. -
isKotlin
Returnstrue
if this symbol was declared in Kotlin source. -
hasOverloadWithOnlyOneParameter
public static boolean hasOverloadWithOnlyOneParameter(com.sun.tools.javac.code.Symbol.MethodSymbol existingMethod, com.sun.tools.javac.util.Name targetMethodName, com.sun.tools.javac.code.Type onlyParameterType, VisitorState state) Returns whetherexistingMethod
has an overload (or "nearly" an overload) with the giventargetMethodName
, and only a single parameter of typeonlyParameterType
. -
getSwitchDefault
-
isSwitchDefault
Returns whethercaseTree
is the default case of a switch statement.
-
annotationClass
contains a member that is aClass
or an array of them, attempting to access that member from the Error Prone checker code will result in a runtime exception.