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 5f3d981fc1b..7223c0de2a8 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 @@ -1681,6 +1681,15 @@ public static SuggestedFix replaceIncludingComments( if (previousMember == null) { tokens = getTokensAfterOpeningBrace(tokens); } + // There can be a lingering semi as the last token of the previous member in enums, e.g.: + // enum { + // A, B, C; <-- extra semi + // int deletingThisVariable; + // } + // Treat this as morally part of the previous member. + if (!tokens.isEmpty() && tokens.get(0).kind() == TokenKind.SEMI) { + tokens = tokens.subList(1, tokens.size()); + } if (tokens.isEmpty()) { return SuggestedFix.replace(tree, replacement); } diff --git a/core/src/test/java/com/google/errorprone/bugpatterns/UnusedVariableTest.java b/core/src/test/java/com/google/errorprone/bugpatterns/UnusedVariableTest.java index bc25c7b2762..b7ea0d61e77 100644 --- a/core/src/test/java/com/google/errorprone/bugpatterns/UnusedVariableTest.java +++ b/core/src/test/java/com/google/errorprone/bugpatterns/UnusedVariableTest.java @@ -180,6 +180,28 @@ public void unusedField() { .doTest(); } + @Test + public void unusedFieldRefactoringInEnum() { + refactoringHelper + .addInputLines( + "Test.java", + "enum UnusedField {", + " A, B, C;", + " private int notUsedInt;", + " UnusedField() {", + " notUsedInt = 1;", + " }", + "}") + .addOutputLines( + "Test.java", // + "enum UnusedField {", + " A, B, C;", + " UnusedField() {", + " }", + "}") + .doTest(); + } + @Test public void unusedLocalVarInitialized() { helper