From 82986358cfa7134cce626706b49dea06796d6dd9 Mon Sep 17 00:00:00 2001 From: ghm Date: Fri, 15 Nov 2024 08:15:24 -0800 Subject: [PATCH] Give PatternMatchingInstanceof a second run over EP, with the improvements in unknown commit. This catches a decent bit more. Turns out not assigning a specific variable is common. I did have to do some manual cleaning up around colliding variable names. PiperOrigin-RevId: 696893465 --- .../google/errorprone/SuppressionInfo.java | 4 +- .../errorprone/dataflow/AccessPath.java | 16 +- .../google/errorprone/dataflow/DataFlow.java | 8 +- .../NullnessAnnotations.java | 8 +- .../NullnessPropagationTransfer.java | 48 ++-- .../inference/InferredNullability.java | 4 +- .../inference/NullnessQualifierInference.java | 8 +- .../errorprone/fixes/SuggestedFixes.java | 10 +- .../matchers/AnnotationMatcher.java | 24 +- .../matchers/ConstructorOfClass.java | 4 +- .../google/errorprone/matchers/Enclosing.java | 8 +- .../matchers/method/BaseMethodMatcher.java | 4 +- .../errorprone/scanner/ErrorProneScanner.java | 252 +++++++++--------- .../google/errorprone/scanner/Scanner.java | 5 +- .../google/errorprone/util/ASTHelpers.java | 156 +++++------ .../com/google/errorprone/util/Comments.java | 8 +- .../errorprone/util/FindIdentifiers.java | 4 +- .../AbstractReturnValueIgnored.java | 10 +- .../AssertThrowsMultipleStatements.java | 4 +- .../bugpatterns/AvoidObjectArrays.java | 4 +- .../bugpatterns/BadShiftAmount.java | 8 +- .../bugpatterns/BooleanParameter.java | 4 +- .../BoxedPrimitiveConstructor.java | 5 +- .../bugpatterns/ByteBufferBackingArray.java | 8 +- .../bugpatterns/CanBeStaticAnalyzer.java | 4 +- .../CheckNotNullMultipleTimes.java | 6 +- .../bugpatterns/CheckReturnValue.java | 4 +- .../ComparisonContractViolated.java | 16 +- .../bugpatterns/ConstantOverflow.java | 5 +- .../bugpatterns/ConstantPatternCompile.java | 13 +- .../errorprone/bugpatterns/DeadException.java | 8 +- .../bugpatterns/DefaultCharset.java | 4 +- .../bugpatterns/DirectInvocationOnMock.java | 15 +- .../bugpatterns/DoNotCallChecker.java | 4 +- .../DoubleBraceInitialization.java | 8 +- .../bugpatterns/DuplicateBranches.java | 4 +- .../bugpatterns/EqualsGetClass.java | 8 +- .../bugpatterns/EqualsReference.java | 4 +- .../FloatingPointAssertionWithinEpsilon.java | 4 +- .../bugpatterns/ForEachIterable.java | 8 +- .../bugpatterns/ForOverrideChecker.java | 4 +- .../bugpatterns/IdentifierName.java | 3 +- .../IncrementInForLoopAndHeader.java | 6 +- .../bugpatterns/LockNotBeforeTry.java | 8 +- .../bugpatterns/LoopConditionChecker.java | 4 +- .../errorprone/bugpatterns/MissingFail.java | 8 +- .../MixedMutabilityReturnType.java | 4 +- .../bugpatterns/MockNotUsedInProduction.java | 4 +- .../bugpatterns/MockitoDoSetup.java | 18 +- .../bugpatterns/MultipleTopLevelClasses.java | 3 +- .../NestedInstanceOfConditions.java | 8 +- .../bugpatterns/PreferredInterfaceType.java | 4 +- .../SizeGreaterThanOrEqualsZero.java | 4 +- .../StatementSwitchToExpressionSwitch.java | 12 +- .../bugpatterns/StreamResourceLeak.java | 6 +- .../bugpatterns/TestExceptionChecker.java | 4 +- .../TypeParameterUnusedInFormals.java | 4 +- .../bugpatterns/UnnecessaryAsync.java | 28 +- .../UnnecessaryLongToIntConversion.java | 5 +- .../bugpatterns/UnusedNestedClass.java | 4 +- .../bugpatterns/UnusedTypeParameter.java | 4 +- .../bugpatterns/UnusedVariable.java | 8 +- .../errorprone/bugpatterns/Varifier.java | 4 +- .../CreatesDuplicateCallHeuristic.java | 13 +- .../EnclosedByReverseHeuristic.java | 8 +- .../CanIgnoreReturnValueSuggester.java | 8 +- .../flogger/FloggerRequiredModifiers.java | 12 +- .../bugpatterns/javadoc/InvalidParam.java | 4 +- .../bugpatterns/nullness/UnsafeWildcard.java | 21 +- .../nullness/VoidMissingNullable.java | 8 +- .../threadsafety/ConstantExpressions.java | 5 +- .../threadsafety/GuardedByExpression.java | 8 +- .../threadsafety/GuardedBySymbolResolver.java | 4 +- .../threadsafety/HeldLockAnalyzer.java | 4 +- .../threadsafety/ImmutableChecker.java | 4 +- .../threadsafety/StaticGuardedByInstance.java | 4 +- .../bugpatterns/time/DateChecker.java | 4 +- .../time/DurationGetTemporalUnit.java | 8 +- .../time/DurationToLongTimeUnit.java | 10 +- .../bugpatterns/time/NearbyCallers.java | 8 +- .../time/TemporalAccessorGetChronoField.java | 9 +- .../bugpatterns/time/TimeUnitMismatch.java | 8 +- .../refaster/ExpressionTemplate.java | 8 +- .../PlaceholderUnificationVisitor.java | 4 +- .../errorprone/refaster/RefasterScanner.java | 4 +- .../google/errorprone/refaster/Template.java | 4 +- .../google/errorprone/refaster/ULiteral.java | 8 +- .../refaster/UPlaceholderExpression.java | 4 +- .../errorprone/refaster/UTemplater.java | 16 +- .../ErrorProneCompilerIntegrationTest.java | 8 +- 90 files changed, 536 insertions(+), 556 deletions(-) diff --git a/check_api/src/main/java/com/google/errorprone/SuppressionInfo.java b/check_api/src/main/java/com/google/errorprone/SuppressionInfo.java index 3b891b9cc5e..8249aeefa66 100644 --- a/check_api/src/main/java/com/google/errorprone/SuppressionInfo.java +++ b/check_api/src/main/java/com/google/errorprone/SuppressionInfo.java @@ -158,8 +158,8 @@ public SuppressionInfo withExtendedSuppressions( for (Pair value : attr.values) { if (value.fst.name.equals(valueName)) { if (value.snd - instanceof Attribute.Array) { // SuppressWarnings/SuppressLint take an array - for (Attribute suppress : ((Attribute.Array) value.snd).values) { + instanceof Attribute.Array array) { // SuppressWarnings/SuppressLint take an array + for (Attribute suppress : array.values) { String suppressedWarning = (String) suppress.getValue(); if (!suppressWarningsStrings.contains(suppressedWarning)) { anyModification = true; diff --git a/check_api/src/main/java/com/google/errorprone/dataflow/AccessPath.java b/check_api/src/main/java/com/google/errorprone/dataflow/AccessPath.java index e4af72b7cb2..6b0d588072a 100644 --- a/check_api/src/main/java/com/google/errorprone/dataflow/AccessPath.java +++ b/check_api/src/main/java/com/google/errorprone/dataflow/AccessPath.java @@ -160,14 +160,14 @@ public static AccessPath fromVariableDecl(VariableDeclarationNode node) { * path and null otherwise */ public static @Nullable AccessPath fromNodeIfTrackable(Node node) { - if (node instanceof LocalVariableNode) { - return fromLocalVariable((LocalVariableNode) node); - } else if (node instanceof VariableDeclarationNode) { - return fromVariableDecl((VariableDeclarationNode) node); - } else if (node instanceof FieldAccessNode) { - return fromFieldAccess((FieldAccessNode) node); - } else if (node instanceof AssignmentNode) { - return fromNodeIfTrackable(((AssignmentNode) node).getTarget()); + if (node instanceof LocalVariableNode localVariableNode) { + return fromLocalVariable(localVariableNode); + } else if (node instanceof VariableDeclarationNode variableDeclarationNode) { + return fromVariableDecl(variableDeclarationNode); + } else if (node instanceof FieldAccessNode fieldAccessNode) { + return fromFieldAccess(fieldAccessNode); + } else if (node instanceof AssignmentNode assignmentNode) { + return fromNodeIfTrackable(assignmentNode.getTarget()); } return null; } diff --git a/check_api/src/main/java/com/google/errorprone/dataflow/DataFlow.java b/check_api/src/main/java/com/google/errorprone/dataflow/DataFlow.java index 31f614d18b2..4db4df7094e 100644 --- a/check_api/src/main/java/com/google/errorprone/dataflow/DataFlow.java +++ b/check_api/src/main/java/com/google/errorprone/dataflow/DataFlow.java @@ -98,11 +98,11 @@ public ControlFlowGraph load(CfgParams key) { ClassTree classTree = null; MethodTree methodTree = null; for (Tree parent : methodPath) { - if (parent instanceof MethodTree) { - methodTree = (MethodTree) parent; + if (parent instanceof MethodTree m) { + methodTree = m; } - if (parent instanceof ClassTree) { - classTree = (ClassTree) parent; + if (parent instanceof ClassTree c) { + classTree = c; break; } } diff --git a/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/NullnessAnnotations.java b/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/NullnessAnnotations.java index 342b059a729..300e6e864c2 100644 --- a/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/NullnessAnnotations.java +++ b/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/NullnessAnnotations.java @@ -92,10 +92,10 @@ public static ImmutableList annotationsRelevantToNullness( private static String simpleName(AnnotationTree annotation) { Tree annotationType = annotation.getAnnotationType(); - if (annotationType instanceof IdentifierTree) { - return ((IdentifierTree) annotationType).getName().toString(); - } else if (annotationType instanceof MemberSelectTree) { - return ((MemberSelectTree) annotationType).getIdentifier().toString(); + if (annotationType instanceof IdentifierTree identifierTree) { + return identifierTree.getName().toString(); + } else if (annotationType instanceof MemberSelectTree memberSelectTree) { + return memberSelectTree.getIdentifier().toString(); } else { throw new AssertionError(annotationType.getKind()); } diff --git a/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/NullnessPropagationTransfer.java b/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/NullnessPropagationTransfer.java index c133ea6c0e8..e9ec9a7ba0d 100644 --- a/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/NullnessPropagationTransfer.java +++ b/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/NullnessPropagationTransfer.java @@ -468,12 +468,12 @@ Nullness visitAssignment(AssignmentNode node, SubNodeValues inputs, Updates upda Nullness value = inputs.valueOfSubNode(node.getExpression()); Node target = node.getTarget(); - if (target instanceof LocalVariableNode) { - updates.set((LocalVariableNode) target, value); + if (target instanceof LocalVariableNode localVariableNode) { + updates.set(localVariableNode, value); } - if (target instanceof ArrayAccessNode) { - setNonnullIfTrackable(updates, ((ArrayAccessNode) target).getArray()); + if (target instanceof ArrayAccessNode arrayAccessNode) { + setNonnullIfTrackable(updates, arrayAccessNode.getArray()); } if (target instanceof FieldAccessNode fieldAccess) { @@ -681,16 +681,16 @@ private static boolean hasNonNullConstantValue(LocalVariableNode node) { private static @Nullable ClassAndField tryGetFieldSymbol(Tree tree) { Symbol symbol = tryGetSymbol(tree); - if (symbol instanceof VarSymbol) { - return ClassAndField.make((VarSymbol) symbol); + if (symbol instanceof VarSymbol varSymbol) { + return ClassAndField.make(varSymbol); } return null; } static @Nullable ClassAndMethod tryGetMethodSymbol(MethodInvocationTree tree, Types types) { Symbol symbol = tryGetSymbol(tree.getMethodSelect()); - if (symbol instanceof MethodSymbol) { - return ClassAndMethod.make((MethodSymbol) symbol, types); + if (symbol instanceof MethodSymbol methodSymbol) { + return ClassAndMethod.make(methodSymbol, types); } return null; } @@ -700,14 +700,14 @@ private static boolean hasNonNullConstantValue(LocalVariableNode node) { * back on core. */ private static @Nullable Symbol tryGetSymbol(Tree tree) { - if (tree instanceof JCIdent) { - return ((JCIdent) tree).sym; + if (tree instanceof JCIdent jCIdent) { + return jCIdent.sym; } - if (tree instanceof JCFieldAccess) { - return ((JCFieldAccess) tree).sym; + if (tree instanceof JCFieldAccess jCFieldAccess) { + return jCFieldAccess.sym; } - if (tree instanceof JCVariableDecl) { - return ((JCVariableDecl) tree).sym; + if (tree instanceof JCVariableDecl jCVariableDecl) { + return jCVariableDecl.sym; } return null; } @@ -763,8 +763,8 @@ Nullness standardFieldNullness( Optional declaredNullness = NullnessAnnotations.fromAnnotationsOn(accessed.symbol); if (declaredNullness.isEmpty()) { Type ftype = accessed.symbol.type; - if (ftype instanceof TypeVariable) { - declaredNullness = NullnessAnnotations.getUpperBound((TypeVariable) ftype); + if (ftype instanceof TypeVariable typeVariable) { + declaredNullness = NullnessAnnotations.getUpperBound(typeVariable); } else { declaredNullness = NullnessAnnotations.fromDefaultAnnotations(accessed.symbol); } @@ -843,12 +843,12 @@ private Nullness returnValueNullness(MethodInvocationNode node, @Nullable ClassA } private static void setNonnullIfTrackable(Updates updates, Node node) { - if (node instanceof LocalVariableNode) { - updates.set((LocalVariableNode) node, NONNULL); - } else if (node instanceof FieldAccessNode) { - updates.set((FieldAccessNode) node, NONNULL); - } else if (node instanceof VariableDeclarationNode) { - updates.set((VariableDeclarationNode) node, NONNULL); + if (node instanceof LocalVariableNode localVariableNode) { + updates.set(localVariableNode, NONNULL); + } else if (node instanceof FieldAccessNode fieldAccessNode) { + updates.set(fieldAccessNode, NONNULL); + } else if (node instanceof VariableDeclarationNode variableDeclarationNode) { + updates.set(variableDeclarationNode, NONNULL); } } @@ -928,8 +928,8 @@ private static List variablesAtIndexes( // TODO(cpovirk): better handling of varargs if (i >= 0 && i < arguments.size()) { Node argument = arguments.get(i); - if (argument instanceof LocalVariableNode) { - result.add((LocalVariableNode) argument); + if (argument instanceof LocalVariableNode localVariableNode) { + result.add(localVariableNode); } } } diff --git a/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/inference/InferredNullability.java b/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/inference/InferredNullability.java index 058b7fb32ab..453c71743a8 100644 --- a/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/inference/InferredNullability.java +++ b/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/inference/InferredNullability.java @@ -73,8 +73,8 @@ private Optional getNullness(InferenceVariable iv) { Optional result; // short-circuit and return if... // ...this inference variable is a `proper` bound, i.e. a concrete nullness lattice element - if (iv instanceof ProperInferenceVar) { - return Optional.of(((ProperInferenceVar) iv).nullness()); + if (iv instanceof ProperInferenceVar properInferenceVar) { + return Optional.of(properInferenceVar.nullness()); // ...we've already computed and memoized a nullness value for it. } else if ((result = inferredMemoTable.get(iv)) != null) { return result; diff --git a/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/inference/NullnessQualifierInference.java b/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/inference/NullnessQualifierInference.java index a4121ce3454..56ba972f6ef 100644 --- a/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/inference/NullnessQualifierInference.java +++ b/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/inference/NullnessQualifierInference.java @@ -162,10 +162,10 @@ private void generateConstraintsFromAnnotations( fromAnnotations = NullnessAnnotations.fromAnnotationsOn(inferredType); } if (!fromAnnotations.isPresent()) { - if (declaredType instanceof TypeVariable) { + if (declaredType instanceof TypeVariable typeVariable) { // Check bounds second so explicit annotations take precedence. Even for bounds we still use // equality constraint below since we have to assume the bound as the "worst" case. - fromAnnotations = NullnessAnnotations.getUpperBound((TypeVariable) declaredType); + fromAnnotations = NullnessAnnotations.getUpperBound(typeVariable); } else { // Look for a default annotation in scope of either the symbol we're looking at or, if this // is a type variable, the type variable declaration's scope, which is effectively the type @@ -485,8 +485,8 @@ private void generateConstraintsForWrite( Optional fromAnnotations = extractExplicitNullness(lType, argSelector.isEmpty() ? decl : null); if (!fromAnnotations.isPresent()) { - if (lType instanceof TypeVariable) { - fromAnnotations = NullnessAnnotations.getUpperBound((TypeVariable) lType); + if (lType instanceof TypeVariable typeVariable) { + fromAnnotations = NullnessAnnotations.getUpperBound(typeVariable); isBound = true; } else { fromAnnotations = NullnessAnnotations.fromDefaultAnnotations(decl); diff --git a/check_api/src/main/java/com/google/errorprone/fixes/SuggestedFixes.java b/check_api/src/main/java/com/google/errorprone/fixes/SuggestedFixes.java index 7f13a755211..34c1f42ea3d 100644 --- a/check_api/src/main/java/com/google/errorprone/fixes/SuggestedFixes.java +++ b/check_api/src/main/java/com/google/errorprone/fixes/SuggestedFixes.java @@ -795,11 +795,11 @@ public static SuggestedFix renameMethodInvocation( Tree methodSelect = tree.getMethodSelect(); Name identifier; int startPos; - if (methodSelect instanceof MemberSelectTree) { - identifier = ((MemberSelectTree) methodSelect).getIdentifier(); - startPos = state.getEndPosition(((MemberSelectTree) methodSelect).getExpression()); - } else if (methodSelect instanceof IdentifierTree) { - identifier = ((IdentifierTree) methodSelect).getName(); + if (methodSelect instanceof MemberSelectTree memberSelectTree) { + identifier = memberSelectTree.getIdentifier(); + startPos = state.getEndPosition(memberSelectTree.getExpression()); + } else if (methodSelect instanceof IdentifierTree identifierTree) { + identifier = identifierTree.getName(); startPos = getStartPosition(tree); } else { throw malformedMethodInvocationTree(tree); diff --git a/check_api/src/main/java/com/google/errorprone/matchers/AnnotationMatcher.java b/check_api/src/main/java/com/google/errorprone/matchers/AnnotationMatcher.java index dcadba37640..f5139e5bc27 100644 --- a/check_api/src/main/java/com/google/errorprone/matchers/AnnotationMatcher.java +++ b/check_api/src/main/java/com/google/errorprone/matchers/AnnotationMatcher.java @@ -40,18 +40,18 @@ public AnnotationMatcher(MatchType matchType, Matcher nodeMatche @Override protected Iterable getChildNodes(T tree, VisitorState state) { - if (tree instanceof ClassTree) { - return ((ClassTree) tree).getModifiers().getAnnotations(); - } else if (tree instanceof VariableTree) { - return ((VariableTree) tree).getModifiers().getAnnotations(); - } else if (tree instanceof MethodTree) { - return ((MethodTree) tree).getModifiers().getAnnotations(); - } else if (tree instanceof CompilationUnitTree) { - return ((CompilationUnitTree) tree).getPackageAnnotations(); - } else if (tree instanceof AnnotatedTypeTree) { - return ((AnnotatedTypeTree) tree).getAnnotations(); - } else if (tree instanceof PackageTree) { - return ((PackageTree) tree).getAnnotations(); + if (tree instanceof ClassTree classTree) { + return classTree.getModifiers().getAnnotations(); + } else if (tree instanceof VariableTree variableTree) { + return variableTree.getModifiers().getAnnotations(); + } else if (tree instanceof MethodTree methodTree) { + return methodTree.getModifiers().getAnnotations(); + } else if (tree instanceof CompilationUnitTree compilationUnitTree) { + return compilationUnitTree.getPackageAnnotations(); + } else if (tree instanceof AnnotatedTypeTree annotatedTypeTree) { + return annotatedTypeTree.getAnnotations(); + } else if (tree instanceof PackageTree packageTree) { + return packageTree.getAnnotations(); } else { throw new IllegalArgumentException( "Cannot access annotations from tree of type " + tree.getClass()); diff --git a/check_api/src/main/java/com/google/errorprone/matchers/ConstructorOfClass.java b/check_api/src/main/java/com/google/errorprone/matchers/ConstructorOfClass.java index 4fa0d1da4fd..f881efc3b30 100644 --- a/check_api/src/main/java/com/google/errorprone/matchers/ConstructorOfClass.java +++ b/check_api/src/main/java/com/google/errorprone/matchers/ConstructorOfClass.java @@ -40,8 +40,8 @@ protected Iterable getChildNodes(ClassTree classTree, Visi // Iterate over members of class (methods and fields). for (Tree member : classTree.getMembers()) { // If this member is a constructor... - if (member instanceof MethodTree && ASTHelpers.getSymbol(member).isConstructor()) { - result.add((MethodTree) member); + if (member instanceof MethodTree methodTree && ASTHelpers.getSymbol(member).isConstructor()) { + result.add(methodTree); } } return result.build(); diff --git a/check_api/src/main/java/com/google/errorprone/matchers/Enclosing.java b/check_api/src/main/java/com/google/errorprone/matchers/Enclosing.java index 15997cc771c..b7138eafd1e 100644 --- a/check_api/src/main/java/com/google/errorprone/matchers/Enclosing.java +++ b/check_api/src/main/java/com/google/errorprone/matchers/Enclosing.java @@ -90,10 +90,10 @@ public boolean matches(T unused, VisitorState state) { } Tree enclosing = pathToEnclosing.getLeaf(); state = state.withPath(pathToEnclosing); - if (enclosing instanceof BlockTree) { - return blockTreeMatcher.matches((BlockTree) enclosing, state); - } else if (enclosing instanceof CaseTree) { - return caseTreeMatcher.matches((CaseTree) enclosing, state); + if (enclosing instanceof BlockTree blockTree) { + return blockTreeMatcher.matches(blockTree, state); + } else if (enclosing instanceof CaseTree caseTree) { + return caseTreeMatcher.matches(caseTree, state); } else { // findEnclosing given two types must return something of one of those types throw new IllegalStateException("enclosing tree not a BlockTree or CaseTree"); diff --git a/check_api/src/main/java/com/google/errorprone/matchers/method/BaseMethodMatcher.java b/check_api/src/main/java/com/google/errorprone/matchers/method/BaseMethodMatcher.java index fa9bd44766e..73c045e0837 100644 --- a/check_api/src/main/java/com/google/errorprone/matchers/method/BaseMethodMatcher.java +++ b/check_api/src/main/java/com/google/errorprone/matchers/method/BaseMethodMatcher.java @@ -36,8 +36,8 @@ interface BaseMethodMatcher { // Don't match constructors as they are neither static nor instance methods. return null; } - if (tree instanceof MethodInvocationTree) { - tree = ((MethodInvocationTree) tree).getMethodSelect(); + if (tree instanceof MethodInvocationTree methodInvocationTree) { + tree = methodInvocationTree.getMethodSelect(); } return MethodMatchState.create(tree, (MethodSymbol) sym); }; diff --git a/check_api/src/main/java/com/google/errorprone/scanner/ErrorProneScanner.java b/check_api/src/main/java/com/google/errorprone/scanner/ErrorProneScanner.java index b6a2960d042..cc3b3ac9eab 100644 --- a/check_api/src/main/java/com/google/errorprone/scanner/ErrorProneScanner.java +++ b/check_api/src/main/java/com/google/errorprone/scanner/ErrorProneScanner.java @@ -302,188 +302,188 @@ private void registerNodeTypes( ImmutableSet.Builder> customSuppressionAnnotationClasses) { customSuppressionAnnotationClasses.addAll(checker.customSuppressionAnnotations()); - if (checker instanceof AnnotatedTypeTreeMatcher) { - annotatedTypeMatchers.add((AnnotatedTypeTreeMatcher) checker); + if (checker instanceof AnnotatedTypeTreeMatcher annotatedTypeTreeMatcher) { + annotatedTypeMatchers.add(annotatedTypeTreeMatcher); } - if (checker instanceof AnnotationTreeMatcher) { - annotationMatchers.add((AnnotationTreeMatcher) checker); + if (checker instanceof AnnotationTreeMatcher annotationTreeMatcher) { + annotationMatchers.add(annotationTreeMatcher); } - if (checker instanceof ArrayAccessTreeMatcher) { - arrayAccessMatchers.add((ArrayAccessTreeMatcher) checker); + if (checker instanceof ArrayAccessTreeMatcher arrayAccessTreeMatcher) { + arrayAccessMatchers.add(arrayAccessTreeMatcher); } - if (checker instanceof ArrayTypeTreeMatcher) { - arrayTypeMatchers.add((ArrayTypeTreeMatcher) checker); + if (checker instanceof ArrayTypeTreeMatcher arrayTypeTreeMatcher) { + arrayTypeMatchers.add(arrayTypeTreeMatcher); } - if (checker instanceof AssertTreeMatcher) { - assertMatchers.add((AssertTreeMatcher) checker); + if (checker instanceof AssertTreeMatcher assertTreeMatcher) { + assertMatchers.add(assertTreeMatcher); } - if (checker instanceof AssignmentTreeMatcher) { - assignmentMatchers.add((AssignmentTreeMatcher) checker); + if (checker instanceof AssignmentTreeMatcher assignmentTreeMatcher) { + assignmentMatchers.add(assignmentTreeMatcher); } - if (checker instanceof BinaryTreeMatcher) { - binaryMatchers.add((BinaryTreeMatcher) checker); + if (checker instanceof BinaryTreeMatcher binaryTreeMatcher) { + binaryMatchers.add(binaryTreeMatcher); } - if (checker instanceof BindingPatternTreeMatcher) { - bindingPatternMatchers.add((BindingPatternTreeMatcher) checker); + if (checker instanceof BindingPatternTreeMatcher bindingPatternTreeMatcher) { + bindingPatternMatchers.add(bindingPatternTreeMatcher); } - if (checker instanceof BlockTreeMatcher) { - blockMatchers.add((BlockTreeMatcher) checker); + if (checker instanceof BlockTreeMatcher blockTreeMatcher) { + blockMatchers.add(blockTreeMatcher); } - if (checker instanceof BreakTreeMatcher) { - breakMatchers.add((BreakTreeMatcher) checker); + if (checker instanceof BreakTreeMatcher breakTreeMatcher) { + breakMatchers.add(breakTreeMatcher); } - if (checker instanceof CaseTreeMatcher) { - caseMatchers.add((CaseTreeMatcher) checker); + if (checker instanceof CaseTreeMatcher caseTreeMatcher) { + caseMatchers.add(caseTreeMatcher); } - if (checker instanceof CatchTreeMatcher) { - catchMatchers.add((CatchTreeMatcher) checker); + if (checker instanceof CatchTreeMatcher catchTreeMatcher) { + catchMatchers.add(catchTreeMatcher); } - if (checker instanceof ClassTreeMatcher) { - classMatchers.add((ClassTreeMatcher) checker); + if (checker instanceof ClassTreeMatcher classTreeMatcher) { + classMatchers.add(classTreeMatcher); } - if (checker instanceof CompilationUnitTreeMatcher) { - compilationUnitMatchers.add((CompilationUnitTreeMatcher) checker); + if (checker instanceof CompilationUnitTreeMatcher compilationUnitTreeMatcher) { + compilationUnitMatchers.add(compilationUnitTreeMatcher); } - if (checker instanceof CompoundAssignmentTreeMatcher) { - compoundAssignmentMatchers.add((CompoundAssignmentTreeMatcher) checker); + if (checker instanceof CompoundAssignmentTreeMatcher compoundAssignmentTreeMatcher) { + compoundAssignmentMatchers.add(compoundAssignmentTreeMatcher); } - if (checker instanceof ConditionalExpressionTreeMatcher) { - conditionalExpressionMatchers.add((ConditionalExpressionTreeMatcher) checker); + if (checker instanceof ConditionalExpressionTreeMatcher conditionalExpressionTreeMatcher) { + conditionalExpressionMatchers.add(conditionalExpressionTreeMatcher); } - if (checker instanceof ContinueTreeMatcher) { - continueMatchers.add((ContinueTreeMatcher) checker); + if (checker instanceof ContinueTreeMatcher continueTreeMatcher) { + continueMatchers.add(continueTreeMatcher); } - if (checker instanceof DoWhileLoopTreeMatcher) { - doWhileLoopMatchers.add((DoWhileLoopTreeMatcher) checker); + if (checker instanceof DoWhileLoopTreeMatcher doWhileLoopTreeMatcher) { + doWhileLoopMatchers.add(doWhileLoopTreeMatcher); } - if (checker instanceof EmptyStatementTreeMatcher) { - emptyStatementMatchers.add((EmptyStatementTreeMatcher) checker); + if (checker instanceof EmptyStatementTreeMatcher emptyStatementTreeMatcher) { + emptyStatementMatchers.add(emptyStatementTreeMatcher); } - if (checker instanceof EnhancedForLoopTreeMatcher) { - enhancedForLoopMatchers.add((EnhancedForLoopTreeMatcher) checker); + if (checker instanceof EnhancedForLoopTreeMatcher enhancedForLoopTreeMatcher) { + enhancedForLoopMatchers.add(enhancedForLoopTreeMatcher); } - if (checker instanceof ExportsTreeMatcher) { - exportsMatchers.add((ExportsTreeMatcher) checker); + if (checker instanceof ExportsTreeMatcher exportsTreeMatcher) { + exportsMatchers.add(exportsTreeMatcher); } - if (checker instanceof ExpressionStatementTreeMatcher) { - expressionStatementMatchers.add((ExpressionStatementTreeMatcher) checker); + if (checker instanceof ExpressionStatementTreeMatcher expressionStatementTreeMatcher) { + expressionStatementMatchers.add(expressionStatementTreeMatcher); } - if (checker instanceof ForLoopTreeMatcher) { - forLoopMatchers.add((ForLoopTreeMatcher) checker); + if (checker instanceof ForLoopTreeMatcher forLoopTreeMatcher) { + forLoopMatchers.add(forLoopTreeMatcher); } - if (checker instanceof IdentifierTreeMatcher) { - identifierMatchers.add((IdentifierTreeMatcher) checker); + if (checker instanceof IdentifierTreeMatcher identifierTreeMatcher) { + identifierMatchers.add(identifierTreeMatcher); } - if (checker instanceof IfTreeMatcher) { - ifMatchers.add((IfTreeMatcher) checker); + if (checker instanceof IfTreeMatcher ifTreeMatcher) { + ifMatchers.add(ifTreeMatcher); } - if (checker instanceof ImportTreeMatcher) { - importMatchers.add((ImportTreeMatcher) checker); + if (checker instanceof ImportTreeMatcher importTreeMatcher) { + importMatchers.add(importTreeMatcher); } - if (checker instanceof InstanceOfTreeMatcher) { - instanceOfMatchers.add((InstanceOfTreeMatcher) checker); + if (checker instanceof InstanceOfTreeMatcher instanceOfTreeMatcher) { + instanceOfMatchers.add(instanceOfTreeMatcher); } - if (checker instanceof IntersectionTypeTreeMatcher) { - intersectionTypeMatchers.add((IntersectionTypeTreeMatcher) checker); + if (checker instanceof IntersectionTypeTreeMatcher intersectionTypeTreeMatcher) { + intersectionTypeMatchers.add(intersectionTypeTreeMatcher); } - if (checker instanceof LabeledStatementTreeMatcher) { - labeledStatementMatchers.add((LabeledStatementTreeMatcher) checker); + if (checker instanceof LabeledStatementTreeMatcher labeledStatementTreeMatcher) { + labeledStatementMatchers.add(labeledStatementTreeMatcher); } - if (checker instanceof LambdaExpressionTreeMatcher) { - lambdaExpressionMatchers.add((LambdaExpressionTreeMatcher) checker); + if (checker instanceof LambdaExpressionTreeMatcher lambdaExpressionTreeMatcher) { + lambdaExpressionMatchers.add(lambdaExpressionTreeMatcher); } - if (checker instanceof LiteralTreeMatcher) { - literalMatchers.add((LiteralTreeMatcher) checker); + if (checker instanceof LiteralTreeMatcher literalTreeMatcher) { + literalMatchers.add(literalTreeMatcher); } - if (checker instanceof MemberReferenceTreeMatcher) { - memberReferenceMatchers.add((MemberReferenceTreeMatcher) checker); + if (checker instanceof MemberReferenceTreeMatcher memberReferenceTreeMatcher) { + memberReferenceMatchers.add(memberReferenceTreeMatcher); } - if (checker instanceof MemberSelectTreeMatcher) { - memberSelectMatchers.add((MemberSelectTreeMatcher) checker); + if (checker instanceof MemberSelectTreeMatcher memberSelectTreeMatcher) { + memberSelectMatchers.add(memberSelectTreeMatcher); } - if (checker instanceof MethodTreeMatcher) { - methodMatchers.add((MethodTreeMatcher) checker); + if (checker instanceof MethodTreeMatcher methodTreeMatcher) { + methodMatchers.add(methodTreeMatcher); } - if (checker instanceof MethodInvocationTreeMatcher) { - methodInvocationMatchers.add((MethodInvocationTreeMatcher) checker); + if (checker instanceof MethodInvocationTreeMatcher methodInvocationTreeMatcher) { + methodInvocationMatchers.add(methodInvocationTreeMatcher); } - if (checker instanceof ModifiersTreeMatcher) { - modifiersMatchers.add((ModifiersTreeMatcher) checker); + if (checker instanceof ModifiersTreeMatcher modifiersTreeMatcher) { + modifiersMatchers.add(modifiersTreeMatcher); } - if (checker instanceof ModuleTreeMatcher) { - moduleMatchers.add((ModuleTreeMatcher) checker); + if (checker instanceof ModuleTreeMatcher moduleTreeMatcher) { + moduleMatchers.add(moduleTreeMatcher); } - if (checker instanceof NewArrayTreeMatcher) { - newArrayMatchers.add((NewArrayTreeMatcher) checker); + if (checker instanceof NewArrayTreeMatcher newArrayTreeMatcher) { + newArrayMatchers.add(newArrayTreeMatcher); } - if (checker instanceof NewClassTreeMatcher) { - newClassMatchers.add((NewClassTreeMatcher) checker); + if (checker instanceof NewClassTreeMatcher newClassTreeMatcher) { + newClassMatchers.add(newClassTreeMatcher); } - if (checker instanceof OpensTreeMatcher) { - opensMatchers.add((OpensTreeMatcher) checker); + if (checker instanceof OpensTreeMatcher opensTreeMatcher) { + opensMatchers.add(opensTreeMatcher); } - if (checker instanceof PackageTreeMatcher) { - packageMatchers.add((PackageTreeMatcher) checker); + if (checker instanceof PackageTreeMatcher packageTreeMatcher) { + packageMatchers.add(packageTreeMatcher); } - if (checker instanceof ParameterizedTypeTreeMatcher) { - parameterizedTypeMatchers.add((ParameterizedTypeTreeMatcher) checker); + if (checker instanceof ParameterizedTypeTreeMatcher parameterizedTypeTreeMatcher) { + parameterizedTypeMatchers.add(parameterizedTypeTreeMatcher); } - if (checker instanceof ParenthesizedTreeMatcher) { - parenthesizedMatchers.add((ParenthesizedTreeMatcher) checker); + if (checker instanceof ParenthesizedTreeMatcher parenthesizedTreeMatcher) { + parenthesizedMatchers.add(parenthesizedTreeMatcher); } - if (checker instanceof PrimitiveTypeTreeMatcher) { - primitiveTypeMatchers.add((PrimitiveTypeTreeMatcher) checker); + if (checker instanceof PrimitiveTypeTreeMatcher primitiveTypeTreeMatcher) { + primitiveTypeMatchers.add(primitiveTypeTreeMatcher); } - if (checker instanceof ProvidesTreeMatcher) { - providesMatchers.add((ProvidesTreeMatcher) checker); + if (checker instanceof ProvidesTreeMatcher providesTreeMatcher) { + providesMatchers.add(providesTreeMatcher); } - if (checker instanceof RequiresTreeMatcher) { - requiresMatchers.add((RequiresTreeMatcher) checker); + if (checker instanceof RequiresTreeMatcher requiresTreeMatcher) { + requiresMatchers.add(requiresTreeMatcher); } - if (checker instanceof ReturnTreeMatcher) { - returnMatchers.add((ReturnTreeMatcher) checker); + if (checker instanceof ReturnTreeMatcher returnTreeMatcher) { + returnMatchers.add(returnTreeMatcher); } - if (checker instanceof SwitchExpressionTreeMatcher) { - switchExpressionMatchers.add((SwitchExpressionTreeMatcher) checker); + if (checker instanceof SwitchExpressionTreeMatcher switchExpressionTreeMatcher) { + switchExpressionMatchers.add(switchExpressionTreeMatcher); } - if (checker instanceof SwitchTreeMatcher) { - switchMatchers.add((SwitchTreeMatcher) checker); + if (checker instanceof SwitchTreeMatcher switchTreeMatcher) { + switchMatchers.add(switchTreeMatcher); } - if (checker instanceof SynchronizedTreeMatcher) { - synchronizedMatchers.add((SynchronizedTreeMatcher) checker); + if (checker instanceof SynchronizedTreeMatcher synchronizedTreeMatcher) { + synchronizedMatchers.add(synchronizedTreeMatcher); } - if (checker instanceof ThrowTreeMatcher) { - throwMatchers.add((ThrowTreeMatcher) checker); + if (checker instanceof ThrowTreeMatcher throwTreeMatcher) { + throwMatchers.add(throwTreeMatcher); } - if (checker instanceof TryTreeMatcher) { - tryMatchers.add((TryTreeMatcher) checker); + if (checker instanceof TryTreeMatcher tryTreeMatcher) { + tryMatchers.add(tryTreeMatcher); } - if (checker instanceof TypeCastTreeMatcher) { - typeCastMatchers.add((TypeCastTreeMatcher) checker); + if (checker instanceof TypeCastTreeMatcher typeCastTreeMatcher) { + typeCastMatchers.add(typeCastTreeMatcher); } - if (checker instanceof TypeParameterTreeMatcher) { - typeParameterMatchers.add((TypeParameterTreeMatcher) checker); + if (checker instanceof TypeParameterTreeMatcher typeParameterTreeMatcher) { + typeParameterMatchers.add(typeParameterTreeMatcher); } - if (checker instanceof UnaryTreeMatcher) { - unaryMatchers.add((UnaryTreeMatcher) checker); + if (checker instanceof UnaryTreeMatcher unaryTreeMatcher) { + unaryMatchers.add(unaryTreeMatcher); } - if (checker instanceof UnionTypeTreeMatcher) { - unionTypeMatchers.add((UnionTypeTreeMatcher) checker); + if (checker instanceof UnionTypeTreeMatcher unionTypeTreeMatcher) { + unionTypeMatchers.add(unionTypeTreeMatcher); } - if (checker instanceof UsesTreeMatcher) { - usesMatchers.add((UsesTreeMatcher) checker); + if (checker instanceof UsesTreeMatcher usesTreeMatcher) { + usesMatchers.add(usesTreeMatcher); } - if (checker instanceof VariableTreeMatcher) { - variableMatchers.add((VariableTreeMatcher) checker); + if (checker instanceof VariableTreeMatcher variableTreeMatcher) { + variableMatchers.add(variableTreeMatcher); } - if (checker instanceof WhileLoopTreeMatcher) { - whileLoopMatchers.add((WhileLoopTreeMatcher) checker); + if (checker instanceof WhileLoopTreeMatcher whileLoopTreeMatcher) { + whileLoopMatchers.add(whileLoopTreeMatcher); } - if (checker instanceof WildcardTreeMatcher) { - wildcardMatchers.add((WildcardTreeMatcher) checker); + if (checker instanceof WildcardTreeMatcher wildcardTreeMatcher) { + wildcardMatchers.add(wildcardTreeMatcher); } - if (checker instanceof YieldTreeMatcher) { - yieldMatchers.add((YieldTreeMatcher) checker); + if (checker instanceof YieldTreeMatcher yieldTreeMatcher) { + yieldMatchers.add(yieldTreeMatcher); } } @@ -1046,11 +1046,11 @@ public Void visitYield(YieldTree tree, VisitorState visitorState) { */ @Override protected void handleError(Suppressible s, Throwable t) { - if (t instanceof ErrorProneError) { - throw (ErrorProneError) t; + if (t instanceof ErrorProneError errorProneError) { + throw errorProneError; } - if (t instanceof CompletionFailure) { - throw (CompletionFailure) t; + if (t instanceof CompletionFailure completionFailure) { + throw completionFailure; } TreePath path = getCurrentPath(); throw new ErrorProneError( diff --git a/check_api/src/main/java/com/google/errorprone/scanner/Scanner.java b/check_api/src/main/java/com/google/errorprone/scanner/Scanner.java index dc96ae76c04..f1a1780f8bd 100644 --- a/check_api/src/main/java/com/google/errorprone/scanner/Scanner.java +++ b/check_api/src/main/java/com/google/errorprone/scanner/Scanner.java @@ -84,9 +84,8 @@ public Void scan(Tree tree, VisitorState state) { */ private SuppressionInfo updateSuppressions(Tree tree, VisitorState state) { SuppressionInfo prevSuppressionInfo = currentSuppressions; - if (tree instanceof CompilationUnitTree) { - currentSuppressions = - currentSuppressions.forCompilationUnit((CompilationUnitTree) tree, state); + if (tree instanceof CompilationUnitTree compilationUnitTree) { + currentSuppressions = currentSuppressions.forCompilationUnit(compilationUnitTree, state); } else { Symbol sym = ASTHelpers.getDeclaredSymbol(tree); if (sym != null) { diff --git a/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java b/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java index 4e06db632d0..32b7113e489 100644 --- a/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java +++ b/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java @@ -225,21 +225,21 @@ public static boolean sameVariable(ExpressionTree expr1, ExpressionTree expr2) { * is null. */ public static @Nullable Symbol getDeclaredSymbol(Tree tree) { - if (tree instanceof PackageTree) { - return getSymbol((PackageTree) tree); + if (tree instanceof PackageTree packageTree) { + return getSymbol(packageTree); } if (tree instanceof TypeParameterTree) { Type type = ((JCTypeParameter) tree).type; return type == null ? null : type.tsym; } - if (tree instanceof ClassTree) { - return getSymbol((ClassTree) tree); + if (tree instanceof ClassTree classTree) { + return getSymbol(classTree); } - if (tree instanceof MethodTree) { - return getSymbol((MethodTree) tree); + if (tree instanceof MethodTree methodTree) { + return getSymbol(methodTree); } - if (tree instanceof VariableTree) { - return getSymbol((VariableTree) tree); + if (tree instanceof VariableTree variableTree) { + return getSymbol(variableTree); } return null; } @@ -250,32 +250,32 @@ public static boolean sameVariable(ExpressionTree expr1, ExpressionTree expr2) { * error. */ public static @Nullable Symbol getSymbol(Tree tree) { - if (tree instanceof AnnotationTree) { - return getSymbol(((AnnotationTree) tree).getAnnotationType()); + if (tree instanceof AnnotationTree annotationTree) { + return getSymbol(annotationTree.getAnnotationType()); } - if (tree instanceof JCFieldAccess) { - return ((JCFieldAccess) tree).sym; + if (tree instanceof JCFieldAccess jcFieldAccess) { + return jcFieldAccess.sym; } - if (tree instanceof JCIdent) { - return ((JCIdent) tree).sym; + if (tree instanceof JCIdent jcIdent) { + return jcIdent.sym; } - if (tree instanceof JCMethodInvocation) { - return getSymbol((MethodInvocationTree) tree); + if (tree instanceof JCMethodInvocation jcMethodInvocation) { + return getSymbol(jcMethodInvocation); } - if (tree instanceof JCNewClass) { - return getSymbol((NewClassTree) tree); + if (tree instanceof JCNewClass jcNewClass) { + return getSymbol(jcNewClass); } - if (tree instanceof MemberReferenceTree) { - return getSymbol((MemberReferenceTree) tree); + if (tree instanceof MemberReferenceTree memberReferenceTree) { + return getSymbol(memberReferenceTree); } - if (tree instanceof JCAnnotatedType) { - return getSymbol(((JCAnnotatedType) tree).underlyingType); + if (tree instanceof JCAnnotatedType jcAnnotatedType) { + return getSymbol(jcAnnotatedType.underlyingType); } - if (tree instanceof ParameterizedTypeTree) { - return getSymbol(((ParameterizedTypeTree) tree).getType()); + if (tree instanceof ParameterizedTypeTree parameterizedTypeTree) { + return getSymbol(parameterizedTypeTree.getType()); } - if (tree instanceof ClassTree) { - return getSymbol((ClassTree) tree); + if (tree instanceof ClassTree classTree) { + return getSymbol(classTree); } return getDeclaredSymbol(tree); @@ -494,8 +494,8 @@ public static Stream enclosingElements(Symbol sym) { ExpressionTree expr = methodInvocationTree; while (expr instanceof JCMethodInvocation) { expr = ((JCMethodInvocation) expr).getMethodSelect(); - if (expr instanceof JCFieldAccess) { - expr = ((JCFieldAccess) expr).getExpression(); + if (expr instanceof JCFieldAccess jCFieldAccess) { + expr = jCFieldAccess.getExpression(); } } @@ -517,10 +517,10 @@ public static Type getReturnType(ExpressionTree expressionTree) { return methodCall.type.getReturnType(); } else if (expressionTree instanceof JCIdent methodCall) { return methodCall.type.getReturnType(); - } else if (expressionTree instanceof JCMethodInvocation) { - return getReturnType(((JCMethodInvocation) expressionTree).getMethodSelect()); - } else if (expressionTree instanceof JCMemberReference) { - return ((JCMemberReference) expressionTree).sym.type.getReturnType(); + } else if (expressionTree instanceof JCMethodInvocation jCMethodInvocation) { + return getReturnType(jCMethodInvocation.getMethodSelect()); + } else if (expressionTree instanceof JCMemberReference jCMemberReference) { + return jCMemberReference.sym.type.getReturnType(); } throw new IllegalArgumentException("Expected a JCFieldAccess or JCIdent"); } @@ -561,10 +561,10 @@ public static Type getReceiverType(ExpressionTree expressionTree) { return methodSelectFieldAccess.selected.type; } else if (expressionTree instanceof JCIdent methodCall) { return methodCall.sym.owner.type; - } else if (expressionTree instanceof JCMethodInvocation) { - return getReceiverType(((JCMethodInvocation) expressionTree).getMethodSelect()); - } else if (expressionTree instanceof JCMemberReference) { - return ((JCMemberReference) expressionTree).getQualifierExpression().type; + } else if (expressionTree instanceof JCMethodInvocation jCMethodInvocation) { + return getReceiverType(jCMethodInvocation.getMethodSelect()); + } else if (expressionTree instanceof JCMemberReference jCMemberReference) { + return jCMemberReference.getQualifierExpression().type; } throw new IllegalArgumentException( "Expected a JCFieldAccess or JCIdent from expression " + expressionTree); @@ -589,16 +589,16 @@ public static Type getReceiverType(ExpressionTree expressionTree) { * } */ public static @Nullable ExpressionTree getReceiver(ExpressionTree expressionTree) { - if (expressionTree instanceof MethodInvocationTree) { - ExpressionTree methodSelect = ((MethodInvocationTree) expressionTree).getMethodSelect(); + if (expressionTree instanceof MethodInvocationTree methodInvocationTree) { + ExpressionTree methodSelect = methodInvocationTree.getMethodSelect(); if (methodSelect instanceof IdentifierTree) { return null; } return getReceiver(methodSelect); - } else if (expressionTree instanceof MemberSelectTree) { - return ((MemberSelectTree) expressionTree).getExpression(); - } else if (expressionTree instanceof MemberReferenceTree) { - return ((MemberReferenceTree) expressionTree).getQualifierExpression(); + } else if (expressionTree instanceof MemberSelectTree memberSelectTree) { + return memberSelectTree.getExpression(); + } else if (expressionTree instanceof MemberReferenceTree memberReferenceTree) { + return memberReferenceTree.getQualifierExpression(); } else { throw new IllegalStateException( String.format( @@ -993,11 +993,11 @@ private static Set directAnnotationsAmong( * annotation inheritance (see JLS 9.6.4.3). */ public static boolean hasDirectAnnotationWithSimpleName(Symbol sym, String simpleName) { - if (sym instanceof MethodSymbol) { - return hasDirectAnnotationWithSimpleName((MethodSymbol) sym, simpleName); + if (sym instanceof MethodSymbol methodSymbol) { + return hasDirectAnnotationWithSimpleName(methodSymbol, simpleName); } - if (sym instanceof VarSymbol) { - return hasDirectAnnotationWithSimpleName((VarSymbol) sym, simpleName); + if (sym instanceof VarSymbol varSymbol) { + return hasDirectAnnotationWithSimpleName(varSymbol, simpleName); } return hasDirectAnnotationWithSimpleName(sym.getAnnotationMirrors().stream(), simpleName); } @@ -1269,15 +1269,15 @@ public static Nullness getNullnessValue( tree = stripParentheses(tree); Type type = ASTHelpers.getType(tree); Object value; - if (tree instanceof JCLiteral) { - value = ((JCLiteral) tree).value; + if (tree instanceof JCLiteral jCLiteral) { + value = jCLiteral.value; } else if (type != null) { value = type.constValue(); } else { return null; } - if (type.hasTag(TypeTag.BOOLEAN) && value instanceof Integer) { - return ((Integer) value) == 1; + if (type.hasTag(TypeTag.BOOLEAN) && value instanceof Integer integer) { + return integer == 1; } if (type.hasTag(TypeTag.CHAR) && value instanceof Integer) { return (char) (int) value; @@ -1349,40 +1349,40 @@ public static boolean isSameType(Type s, Type t, VisitorState state) { /** Returns the modifiers tree of the given class, method, or variable declaration. */ public static @Nullable ModifiersTree getModifiers(Tree tree) { - if (tree instanceof ClassTree) { - return ((ClassTree) tree).getModifiers(); + if (tree instanceof ClassTree classTree) { + return classTree.getModifiers(); } - if (tree instanceof MethodTree) { - return ((MethodTree) tree).getModifiers(); + if (tree instanceof MethodTree methodTree) { + return methodTree.getModifiers(); } - if (tree instanceof VariableTree) { - return ((VariableTree) tree).getModifiers(); + if (tree instanceof VariableTree variableTree) { + return variableTree.getModifiers(); } - if (tree instanceof ModifiersTree) { - return (ModifiersTree) tree; + if (tree instanceof ModifiersTree modifiersTree) { + return modifiersTree; } return null; } /** Returns the annotations of the given tree, or an empty list. */ public static List getAnnotations(Tree tree) { - if (tree instanceof TypeParameterTree) { - return ((TypeParameterTree) tree).getAnnotations(); + if (tree instanceof TypeParameterTree typeParameterTree) { + return typeParameterTree.getAnnotations(); } - if (tree instanceof ModuleTree) { - return ((ModuleTree) tree).getAnnotations(); + if (tree instanceof ModuleTree moduleTree) { + return moduleTree.getAnnotations(); } - if (tree instanceof PackageTree) { - return ((PackageTree) tree).getAnnotations(); + if (tree instanceof PackageTree packageTree) { + return packageTree.getAnnotations(); } - if (tree instanceof NewArrayTree) { - return ((NewArrayTree) tree).getAnnotations(); + if (tree instanceof NewArrayTree newArrayTree) { + return newArrayTree.getAnnotations(); } - if (tree instanceof AnnotatedTypeTree) { - return ((AnnotatedTypeTree) tree).getAnnotations(); + if (tree instanceof AnnotatedTypeTree annotatedTypeTree) { + return annotatedTypeTree.getAnnotations(); } - if (tree instanceof ModifiersTree) { - return ((ModifiersTree) tree).getAnnotations(); + if (tree instanceof ModifiersTree modifiersTree) { + return modifiersTree.getAnnotations(); } ModifiersTree modifiersTree = getModifiers(tree); return modifiersTree == null ? ImmutableList.of() : modifiersTree.getAnnotations(); @@ -1475,10 +1475,10 @@ public static List getAnnotationsWithSimpleName( private static boolean hasSimpleName(AnnotationTree annotation, String name) { Tree annotationType = annotation.getAnnotationType(); javax.lang.model.element.Name simpleName; - if (annotationType instanceof IdentifierTree) { - simpleName = ((IdentifierTree) annotationType).getName(); - } else if (annotationType instanceof MemberSelectTree) { - simpleName = ((MemberSelectTree) annotationType).getIdentifier(); + if (annotationType instanceof IdentifierTree identifierTree) { + simpleName = identifierTree.getName(); + } else if (annotationType instanceof MemberSelectTree memberSelectTree) { + simpleName = memberSelectTree.getIdentifier(); } else { return false; } @@ -1892,8 +1892,8 @@ public Type visitAnnotation(AnnotationTree tree, Void unused) { return null; } - if (tree instanceof SwitchTree) { - return ((SwitchTree) tree).getExpression(); + if (tree instanceof SwitchTree switchTree) { + return switchTree.getExpression(); } // Reflection is required for JDK < 12 try { @@ -2351,8 +2351,8 @@ public void scanResources(TryTree tree) { for (Tree resource : tree.getResources()) { Symbol symbol = getType(resource).tsym; - if (symbol instanceof ClassSymbol) { - getCloseMethod((ClassSymbol) symbol, state) + if (symbol instanceof ClassSymbol classSymbol) { + getCloseMethod(classSymbol, state) .ifPresent(methodSymbol -> getThrownTypes().addAll(methodSymbol.getThrownTypes())); } } diff --git a/check_api/src/main/java/com/google/errorprone/util/Comments.java b/check_api/src/main/java/com/google/errorprone/util/Comments.java index d06f1a017e0..593ba24106f 100644 --- a/check_api/src/main/java/com/google/errorprone/util/Comments.java +++ b/check_api/src/main/java/com/google/errorprone/util/Comments.java @@ -302,10 +302,10 @@ private static Tree getNextNodeOrParent(Tree current, VisitorState state) { Tree parent = enclosingPath.getLeaf(); - if (parent instanceof BlockTree) { - return after(predecessorNode, ((BlockTree) parent).getStatements(), parent); - } else if (parent instanceof ClassTree) { - return after(predecessorNode, ((ClassTree) parent).getMembers(), parent); + if (parent instanceof BlockTree blockTree) { + return after(predecessorNode, blockTree.getStatements(), parent); + } else if (parent instanceof ClassTree classTree) { + return after(predecessorNode, classTree.getMembers(), parent); } return parent; } diff --git a/check_api/src/main/java/com/google/errorprone/util/FindIdentifiers.java b/check_api/src/main/java/com/google/errorprone/util/FindIdentifiers.java index dc00e7c1fac..1bb8bd78819 100644 --- a/check_api/src/main/java/com/google/errorprone/util/FindIdentifiers.java +++ b/check_api/src/main/java/com/google/errorprone/util/FindIdentifiers.java @@ -137,9 +137,9 @@ private static Symbol findIdent( return null; } Tree leaf = parent.getLeaf(); - if (leaf instanceof ClassTree + if (leaf instanceof ClassTree classTree && ((ClassTree) leaf).getMembers().contains(treePath.getLeaf())) { - return (ClassTree) leaf; + return classTree; } treePath = parent; } diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/AbstractReturnValueIgnored.java b/core/src/main/java/com/google/errorprone/bugpatterns/AbstractReturnValueIgnored.java index 256bfa1d025..3aa3db1c59c 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/AbstractReturnValueIgnored.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/AbstractReturnValueIgnored.java @@ -462,8 +462,8 @@ private Description checkLostType(MethodInvocationTree tree, VisitorState state) } } for (Type toAdd : currentTypeParam.getBounds()) { - if (toAdd.tsym instanceof TypeVariableSymbol) { - queue.add((TypeVariableSymbol) toAdd.tsym); + if (toAdd.tsym instanceof TypeVariableSymbol typeVariableSymbol) { + queue.add(typeVariableSymbol); } } } @@ -593,8 +593,7 @@ public Description matchReturn(ReturnTree tree, VisitorState state) { if (isSubtype(resultType, lostType, state)) { // Traverse enclosing nodes of this return tree until either a lambda or a Method is reached. for (Tree enclosing : state.getPath()) { - if (enclosing instanceof MethodTree) { - MethodTree methodTree = (MethodTree) enclosing; + if (enclosing instanceof MethodTree methodTree) { MethodSymbol symbol = getSymbol(methodTree); if (isSubtype(objectType, symbol.getReturnType(), state) && !isExemptedInterfaceMethod(symbol, state)) { @@ -606,8 +605,7 @@ public Description matchReturn(ReturnTree tree, VisitorState state) { break; } } - if (enclosing instanceof LambdaExpressionTree) { - LambdaExpressionTree lambdaTree = (LambdaExpressionTree) enclosing; + if (enclosing instanceof LambdaExpressionTree lambdaTree) { if (isObjectReturningLambdaExpression(lambdaTree, state)) { return buildDescription(tree) .setMessage(lostTypeMessage(resultType.toString(), "Object")) diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/AssertThrowsMultipleStatements.java b/core/src/main/java/com/google/errorprone/bugpatterns/AssertThrowsMultipleStatements.java index a3a4ea27d47..682c52223a2 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/AssertThrowsMultipleStatements.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/AssertThrowsMultipleStatements.java @@ -69,8 +69,8 @@ public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState int endPosition = state.getEndPosition(statements.get(statements.size() - 2)); SuggestedFix.Builder fix = SuggestedFix.builder(); // if the last statement is an expression, convert from a block to expression lambda - if (last instanceof ExpressionStatementTree) { - fix.replace(body, state.getSourceForNode(((ExpressionStatementTree) last).getExpression())); + if (last instanceof ExpressionStatementTree expressionStatementTree) { + fix.replace(body, state.getSourceForNode(expressionStatementTree.getExpression())); } else { fix.replace(startPosition, endPosition, ""); } diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/AvoidObjectArrays.java b/core/src/main/java/com/google/errorprone/bugpatterns/AvoidObjectArrays.java index f3309bdb44d..17a2745729e 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/AvoidObjectArrays.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/AvoidObjectArrays.java @@ -96,8 +96,8 @@ private Description createDescription( String message = String.format("Avoid %s a %s", verb, prettyType(type, state)); - if (type instanceof ArrayType) { - type = ((ArrayType) type).getComponentType(); + if (type instanceof ArrayType arrayType) { + type = arrayType.getComponentType(); boolean isMultiDimensional = (type instanceof ArrayType); if (!isMultiDimensional) { message += String.format("; consider an %s<%s> instead", newType, prettyType(type, state)); diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/BadShiftAmount.java b/core/src/main/java/com/google/errorprone/bugpatterns/BadShiftAmount.java index 3e8f7213e7a..2867776f3c1 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/BadShiftAmount.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/BadShiftAmount.java @@ -66,10 +66,10 @@ public boolean matches(BinaryTree tree, VisitorState state) { } ExpressionTree rightOperand = tree.getRightOperand(); - if (rightOperand instanceof LiteralTree) { - Object rightValue = ((LiteralTree) rightOperand).getValue(); - if (rightValue instanceof Number) { - int intValue = ((Number) rightValue).intValue(); + if (rightOperand instanceof LiteralTree literalTree) { + Object rightValue = literalTree.getValue(); + if (rightValue instanceof Number number) { + int intValue = number.intValue(); return intValue < 0 || intValue > 31; } } diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/BooleanParameter.java b/core/src/main/java/com/google/errorprone/bugpatterns/BooleanParameter.java index b55eacd8b5c..0e7937d1300 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/BooleanParameter.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/BooleanParameter.java @@ -145,8 +145,8 @@ private static boolean isBooleanLiteral(ExpressionTree tree) { private static boolean areSingleArgumentsSelfDocumenting(Tree tree) { // Consider single-argument booleans for classes whose names contain "Boolean" to be self- // documenting. This is aimed at classes like AtomicBoolean which simply wrap a value. - if (tree instanceof NewClassTree) { - Symbol symbol = ASTHelpers.getSymbol(((NewClassTree) tree).getIdentifier()); + if (tree instanceof NewClassTree newClassTree) { + Symbol symbol = ASTHelpers.getSymbol(newClassTree.getIdentifier()); return symbol != null && Ascii.toLowerCase(symbol.getSimpleName()).contains("boolean"); } return true; diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/BoxedPrimitiveConstructor.java b/core/src/main/java/com/google/errorprone/bugpatterns/BoxedPrimitiveConstructor.java index 00a09b44ce1..119f59232e9 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/BoxedPrimitiveConstructor.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/BoxedPrimitiveConstructor.java @@ -96,9 +96,8 @@ private static Fix buildFix(NewClassTree tree, VisitorState state) { Object value = literalValue(tree.getArguments().iterator().next()); if (value instanceof Boolean) { return SuggestedFix.replace(tree, literalFix((boolean) value, autoboxFix)); - } else if (value instanceof String) { - return SuggestedFix.replace( - tree, literalFix(Boolean.parseBoolean((String) value), autoboxFix)); + } else if (value instanceof String string) { + return SuggestedFix.replace(tree, literalFix(Boolean.parseBoolean(string), autoboxFix)); } } diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/ByteBufferBackingArray.java b/core/src/main/java/com/google/errorprone/bugpatterns/ByteBufferBackingArray.java index 1d07ab9ce33..c2df097a585 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/ByteBufferBackingArray.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/ByteBufferBackingArray.java @@ -86,8 +86,8 @@ public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState } // Checks for validating use on method scope. - if (bufferSymbol.owner instanceof MethodSymbol) { - MethodTree enclosingMethod = ASTHelpers.findMethod((MethodSymbol) bufferSymbol.owner, state); + if (bufferSymbol.owner instanceof MethodSymbol methodSymbol) { + MethodTree enclosingMethod = ASTHelpers.findMethod(methodSymbol, state); if (enclosingMethod == null || ValidByteBufferArrayScanner.scan(enclosingMethod, state, bufferSymbol)) { return Description.NO_MATCH; @@ -95,8 +95,8 @@ public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState } // Checks for validating use on fields. - if (bufferSymbol.owner instanceof ClassSymbol) { - ClassTree enclosingClass = ASTHelpers.findClass((ClassSymbol) bufferSymbol.owner, state); + if (bufferSymbol.owner instanceof ClassSymbol classSymbol) { + ClassTree enclosingClass = ASTHelpers.findClass(classSymbol, state); if (enclosingClass == null) { return Description.NO_MATCH; } diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/CanBeStaticAnalyzer.java b/core/src/main/java/com/google/errorprone/bugpatterns/CanBeStaticAnalyzer.java index 7d5587e77ad..be4e4f5c1f7 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/CanBeStaticAnalyzer.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/CanBeStaticAnalyzer.java @@ -106,8 +106,8 @@ private static boolean isOwnedBy(Symbol sym, Symbol owner, Types types) { if (sym.owner == owner) { return true; } - if (owner instanceof TypeSymbol) { - return sym.isMemberOf((TypeSymbol) owner, types); + if (owner instanceof TypeSymbol typeSymbol) { + return sym.isMemberOf(typeSymbol, types); } return false; } diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/CheckNotNullMultipleTimes.java b/core/src/main/java/com/google/errorprone/bugpatterns/CheckNotNullMultipleTimes.java index ea4eff7984c..16fbbe5b29d 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/CheckNotNullMultipleTimes.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/CheckNotNullMultipleTimes.java @@ -72,9 +72,9 @@ public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) { && getCurrentPath().getParentPath().getLeaf() instanceof StatementTree && CHECK_NOT_NULL.matches(tree, state)) { Symbol symbol = getSymbol(arguments.get(0)); - if (symbol instanceof VarSymbol && isConsideredFinal(symbol)) { - variables.add((VarSymbol) symbol); - lastCheck.put((VarSymbol) symbol, tree); + if (symbol instanceof VarSymbol varSymbol && isConsideredFinal(symbol)) { + variables.add(varSymbol); + lastCheck.put(varSymbol, tree); } } return super.visitMethodInvocation(tree, null); diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/CheckReturnValue.java b/core/src/main/java/com/google/errorprone/bugpatterns/CheckReturnValue.java index c8f88225265..f7026898f81 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/CheckReturnValue.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/CheckReturnValue.java @@ -202,8 +202,8 @@ private static Optional methodToInspect(ExpressionTree tree) { // corresponding constructor of the supertype (e.g.: if I extend a class with a @CIRV // constructor that I delegate to, then my anonymous class's constructor should *also* be // considered @CIRV). - if (tree instanceof NewClassTree) { - ClassTree anonymousClazz = ((NewClassTree) tree).getClassBody(); + if (tree instanceof NewClassTree newClassTree) { + ClassTree anonymousClazz = newClassTree.getClassBody(); if (anonymousClazz != null) { // There should be a single defined constructor in the anonymous class body var constructor = diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/ComparisonContractViolated.java b/core/src/main/java/com/google/errorprone/bugpatterns/ComparisonContractViolated.java index 521d0d7be0d..67738128da5 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/ComparisonContractViolated.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/ComparisonContractViolated.java @@ -100,10 +100,10 @@ private ComparisonResult forInt(int x) { @Override public ComparisonResult visitMemberSelect(MemberSelectTree node, VisitorState state) { Symbol sym = ASTHelpers.getSymbol(node); - if (sym instanceof VarSymbol) { - Object value = ((VarSymbol) sym).getConstantValue(); - if (value instanceof Integer) { - return forInt((Integer) value); + if (sym instanceof VarSymbol varSymbol) { + Object value = varSymbol.getConstantValue(); + if (value instanceof Integer integer) { + return forInt(integer); } } return super.visitMemberSelect(node, state); @@ -112,10 +112,10 @@ public ComparisonResult visitMemberSelect(MemberSelectTree node, VisitorState st @Override public ComparisonResult visitIdentifier(IdentifierTree node, VisitorState state) { Symbol sym = ASTHelpers.getSymbol(node); - if (sym instanceof VarSymbol) { - Object value = ((VarSymbol) sym).getConstantValue(); - if (value instanceof Integer) { - return forInt((Integer) value); + if (sym instanceof VarSymbol varSymbol) { + Object value = varSymbol.getConstantValue(); + if (value instanceof Integer integer) { + return forInt(integer); } } return super.visitIdentifier(node, state); diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/ConstantOverflow.java b/core/src/main/java/com/google/errorprone/bugpatterns/ConstantOverflow.java index 0f147ea8ba7..205c4711903 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/ConstantOverflow.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/ConstantOverflow.java @@ -95,8 +95,9 @@ public Description matchBinary(BinaryTree tree, VisitorState state) { } SuggestedFix.Builder fix = SuggestedFix.builder().postfixWith(expr, "L"); Tree parent = state.getPath().getParentPath().getLeaf(); - if (parent instanceof VariableTree && isSameType(getType(parent), intType, state)) { - Tree type = ((VariableTree) parent).getType(); + if (parent instanceof VariableTree variableTree + && isSameType(getType(parent), intType, state)) { + Tree type = variableTree.getType(); if (hasExplicitSource(type, state)) { fix.replace(type, "long"); } diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/ConstantPatternCompile.java b/core/src/main/java/com/google/errorprone/bugpatterns/ConstantPatternCompile.java index c52700a5147..871564c4f9b 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/ConstantPatternCompile.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/ConstantPatternCompile.java @@ -125,8 +125,8 @@ private Optional tryFix( return Optional.empty(); } Tree parent = state.getPath().getParentPath().getLeaf(); - if (parent instanceof VariableTree) { - return handleVariable((VariableTree) parent, state); + if (parent instanceof VariableTree variableTree) { + return handleVariable(variableTree, state); } return Optional.of(handleInlineExpression(tree, state, nameUniquifier)); @@ -361,12 +361,11 @@ public Void visitIdentifier(IdentifierTree tree, Void unused) { return null; } ExpressionTree matchTree = ((MethodInvocationTree) grandParent).getArguments().get(0); - if (matchTree instanceof IdentifierTree) { - return convertToConstantName(((IdentifierTree) matchTree).getName().toString()); + if (matchTree instanceof IdentifierTree identifierTree) { + return convertToConstantName(identifierTree.getName().toString()); } - if (matchTree instanceof MethodInvocationTree) { - return convertToConstantName( - getSymbol((MethodInvocationTree) matchTree).getSimpleName().toString()); + if (matchTree instanceof MethodInvocationTree methodInvocationTree) { + return convertToConstantName(getSymbol(methodInvocationTree).getSimpleName().toString()); } return null; } diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/DeadException.java b/core/src/main/java/com/google/errorprone/bugpatterns/DeadException.java index 0243ea5595c..d9ad7c3aea5 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/DeadException.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/DeadException.java @@ -103,10 +103,10 @@ protected Iterable getChildNodes(T tree, VisitorState s if (enclosing == null) { return ImmutableList.of(); } - if (enclosing instanceof BlockTree) { - return ((BlockTree) enclosing).getStatements(); - } else if (enclosing instanceof CaseTree) { - return ((CaseTree) enclosing).getStatements(); + if (enclosing instanceof BlockTree blockTree) { + return blockTree.getStatements(); + } else if (enclosing instanceof CaseTree caseTree) { + return caseTree.getStatements(); } else { // findEnclosing given two types must return something of one of those types throw new IllegalStateException("enclosing tree not a BlockTree or CaseTree"); diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/DefaultCharset.java b/core/src/main/java/com/google/errorprone/bugpatterns/DefaultCharset.java index 452d18e49f3..06e08dbf294 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/DefaultCharset.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/DefaultCharset.java @@ -214,9 +214,9 @@ public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState } if (STRING_GET_BYTES.matches(tree, state)) { Tree parent = state.getPath().getParentPath().getLeaf(); - if (parent instanceof ExpressionTree + if (parent instanceof ExpressionTree expressionTree && BYTESTRING_COPY_FROM.matches((ExpressionTree) parent, state)) { - return byteStringFixes(tree, (ExpressionTree) parent, state); + return byteStringFixes(tree, expressionTree, state); } else { return appendCharsets(tree, tree.getMethodSelect(), tree.getArguments(), state); } diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/DirectInvocationOnMock.java b/core/src/main/java/com/google/errorprone/bugpatterns/DirectInvocationOnMock.java index f5935f99766..12f03de61d2 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/DirectInvocationOnMock.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/DirectInvocationOnMock.java @@ -75,17 +75,16 @@ public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) { var receiver = getReceiver(tree); if (receiver != null && WHEN.matches(receiver, state)) { ExpressionTree firstArgument = ((MethodInvocationTree) receiver).getArguments().get(0); - var firstArgumentSymbol = getSymbol(firstArgument); - if (firstArgumentSymbol instanceof MethodSymbol) { - methodsCallingRealImplementations.add((MethodSymbol) firstArgumentSymbol); + if (getSymbol(firstArgument) instanceof MethodSymbol methodSymbol) { + methodsCallingRealImplementations.add(methodSymbol); } } return super.visitMethodInvocation(tree, null); } if (DO_CALL_REAL_METHOD.matches(tree, state)) { - var methodSymbol = getSymbol(getCurrentPath().getParentPath().getParentPath().getLeaf()); - if (methodSymbol instanceof MethodSymbol) { - methodsCallingRealImplementations.add((MethodSymbol) methodSymbol); + if (getSymbol(getCurrentPath().getParentPath().getParentPath().getLeaf()) + instanceof MethodSymbol methodSymbol) { + methodsCallingRealImplementations.add(methodSymbol); } return super.visitMethodInvocation(tree, null); } @@ -160,8 +159,8 @@ public Void visitVariable(VariableTree tree, Void unused) { public Void visitAssignment(AssignmentTree tree, Void unused) { if (MOCK.matches(tree.getExpression(), state)) { var symbol = getSymbol(tree.getVariable()); - if (symbol instanceof VarSymbol) { - mocks.add((VarSymbol) symbol); + if (symbol instanceof VarSymbol varSymbol) { + mocks.add(varSymbol); } } return super.visitAssignment(tree, null); diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/DoNotCallChecker.java b/core/src/main/java/com/google/errorprone/bugpatterns/DoNotCallChecker.java index b3512da95e5..b749e93da68 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/DoNotCallChecker.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/DoNotCallChecker.java @@ -404,10 +404,10 @@ public Void visitVariable(VariableTree node, Void unused) { @Override public Void visitAssignment(AssignmentTree node, Void unused) { Symbol assignee = getSymbol(node.getVariable()); - if (assignee instanceof VarSymbol && isConsideredFinal(assignee)) { + if (assignee instanceof VarSymbol varSymbol && isConsideredFinal(assignee)) { Type type = getType(node.getExpression()); if (type != null) { - assignedTypes.put((VarSymbol) assignee, type); + assignedTypes.put(varSymbol, type); } } return super.visitAssignment(node, null); diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/DoubleBraceInitialization.java b/core/src/main/java/com/google/errorprone/bugpatterns/DoubleBraceInitialization.java index e8546616b60..970c4427b9f 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/DoubleBraceInitialization.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/DoubleBraceInitialization.java @@ -154,8 +154,8 @@ Optional maybeFix(NewClassTree tree, VisitorState state, BlockTree block) { && symbol.getModifiers().contains(Modifier.FINAL) && symbol.getKind() == ElementKind.FIELD; } - if (enclosing instanceof ReturnTree) { - toReplace = ((ReturnTree) enclosing).getExpression(); + if (enclosing instanceof ReturnTree returnTree) { + toReplace = returnTree.getExpression(); MethodTree enclosingMethod = ASTHelpers.findEnclosingNode(path, MethodTree.class); typeTree = enclosingMethod == null ? null : enclosingMethod.getReturnType(); } @@ -187,8 +187,8 @@ Optional maybeFix(NewClassTree tree, VisitorState state, BlockTree block) { if (unmodifiable != null || constant) { // there's an enclosing unmodifiable* call, or we're in the initializer of a constant, // so rewrite the variable's type to be immutable and drop the unmodifiable* method - if (typeTree instanceof ParameterizedTypeTree) { - typeTree = ((ParameterizedTypeTree) typeTree).getType(); + if (typeTree instanceof ParameterizedTypeTree parameterizedTypeTree) { + typeTree = parameterizedTypeTree.getType(); } if (typeTree != null) { fix.replace(typeTree, immutableType); diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/DuplicateBranches.java b/core/src/main/java/com/google/errorprone/bugpatterns/DuplicateBranches.java index 7e2f5d393fe..25ba7453fc7 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/DuplicateBranches.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/DuplicateBranches.java @@ -73,9 +73,9 @@ private Description match(Tree tree, Tree thenTree, Tree elseTree, VisitorState int start = getStartPosition(elseTree); int end = state.getEndPosition(elseTree); boolean needsBraces = false; - if (elseTree instanceof BlockTree) { + if (elseTree instanceof BlockTree blockTree) { needsBraces = !state.getPath().getParentPath().getLeaf().getKind().equals(Kind.BLOCK); - var statements = ((BlockTree) elseTree).getStatements(); + var statements = blockTree.getStatements(); if (statements.isEmpty()) { start = end; } else { diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/EqualsGetClass.java b/core/src/main/java/com/google/errorprone/bugpatterns/EqualsGetClass.java index 6619a76b8d0..09c8e9f7882 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/EqualsGetClass.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/EqualsGetClass.java @@ -123,10 +123,10 @@ private static boolean matchesThis(ExpressionTree tree) { return true; } while (!(receiver instanceof IdentifierTree)) { - if (receiver instanceof ParenthesizedTree) { - receiver = ((ParenthesizedTree) receiver).getExpression(); - } else if (receiver instanceof TypeCastTree) { - receiver = ((TypeCastTree) receiver).getExpression(); + if (receiver instanceof ParenthesizedTree parenthesizedTree) { + receiver = parenthesizedTree.getExpression(); + } else if (receiver instanceof TypeCastTree typeCastTree) { + receiver = typeCastTree.getExpression(); } else { return false; } diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/EqualsReference.java b/core/src/main/java/com/google/errorprone/bugpatterns/EqualsReference.java index 97157c54699..dc6b6d4e9b7 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/EqualsReference.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/EqualsReference.java @@ -76,8 +76,8 @@ public Void visitMethodInvocation( methodInvocationTree.getArguments().size() == 1 && Objects.equals( ASTHelpers.getSymbol(methodInvocationTree.getArguments().get(0)), varSymbol); - if (methodSelectTree instanceof MemberSelectTree) { - memberSelectTree = (MemberSelectTree) methodSelectTree; + if (methodSelectTree instanceof MemberSelectTree m) { + memberSelectTree = m; ExpressionTree e = memberSelectTree.getExpression(); // this.equals(o) // not using o.equals(this) because all instances of this were false positives diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/FloatingPointAssertionWithinEpsilon.java b/core/src/main/java/com/google/errorprone/bugpatterns/FloatingPointAssertionWithinEpsilon.java index a06205db766..6c71f8da607 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/FloatingPointAssertionWithinEpsilon.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/FloatingPointAssertionWithinEpsilon.java @@ -249,8 +249,8 @@ private String castArgumentIfNecessary(ExpressionTree tree, VisitorState state) if (state.getTypes().unboxedTypeOrType(type).getTag() == typeTag) { return source; } - if (tree instanceof LiteralTree) { - Optional suffixed = suffixLiteralIfPossible((LiteralTree) tree, state); + if (tree instanceof LiteralTree literalTree) { + Optional suffixed = suffixLiteralIfPossible(literalTree, state); if (suffixed.isPresent()) { return suffixed.get(); } diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/ForEachIterable.java b/core/src/main/java/com/google/errorprone/bugpatterns/ForEachIterable.java index 55a9b8e6236..435c2b7f8c4 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/ForEachIterable.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/ForEachIterable.java @@ -71,11 +71,11 @@ public Description matchVariable(VariableTree tree, VisitorState state) { return NO_MATCH; } Tree parent = state.getPath().getParentPath().getLeaf(); - if (parent instanceof BlockTree) { - return matchWhile(tree, (BlockTree) parent, state); + if (parent instanceof BlockTree blockTree) { + return matchWhile(tree, blockTree, state); } - if (parent instanceof ForLoopTree) { - return matchFor(tree, (ForLoopTree) parent, state); + if (parent instanceof ForLoopTree forLoopTree) { + return matchFor(tree, forLoopTree, state); } return NO_MATCH; } diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/ForOverrideChecker.java b/core/src/main/java/com/google/errorprone/bugpatterns/ForOverrideChecker.java index f20ae10e09f..4a937ab01c3 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/ForOverrideChecker.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/ForOverrideChecker.java @@ -152,8 +152,8 @@ public Description matchMethod(MethodTree tree, VisitorState state) { path = path.getParentPath(); if (path != null) { Tree leaf = path.getLeaf(); - if (leaf instanceof MethodTree) { - return (MethodTree) leaf; + if (leaf instanceof MethodTree methodTree) { + return methodTree; } // if we find a ClassTree before a MethodTree, we must be an initializer if (leaf instanceof ClassTree) { diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/IdentifierName.java b/core/src/main/java/com/google/errorprone/bugpatterns/IdentifierName.java index 9cd1344d113..c841c3c11ea 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/IdentifierName.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/IdentifierName.java @@ -191,10 +191,9 @@ private static boolean hasTestAnnotation(MethodSymbol symbol) { public Description matchVariable(VariableTree tree, VisitorState state) { VarSymbol symbol = getSymbol(tree); String name = tree.getName().toString(); - if (symbol.owner instanceof MethodSymbol + if (symbol.owner instanceof MethodSymbol methodSymbol && symbol.getKind() == ElementKind.PARAMETER && state.getPath().getParentPath().getLeaf().getKind() != Kind.LAMBDA_EXPRESSION) { - var methodSymbol = (MethodSymbol) symbol.owner; int index = methodSymbol.getParameters().indexOf(symbol); var maybeSuper = ASTHelpers.streamSuperMethods(methodSymbol, state.getTypes()).findFirst(); if (maybeSuper.isPresent()) { diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/IncrementInForLoopAndHeader.java b/core/src/main/java/com/google/errorprone/bugpatterns/IncrementInForLoopAndHeader.java index 7b389f87eae..caf19d9bfdf 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/IncrementInForLoopAndHeader.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/IncrementInForLoopAndHeader.java @@ -81,9 +81,9 @@ public Description matchForLoop(ForLoopTree forLoopTree, VisitorState visitorSta } private static Optional returnUnarySym(StatementTree s) { - if (s instanceof ExpressionStatementTree) { - if (((ExpressionStatementTree) s).getExpression() instanceof UnaryTree) { - UnaryTree unaryTree = (UnaryTree) ((ExpressionStatementTree) s).getExpression(); + if (s instanceof ExpressionStatementTree expressionStatementTree) { + if (expressionStatementTree.getExpression() instanceof UnaryTree) { + UnaryTree unaryTree = (UnaryTree) expressionStatementTree.getExpression(); return Optional.ofNullable(ASTHelpers.getSymbol(unaryTree.getExpression())); } } diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/LockNotBeforeTry.java b/core/src/main/java/com/google/errorprone/bugpatterns/LockNotBeforeTry.java index c7edb68e67b..8b46111414e 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/LockNotBeforeTry.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/LockNotBeforeTry.java @@ -117,9 +117,9 @@ private Description describe( // Scan through the enclosing statements for (StatementTree statement : Iterables.skip(block.getStatements(), index + 1)) { // ... for a try/finally which releases this lock. - if (statement instanceof TryTree && releases((TryTree) statement, lockee, state)) { + if (statement instanceof TryTree tryTree && releases((TryTree) statement, lockee, state)) { int start = getStartPosition(statement); - int end = getStartPosition(((TryTree) statement).getBlock().getStatements().get(0)); + int end = getStartPosition(tryTree.getBlock().getStatements().get(0)); SuggestedFix fix = SuggestedFix.builder() .replace(start, end, "") @@ -134,8 +134,8 @@ private Description describe( .build(); } // ... or an unlock at the same level. - if (statement instanceof ExpressionStatementTree) { - ExpressionTree expression = ((ExpressionStatementTree) statement).getExpression(); + if (statement instanceof ExpressionStatementTree expressionStatementTree) { + ExpressionTree expression = expressionStatementTree.getExpression(); if (acquires(expression, lockee, state)) { return buildDescription(lockInvocation) .setMessage( diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/LoopConditionChecker.java b/core/src/main/java/com/google/errorprone/bugpatterns/LoopConditionChecker.java index 3be72c92739..c99fb87cee1 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/LoopConditionChecker.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/LoopConditionChecker.java @@ -113,10 +113,10 @@ public LoopConditionVisitor(ImmutableSet.Builder conditionVars @Override public Boolean visitIdentifier(IdentifierTree tree, Void unused) { Symbol sym = ASTHelpers.getSymbol(tree); - if (sym instanceof Symbol.VarSymbol) { + if (sym instanceof Symbol.VarSymbol varSymbol) { switch (sym.getKind()) { case LOCAL_VARIABLE, PARAMETER -> { - conditionVars.add((Symbol.VarSymbol) sym); + conditionVars.add(varSymbol); return true; } default -> {} diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/MissingFail.java b/core/src/main/java/com/google/errorprone/bugpatterns/MissingFail.java index 45c927f3970..95bdf4c8f12 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/MissingFail.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/MissingFail.java @@ -480,10 +480,10 @@ public boolean matches(MethodInvocationTree methodInvocationTree, VisitorState s private static boolean matches(List expressionTrees) { Set foundValues = new HashSet<>(); for (Tree tree : expressionTrees) { - if (tree instanceof LiteralTree) { - Object value = ((LiteralTree) tree).getValue(); - if (value instanceof Integer) { - boolean duplicate = !foundValues.add((Integer) value); + if (tree instanceof LiteralTree literalTree) { + Object value = literalTree.getValue(); + if (value instanceof Integer integer) { + boolean duplicate = !foundValues.add(integer); if (!duplicate && foundValues.size() > 1) { return true; } diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/MixedMutabilityReturnType.java b/core/src/main/java/com/google/errorprone/bugpatterns/MixedMutabilityReturnType.java index fed19ec3fe4..2b3b4738bf1 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/MixedMutabilityReturnType.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/MixedMutabilityReturnType.java @@ -412,8 +412,8 @@ public Void visitIdentifier(IdentifierTree identifier, Void unused) { } if (parent instanceof MemberSelectTree) { Tree grandParent = getCurrentPath().getParentPath().getParentPath().getLeaf(); - if (grandParent instanceof MethodInvocationTree) { - if (!details.appendMethods().matches((MethodInvocationTree) grandParent, state)) { + if (grandParent instanceof MethodInvocationTree methodInvocationTree) { + if (!details.appendMethods().matches(methodInvocationTree, state)) { failed = true; return null; } diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/MockNotUsedInProduction.java b/core/src/main/java/com/google/errorprone/bugpatterns/MockNotUsedInProduction.java index 5ecbb63a445..8a929f29687 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/MockNotUsedInProduction.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/MockNotUsedInProduction.java @@ -107,8 +107,8 @@ public Void visitIdentifier(IdentifierTree identifier, Void unused) { private void handle(Tree tree) { var symbol = getSymbol(tree); - if (symbol instanceof VarSymbol) { - usedMocks.add((VarSymbol) symbol); + if (symbol instanceof VarSymbol varSymbol) { + usedMocks.add(varSymbol); } } }.scan(state.getPath(), null); diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/MockitoDoSetup.java b/core/src/main/java/com/google/errorprone/bugpatterns/MockitoDoSetup.java index b2a67cae0c7..351f600a112 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/MockitoDoSetup.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/MockitoDoSetup.java @@ -138,11 +138,11 @@ public Void visitVariable(VariableTree tree, Void unused) { public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) { if (DO_THROW.matches(tree, state)) { var whenCall = getCurrentPath().getParentPath().getParentPath().getLeaf(); - if ((whenCall instanceof MethodInvocationTree) - && INSTANCE_WHEN.matches((MethodInvocationTree) whenCall, state)) { - var whenTarget = getSymbol(((MethodInvocationTree) whenCall).getArguments().get(0)); - if (whenTarget instanceof VarSymbol) { - spiesOrThrows.add((VarSymbol) whenTarget); + if (whenCall instanceof MethodInvocationTree methodInvocationTree + && INSTANCE_WHEN.matches(methodInvocationTree, state)) { + var whenTarget = getSymbol(methodInvocationTree.getArguments().get(0)); + if (whenTarget instanceof VarSymbol varSymbol) { + spiesOrThrows.add(varSymbol); } } } @@ -151,8 +151,8 @@ public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) { if (STATIC_WHEN.matches(receiver, state)) { var mock = getReceiver(((MethodInvocationTree) receiver).getArguments().get(0)); var mockSymbol = getSymbol(mock); - if (mockSymbol instanceof VarSymbol) { - spiesOrThrows.add((VarSymbol) mockSymbol); + if (mockSymbol instanceof VarSymbol varSymbol) { + spiesOrThrows.add(varSymbol); } } } @@ -163,8 +163,8 @@ public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) { public Void visitAssignment(AssignmentTree tree, Void unused) { if (SPY.matches(tree.getExpression(), state)) { var symbol = getSymbol(tree.getVariable()); - if (symbol instanceof VarSymbol) { - spiesOrThrows.add((VarSymbol) symbol); + if (symbol instanceof VarSymbol varSymbol) { + spiesOrThrows.add(varSymbol); } } return super.visitAssignment(tree, null); diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/MultipleTopLevelClasses.java b/core/src/main/java/com/google/errorprone/bugpatterns/MultipleTopLevelClasses.java index b1ae03d75fb..0eaae206abc 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/MultipleTopLevelClasses.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/MultipleTopLevelClasses.java @@ -48,8 +48,7 @@ public final class MultipleTopLevelClasses extends BugChecker public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) { List names = new ArrayList<>(); for (Tree member : tree.getTypeDecls()) { - if (member instanceof ClassTree) { - ClassTree classMember = (ClassTree) member; + if (member instanceof ClassTree classMember) { switch (classMember.getKind()) { case CLASS, INTERFACE, ANNOTATION_TYPE, ENUM -> { if (isSuppressed(classMember, state)) { diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/NestedInstanceOfConditions.java b/core/src/main/java/com/google/errorprone/bugpatterns/NestedInstanceOfConditions.java index c31bf255a58..fba7fe1e584 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/NestedInstanceOfConditions.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/NestedInstanceOfConditions.java @@ -85,10 +85,10 @@ public AssignmentTreeMatcher(ExpressionTree e) { @Override public boolean matches(Tree tree, VisitorState visitorState) { - if (tree instanceof AssignmentTree) { + if (tree instanceof AssignmentTree assignmentTree) { return visitorState .getSourceForNode(variableExpressionTree) - .equals(visitorState.getSourceForNode(((AssignmentTree) tree).getVariable())); + .equals(visitorState.getSourceForNode(assignmentTree.getVariable())); } return false; @@ -111,8 +111,8 @@ public NestedInstanceOfMatcher(ExpressionTree e, Tree t) { @Override public boolean matches(Tree tree, VisitorState state) { - if (tree instanceof IfTree) { - ExpressionTree conditionTree = ASTHelpers.stripParentheses(((IfTree) tree).getCondition()); + if (tree instanceof IfTree ifTree) { + ExpressionTree conditionTree = ASTHelpers.stripParentheses(ifTree.getCondition()); if (conditionTree instanceof InstanceOfTree instanceOfTree) { diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/PreferredInterfaceType.java b/core/src/main/java/com/google/errorprone/bugpatterns/PreferredInterfaceType.java index 340331f8bf8..edc749c0d14 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/PreferredInterfaceType.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/PreferredInterfaceType.java @@ -280,8 +280,8 @@ private static String getMessage(Symbol symbol, Type newType, VisitorState state !isImmutable(targetType(symbol)) && isImmutable(newType) ? IMMUTABLE_MESSAGE : NON_IMMUTABLE_MESSAGE; - if (symbol instanceof MethodSymbol) { - if (!findSuperMethods((MethodSymbol) symbol, state.getTypes()).isEmpty()) { + if (symbol instanceof MethodSymbol methodSymbol) { + if (!findSuperMethods(methodSymbol, state.getTypes()).isEmpty()) { return "Method return" + messageBase + OVERRIDE_NOTE; } else { return "Method return" + messageBase; diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/SizeGreaterThanOrEqualsZero.java b/core/src/main/java/com/google/errorprone/bugpatterns/SizeGreaterThanOrEqualsZero.java index d65251e8aac..702cddede3b 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/SizeGreaterThanOrEqualsZero.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/SizeGreaterThanOrEqualsZero.java @@ -158,8 +158,8 @@ public Description matchBinary(BinaryTree tree, VisitorState state) { } else if (PROTO_REPEATED_FIELD_COUNT_METHOD.matches(callToSize, state)) { return provideReplacementForProtoMethodInvocation(tree, callToSize, state); } - } else if (operand instanceof MemberSelectTree) { - if (arrayLengthMatcher((MemberSelectTree) operand, state)) { + } else if (operand instanceof MemberSelectTree memberSelectTree) { + if (arrayLengthMatcher(memberSelectTree, state)) { return removeEqualsFromComparison(tree, state, expressionType); } } diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/StatementSwitchToExpressionSwitch.java b/core/src/main/java/com/google/errorprone/bugpatterns/StatementSwitchToExpressionSwitch.java index 3509f35a1c5..4bb86a577ac 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/StatementSwitchToExpressionSwitch.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/StatementSwitchToExpressionSwitch.java @@ -424,8 +424,8 @@ private static AssignmentSwitchAnalysisState analyzeCaseForAssignmentSwitch( caseAssignmentTargetOptional = Optional.of(compoundAssignmentTree.getVariable()); caseAssignmentKindOptional = Optional.of(compoundAssignmentTree.getKind()); caseAssignmentTreeOptional = Optional.of(expression); - } else if (expression instanceof AssignmentTree) { - caseAssignmentTargetOptional = Optional.of(((AssignmentTree) expression).getVariable()); + } else if (expression instanceof AssignmentTree assignmentTree) { + caseAssignmentTargetOptional = Optional.of(assignmentTree.getVariable()); caseAssignmentKindOptional = Optional.of(Tree.Kind.ASSIGNMENT); caseAssignmentTreeOptional = Optional.of(expression); } @@ -1212,10 +1212,10 @@ private static String transformAssignOrThrowBlock( int unused = extractLhsComments(caseTree, state, transformedBlockBuilder); ExpressionTree expression = ((ExpressionStatementTree) statements.get(0)).getExpression(); Optional rhs = Optional.empty(); - if (expression instanceof CompoundAssignmentTree) { - rhs = Optional.of(((CompoundAssignmentTree) expression).getExpression()); - } else if (expression instanceof AssignmentTree) { - rhs = Optional.of(((AssignmentTree) expression).getExpression()); + if (expression instanceof CompoundAssignmentTree compoundAssignmentTree) { + rhs = Optional.of(compoundAssignmentTree.getExpression()); + } else if (expression instanceof AssignmentTree assignmentTree) { + rhs = Optional.of(assignmentTree.getExpression()); } codeBlockStart = getStartPosition(rhs.get()); } else { diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/StreamResourceLeak.java b/core/src/main/java/com/google/errorprone/bugpatterns/StreamResourceLeak.java index 7cb05590cd3..7b332fbee0d 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/StreamResourceLeak.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/StreamResourceLeak.java @@ -99,7 +99,7 @@ private static SuggestedFix definiteFix(ExpressionTree tree, VisitorState state) fix.replace(tree, "stream"); fix.postfixWith(statement, "}"); return fix.build(); - } else if (parent instanceof VariableTree) { + } else if (parent instanceof VariableTree variableTree) { // If the stream is assigned to a variable, wrap the variable in a try-with-resources // that includes all statements in the same block that reference the variable. Tree grandParent = parentPath.getParentPath().getLeaf(); @@ -130,9 +130,7 @@ public Void visitIdentifier(IdentifierTree tree, Void unused) { } fix.prefixWith(parent, "try ("); fix.replace( - state.getEndPosition(((VariableTree) parent).getInitializer()), - state.getEndPosition(parent), - ") {"); + state.getEndPosition(variableTree.getInitializer()), state.getEndPosition(parent), ") {"); fix.postfixWith(statements.get(lastUse), "}"); return fix.build(); } else if (parent instanceof EnhancedForLoopTree) { diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/TestExceptionChecker.java b/core/src/main/java/com/google/errorprone/bugpatterns/TestExceptionChecker.java index 6f9eb72f103..4c97d0facfd 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/TestExceptionChecker.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/TestExceptionChecker.java @@ -98,8 +98,8 @@ private static SuggestedFix buildFix( prefix.append( String.format("assertThrows(%s, () -> ", state.getSourceForNode(expectedException))); StatementTree last = getLast(statements); - if (last instanceof ExpressionStatementTree) { - ExpressionTree expression = ((ExpressionStatementTree) last).getExpression(); + if (last instanceof ExpressionStatementTree expressionStatementTree) { + ExpressionTree expression = expressionStatementTree.getExpression(); fix.prefixWith(expression, prefix.toString()); fix.postfixWith(expression, ")"); } else { diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/TypeParameterUnusedInFormals.java b/core/src/main/java/com/google/errorprone/bugpatterns/TypeParameterUnusedInFormals.java index 6fc8414543c..d828a47cbf2 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/TypeParameterUnusedInFormals.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/TypeParameterUnusedInFormals.java @@ -95,9 +95,9 @@ static Set visit(Type type) { @Override public Void visitClassType(Type.ClassType type, Void unused) { - if (type instanceof Type.IntersectionClassType) { + if (type instanceof Type.IntersectionClassType intersectionClassType) { // TypeVisitor doesn't support intersection types natively - visitIntersectionClassType((Type.IntersectionClassType) type); + visitIntersectionClassType(intersectionClassType); } else { for (Type t : type.getTypeArguments()) { t.accept(this, null); diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryAsync.java b/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryAsync.java index e15c4a437a4..1dc32b24f62 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryAsync.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryAsync.java @@ -155,44 +155,34 @@ public Void visitIdentifier(IdentifierTree tree, Void unused) { if (isVariableDeclarationItself(parentTree)) { return super.visitIdentifier(tree, null); } - if (parentTree instanceof MemberSelectTree) { + if (parentTree instanceof MemberSelectTree memberSelectTree) { var grandparent = (MethodInvocationTree) getCurrentPath().getParentPath().getParentPath().getLeaf(); - if (((MemberSelectTree) parentTree).getIdentifier().contentEquals("set")) { + if (memberSelectTree.getIdentifier().contentEquals("set")) { fix.replace( grandparent, format( "%s = %s", state.getSourceForNode(tree), state.getSourceForNode(grandparent.getArguments().get(0)))); - } else if (((MemberSelectTree) parentTree).getIdentifier().contentEquals("get")) { + } else if (memberSelectTree.getIdentifier().contentEquals("get")) { fix.replace(grandparent, state.getSourceForNode(tree)); - } else if (((MemberSelectTree) parentTree) - .getIdentifier() - .contentEquals("getAndIncrement")) { + } else if (memberSelectTree.getIdentifier().contentEquals("getAndIncrement")) { fix.replace(grandparent, format("%s++", state.getSourceForNode(tree))); - } else if (((MemberSelectTree) parentTree) - .getIdentifier() - .contentEquals("getAndDecrement")) { + } else if (memberSelectTree.getIdentifier().contentEquals("getAndDecrement")) { fix.replace(grandparent, format("%s--", state.getSourceForNode(tree))); - } else if (((MemberSelectTree) parentTree) - .getIdentifier() - .contentEquals("incrementAndGet")) { + } else if (memberSelectTree.getIdentifier().contentEquals("incrementAndGet")) { fix.replace(grandparent, format("++%s", state.getSourceForNode(tree))); - } else if (((MemberSelectTree) parentTree) - .getIdentifier() - .contentEquals("decrementAndGet")) { + } else if (memberSelectTree.getIdentifier().contentEquals("decrementAndGet")) { fix.replace(grandparent, format("--%s", state.getSourceForNode(tree))); - } else if (((MemberSelectTree) parentTree) - .getIdentifier() - .contentEquals("compareAndSet")) { + } else if (memberSelectTree.getIdentifier().contentEquals("compareAndSet")) { fix.replace( grandparent, format( "%s = %s", state.getSourceForNode(tree), state.getSourceForNode(grandparent.getArguments().get(1)))); - } else if (((MemberSelectTree) parentTree).getIdentifier().contentEquals("addAndGet")) { + } else if (memberSelectTree.getIdentifier().contentEquals("addAndGet")) { fix.replace( grandparent, format( diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryLongToIntConversion.java b/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryLongToIntConversion.java index 46b1c1cb425..a34880d8af0 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryLongToIntConversion.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryLongToIntConversion.java @@ -109,8 +109,9 @@ public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState } // Match if the arg is a type cast from a long to an int. - if (arg instanceof TypeCastTree && LONG_TO_INT_CAST.matches((TypeCastTree) arg, state)) { - ExpressionTree castedExpression = ((TypeCastTree) arg).getExpression(); + if (arg instanceof TypeCastTree typeCastTree + && LONG_TO_INT_CAST.matches(typeCastTree, state)) { + ExpressionTree castedExpression = typeCastTree.getExpression(); return buildDescription(tree) // Remove the type cast. .addFix(SuggestedFix.replace(arg, state.getSourceForNode(castedExpression))) diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/UnusedNestedClass.java b/core/src/main/java/com/google/errorprone/bugpatterns/UnusedNestedClass.java index 57aebe9705d..bc8eb0ae9b2 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/UnusedNestedClass.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/UnusedNestedClass.java @@ -125,8 +125,8 @@ public Void visitIdentifier(IdentifierTree identifierTree, Void unused) { private void handle(Tree node) { for (Symbol symbol = getSymbol(node); symbol != null; symbol = enclosingClass(symbol)) { - if (symbol instanceof ClassSymbol && !withinClasses.contains(symbol)) { - usedClasses.add((ClassSymbol) symbol); + if (symbol instanceof ClassSymbol classSymbol && !withinClasses.contains(symbol)) { + usedClasses.add(classSymbol); } } } diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/UnusedTypeParameter.java b/core/src/main/java/com/google/errorprone/bugpatterns/UnusedTypeParameter.java index daf973490b9..10a8e7306c0 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/UnusedTypeParameter.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/UnusedTypeParameter.java @@ -91,8 +91,8 @@ private static ImmutableMultiset findUsedIdentifiers( @Override public Void scan(Tree tree, Void unused) { var symbol = getSymbol(tree); - if (symbol instanceof TypeVariableSymbol) { - identifiers.add((TypeVariableSymbol) symbol); + if (symbol instanceof TypeVariableSymbol typeVariableSymbol) { + identifiers.add(typeVariableSymbol); } return super.scan(tree, null); } diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/UnusedVariable.java b/core/src/main/java/com/google/errorprone/bugpatterns/UnusedVariable.java index a80931ea707..9e33e1a92f7 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/UnusedVariable.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/UnusedVariable.java @@ -482,8 +482,8 @@ private static ImmutableList buildUnusedVarFixes( } else if (statement.getKind() == Kind.EXPRESSION_STATEMENT) { JCTree tree = (JCTree) ((ExpressionStatementTree) statement).getExpression(); - if (tree instanceof CompoundAssignmentTree) { - if (hasSideEffect(((CompoundAssignmentTree) tree).getExpression())) { + if (tree instanceof CompoundAssignmentTree compoundAssignmentTree) { + if (hasSideEffect(compoundAssignmentTree.getExpression())) { // If it's a compound assignment, there's no reason we'd want to remove the expression, // so don't set `encounteredSideEffects` based on this usage. SuggestedFix replacement = @@ -495,8 +495,8 @@ private static ImmutableList buildUnusedVarFixes( removeSideEffectsFix.merge(replacement); continue; } - } else if (tree instanceof AssignmentTree) { - if (hasSideEffect(((AssignmentTree) tree).getExpression())) { + } else if (tree instanceof AssignmentTree assignmentTree) { + if (hasSideEffect(assignmentTree.getExpression())) { encounteredSideEffects = true; keepSideEffectsFix.replace( tree.getStartPosition(), ((JCAssign) tree).getExpression().getStartPosition(), ""); diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/Varifier.java b/core/src/main/java/com/google/errorprone/bugpatterns/Varifier.java index f7ff65a1e4a..03d82aff39e 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/Varifier.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/Varifier.java @@ -95,12 +95,12 @@ && isSameType( return fix(tree); } // Foo foo = new Foo(...); - if (initializer instanceof NewClassTree + if (initializer instanceof NewClassTree newClassTree && isSameType( getType(((NewClassTree) initializer).getIdentifier()), getType(tree.getType()), state)) { - var identifier = ((NewClassTree) initializer).getIdentifier(); + var identifier = newClassTree.getIdentifier(); if (identifier instanceof ParameterizedTypeTree && ((ParameterizedTypeTree) identifier).getTypeArguments().isEmpty()) { return NO_MATCH; diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/CreatesDuplicateCallHeuristic.java b/core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/CreatesDuplicateCallHeuristic.java index 759f5c29f7f..39910447f21 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/CreatesDuplicateCallHeuristic.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/CreatesDuplicateCallHeuristic.java @@ -121,15 +121,14 @@ private void addToResult(MethodSymbol foundSymbol, Tree tree) { } private ImmutableList createParameterList(Tree tree) { - if (tree instanceof MethodInvocationTree) { - return Parameter.createListFromExpressionTrees( - ((MethodInvocationTree) tree).getArguments()); + if (tree instanceof MethodInvocationTree methodInvocationTree) { + return Parameter.createListFromExpressionTrees(methodInvocationTree.getArguments()); } - if (tree instanceof NewClassTree) { - return Parameter.createListFromExpressionTrees(((NewClassTree) tree).getArguments()); + if (tree instanceof NewClassTree newClassTree) { + return Parameter.createListFromExpressionTrees(newClassTree.getArguments()); } - if (tree instanceof MethodTree) { - return Parameter.createListFromVariableTrees(((MethodTree) tree).getParameters()); + if (tree instanceof MethodTree methodTree) { + return Parameter.createListFromVariableTrees(methodTree.getParameters()); } return ImmutableList.of(); } diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/EnclosedByReverseHeuristic.java b/core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/EnclosedByReverseHeuristic.java index 99fb4f73909..a39f5f001d6 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/EnclosedByReverseHeuristic.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/EnclosedByReverseHeuristic.java @@ -87,12 +87,12 @@ public boolean isAcceptableChange( } private static Optional getName(Tree tree) { - if (tree instanceof MethodTree) { - return Optional.of(((MethodTree) tree).getName().toString()); + if (tree instanceof MethodTree methodTree) { + return Optional.of(methodTree.getName().toString()); } - if (tree instanceof ClassTree) { - return Optional.of(((ClassTree) tree).getSimpleName().toString()); + if (tree instanceof ClassTree classTree) { + return Optional.of(classTree.getSimpleName().toString()); } return Optional.empty(); diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/checkreturnvalue/CanIgnoreReturnValueSuggester.java b/core/src/main/java/com/google/errorprone/bugpatterns/checkreturnvalue/CanIgnoreReturnValueSuggester.java index 1c59f571d2e..ef747fa3cc8 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/checkreturnvalue/CanIgnoreReturnValueSuggester.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/checkreturnvalue/CanIgnoreReturnValueSuggester.java @@ -242,8 +242,8 @@ private static boolean classLooksLikeBuilder(Symbol owner, VisitorState state) { private static boolean isSimpleReturnThisMethod(MethodTree methodTree) { if (methodTree.getBody() != null && methodTree.getBody().getStatements().size() == 1) { StatementTree onlyStatement = methodTree.getBody().getStatements().get(0); - if (onlyStatement instanceof ReturnTree) { - return returnsThisOrSelf((ReturnTree) onlyStatement); + if (onlyStatement instanceof ReturnTree returnTree) { + return returnsThisOrSelf(returnTree); } } return false; @@ -251,8 +251,8 @@ private static boolean isSimpleReturnThisMethod(MethodTree methodTree) { private static boolean isIdentifier(ExpressionTree expr, String identifierName) { expr = stripParentheses(expr); - if (expr instanceof IdentifierTree) { - return ((IdentifierTree) expr).getName().contentEquals(identifierName); + if (expr instanceof IdentifierTree identifierTree) { + return identifierTree.getName().contentEquals(identifierName); } return false; } diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/flogger/FloggerRequiredModifiers.java b/core/src/main/java/com/google/errorprone/bugpatterns/flogger/FloggerRequiredModifiers.java index dc249d93658..eaaa88b741d 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/flogger/FloggerRequiredModifiers.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/flogger/FloggerRequiredModifiers.java @@ -146,9 +146,9 @@ public Description matchVariable(VariableTree tree, VisitorState state) { private static boolean isConstantLogger( ExpressionTree initializer, ClassSymbol owner, VisitorState state) { - if (initializer instanceof MethodInvocationTree) { + if (initializer instanceof MethodInvocationTree methodInvocationTree) { Type loggerType = LOGGER_TYPE.get(state); - MethodInvocationTree method = (MethodInvocationTree) initializer; + MethodInvocationTree method = methodInvocationTree; MethodSymbol methodSym = ASTHelpers.getSymbol(method); if (methodSym.isStatic() && methodSym.owner.equals(owner) @@ -396,8 +396,8 @@ private static ClassTree outermostClassTree(TreePath path) { ClassTree result = null; while (path != null) { Tree leaf = path.getLeaf(); - if (leaf instanceof ClassTree) { - result = (ClassTree) leaf; + if (leaf instanceof ClassTree classTree) { + result = classTree; } path = path.getParentPath(); } @@ -460,8 +460,8 @@ private Description rehomeLogger(ExpressionTree tree, VisitorState state) { return NO_MATCH; } } - if (parent instanceof ClassTree) { - outermostClassOfFile = (ClassTree) parent; + if (parent instanceof ClassTree classTree) { + outermostClassOfFile = classTree; } } diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/javadoc/InvalidParam.java b/core/src/main/java/com/google/errorprone/bugpatterns/javadoc/InvalidParam.java index d2604307154..54c1a8e1e5e 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/javadoc/InvalidParam.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/javadoc/InvalidParam.java @@ -152,8 +152,8 @@ public Void visitParam(ParamTree paramTree, Void unused) { ImmutableSet paramNames = paramTree.isTypeParameter() ? typeParameters : parameters; if (!paramTree.getDescription().isEmpty()) { var firstDescription = paramTree.getDescription().get(0); - if (firstDescription instanceof DCText) { - if (((DCText) firstDescription).getBody().startsWith(":")) { + if (firstDescription instanceof DCText dcText) { + if (dcText.getBody().startsWith(":")) { int colonLocation = Utils.getEndPosition(paramTree.getName(), state); if (state.getSourceCode().charAt(colonLocation) == ':') { state.reportMatch( diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/nullness/UnsafeWildcard.java b/core/src/main/java/com/google/errorprone/bugpatterns/nullness/UnsafeWildcard.java index 397c875e6aa..73726890898 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/nullness/UnsafeWildcard.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/nullness/UnsafeWildcard.java @@ -284,8 +284,9 @@ private Description checkForUnsafeWildcards( int i = 0; for (Type arg : targetType.getTypeArguments()) { // Check components of generic types (getTypeArguments() is empty for other kinds of types) - if (arg instanceof WildcardType && ((WildcardType) arg).getSuperBound() != null) { - Type lowerBound = ((WildcardType) arg).getSuperBound(); + if (arg instanceof WildcardType wildcardType + && ((WildcardType) arg).getSuperBound() != null) { + Type lowerBound = wildcardType.getSuperBound(); // We only check lower bounds that are themselves type variables with trivial upper bounds. // Javac already checks other lower bounds, namely lower bounds that are concrete types or // type variables with non-trivial upper bounds, to be in bounds of the corresponding type @@ -336,14 +337,12 @@ private Description checkForUnsafeWildcards( if (contained != Description.NO_MATCH) { return contained; } - } else if (arg instanceof WildcardType && ((WildcardType) arg).getExtendsBound() != null) { + } else if (arg instanceof WildcardType wildcardType + && wildcardType.getExtendsBound() != null) { // Check the wildcard's bound Description contained = checkForUnsafeWildcards( - tree, - messageHeader + i + " nested: ", - ((WildcardType) arg).getExtendsBound(), - state); + tree, messageHeader + i + " nested: ", wildcardType.getExtendsBound(), state); if (contained != Description.NO_MATCH) { return contained; } @@ -358,8 +357,8 @@ private Description checkForUnsafeWildcards( ++i; } // For union and intersection types, check their components. - if (targetType instanceof IntersectionClassType) { - for (Type bound : ((IntersectionClassType) targetType).getExplicitComponents()) { + if (targetType instanceof IntersectionClassType intersectionClassType) { + for (Type bound : intersectionClassType.getExplicitComponents()) { Description contained = checkForUnsafeWildcards(tree, messageHeader + "bound ", bound, state); if (contained != Description.NO_MATCH) { @@ -367,8 +366,8 @@ private Description checkForUnsafeWildcards( } } } - if (targetType instanceof UnionClassType) { - for (Type alternative : ((UnionClassType) targetType).getAlternativeTypes()) { + if (targetType instanceof UnionClassType unionClassType) { + for (Type alternative : unionClassType.getAlternativeTypes()) { Description contained = checkForUnsafeWildcards(tree, messageHeader + "alternative ", alternative, state); if (contained != Description.NO_MATCH) { diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/nullness/VoidMissingNullable.java b/core/src/main/java/com/google/errorprone/bugpatterns/nullness/VoidMissingNullable.java index 1c0d97fcb5e..fe9be25f990 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/nullness/VoidMissingNullable.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/nullness/VoidMissingNullable.java @@ -101,8 +101,8 @@ public Description matchParameterizedType( } for (Tree tree : parameterizedTypeTree.getTypeArguments()) { - if (tree instanceof WildcardTree) { - tree = ((WildcardTree) tree).getBound(); + if (tree instanceof WildcardTree wildcardTree) { + tree = wildcardTree.getBound(); } checkTree(tree, state); } @@ -210,8 +210,8 @@ private boolean typeMatches(Type type, VisitorState state) { } private static List annotationsIfAnnotatedTypeTree(Tree tree) { - if (tree instanceof AnnotatedTypeTree) { - return ((AnnotatedTypeTree) tree).getAnnotations(); + if (tree instanceof AnnotatedTypeTree annotatedTypeTree) { + return annotatedTypeTree.getAnnotations(); } return ImmutableList.of(); } diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ConstantExpressions.java b/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ConstantExpressions.java index c3f7876fe07..dde61078dab 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ConstantExpressions.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ConstantExpressions.java @@ -359,9 +359,10 @@ public Optional symbolizeImmutableExpression( if (isPureIdentifier(tree)) { return Optional.of( PureMethodInvocation.of(getSymbol(tree), ImmutableList.of(), receiverConstant)); - } else if (tree instanceof MethodInvocationTree && pureMethods.matches(tree, state)) { + } else if (tree instanceof MethodInvocationTree methodInvocationTree + && pureMethods.matches(tree, state)) { ImmutableList.Builder arguments = ImmutableList.builder(); - for (ExpressionTree argument : ((MethodInvocationTree) tree).getArguments()) { + for (ExpressionTree argument : methodInvocationTree.getArguments()) { Optional argumentConstant = constantExpression(argument, state); if (argumentConstant.isEmpty()) { return Optional.empty(); diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/GuardedByExpression.java b/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/GuardedByExpression.java index 651c08a7e30..8473540f7ea 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/GuardedByExpression.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/GuardedByExpression.java @@ -227,11 +227,11 @@ TypeLiteral typeLiteral(Symbol type) { } Select select(GuardedByExpression base, Symbol member) { - if (member instanceof VarSymbol) { - return select(base, (VarSymbol) member); + if (member instanceof VarSymbol varSymbol) { + return select(base, varSymbol); } - if (member instanceof MethodSymbol) { - return select(base, (MethodSymbol) member); + if (member instanceof MethodSymbol methodSymbol) { + return select(base, methodSymbol); } throw new IllegalStateException("Bad select expression: expected symbol " + member.getKind()); } diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/GuardedBySymbolResolver.java b/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/GuardedBySymbolResolver.java index 0a7b5e9afc8..4e7bf12ba7a 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/GuardedBySymbolResolver.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/GuardedBySymbolResolver.java @@ -224,8 +224,8 @@ private T getMember( ExpressionTree arg = method.argument(idx); if (arg != null) { Symbol sym = ASTHelpers.getSymbol(arg); - if (sym instanceof VarSymbol) { - return (VarSymbol) sym; + if (sym instanceof VarSymbol varSymbol) { + return varSymbol; } } return param; diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/HeldLockAnalyzer.java b/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/HeldLockAnalyzer.java index 2347d03886f..866b756f3bd 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/HeldLockAnalyzer.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/HeldLockAnalyzer.java @@ -495,8 +495,8 @@ private static boolean isGuardReferenceAbsolute(GuardedByExpression guard) { /** Gets the base expression of a (possibly nested) member select expression. */ private static GuardedByExpression getSelectInstance(GuardedByExpression guard) { - if (guard instanceof Select) { - return getSelectInstance(((Select) guard).base()); + if (guard instanceof Select select) { + return getSelectInstance(select.base()); } return guard; } diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableChecker.java b/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableChecker.java index be0c52425d1..ff11b745267 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableChecker.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableChecker.java @@ -456,10 +456,10 @@ public Void visitIdentifier(IdentifierTree tree, Void unused) { } private void handleIdentifier(Symbol symbol) { - if (symbol instanceof VarSymbol + if (symbol instanceof VarSymbol varSymbol && !variablesOwnedByLambda.contains(symbol) && !isStatic(symbol)) { - variablesClosed.add((VarSymbol) symbol); + variablesClosed.add(varSymbol); } } }.scan(state.getPath(), null); diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/StaticGuardedByInstance.java b/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/StaticGuardedByInstance.java index 25dbd0eb8f7..4594b2cefc7 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/StaticGuardedByInstance.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/StaticGuardedByInstance.java @@ -85,8 +85,8 @@ static SetMultimap scan(Tree tree) { private void recordWrite(ExpressionTree variable) { Symbol sym = ASTHelpers.getSymbol(variable); - if (sym instanceof VarSymbol) { - writes.put((VarSymbol) sym, variable); + if (sym instanceof VarSymbol varSymbol) { + writes.put(varSymbol, variable); } } diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/time/DateChecker.java b/core/src/main/java/com/google/errorprone/bugpatterns/time/DateChecker.java index 95ab482a298..f990dac2fe4 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/time/DateChecker.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/time/DateChecker.java @@ -157,8 +157,8 @@ private static void checkYear(ExpressionTree tree, List errors) { private static void checkMonth(ExpressionTree tree, List errors) { checkBounds(tree, "0-based month", MONTH_RANGE, errors); - if (tree instanceof LiteralTree) { - int monthValue = (int) ((LiteralTree) tree).getValue(); + if (tree instanceof LiteralTree literalTree) { + int monthValue = (int) literalTree.getValue(); try { errors.add( String.format( diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/time/DurationGetTemporalUnit.java b/core/src/main/java/com/google/errorprone/bugpatterns/time/DurationGetTemporalUnit.java index c61dcec50fe..4c38a9f580a 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/time/DurationGetTemporalUnit.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/time/DurationGetTemporalUnit.java @@ -107,11 +107,11 @@ static Optional getInvalidChronoUnit( } private static Optional getEnumName(ExpressionTree temporalUnit) { - if (temporalUnit instanceof IdentifierTree) { // e.g., SECONDS - return Optional.of(((IdentifierTree) temporalUnit).getName().toString()); + if (temporalUnit instanceof IdentifierTree identifierTree) { // e.g., SECONDS + return Optional.of(identifierTree.getName().toString()); } - if (temporalUnit instanceof MemberSelectTree) { // e.g., ChronoUnit.SECONDS - return Optional.of(((MemberSelectTree) temporalUnit).getIdentifier().toString()); + if (temporalUnit instanceof MemberSelectTree memberSelectTree) { // e.g., ChronoUnit.SECONDS + return Optional.of(memberSelectTree.getIdentifier().toString()); } return Optional.empty(); } diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/time/DurationToLongTimeUnit.java b/core/src/main/java/com/google/errorprone/bugpatterns/time/DurationToLongTimeUnit.java index 6950b273498..1e0101900f1 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/time/DurationToLongTimeUnit.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/time/DurationToLongTimeUnit.java @@ -171,13 +171,11 @@ private Description describeTimeUnitConversionFix( * TimeUnit it likely represents. */ static Optional getTimeUnit(ExpressionTree timeUnit) { - if (timeUnit instanceof IdentifierTree) { // e.g., SECONDS - return Enums.getIfPresent(TimeUnit.class, ((IdentifierTree) timeUnit).getName().toString()) - .toJavaUtil(); + if (timeUnit instanceof IdentifierTree identifierTree) { // e.g., SECONDS + return Enums.getIfPresent(TimeUnit.class, identifierTree.getName().toString()).toJavaUtil(); } - if (timeUnit instanceof MemberSelectTree) { // e.g., TimeUnit.SECONDS - return Enums.getIfPresent( - TimeUnit.class, ((MemberSelectTree) timeUnit).getIdentifier().toString()) + if (timeUnit instanceof MemberSelectTree memberSelectTree) { // e.g., TimeUnit.SECONDS + return Enums.getIfPresent(TimeUnit.class, memberSelectTree.getIdentifier().toString()) .toJavaUtil(); } return Optional.empty(); diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/time/NearbyCallers.java b/core/src/main/java/com/google/errorprone/bugpatterns/time/NearbyCallers.java index ff076360890..1d616745d30 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/time/NearbyCallers.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/time/NearbyCallers.java @@ -151,8 +151,8 @@ private static Optional> buildProtoGetterChain( if (!IS_IMMUTABLE_PROTO_GETTER.matches(expr, state)) { return Optional.empty(); } - if (expr instanceof JCFieldAccess) { - expr = ((JCFieldAccess) expr).getExpression(); + if (expr instanceof JCFieldAccess fieldAccess) { + expr = fieldAccess.getExpression(); } symbolChain.add(ASTHelpers.getSymbol(expr)); } @@ -184,8 +184,8 @@ private static ImmutableList getNearbyTreesToScan(VisitorState state) { // fields ImmutableList.Builder treesToScan = ImmutableList.builder(); for (Tree member : ((ClassTree) parent).getMembers()) { - if (member instanceof VariableTree) { - ExpressionTree expressionTree = ((VariableTree) member).getInitializer(); + if (member instanceof VariableTree variableTree) { + ExpressionTree expressionTree = variableTree.getInitializer(); if (expressionTree != null) { treesToScan.add(expressionTree); } diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/time/TemporalAccessorGetChronoField.java b/core/src/main/java/com/google/errorprone/bugpatterns/time/TemporalAccessorGetChronoField.java index 78cf3c5f0da..ba2866ff927 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/time/TemporalAccessorGetChronoField.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/time/TemporalAccessorGetChronoField.java @@ -155,11 +155,12 @@ private static boolean isDefinitelyInvalidChronoField( } private static Optional getEnumName(ExpressionTree chronoField) { - if (chronoField instanceof IdentifierTree) { // e.g., SECOND_OF_DAY - return Optional.of(((IdentifierTree) chronoField).getName().toString()); + if (chronoField instanceof IdentifierTree identifierTree) { // e.g., SECOND_OF_DAY + return Optional.of(identifierTree.getName().toString()); } - if (chronoField instanceof MemberSelectTree) { // e.g., ChronoField.SECOND_OF_DAY - return Optional.of(((MemberSelectTree) chronoField).getIdentifier().toString()); + if (chronoField + instanceof MemberSelectTree memberSelectTree) { // e.g., ChronoField.SECOND_OF_DAY + return Optional.of(memberSelectTree.getIdentifier().toString()); } return Optional.empty(); } diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/time/TimeUnitMismatch.java b/core/src/main/java/com/google/errorprone/bugpatterns/time/TimeUnitMismatch.java index 5a63720fce0..6f7bd81d7df 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/time/TimeUnitMismatch.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/time/TimeUnitMismatch.java @@ -561,14 +561,14 @@ public static TreeAndTimeUnit of( private static @Nullable Long conversionFactor(ExpressionTree tree) { var constValue = constValue(tree); - if (constValue instanceof Long) { + if (constValue instanceof Long l) { // Don't count 0 to be a valid conversion factor, because it _does_ show up as a conversion // factor if you're doing integer division (i.e. 1 millisecond = 0 seconds, so the conversion // factor naively looks like 0). - return (Long) constValue == 0L ? null : (Long) constValue; + return l == 0L ? null : l; } - if (constValue instanceof Integer) { - return (Integer) constValue == 0 ? null : ((Integer) constValue).longValue(); + if (constValue instanceof Integer integer) { + return integer == 0 ? null : integer.longValue(); } return null; } diff --git a/core/src/main/java/com/google/errorprone/refaster/ExpressionTemplate.java b/core/src/main/java/com/google/errorprone/refaster/ExpressionTemplate.java index a42bdf4029e..0e2310cb83d 100644 --- a/core/src/main/java/com/google/errorprone/refaster/ExpressionTemplate.java +++ b/core/src/main/java/com/google/errorprone/refaster/ExpressionTemplate.java @@ -151,10 +151,10 @@ public Boolean reduce(Boolean a, Boolean b) { @Override public Boolean visitOther(Tree t, Unifier u) { - if (t instanceof UPlaceholderExpression) { - return ((UPlaceholderExpression) t).reverify(u); - } else if (t instanceof UPlaceholderStatement) { - return ((UPlaceholderStatement) t).reverify(u); + if (t instanceof UPlaceholderExpression uPlaceholderExpression) { + return uPlaceholderExpression.reverify(u); + } else if (t instanceof UPlaceholderStatement uPlaceholderStatement) { + return uPlaceholderStatement.reverify(u); } else { return super.visitOther(t, u); } diff --git a/core/src/main/java/com/google/errorprone/refaster/PlaceholderUnificationVisitor.java b/core/src/main/java/com/google/errorprone/refaster/PlaceholderUnificationVisitor.java index 9a59350dd33..6e43cd20f40 100644 --- a/core/src/main/java/com/google/errorprone/refaster/PlaceholderUnificationVisitor.java +++ b/core/src/main/java/com/google/errorprone/refaster/PlaceholderUnificationVisitor.java @@ -184,8 +184,8 @@ private Choice> unifyParam( } public Choice> unify(@Nullable Tree node, State state) { - if (node instanceof ExpressionTree) { - return unifyExpression((ExpressionTree) node, state); + if (node instanceof ExpressionTree expressionTree) { + return unifyExpression(expressionTree, state); } else if (node == null) { return Choice.of(state.withResult(null)); } else { diff --git a/core/src/main/java/com/google/errorprone/refaster/RefasterScanner.java b/core/src/main/java/com/google/errorprone/refaster/RefasterScanner.java index 95d0423888f..e17109b13a6 100644 --- a/core/src/main/java/com/google/errorprone/refaster/RefasterScanner.java +++ b/core/src/main/java/com/google/errorprone/refaster/RefasterScanner.java @@ -69,8 +69,8 @@ public Void visitClass(ClassTree node, Context context) { if (sym == null || !sym.getQualifiedName().contentEquals(rule().qualifiedTemplateClass())) { ListBuffer statements = new ListBuffer<>(); for (Tree tree : node.getMembers()) { - if (tree instanceof JCStatement) { - statements.append((JCStatement) tree); + if (tree instanceof JCStatement jCStatement) { + statements.append(jCStatement); } else { tree.accept(this, context); } diff --git a/core/src/main/java/com/google/errorprone/refaster/Template.java b/core/src/main/java/com/google/errorprone/refaster/Template.java index 6175c60cd29..cf53d8a5433 100644 --- a/core/src/main/java/com/google/errorprone/refaster/Template.java +++ b/core/src/main/java/com/google/errorprone/refaster/Template.java @@ -323,10 +323,10 @@ public void visitApply(JCMethodInvocation tree) { @Override public void printStat(JCTree tree) throws IOException { - if (tree instanceof JCExpressionStatement + if (tree instanceof JCExpressionStatement jCExpressionStatement && ((JCExpressionStatement) tree).getExpression() instanceof JCMethodInvocation) { JCMethodInvocation invocation = - (JCMethodInvocation) ((JCExpressionStatement) tree).getExpression(); + (JCMethodInvocation) jCExpressionStatement.getExpression(); JCExpression select = invocation.getMethodSelect(); if (select != null && select.toString().equals("Refaster.emitComment")) { String commentLiteral = diff --git a/core/src/main/java/com/google/errorprone/refaster/ULiteral.java b/core/src/main/java/com/google/errorprone/refaster/ULiteral.java index 6650e70fcaf..bc26847b937 100644 --- a/core/src/main/java/com/google/errorprone/refaster/ULiteral.java +++ b/core/src/main/java/com/google/errorprone/refaster/ULiteral.java @@ -96,10 +96,10 @@ private static boolean integral(@Nullable Object o) { } private static boolean match(@Nullable Object a, @Nullable Object b) { - if (a instanceof Number && b instanceof Number) { - return (integral(a) && integral(b)) - ? ((Number) a).longValue() == ((Number) b).longValue() - : Double.compare(((Number) a).doubleValue(), ((Number) b).doubleValue()) == 0; + if (a instanceof Number aNum && b instanceof Number bNum) { + return (integral(aNum) && integral(bNum)) + ? aNum.longValue() == bNum.longValue() + : Double.compare(aNum.doubleValue(), bNum.doubleValue()) == 0; } else { return Objects.equals(a, b); } diff --git a/core/src/main/java/com/google/errorprone/refaster/UPlaceholderExpression.java b/core/src/main/java/com/google/errorprone/refaster/UPlaceholderExpression.java index 6c579243221..c61b4a606f4 100644 --- a/core/src/main/java/com/google/errorprone/refaster/UPlaceholderExpression.java +++ b/core/src/main/java/com/google/errorprone/refaster/UPlaceholderExpression.java @@ -97,9 +97,9 @@ public T copy(T tree, Inliner inliner) { @Override public JCTree visitIdentifier(IdentifierTree node, Inliner inliner) { - if (node instanceof PlaceholderParamIdent) { + if (node instanceof PlaceholderParamIdent placeholderParamIdent) { try { - return arguments.get(((PlaceholderParamIdent) node).param).inline(inliner); + return arguments.get(placeholderParamIdent.param).inline(inliner); } catch (CouldNotResolveImportException e) { throw new UncheckedCouldNotResolveImportException(e); } diff --git a/core/src/main/java/com/google/errorprone/refaster/UTemplater.java b/core/src/main/java/com/google/errorprone/refaster/UTemplater.java index 3484b107092..72fba3491b0 100644 --- a/core/src/main/java/com/google/errorprone/refaster/UTemplater.java +++ b/core/src/main/java/com/google/errorprone/refaster/UTemplater.java @@ -156,9 +156,9 @@ public static Template createTemplate(Context context, MethodTree decl) { if (genericType instanceof UForAll forAllType) { typeParameters = forAllType.getTypeVars(); methodType = (UMethodType) forAllType.getQuantifiedType(); - } else if (genericType instanceof UMethodType) { + } else if (genericType instanceof UMethodType uMethodType) { typeParameters = ImmutableList.of(); - methodType = (UMethodType) genericType; + methodType = uMethodType; } else { throw new IllegalArgumentException( "Expected genericType to be either a ForAll or a UMethodType, but was " + genericType); @@ -330,8 +330,8 @@ public UAnnotatedType visitAnnotatedType(AnnotatedTypeTree tree, Void v) { @Override public UExpression visitMemberSelect(MemberSelectTree tree, Void v) { Symbol sym = ASTHelpers.getSymbol(tree); - if (sym instanceof ClassSymbol) { - return UClassIdent.create((ClassSymbol) sym); + if (sym instanceof ClassSymbol classSymbol) { + return UClassIdent.create(classSymbol); } else if (isStatic(sym)) { ExpressionTree selected = tree.getExpression(); checkState( @@ -591,8 +591,8 @@ public UMemberReference visitMemberReference(MemberReferenceTree tree, Void v) { @Override public UExpression visitIdentifier(IdentifierTree tree, Void v) { Symbol sym = ASTHelpers.getSymbol(tree); - if (sym instanceof ClassSymbol) { - return UClassIdent.create((ClassSymbol) sym); + if (sym instanceof ClassSymbol classSymbol) { + return UClassIdent.create(classSymbol); } else if (sym != null && isStatic(sym)) { return staticMember(sym); } else if (freeVariables.containsKey(tree.getName().toString())) { @@ -884,9 +884,9 @@ public UMethodType visitMethodType(MethodType type, Void v) { @Override public UType visitClassType(ClassType type, Void v) { - if (type instanceof IntersectionClassType) { + if (type instanceof IntersectionClassType intersectionClassType) { return UIntersectionClassType.create( - templateTypes(((IntersectionClassType) type).getComponents())); + templateTypes(intersectionClassType.getComponents())); } return UClassType.create( type.tsym.getQualifiedName().toString(), templateTypes(type.getTypeArguments())); diff --git a/core/src/test/java/com/google/errorprone/ErrorProneCompilerIntegrationTest.java b/core/src/test/java/com/google/errorprone/ErrorProneCompilerIntegrationTest.java index 560f8e403d5..c8783cf8352 100644 --- a/core/src/test/java/com/google/errorprone/ErrorProneCompilerIntegrationTest.java +++ b/core/src/test/java/com/google/errorprone/ErrorProneCompilerIntegrationTest.java @@ -260,10 +260,10 @@ static class SuperCallMatcher extends BugChecker implements MethodInvocationTree public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { Tree select = tree.getMethodSelect(); Name name; - if (select instanceof MemberSelectTree) { - name = ((MemberSelectTree) select).getIdentifier(); - } else if (select instanceof IdentifierTree) { - name = ((IdentifierTree) select).getName(); + if (select instanceof MemberSelectTree memberSelectTree) { + name = memberSelectTree.getIdentifier(); + } else if (select instanceof IdentifierTree identifierTree) { + name = identifierTree.getName(); } else { return NO_MATCH; }