google / google/error-prone

MethodSymbol annotations are not available when retrieving from findEnclosing()

Open
#1,203 0 comments 1 reaction 0 assignees View on GitHub
Dominant language
Java
Stars
7.2k
Forks
820
Avg merge
5h 9m
Merged PRs (30d)
50

Description

### Description of the problem / feature request:

I've got a checker where I'm trying to check the annotations on an enclosing method, but when checking for these annotations, the MethodSymbol returned reports that it has no annotations

### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.

```java
@Test
public void anonymousClassNegativeReturnMethod() {
testHelper
.addSourceLines(
"A.java",
"import com.uber.errorprone.annotations.KotlinOnly;",
"public interface A {",
" @KotlinOnly public void a();",
"}")
.addSourceLines(
"B.java",
"import com.uber.errorprone.annotations.KotlinOnly;",
"public class B {",
" @KotlinOnly public final A b() {",
" return new A() {",
" @Override public void a() {}",
" };",
" }",
"}")
.doTest();
}
```

If you check the anonymous return in `B#b()` and try to resolve the `@KotlinOnly` annotation on `b()` in a `matchClass` context, it will report no methods.

```java
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
Symbol.ClassSymbol symbol = ASTHelpers.getSymbol(tree);
if (symbol == null) {
return NO_MATCH;
}
boolean isAnonymous = symbol.getNestingKind().equals(NestingKind.ANONYMOUS);
if (isAnonymous) {
if (isInReturnTree(state) && isEnclosedInKotlinOnlyMethod(state)) {
return NO_MATCH;
}
}
}

private static boolean isInReturnTree(VisitorState state) {
return state.findEnclosing(ReturnTree.class) != null;
}

private static boolean isEnclosedInKotlinOnlyMethod(VisitorState state) {
MethodTree method = state.findEnclosing(MethodTree.class);
if (method == null) {
return false;
}
// This returns false!
return hasAnnotation(ASTHelpers.getSymbol(method), "com.uber.errorprone.annotations.KotlinOnly", state);
}
```

Should note that this appears to work fine if I match from, say, a lambda expression

```java
@Override
public Description matchLambdaExpression(LambdaExpressionTree tree,
VisitorState state) {
if (isInReturnTree(state) && isEnclosedInKotlinOnlyMethod(state)) {
return NO_MATCH;
}
}
```

### What version of Error Prone are you using?

2.3.0 for now

### Have you found anything relevant by searching the web?

Checked both the issue tracker and google group to no avail. A lot of findEnclosing usages but none that check annotations.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.