Skip to content

Commit

Permalink
Run PatternMatchingInstanceof over EP.
Browse files Browse the repository at this point in the history
PiperOrigin-RevId: 673780652
  • Loading branch information
graememorgan authored and Error Prone Team committed Nov 15, 2024
1 parent e5fd194 commit 281c9d3
Show file tree
Hide file tree
Showing 49 changed files with 91 additions and 169 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -476,8 +476,7 @@ Nullness visitAssignment(AssignmentNode node, SubNodeValues inputs, Updates upda
setNonnullIfTrackable(updates, ((ArrayAccessNode) target).getArray());
}

if (target instanceof FieldAccessNode) {
FieldAccessNode fieldAccess = (FieldAccessNode) target;
if (target instanceof FieldAccessNode fieldAccess) {
if (!fieldAccess.isStatic()) {
setNonnullIfTrackable(updates, fieldAccess.getReceiver());
}
Expand Down Expand Up @@ -967,8 +966,7 @@ static final class MemberName {

@Override
public boolean equals(Object obj) {
if (obj instanceof MemberName) {
MemberName other = (MemberName) obj;
if (obj instanceof MemberName other) {
return clazz.equals(other.clazz) && member.equals(other.member);
}
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1593,11 +1593,7 @@ public static Optional<SuggestedFix> suggestExemptingAnnotation(
}

private static boolean isAnonymousClassTree(Tree t) {
if (t instanceof ClassTree) {
ClassTree classTree = (ClassTree) t;
return classTree.getSimpleName().contentEquals("");
}
return false;
return t instanceof ClassTree classTree && classTree.getSimpleName().contentEquals("");
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,7 @@ public boolean matches(AnnotationTree annotationTree, VisitorState state) {

expressionTree = ASTHelpers.stripParentheses(expressionTree);

if (expressionTree instanceof NewArrayTree) {
NewArrayTree arrayTree = (NewArrayTree) expressionTree;
if (expressionTree instanceof NewArrayTree arrayTree) {
for (ExpressionTree elementTree : arrayTree.getInitializers()) {
if (valueMatcher.matches(elementTree, state)) {
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,10 @@ public AnnotationType(String annotationClassName) {
@Override
public boolean matches(AnnotationTree annotationTree, VisitorState state) {
Tree type = annotationTree.getAnnotationType();
if (type.getKind() == Tree.Kind.IDENTIFIER && type instanceof JCTree.JCIdent) {
JCTree.JCIdent jcIdent = (JCTree.JCIdent) type;
if (type.getKind() == Tree.Kind.IDENTIFIER && type instanceof JCTree.JCIdent jcIdent) {
return jcIdent.sym.getQualifiedName().contentEquals(annotationClassName);
} else if (type.getKind() == Tree.Kind.MEMBER_SELECT && type instanceof JCTree.JCFieldAccess) {
JCTree.JCFieldAccess jcFieldAccess = (JCTree.JCFieldAccess) type;
} else if (type.getKind() == Tree.Kind.MEMBER_SELECT
&& type instanceof JCTree.JCFieldAccess jcFieldAccess) {
return jcFieldAccess.sym.getQualifiedName().contentEquals(annotationClassName);
} else {
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -296,8 +296,7 @@ public static Matcher<? super MethodInvocationTree> receiverSameAsArgument(int a
ExpressionTree arg = args.get(argNum);

JCExpression methodSelect = (JCExpression) t.getMethodSelect();
if (methodSelect instanceof JCFieldAccess) {
JCFieldAccess fieldAccess = (JCFieldAccess) methodSelect;
if (methodSelect instanceof JCFieldAccess fieldAccess) {
return ASTHelpers.sameVariable(fieldAccess.getExpression(), arg);
} else if (methodSelect instanceof JCIdent) {
// A bare method call: "equals(foo)". Receiver is implicitly "this".
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,7 @@ public StringLiteral(Pattern pattern) {

@Override
public boolean matches(ExpressionTree expressionTree, VisitorState state) {
if (expressionTree instanceof LiteralTree) {
LiteralTree literalTree = (LiteralTree) expressionTree;
if (expressionTree instanceof LiteralTree literalTree) {
Object actualValue = literalTree.getValue();
return actualValue instanceof String && matcher.test((String) actualValue);
} else {
Expand Down
21 changes: 7 additions & 14 deletions check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java
Original file line number Diff line number Diff line change
Expand Up @@ -508,11 +508,9 @@ public static Stream<Symbol> enclosingElements(Symbol sym) {
* <p>TODO(eaftan): Are there other places this could be used?
*/
public static Type getReturnType(ExpressionTree expressionTree) {
if (expressionTree instanceof JCFieldAccess) {
JCFieldAccess methodCall = (JCFieldAccess) expressionTree;
if (expressionTree instanceof JCFieldAccess methodCall) {
return methodCall.type.getReturnType();
} else if (expressionTree instanceof JCIdent) {
JCIdent methodCall = (JCIdent) expressionTree;
} else if (expressionTree instanceof JCIdent methodCall) {
return methodCall.type.getReturnType();
} else if (expressionTree instanceof JCMethodInvocation) {
return getReturnType(((JCMethodInvocation) expressionTree).getMethodSelect());
Expand Down Expand Up @@ -554,11 +552,9 @@ public static Type getReturnType(ExpressionTree expressionTree) {
* }</pre>
*/
public static Type getReceiverType(ExpressionTree expressionTree) {
if (expressionTree instanceof JCFieldAccess) {
JCFieldAccess methodSelectFieldAccess = (JCFieldAccess) expressionTree;
if (expressionTree instanceof JCFieldAccess methodSelectFieldAccess) {
return methodSelectFieldAccess.selected.type;
} else if (expressionTree instanceof JCIdent) {
JCIdent methodCall = (JCIdent) expressionTree;
} else if (expressionTree instanceof JCIdent methodCall) {
return methodCall.sym.owner.type;
} else if (expressionTree instanceof JCMethodInvocation) {
return getReceiverType(((JCMethodInvocation) expressionTree).getMethodSelect());
Expand Down Expand Up @@ -1127,8 +1123,7 @@ public static LinkedHashSet<String> enumValues(TypeSymbol enumType) {
Scope scope = enumType.members();
Deque<String> values = new ArrayDeque<>();
for (Symbol sym : scope.getSymbols()) {
if (sym instanceof VarSymbol) {
VarSymbol var = (VarSymbol) sym;
if (sym instanceof VarSymbol var) {
if ((var.flags() & Flags.ENUM) != 0) {
/*
* Javac gives us the members backwards, apparently. It's worth making an effort to
Expand All @@ -1154,8 +1149,7 @@ public static boolean isGeneratedConstructor(MethodTree tree) {
public static List<MethodTree> getConstructors(ClassTree classTree) {
List<MethodTree> constructors = new ArrayList<>();
for (Tree member : classTree.getMembers()) {
if (member instanceof MethodTree) {
MethodTree methodTree = (MethodTree) member;
if (member instanceof MethodTree methodTree) {
if (getSymbol(methodTree).isConstructor()) {
constructors.add(methodTree);
}
Expand Down Expand Up @@ -2606,8 +2600,7 @@ public Void visitForAll(Type.ForAll t, Type other) {

@Override
public Void visitWildcardType(WildcardType t, Type type) {
if (type instanceof WildcardType) {
WildcardType other = (WildcardType) type;
if (type instanceof WildcardType other) {
scan(t.getExtendsBound(), other.getExtendsBound());
scan(t.getSuperBound(), other.getSuperBound());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -314,8 +314,7 @@ && isSameType(type.getReturnType(), streamType, state)) {
break;
case VARIABLE:
Symbol sym = getSymbol(path.getLeaf());
if (sym instanceof VarSymbol) {
VarSymbol var = (VarSymbol) sym;
if (sym instanceof VarSymbol var) {
if (var.getKind() == ElementKind.RESOURCE_VARIABLE
|| isClosedInFinallyClause(var, path, state)
|| ASTHelpers.variableIsStaticFinal(var)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,8 +153,7 @@ private Description handle(Tree tree, Name name, ModifiersTree modifiers, Visito
private static List<ErrorProneToken> annotationTokens(
Tree tree, VisitorState state, int annotationEnd) {
int endPos;
if (tree instanceof JCMethodDecl) {
JCMethodDecl methodTree = (JCMethodDecl) tree;
if (tree instanceof JCMethodDecl methodTree) {
if (methodTree.getReturnType() != null) {
endPos = getStartPosition(methodTree.getReturnType());
} else if (!methodTree.getParameters().isEmpty()) {
Expand All @@ -167,15 +166,13 @@ private static List<ErrorProneToken> annotationTokens(
} else {
endPos = state.getEndPosition(methodTree);
}
} else if (tree instanceof JCVariableDecl) {
JCVariableDecl variableTree = (JCVariableDecl) tree;
} else if (tree instanceof JCVariableDecl variableTree) {
endPos = getStartPosition(variableTree.getType());
if (endPos == -1) {
// handle 'var'
endPos = state.getEndPosition(variableTree.getModifiers());
}
} else if (tree instanceof JCClassDecl) {
JCClassDecl classTree = (JCClassDecl) tree;
} else if (tree instanceof JCClassDecl classTree) {
endPos =
classTree.getMembers().isEmpty()
? state.getEndPosition(classTree)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,20 +131,19 @@ private static Matcher<MethodTree> returning(String type) {
public Description matchClass(ClassTree tree, VisitorState state) {
if (ASTHelpers.hasAnnotation(tree, "com.google.auto.value.AutoValue", state)) {
for (Tree memberTree : tree.getMembers()) {
if (memberTree instanceof MethodTree && !isSuppressed(memberTree, state)) {
MethodTree methodTree = (MethodTree) memberTree;
if (ABSTRACT_MATCHER.matches(methodTree, state)) {
for (Map.Entry<String, Matcher<MethodTree>> entry : REPLACEMENT_TO_MATCHERS.entries()) {
if (entry.getValue().matches(methodTree, state)) {
state.reportMatch(
buildDescription(methodTree)
.setMessage(
String.format(
"AutoValue instances should be deeply immutable. Therefore, we"
+ " recommend returning %s instead.",
entry.getKey()))
.build());
}
if (memberTree instanceof MethodTree methodTree
&& !isSuppressed(memberTree, state)
&& ABSTRACT_MATCHER.matches(methodTree, state)) {
for (Map.Entry<String, Matcher<MethodTree>> entry : REPLACEMENT_TO_MATCHERS.entries()) {
if (entry.getValue().matches(methodTree, state)) {
state.reportMatch(
buildDescription(methodTree)
.setMessage(
String.format(
"AutoValue instances should be deeply immutable. Therefore, we"
+ " recommend returning %s instead.",
entry.getKey()))
.build());
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,7 @@ public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState s
String filename = Files.getNameWithoutExtension(ASTHelpers.getFileName(tree));
List<String> names = new ArrayList<>();
for (Tree member : tree.getTypeDecls()) {
if (member instanceof ClassTree) {
ClassTree classMember = (ClassTree) member;
if (member instanceof ClassTree classMember) {
if (isSuppressed(classMember, state)) {
// If any top-level classes have @SuppressWarnings("ClassName"), ignore
// this compilation unit. We can't rely on the normal suppression
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,7 @@ public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState
return NO_MATCH;
}
ExpressionTree onlyArgument = tree.getArguments().get(0);
if (onlyArgument instanceof IdentifierTree) {
IdentifierTree onlyArgumentIdentifier = (IdentifierTree) onlyArgument;
if (onlyArgument instanceof IdentifierTree onlyArgumentIdentifier) {
Name constructorParamName = oneArgConstructors.get(0).getParameters().get(0).getSimpleName();
if (constructorParamName.equals(onlyArgumentIdentifier.getName())) {
return NO_MATCH;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,9 +156,8 @@ private static Fix buildFix(TreePath path, VisitorState state) {
replacement.append("return builder.build();");
fix.replace(enclosing, replacement.toString());
return fix.build();
} else if (enclosing instanceof VariableTree && isStatic(getSymbol(enclosing))) {
} else if (enclosing instanceof VariableTree variableTree && isStatic(getSymbol(enclosing))) {
// update `static FOO = <builder>` to declare a helper method named create<builder>
VariableTree variableTree = (VariableTree) enclosing;
String factory =
String.format(
"create%s",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,7 @@ public Void visitMemberSelect(MemberSelectTree memberSelectTree, Void unused) {
@Override
public Void visitIdentifier(IdentifierTree identifierTree, Void unused) {
Tree parent = getCurrentPath().getParentPath().getLeaf();
if (parent instanceof NewClassTree) {
NewClassTree newClassTree = (NewClassTree) parent;
if (parent instanceof NewClassTree newClassTree) {
if (newClassTree.getIdentifier().equals(identifierTree)
&& newClassTree.getEnclosingExpression() != null) {
// don't try to fix instantiations with explicit enclosing instances, e.g. `a.new B();`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,8 +145,7 @@ Optional<Fix> maybeFix(NewClassTree tree, VisitorState state, BlockTree block) {
if (enclosing instanceof ParenthesizedTree) {
continue;
}
if (enclosing instanceof VariableTree) {
VariableTree enclosingVariable = (VariableTree) enclosing;
if (enclosing instanceof VariableTree enclosingVariable) {
toReplace = enclosingVariable.getInitializer();
typeTree = enclosingVariable.getType();
VarSymbol symbol = ASTHelpers.getSymbol(enclosingVariable);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -245,8 +245,7 @@ private void makeAlwaysFalse() {
enclosingPath = enclosingPath.getParentPath();
}
Tree enclosing = enclosingPath.getLeaf();
if (enclosing instanceof IfTree) {
IfTree ifTree = (IfTree) enclosing;
if (enclosing instanceof IfTree ifTree) {
if (ifTree.getElseStatement() == null) {
fix.replace(ifTree, "");
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,7 @@ private static int caseEndPosition(VisitorState state, CaseTree caseTree) {
// end of the block
if (caseTree.getStatements().size() == 1) {
StatementTree only = getOnlyElement(caseTree.getStatements());
if (only instanceof BlockTree) {
BlockTree blockTree = (BlockTree) only;
if (only instanceof BlockTree blockTree) {
return blockTree.getStatements().isEmpty()
? getStartPosition(blockTree)
: state.getEndPosition(getLast(blockTree.getStatements()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,8 +139,7 @@ public boolean matches(T tree, VisitorState state) {

/** Match a tree in the ancestor chain given the ancestor's immediate descendant. */
protected MatchResult matchAncestor(Tree leaf, Tree prevTree) {
if (leaf instanceof TryTree) {
TryTree tryTree = (TryTree) leaf;
if (leaf instanceof TryTree tryTree) {
if (tryTree.getFinallyBlock() != null && tryTree.getFinallyBlock().equals(prevTree)) {
return MatchResult.FOUND_ERROR;
}
Expand Down Expand Up @@ -214,8 +213,7 @@ protected MatchResult matchAncestor(Tree leaf, Tree prevTree) {
private static class FinallyThrowMatcher extends FinallyCompletionMatcher<ThrowTree> {
@Override
protected MatchResult matchAncestor(Tree tree, Tree prevTree) {
if (tree instanceof TryTree) {
TryTree tryTree = (TryTree) tree;
if (tree instanceof TryTree tryTree) {
if (tryTree.getBlock().equals(prevTree) && !tryTree.getCatches().isEmpty()) {
// The current ancestor is a try block with associated catch blocks.
return MatchResult.NO_MATCH;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -214,8 +214,7 @@ private static boolean expressionsEqual(ExpressionTree expr1, ExpressionTree exp
&& expressionsEqual(arrayAccessTree1.getIndex(), arrayAccessTree2.getIndex());
}

if (expr1 instanceof LiteralTree) {
LiteralTree literalTree1 = (LiteralTree) expr1;
if (expr1 instanceof LiteralTree literalTree1) {
LiteralTree literalTree2 = (LiteralTree) expr2;
return literalTree1.getValue().equals(literalTree2.getValue());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,14 +83,12 @@ public Description matchClass(ClassTree tree, VisitorState state) {
}
SuggestedFix.Builder suggestedFix = SuggestedFix.builder();
for (Tree member : members) {
if (member instanceof VariableTree) {
VariableTree variableTree = (VariableTree) member;
if (member instanceof VariableTree variableTree) {
SuggestedFixes.addModifiers(
variableTree, state, Modifier.FINAL, Modifier.STATIC, Modifier.PUBLIC)
.ifPresent(suggestedFix::merge);
}
if (member instanceof MethodTree) {
MethodTree methodTree = (MethodTree) member;
if (member instanceof MethodTree methodTree) {
SuggestedFixes.addModifiers(methodTree, state, Modifier.PUBLIC)
.ifPresent(suggestedFix::merge);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,9 +123,8 @@ static Operand create(Kind kind, CharSequence value, CharSequence source) {

static Operand classify(JCTree tree, VisitorState state) {
CharSequence source = state.getSourceForNode(tree);
if (tree instanceof MethodInvocationTree) {
if (tree instanceof MethodInvocationTree receiverInvocation) {
// expr.getClass() -> "expr"
MethodInvocationTree receiverInvocation = (MethodInvocationTree) tree;
MethodSymbol sym = ASTHelpers.getSymbol(receiverInvocation);
if (sym.getSimpleName().contentEquals("getClass") && sym.params().isEmpty()) {
if (receiverInvocation.getMethodSelect() instanceof IdentifierTree) {
Expand All @@ -137,9 +136,8 @@ static Operand classify(JCTree tree, VisitorState state) {
state.getSourceForNode(ASTHelpers.getReceiver(receiverInvocation)),
source);
}
} else if (tree instanceof MemberSelectTree) {
} else if (tree instanceof MemberSelectTree select) {
// Foo.class -> "Foo"
MemberSelectTree select = (MemberSelectTree) tree;
if (select.getIdentifier().contentEquals("class")) {
return Operand.create(Kind.LITERAL, state.getSourceForNode(select.getExpression()), source);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -252,8 +252,7 @@ private Description describeIfObsolete(
type = ASTHelpers.getType(parent);
} else if (parent instanceof ReturnTree || parent instanceof LambdaExpressionTree) {
type = getMethodOrLambdaReturnType(state);
} else if (parent instanceof MethodInvocationTree) {
MethodInvocationTree tree = (MethodInvocationTree) parent;
} else if (parent instanceof MethodInvocationTree tree) {
int idx = tree.getArguments().indexOf(state.getPath().getLeaf());
if (idx == -1) {
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,7 @@ private void handleConstantLookup(MethodInvocationTree tree) {
String argumentValue = ASTHelpers.constValue(argumentExpr, String.class);
if (argumentValue != null) {
ExpressionTree methodSelect = tree.getMethodSelect();
if (methodSelect instanceof JCFieldAccess) {
JCFieldAccess fieldAccess = (JCFieldAccess) methodSelect;
if (methodSelect instanceof JCFieldAccess fieldAccess) {
Name method = fieldAccess.name;
result.add(new CallSite(method, argumentValue, argumentExpr, tree));
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -406,8 +406,7 @@ public Void visitIdentifier(IdentifierTree identifier, Void unused) {
if (!getSymbol(identifier).equals(symbol)) {
return null;
}
if (parent instanceof VariableTree) {
VariableTree variable = (VariableTree) parent;
if (parent instanceof VariableTree variable) {
fix.replace(variable.getType(), qualifyType(state, fix, details.builderType()));
return null;
}
Expand Down
Loading

0 comments on commit 281c9d3

Please sign in to comment.