diff --git a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/AmbiguousJsonCreator.java b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/AmbiguousJsonCreator.java index 8eec308ef17..8958aff4073 100644 --- a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/AmbiguousJsonCreator.java +++ b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/AmbiguousJsonCreator.java @@ -18,7 +18,7 @@ import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.MethodTree; -import com.sun.source.tree.Tree; +import com.sun.source.tree.Tree.Kind; import com.sun.tools.javac.code.Symbol; import java.util.Map; import javax.lang.model.element.AnnotationValue; @@ -46,7 +46,7 @@ public Description matchAnnotation(AnnotationTree tree, VisitorState state) { } ClassTree clazz = state.findEnclosing(ClassTree.class); - if (clazz == null || clazz.getKind() != Tree.Kind.ENUM) { + if (clazz == null || clazz.getKind() != Kind.ENUM) { return Description.NO_MATCH; } diff --git a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/CanonicalAnnotationSyntax.java b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/CanonicalAnnotationSyntax.java index b2073c71674..7851df4f2da 100644 --- a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/CanonicalAnnotationSyntax.java +++ b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/CanonicalAnnotationSyntax.java @@ -19,7 +19,6 @@ import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.NewArrayTree; -import com.sun.source.tree.Tree.Kind; import java.util.ArrayList; import java.util.List; import java.util.Optional; @@ -119,7 +118,7 @@ private static Optional dropRedundantCurlies(AnnotationTree tree, VisitorSt * the expression as a whole. */ ExpressionTree value = - (arg.getKind() == Kind.ASSIGNMENT) ? ((AssignmentTree) arg).getExpression() : arg; + (arg instanceof AssignmentTree assignment) ? assignment.getExpression() : arg; /* Store a fix for each expression that was successfully simplified. */ simplifyAttributeValue(value, state) @@ -130,13 +129,10 @@ private static Optional dropRedundantCurlies(AnnotationTree tree, VisitorSt } private static Optional simplifyAttributeValue(ExpressionTree expr, VisitorState state) { - if (expr.getKind() != Kind.NEW_ARRAY) { - /* There are no curly braces or commas to be dropped here. */ - return Optional.empty(); - } - - NewArrayTree array = (NewArrayTree) expr; - return simplifySingletonArray(array, state).or(() -> dropTrailingComma(array, state)); + /* Drop curly braces or commas if possible. */ + return expr instanceof NewArrayTree newArray + ? simplifySingletonArray(newArray, state).or(() -> dropTrailingComma(newArray, state)) + : Optional.empty(); } /** Returns the expression describing the array's sole element, if any. */ diff --git a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/DirectReturn.java b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/DirectReturn.java index 212d0b12455..d6c40eb72ef 100644 --- a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/DirectReturn.java +++ b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/DirectReturn.java @@ -98,19 +98,17 @@ public Description matchBlock(BlockTree tree, VisitorState state) { } private static Optional tryMatchAssignment(Symbol targetSymbol, Tree tree) { - if (tree instanceof ExpressionStatementTree) { - return tryMatchAssignment(targetSymbol, ((ExpressionStatementTree) tree).getExpression()); + if (tree instanceof ExpressionStatementTree expressionStatement) { + return tryMatchAssignment(targetSymbol, expressionStatement.getExpression()); } - if (tree instanceof AssignmentTree) { - AssignmentTree assignment = (AssignmentTree) tree; + if (tree instanceof AssignmentTree assignment) { return targetSymbol.equals(ASTHelpers.getSymbol(assignment.getVariable())) ? Optional.of(assignment.getExpression()) : Optional.empty(); } - if (tree instanceof VariableTree) { - VariableTree declaration = (VariableTree) tree; + if (tree instanceof VariableTree declaration) { return declaration.getModifiers().getAnnotations().isEmpty() && targetSymbol.equals(ASTHelpers.getSymbol(declaration)) ? Optional.ofNullable(declaration.getInitializer()) @@ -148,11 +146,11 @@ private static boolean isIdentifierSymbolReferencedInAssociatedFinallyBlock( Streams.stream(state.getPath()).skip(1), Streams.stream(state.getPath()), (tree, child) -> { - if (!(tree instanceof TryTree)) { + if (!(tree instanceof TryTree tryTree)) { return null; } - BlockTree finallyBlock = ((TryTree) tree).getFinallyBlock(); + BlockTree finallyBlock = tryTree.getFinallyBlock(); return !child.equals(finallyBlock) ? finallyBlock : null; }) .anyMatch(finallyBlock -> referencesIdentifierSymbol(symbol, finallyBlock)); diff --git a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/FormatStringConcatenation.java b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/FormatStringConcatenation.java index 4c8f1fdd4ae..1e19df51575 100644 --- a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/FormatStringConcatenation.java +++ b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/FormatStringConcatenation.java @@ -240,8 +240,8 @@ private static class ReplacementArgumentsConstructor } private void appendExpression(Tree tree) { - if (tree instanceof LiteralTree) { - formatString.append(((LiteralTree) tree).getValue()); + if (tree instanceof LiteralTree literal) { + formatString.append(literal.getValue()); } else { formatString.append(formatSpecifier); formatArguments.add(tree); diff --git a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/IsInstanceLambdaUsage.java b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/IsInstanceLambdaUsage.java index 75c4e1b6309..0490ac54a5e 100644 --- a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/IsInstanceLambdaUsage.java +++ b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/IsInstanceLambdaUsage.java @@ -16,7 +16,6 @@ import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.InstanceOfTree; import com.sun.source.tree.LambdaExpressionTree; -import com.sun.source.tree.Tree.Kind; import com.sun.source.tree.VariableTree; import tech.picnic.errorprone.bugpatterns.util.SourceCode; @@ -42,12 +41,12 @@ public IsInstanceLambdaUsage() {} @Override public Description matchLambdaExpression(LambdaExpressionTree tree, VisitorState state) { - if (tree.getParameters().size() != 1 || tree.getBody().getKind() != Kind.INSTANCE_OF) { + if (tree.getParameters().size() != 1 + || !(tree.getBody() instanceof InstanceOfTree instanceOf)) { return Description.NO_MATCH; } VariableTree param = Iterables.getOnlyElement(tree.getParameters()); - InstanceOfTree instanceOf = (InstanceOfTree) tree.getBody(); if (!ASTHelpers.getSymbol(param).equals(ASTHelpers.getSymbol(instanceOf.getExpression()))) { return Description.NO_MATCH; } diff --git a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/JUnitValueSource.java b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/JUnitValueSource.java index 75fc9ee39aa..14bd20b9a1b 100644 --- a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/JUnitValueSource.java +++ b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/JUnitValueSource.java @@ -257,8 +257,8 @@ private static Optional tryExtractValueSourceAttributeValue( arguments.stream() .map( arg -> - arg instanceof MethodInvocationTree - ? Iterables.getOnlyElement(((MethodInvocationTree) arg).getArguments()) + arg instanceof MethodInvocationTree methodInvocation + ? Iterables.getOnlyElement(methodInvocation.getArguments()) : arg) .map(argument -> SourceCode.treeToString(argument, state)) .collect(joining(", "))) @@ -285,11 +285,10 @@ private static Optional getElementIfSingleton(Collection collection) { private static Matcher isSingleDimensionArrayCreationWithAllElementsMatching( Matcher elementMatcher) { return (tree, state) -> { - if (!(tree instanceof NewArrayTree)) { + if (!(tree instanceof NewArrayTree newArray)) { return false; } - NewArrayTree newArray = (NewArrayTree) tree; return newArray.getDimensions().isEmpty() && !newArray.getInitializers().isEmpty() && newArray.getInitializers().stream() diff --git a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/LexicographicalAnnotationAttributeListing.java b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/LexicographicalAnnotationAttributeListing.java index bd346140a55..46d0cd89cf0 100644 --- a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/LexicographicalAnnotationAttributeListing.java +++ b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/LexicographicalAnnotationAttributeListing.java @@ -31,7 +31,6 @@ import com.sun.source.tree.NewArrayTree; import com.sun.source.tree.PrimitiveTypeTree; import com.sun.source.tree.Tree; -import com.sun.source.tree.Tree.Kind; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Symtab; import com.sun.tools.javac.code.Type; @@ -119,13 +118,9 @@ private Optional sortArrayElements(AnnotationTree tree, VisitorState state) } private static Optional extractArray(ExpressionTree expr) { - if (expr.getKind() == Kind.ASSIGNMENT) { - return extractArray(((AssignmentTree) expr).getExpression()); - } - - return Optional.of(expr) - .filter(e -> e.getKind() == Kind.NEW_ARRAY) - .map(NewArrayTree.class::cast); + return expr instanceof AssignmentTree assignment + ? extractArray(assignment.getExpression()) + : Optional.of(expr).filter(NewArrayTree.class::isInstance).map(NewArrayTree.class::cast); } private static Optional suggestSorting( @@ -197,8 +192,8 @@ private static ImmutableList> getStructure(ExpressionTree public @Nullable Void visitLiteral(LiteralTree node, @Nullable Void unused) { Object value = ASTHelpers.constValue(node); nodes.add( - value instanceof String - ? STRING_ARGUMENT_SPLITTER.splitToStream((String) value).collect(toImmutableList()) + value instanceof String str + ? STRING_ARGUMENT_SPLITTER.splitToStream(str).collect(toImmutableList()) : ImmutableList.of(String.valueOf(value))); return super.visitLiteral(node, unused); diff --git a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/MethodReferenceUsage.java b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/MethodReferenceUsage.java index 2825dd6fc83..d86bc65dd44 100644 --- a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/MethodReferenceUsage.java +++ b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/MethodReferenceUsage.java @@ -27,7 +27,6 @@ import com.sun.source.tree.ParenthesizedTree; import com.sun.source.tree.ReturnTree; import com.sun.source.tree.Tree; -import com.sun.source.tree.Tree.Kind; import com.sun.source.tree.VariableTree; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Type; @@ -85,6 +84,7 @@ public Description matchLambdaExpression(LambdaExpressionTree tree, VisitorState .orElse(Description.NO_MATCH); } + // XXX: Use switch pattern matching once the targeted JDK supports this. private static Optional constructMethodRef( LambdaExpressionTree lambdaExpr, Tree subTree) { return switch (subTree.getKind()) { @@ -114,34 +114,35 @@ private static Optional constructMethodRef( .flatMap(expectedInstance -> constructMethodRef(lambdaExpr, subTree, expectedInstance)); } - @SuppressWarnings( - "java:S1151" /* Extracting `IDENTIFIER` case block to separate method does not improve readability. */) + // XXX: Review whether to use switch pattern matching once the targeted JDK supports this. private static Optional constructMethodRef( LambdaExpressionTree lambdaExpr, MethodInvocationTree subTree, Optional expectedInstance) { ExpressionTree methodSelect = subTree.getMethodSelect(); - return switch (methodSelect.getKind()) { - case IDENTIFIER -> { - if (expectedInstance.isPresent()) { - /* Direct method call; there is no matching "implicit parameter". */ - yield Optional.empty(); - } - Symbol sym = ASTHelpers.getSymbol(methodSelect); - yield ASTHelpers.isStatic(sym) - ? constructFix(lambdaExpr, sym.owner, methodSelect) - : constructFix(lambdaExpr, "this", methodSelect); + + if (methodSelect instanceof IdentifierTree) { + if (expectedInstance.isPresent()) { + /* Direct method call; there is no matching "implicit parameter". */ + return Optional.empty(); } - case MEMBER_SELECT -> constructMethodRef( - lambdaExpr, (MemberSelectTree) methodSelect, expectedInstance); - default -> throw new VerifyException( - "Unexpected type of expression: " + methodSelect.getKind()); - }; + + Symbol sym = ASTHelpers.getSymbol(methodSelect); + return ASTHelpers.isStatic(sym) + ? constructFix(lambdaExpr, sym.owner, methodSelect) + : constructFix(lambdaExpr, "this", methodSelect); + } + + if (methodSelect instanceof MemberSelectTree memberSelect) { + return constructMethodRef(lambdaExpr, memberSelect, expectedInstance); + } + + throw new VerifyException("Unexpected type of expression: " + methodSelect.getKind()); } private static Optional constructMethodRef( LambdaExpressionTree lambdaExpr, MemberSelectTree subTree, Optional expectedInstance) { - if (subTree.getExpression().getKind() != Kind.IDENTIFIER) { + if (!(subTree.getExpression() instanceof IdentifierTree identifier)) { // XXX: Could be parenthesized. Handle. Also in other classes. /* * Only suggest a replacement if the method select's expression provably doesn't have @@ -150,12 +151,12 @@ private static Optional constructMethodRef( return Optional.empty(); } - Name lhs = ((IdentifierTree) subTree.getExpression()).getName(); + Name lhs = identifier.getName(); if (expectedInstance.isEmpty()) { return constructFix(lambdaExpr, lhs, subTree.getIdentifier()); } - Type lhsType = ASTHelpers.getType(subTree.getExpression()); + Type lhsType = ASTHelpers.getType(identifier); if (lhsType == null || !expectedInstance.orElseThrow().equals(lhs)) { return Optional.empty(); } @@ -180,8 +181,8 @@ private static Optional> matchArguments( for (int i = 0; i < args.size(); i++) { ExpressionTree arg = args.get(i); - if (arg.getKind() != Kind.IDENTIFIER - || !((IdentifierTree) arg).getName().equals(expectedArguments.get(i + diff))) { + if (!(arg instanceof IdentifierTree identifier) + || !identifier.getName().equals(expectedArguments.get(i + diff))) { return Optional.empty(); } } diff --git a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/MissingRefasterAnnotation.java b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/MissingRefasterAnnotation.java index 12c71af6199..c8cdbb9eed2 100644 --- a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/MissingRefasterAnnotation.java +++ b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/MissingRefasterAnnotation.java @@ -47,7 +47,7 @@ public MissingRefasterAnnotation() {} public Description matchClass(ClassTree tree, VisitorState state) { long methodTypes = tree.getMembers().stream() - .filter(member -> member.getKind() == Tree.Kind.METHOD) + .filter(MethodTree.class::isInstance) .map(MethodTree.class::cast) .filter(method -> !ASTHelpers.isGeneratedConstructor(method)) .map(method -> REFASTER_ANNOTATION.matches(method, state)) diff --git a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/MockitoMockClassReference.java b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/MockitoMockClassReference.java index 1ed193468f8..be164b277d3 100644 --- a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/MockitoMockClassReference.java +++ b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/MockitoMockClassReference.java @@ -67,6 +67,7 @@ public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState return describeMatch(tree, SuggestedFixes.removeElement(arguments.get(0), arguments, state)); } + // XXX: Use switch pattern matching once the targeted JDK supports this. private static boolean isTypeDerivableFromContext(MethodInvocationTree tree, VisitorState state) { Tree parent = state.getPath().getParentPath().getLeaf(); return switch (parent.getKind()) { diff --git a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/PrimitiveComparison.java b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/PrimitiveComparison.java index 2ab00020ee8..997a52f644e 100644 --- a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/PrimitiveComparison.java +++ b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/PrimitiveComparison.java @@ -21,6 +21,7 @@ import com.google.errorprone.matchers.Matcher; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; +import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.LambdaExpressionTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodInvocationTree; @@ -146,39 +147,42 @@ private static String getPreferredMethod(Type cmpType, boolean isStatic, Visitor return isStatic ? "comparing" : "thenComparing"; } + // XXX: Use switch pattern matching once the targeted JDK supports this. private static Optional getPotentiallyBoxedReturnType(ExpressionTree tree) { - return switch (tree.getKind()) { - case LAMBDA_EXPRESSION -> { - /* Return the lambda expression's actual return type. */ - yield Optional.ofNullable(ASTHelpers.getType(((LambdaExpressionTree) tree).getBody())); - } - case MEMBER_REFERENCE -> { - /* Return the method's declared return type. */ - // XXX: Very fragile. Do better. - Type subType2 = ((JCMemberReference) tree).referentType; - yield Optional.of(subType2.getReturnType()); - } - default -> { - /* This appears to be a genuine `{,ToInt,ToLong,ToDouble}Function`. */ - yield Optional.empty(); - } - }; + if (tree instanceof LambdaExpressionTree lambdaExpression) { + /* Return the lambda expression's actual return type. */ + return Optional.ofNullable(ASTHelpers.getType(lambdaExpression.getBody())); + } + + // XXX: The match against a concrete type and reference to one of its fields is fragile. Do + // better. + if (tree instanceof JCMemberReference memberReference) { + /* Return the method's declared return type. */ + Type subType = memberReference.referentType; + return Optional.of(subType.getReturnType()); + } + + /* This appears to be a genuine `{,ToInt,ToLong,ToDouble}Function`. */ + return Optional.empty(); } private static Fix suggestFix( MethodInvocationTree tree, String preferredMethodName, VisitorState state) { ExpressionTree expr = tree.getMethodSelect(); - return switch (expr.getKind()) { - case IDENTIFIER -> SuggestedFix.builder() + + if (expr instanceof IdentifierTree) { + return SuggestedFix.builder() .addStaticImport(Comparator.class.getName() + '.' + preferredMethodName) .replace(expr, preferredMethodName) .build(); - case MEMBER_SELECT -> { - MemberSelectTree ms = (MemberSelectTree) tree.getMethodSelect(); - yield SuggestedFix.replace( - ms, SourceCode.treeToString(ms.getExpression(), state) + '.' + preferredMethodName); - } - default -> throw new VerifyException("Unexpected type of expression: " + expr.getKind()); - }; + } + + if (expr instanceof MemberSelectTree memberSelect) { + return SuggestedFix.replace( + memberSelect, + SourceCode.treeToString(memberSelect.getExpression(), state) + '.' + preferredMethodName); + } + + throw new VerifyException("Unexpected type of expression: " + expr.getKind()); } } diff --git a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/RedundantStringConversion.java b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/RedundantStringConversion.java index bd670101b8e..aed928259b4 100644 --- a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/RedundantStringConversion.java +++ b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/RedundantStringConversion.java @@ -325,11 +325,10 @@ private Optional trySimplify( } private Optional trySimplify(ExpressionTree tree, VisitorState state) { - if (tree.getKind() != Kind.METHOD_INVOCATION) { + if (!(tree instanceof MethodInvocationTree methodInvocation)) { return Optional.empty(); } - MethodInvocationTree methodInvocation = (MethodInvocationTree) tree; if (!conversionMethodMatcher.matches(methodInvocation, state)) { return Optional.empty(); } @@ -345,13 +344,12 @@ private Optional trySimplify(ExpressionTree tree, VisitorState s private static Optional trySimplifyNullaryMethod( MethodInvocationTree methodInvocation, VisitorState state) { - if (!instanceMethod().matches(methodInvocation, state)) { + if (!instanceMethod().matches(methodInvocation, state) + || !(methodInvocation.getMethodSelect() instanceof MemberSelectTree memberSelect)) { return Optional.empty(); } - return Optional.of(methodInvocation.getMethodSelect()) - .filter(methodSelect -> methodSelect.getKind() == Kind.MEMBER_SELECT) - .map(methodSelect -> ((MemberSelectTree) methodSelect).getExpression()) + return Optional.of(memberSelect.getExpression()) .filter(expr -> !"super".equals(SourceCode.treeToString(expr, state))); } diff --git a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/SpringMvcAnnotation.java b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/SpringMvcAnnotation.java index 1fa027d2632..614a12e748c 100644 --- a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/SpringMvcAnnotation.java +++ b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/SpringMvcAnnotation.java @@ -1,6 +1,5 @@ package tech.picnic.errorprone.bugpatterns; -import static com.google.common.base.Verify.verify; import static com.google.errorprone.BugPattern.LinkType.CUSTOM; import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION; import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION; @@ -24,7 +23,6 @@ import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.NewArrayTree; -import com.sun.source.tree.Tree.Kind; import java.util.Optional; import tech.picnic.errorprone.bugpatterns.util.AnnotationAttributeMatcher; import tech.picnic.errorprone.bugpatterns.util.SourceCode; @@ -79,22 +77,19 @@ private static Optional trySimplification( } private static Optional extractUniqueMethod(ExpressionTree arg, VisitorState state) { - verify( - arg.getKind() == Kind.ASSIGNMENT, - "Annotation attribute is not an assignment: %s", - arg.getKind()); - - ExpressionTree expr = ((AssignmentTree) arg).getExpression(); - if (expr.getKind() != Kind.NEW_ARRAY) { - return Optional.of(extractMethod(expr, state)); + if (!(arg instanceof AssignmentTree assignment)) { + throw new VerifyException("Annotation attribute is not an assignment:" + arg.getKind()); } - NewArrayTree newArray = (NewArrayTree) expr; - return Optional.of(newArray.getInitializers()) - .filter(args -> args.size() == 1) - .map(args -> extractMethod(args.get(0), state)); + ExpressionTree expr = assignment.getExpression(); + return expr instanceof NewArrayTree newArray + ? Optional.of(newArray.getInitializers()) + .filter(args -> args.size() == 1) + .map(args -> extractMethod(args.get(0), state)) + : Optional.of(extractMethod(expr, state)); } + // XXX: Use switch pattern matching once the targeted JDK supports this. private static String extractMethod(ExpressionTree expr, VisitorState state) { return switch (expr.getKind()) { case IDENTIFIER -> SourceCode.treeToString(expr, state); diff --git a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/StaticImport.java b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/StaticImport.java index ae6a7928563..83225abf35a 100644 --- a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/StaticImport.java +++ b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/StaticImport.java @@ -24,6 +24,7 @@ import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.Tree; +import com.sun.source.tree.Tree.Kind; import com.sun.tools.javac.code.Type; import java.util.Optional; @@ -215,11 +216,10 @@ private static boolean isCandidateContext(VisitorState state) { Tree parentTree = requireNonNull(state.getPath().getParentPath(), "MemberSelectTree lacks enclosing node") .getLeaf(); - return switch (parentTree.getKind()) { - case IMPORT, MEMBER_SELECT -> false; - case METHOD_INVOCATION -> ((MethodInvocationTree) parentTree).getTypeArguments().isEmpty(); - default -> true; - }; + + return parentTree instanceof MethodInvocationTree methodInvocation + ? methodInvocation.getTypeArguments().isEmpty() + : (parentTree.getKind() != Kind.IMPORT && parentTree.getKind() != Kind.MEMBER_SELECT); } private static boolean isCandidate(MemberSelectTree tree) { diff --git a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/util/AnnotationAttributeMatcher.java b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/util/AnnotationAttributeMatcher.java index fc10d03f45c..ca4bbfb741d 100644 --- a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/util/AnnotationAttributeMatcher.java +++ b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/util/AnnotationAttributeMatcher.java @@ -9,7 +9,6 @@ import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.ExpressionTree; -import com.sun.source.tree.Tree.Kind; import com.sun.tools.javac.code.Type; import java.io.Serializable; import java.util.HashSet; @@ -116,8 +115,8 @@ public Stream extractMatchingArguments(AnnotationTree tree) { } private static String extractAttributeName(ExpressionTree expr) { - return (expr.getKind() == Kind.ASSIGNMENT) - ? ASTHelpers.getSymbol(((AssignmentTree) expr).getVariable()).getSimpleName().toString() + return (expr instanceof AssignmentTree assignment) + ? ASTHelpers.getSymbol(assignment.getVariable()).getSimpleName().toString() : "value"; } diff --git a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/util/MoreJUnitMatchers.java b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/util/MoreJUnitMatchers.java index 04b230b61e6..6ca0a850298 100644 --- a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/util/MoreJUnitMatchers.java +++ b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/util/MoreJUnitMatchers.java @@ -97,14 +97,13 @@ public static ImmutableList getMethodSourceFactoryDescriptors( String methodName = method.getName().toString(); ExpressionTree value = AnnotationMatcherUtils.getArgument(methodSourceAnnotation, "value"); - if (!(value instanceof NewArrayTree)) { + if (!(value instanceof NewArrayTree newArray)) { return ImmutableList.of(toMethodSourceFactoryDescriptor(value, methodName)); } - return ((NewArrayTree) value) - .getInitializers().stream() - .map(name -> toMethodSourceFactoryDescriptor(name, methodName)) - .collect(toImmutableList()); + return newArray.getInitializers().stream() + .map(name -> toMethodSourceFactoryDescriptor(name, methodName)) + .collect(toImmutableList()); } private static String toMethodSourceFactoryDescriptor( diff --git a/refaster-support/src/main/java/tech/picnic/errorprone/refaster/matchers/ThrowsCheckedException.java b/refaster-support/src/main/java/tech/picnic/errorprone/refaster/matchers/ThrowsCheckedException.java index 15d743e6968..aa11abcdf34 100644 --- a/refaster-support/src/main/java/tech/picnic/errorprone/refaster/matchers/ThrowsCheckedException.java +++ b/refaster-support/src/main/java/tech/picnic/errorprone/refaster/matchers/ThrowsCheckedException.java @@ -29,8 +29,8 @@ public boolean matches(ExpressionTree tree, VisitorState state) { } private static Collection getThrownTypes(ExpressionTree tree, VisitorState state) { - if (tree instanceof LambdaExpressionTree) { - return ASTHelpers.getThrownExceptions(((LambdaExpressionTree) tree).getBody(), state); + if (tree instanceof LambdaExpressionTree lambdaExpression) { + return ASTHelpers.getThrownExceptions(lambdaExpression.getBody(), state); } if (tree instanceof MemberReferenceTree) { diff --git a/refaster-support/src/test/java/tech/picnic/errorprone/refaster/matchers/AbstractMatcherTestChecker.java b/refaster-support/src/test/java/tech/picnic/errorprone/refaster/matchers/AbstractMatcherTestChecker.java index c0361ab6e3e..33882a344d0 100644 --- a/refaster-support/src/test/java/tech/picnic/errorprone/refaster/matchers/AbstractMatcherTestChecker.java +++ b/refaster-support/src/test/java/tech/picnic/errorprone/refaster/matchers/AbstractMatcherTestChecker.java @@ -34,7 +34,7 @@ public Description matchCompilationUnit(CompilationUnitTree compilationUnit, Vis new TreeScanner<@Nullable Void, @Nullable Void>() { @Override public @Nullable Void scan(Tree tree, @Nullable Void unused) { - if (tree instanceof ExpressionTree && delegate.matches((ExpressionTree) tree, state)) { + if (tree instanceof ExpressionTree expression && delegate.matches(expression, state)) { state.reportMatch(describeMatch(tree)); } diff --git a/refaster-test-support/src/main/java/tech/picnic/errorprone/refaster/test/RefasterRuleCollection.java b/refaster-test-support/src/main/java/tech/picnic/errorprone/refaster/test/RefasterRuleCollection.java index 8fd5803bc4d..b5f48e0a833 100644 --- a/refaster-test-support/src/main/java/tech/picnic/errorprone/refaster/test/RefasterRuleCollection.java +++ b/refaster-test-support/src/main/java/tech/picnic/errorprone/refaster/test/RefasterRuleCollection.java @@ -152,8 +152,8 @@ private void reportIncorrectClassName(CompilationUnitTree tree, VisitorState sta String expectedClassName = ruleCollectionUnderTest + "Test"; for (Tree typeDeclaration : tree.getTypeDecls()) { - if (typeDeclaration instanceof ClassTree) { - if (!((ClassTree) typeDeclaration).getSimpleName().contentEquals(expectedClassName)) { + if (typeDeclaration instanceof ClassTree classTree) { + if (!classTree.getSimpleName().contentEquals(expectedClassName)) { state.reportMatch( describeMatch( typeDeclaration,