Class ASTHelpers
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic final classScanner for determining what types are thrown by a tree. -
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 com.google.common.collect.ImmutableSet<String> asFlagSet(long flags) Returns a set of strings representing the flags in the given long.static booleancanBeRemoved(com.sun.tools.javac.code.Symbol.ClassSymbol symbol) static booleancanBeRemoved(com.sun.tools.javac.code.Symbol.VarSymbol symbol) static booleancanBeRemoved(com.sun.tools.javac.code.Symbol symbol, VisitorState state) Returns whether this symbol is safe to remove.static com.sun.tools.javac.code.Symbol.MethodSymbolcanonicalConstructor(com.sun.tools.javac.code.Symbol.ClassSymbol record, VisitorState state) Finds the canonical constructor on a record.static @Nullable ObjectconstValue(Tree tree) Returns the compile-time constant value of a tree if it has one, ornull.static <T> @Nullable TconstValue(Tree tree, Class<? extends T> clazz) Returns the compile-time constant value of a tree if it is of type clazz, ornull.static booleancontainsComments(Tree tree, VisitorState state) Returns whether the giventreecontains any comments in its source.static StringcreatePrivateConstructor(ClassTree classTree) Returns a no arg private constructor for theClassTree.static @Nullable com.sun.tools.javac.code.Symbol.ClassSymbolenclosingClass(com.sun.tools.javac.code.Symbol sym) Return the enclosingClassSymbolof 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.PackageSymbolenclosingPackage(com.sun.tools.javac.code.Symbol sym) Return the enclosingPackageSymbolof the given symbol, ornull.static LinkedHashSet<String> enumValues(com.sun.tools.javac.code.Symbol.TypeSymbol enumType) static @Nullable ClassTreefindClass(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 MethodTreefindEnclosingMethod(VisitorState state) Finds the enclosingMethodTree.static <T> @Nullable TfindEnclosingNode(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 ofstartClasswith a certainnamethat match the givenpredicate.static @Nullable MethodTreefindMethod(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 TreePathfindPathFromEnclosingNodeToTopLevel(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 @Nullable com.sun.tools.javac.code.Symbol.MethodSymbolfindSuperMethodInType(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 includingmethodSymbolitself, 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.IfannotationClasscontains a member that is aClassor an array of them, attempting to access that member from the Error Prone checker code will result in a runtime exception.static AnnotationMirrorgetAnnotationMirror(AnnotationTree annotationTree) Return a mirror of this annotation.static @Nullable Stringstatic 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 ofAnnotationTreewith the given simple name.static @Nullable com.sun.tools.javac.code.TypeAnnotations.AnnotationTypegetAnnotationType(AnnotationTree anno, @Nullable com.sun.tools.javac.code.Symbol target, VisitorState state) Returns whetherannocorresponds to a type annotation, ornullif it could not be determined.static @Nullable AnnotationTreegetAnnotationWithSimpleName(List<? extends AnnotationTree> annotations, String name) Returns anAnnotationTreewith 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.SymbolgetDeclaredSymbol(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 forElement.getEnclosedElements()to avoid binary compatibility issues for covariant overrides in subtypes ofSymbol.static TreegetErasedTypeTree(Tree tree) Returns the erasure of the given type tree, i.e.static @Nullable StringExtract the filename from aCompilationUnitTree, with special handling for jar files.static @Nullable StringgetFileNameFromUri(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@Generatedannotation on enclosing classes, if present.static com.google.common.collect.ImmutableSet<String> getGeneratedBy(com.sun.tools.javac.code.Symbol symbol) Returns the values of the given symbol'sGeneratedannotations, if present.static com.google.common.collect.ImmutableSet<String> getGeneratedBy(com.sun.tools.javac.code.Symbol symbol, VisitorState state) Deprecated.TODO(ghm): delete after a JavaBuilder releasestatic @Nullable ModifiersTreegetModifiers(Tree tree) Returns the modifiers tree of the given class, method, or variable declaration.static NullnessgetNullnessValue(ExpressionTree expr, VisitorState state, NullnessAnalysis nullnessAnalysis) Returns theNullnessfor an expression as determined by the nullness dataflow analysis.static @Nullable ExpressionTreegetReceiver(ExpressionTree expressionTree) Returns the receiver of an expression.static com.sun.tools.javac.code.TypegetReceiverType(ExpressionTree expressionTree) Returns the type of a receiver of a method call expression.static @Nullable com.sun.tools.javac.code.TypegetResultType(ExpressionTree expressionTree) Returns the type that this expression tree will evaluate to.static com.sun.tools.javac.code.TypegetReturnType(ExpressionTree expressionTree) Gives the return type of an ExpressionTree that represents a method select.static @Nullable ExpressionTreegetRootAssignable(MethodInvocationTree methodInvocationTree) Find the root assignable expression of a chain of field accesses.static intgetStartPosition(Tree tree) Returns the start position of the node.getSwitchDefault(SwitchTree switchTree) static com.sun.tools.javac.code.Symbol.ClassSymbolGets the symbol for a class.static com.sun.tools.javac.code.Symbol.MethodSymbolgetSymbol(MemberReferenceTree tree) Gets the symbol for a member reference.static com.sun.tools.javac.code.Symbol.MethodSymbolGets the symbol for a method invocation.static com.sun.tools.javac.code.Symbol.MethodSymbolgetSymbol(MethodTree tree) Gets the symbol for a method.static com.sun.tools.javac.code.Symbol.MethodSymbolgetSymbol(NewClassTree tree) Gets the method symbol for a new class.static com.sun.tools.javac.code.Symbol.PackageSymbolgetSymbol(PackageTree tree) Gets the symbol for a package.static @Nullable com.sun.tools.javac.code.SymbolGets the symbol for a tree.static com.sun.tools.javac.code.Symbol.VarSymbolgetSymbol(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.ClassTypeReturns theClassTypefor the given typeClassTreeornullif the type could not be determined.static @Nullable com.sun.tools.javac.code.TypeReturns theTypeof the given tree, ornullif 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.TypegetUpperBound(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 booleanhasAnnotation(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 booleanhasAnnotation(Tree tree, String annotationClass, VisitorState state) Check for the presence of an annotation, considering annotation inheritance.static booleanhasAnnotation(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 booleanhasAnnotation(com.sun.tools.javac.code.Symbol sym, String annotationClass, VisitorState state) Determines whether a symbol has an annotation of the given type.static booleanhasDirectAnnotation(com.sun.tools.javac.code.Symbol.MethodSymbol sym, String qualifiedName) Check for the presence of an annotation with the given qualified name directly on this symbol or its type.static booleanhasDirectAnnotationWithSimpleName(Tree tree, String simpleName) Check for the presence of an annotation with a specific simple name directly on this symbol.static booleanhasDirectAnnotationWithSimpleName(com.sun.tools.javac.code.Symbol.MethodSymbol sym, String simpleName) static booleanhasDirectAnnotationWithSimpleName(com.sun.tools.javac.code.Symbol.VarSymbol sym, String simpleName) static booleanhasDirectAnnotationWithSimpleName(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 booleanhasExplicitSource(Tree tree, VisitorState state) Returns whether the given tree has an explicit source code representation.static booleanhasImplicitType(VariableTree tree, VisitorState state) Returns whether this is avaror a lambda parameter that has no explicit type.static booleanhasOverloadWithOnlyOneParameter(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 whetherexistingMethodhas an overload (or "nearly" an overload) with the giventargetMethodName, and only a single parameter of typeonlyParameterType.static booleaninSamePackage(com.sun.tools.javac.code.Symbol targetSymbol, VisitorState state) Return true if the given symbol is defined in the current package.static booleanisAbstract(com.sun.tools.javac.code.Symbol.MethodSymbol method) Returns true if the given method symbol is abstract.static booleanisBugCheckerCode(VisitorState state) Returnstrueif the code is in a BugChecker class.static booleanisCastable(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 booleanisCheckedExceptionType(com.sun.tools.javac.code.Type t, VisitorState state) Returns true iftis a subtype of Throwable but not a subtype of RuntimeException or Error.static booleanisConsideredFinal(com.sun.tools.javac.code.Symbol symbol) Returns whethersymbolis final or effectively final.static booleanisEffectivelyPrivate(com.sun.tools.javac.code.Symbol symbol) Returns whether this symbol or any of its owners are private.static booleanReturns true if the given tree is a generated constructor.static booleanAttempts 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 booleanisJUnitTestCode(VisitorState state) Returns true if the leaf node in theTreePathfromstatesits somewhere underneath a class or method that is marked as JUnit 3 or 4 test code.static booleanisKotlin(com.sun.tools.javac.code.Symbol symbol, VisitorState state) Returnstrueif this symbol was declared in Kotlin source.static booleanisRecord(com.sun.tools.javac.code.Symbol symbol) Returns whether the givenSymbolis a record, a record's canonical constructor or a member that is part of a record's state vector.static booleanisSameType(com.sun.tools.javac.code.Type s, com.sun.tools.javac.code.Type t, VisitorState state) Returns true iferasure(s) == erasure(t).static booleanisStatic(com.sun.tools.javac.code.Symbol symbol) Returns true if the symbol is static.static booleanisSubtype(com.sun.tools.javac.code.Type s, com.sun.tools.javac.code.Type t, VisitorState state) Returns true iferasure(s) <: erasure(t).static booleanstatic booleanisSwitchDefault(CaseTree caseTree) Returns whethercaseTreeis the default case of a switch statement.static booleanisTestNgTestCode(VisitorState state) Returns true if the leaf node in theTreePathfromstatesits somewhere underneath a class or method that is marked as TestNG test code.static booleanisVoidType(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 ofstartClasswith a certainnamethat match the givenpredicate.static booleanmethodCanBeOverridden(com.sun.tools.javac.code.Symbol.MethodSymbol methodSymbol) Determines whether a method can be overridden.static booleanmethodIsPublicAndNotAnOverride(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.ClassSymboloutermostClass(com.sun.tools.javac.code.Symbol symbol) Returns the outermost enclosing owning class, ornull.static booleanrequiresParentheses(ExpressionTree expression, VisitorState state) Checks whether an expression requires parentheses.static @Nullable com.sun.tools.javac.code.Symbol.MethodSymbolresolveExistingMethod(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 appropriateargTypesandtyargTypesand return its MethodSymbol.static booleansameVariable(ExpressionTree expr1, ExpressionTree expr2) Determines whether two expressions refer to the same variable.static booleanshouldKeep(Tree tree) Deprecated.use@com.google.errorprone.bugpatterns.WellKnownKeepinstead.static Stream<ExpressionTree> Returns aStreamofExpressionTrees 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 booleanstringContainsComments(CharSequence source, com.sun.tools.javac.util.Context context) Returns true if the given source code contains comments.static ExpressionTreeGiven an ExpressionTree, removes any enclosing parentheses.static TreestripParentheses(Tree tree) Removes any enclosing parentheses from the tree.static @Nullable TargetTypetargetType(VisitorState state) Deprecated.use TargetType.targetType directlystatic booleanvariableIsStaticFinal(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 iftreedoes 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, iftreeis 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. Returnssymitself first, followed by its owners, closest first, up to the owning package and possibly module. -
findEnclosingNode
-
findEnclosingMethod
Finds the enclosingMethodTree. Returnsnullif 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
getReturnTypewith 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 aStreamofExpressionTrees 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 includingmethodSymbolitself, 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) -
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 ofstartClasswith a certainnamethat match the givenpredicate.- Returns:
- The (possibly empty) list of methods in any superclass that match
predicateand have the givenname. Results are returned least-abstract first, i.e., starting in thestartClassitself, 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 ofstartClasswith a certainnamethat match the givenpredicate.- Returns:
- The (possibly empty) set of methods in any superclass that match
predicateand 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 givenSymbolis 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) -
hasDirectAnnotation
public static boolean hasDirectAnnotation(com.sun.tools.javac.code.Symbol.MethodSymbol sym, String qualifiedName) Check for the presence of an annotation with the given qualified 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
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
Deprecated.use@com.google.errorprone.bugpatterns.WellKnownKeepinstead. -
getAnnotation
@Deprecated public static <T extends Annotation> @Nullable T getAnnotation(Tree tree, Class<T> annotationClass) Deprecated.IfannotationClasscontains a member that is aClassor 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.MethodSymbolthat 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 agetAnnotationsmethod declared on a specificTreesubclass) 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.IfannotationClasscontains a member that is aClassor 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 forElement.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 theTypeof the given tree, ornullif the type could not be determined. -
getType
Returns theClassTypefor the given typeClassTreeornullif 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 enclosingClassSymbolof 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 enclosingPackageSymbolof the given symbol, ornull.Prefer this to
Symbol.packge(), which throws aNullPointerExceptionfor 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 theNullnessfor 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 iftis 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 theTreePathfromstatesits somewhere underneath a class or method that is marked as JUnit 3 or 4 test code. -
isTestNgTestCode
Returns true if the leaf node in theTreePathfromstatesits 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 anAnnotationTreewith the given simple name, ornull. -
getAnnotationsWithSimpleName
public static List<AnnotationTree> getAnnotationsWithSimpleName(List<? extends AnnotationTree> annotations, String name) Returns a list ofAnnotationTreewith the given simple name. This is useful forRepeatableannotations -
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 whetherannocorresponds to a type annotation, ornullif 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 appropriateargTypesandtyargTypesand 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());methcould be different MethodSymbol's depending on whethersymbolrepresentedBorA. (B's hashCode method or Object#hashCode).- Returns:
- a MethodSymbol representing the method symbol resolved from the context of this type,
or
nullif the method could not be resolved.
-
getGeneratedBy
Returns the value of the@Generatedannotation on enclosing classes, if present.Although
@Generatedcan 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) Returns the values of the given symbol'sGeneratedannotations, if present. If the annotation doesn't havevaluesset, returns the string name of the annotation itself. -
getGeneratedBy
@Deprecated public static com.google.common.collect.ImmutableSet<String> getGeneratedBy(com.sun.tools.javac.code.Symbol symbol, VisitorState state) Deprecated.TODO(ghm): delete after a JavaBuilder release -
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.
-
targetType
Deprecated.use TargetType.targetType directly -
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.
-
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
TypeMirror.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
AnnotationMirrorfor the annotation represented byannotationTree.
-
containsComments
Returns whether the giventreecontains 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 whethersymbolis 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
Returnstrueif 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. Returnsfalsefor 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
defaultmethods to be abstract. -
asFlagSet
Returns a set of strings representing the flags in the given long. This uses the bit encoding fromFlags.- Returns:
- a set of strings representing the flags in the given long, in lowercase. Elements of the set are strings like "static" or "final".
-
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 aTypeSubstitutionfrom[K, V]to[String, Integer]. -
hasImplicitType
Returns whether this is avaror a lambda parameter that has no explicit type. -
hasExplicitSource
Returns whether the given tree has an explicit source code representation. -
isKotlin
Returnstrueif 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 whetherexistingMethodhas an overload (or "nearly" an overload) with the giventargetMethodName, and only a single parameter of typeonlyParameterType. -
getSwitchDefault
-
isSwitchDefault
Returns whethercaseTreeis the default case of a switch statement. This includescase null, default ->.
-
annotationClasscontains a member that is aClassor an array of them, attempting to access that member from the Error Prone checker code will result in a runtime exception.