aboutsummaryrefslogtreecommitdiff
path: root/errorprone/src/main/java/org/robolectric/errorprone/bugpatterns/Helpers.java
blob: 234b96e5bec977328a6b72097aa1d5fcd6f6761c (plain)
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
package org.robolectric.errorprone.bugpatterns;

import static com.google.errorprone.util.ASTHelpers.findEnclosingNode;
import static com.google.errorprone.util.ASTHelpers.hasAnnotation;

import com.google.errorprone.VisitorState;
import com.google.errorprone.predicates.TypePredicate;
import com.google.errorprone.suppliers.Supplier;
import com.google.errorprone.suppliers.Suppliers;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.Tree;
import com.sun.source.util.TreePath;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.tree.JCTree.JCClassDecl;
import org.robolectric.annotation.Implements;

/** Matchers for {@link ShadowUsageCheck}. */
public class Helpers {

  /** Match sub-types or implementations of the given type. */
  public static TypePredicate isCastableTo(Supplier<Type> type) {
    return new CastableTo(type);
  }

  /** Match sub-types or implementations of the given type. */
  public static TypePredicate isCastableTo(String type) {
    return new CastableTo(Suppliers.typeFromString(type));
  }

  public static boolean isInShadowClass(TreePath path, VisitorState state) {
    Tree leaf = path.getLeaf();
    JCClassDecl classDecl = JCClassDecl.class.isInstance(leaf)
        ? (JCClassDecl) leaf
        : findEnclosingNode(state.getPath(), JCClassDecl.class);

    return hasAnnotation(classDecl, Implements.class, state);
  }

  /** Matches implementations of the given interface. */
  public static class CastableTo implements TypePredicate {

    public final Supplier<Type> expected;

    public CastableTo(Supplier<Type> type) {
      this.expected = type;
    }

    @Override
    public boolean apply(Type type, VisitorState state) {
      Type bound = expected.get(state);
      if (bound == null || type == null) {
        // TODO(cushon): type suppliers are allowed to return null :(
        return false;
      }
      return ASTHelpers.isCastable(type, bound, state);
    }
  }

}