From 0be7a89cbf65738e3351a9dc102ca1bec83cb9a4 Mon Sep 17 00:00:00 2001 From: Liam Miller-Cushon Date: Thu, 25 Jan 2024 13:48:56 -0800 Subject: [PATCH] Work around a javac end position bug for empty statements See https://bugs.openjdk.org/browse/JDK-8324736 Fixes https://github.com/google/error-prone/issues/4245 PiperOrigin-RevId: 601554857 --- .../bugpatterns/EmptyTopLevelDeclaration.java | 12 +++++++++++- .../bugpatterns/EmptyTopLevelDeclarationTest.java | 13 +++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/EmptyTopLevelDeclaration.java b/core/src/main/java/com/google/errorprone/bugpatterns/EmptyTopLevelDeclaration.java index a896c2bc295..622b5a662f6 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/EmptyTopLevelDeclaration.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/EmptyTopLevelDeclaration.java @@ -19,6 +19,7 @@ import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Description.NO_MATCH; +import static com.google.errorprone.util.ASTHelpers.getStartPosition; import com.google.common.collect.ImmutableList; import com.google.errorprone.BugPattern; @@ -44,7 +45,16 @@ public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState s return NO_MATCH; } SuggestedFix.Builder fixBuilder = SuggestedFix.builder(); - toDelete.forEach(fixBuilder::delete); + toDelete.forEach( + x -> { + int start = getStartPosition(x); + int end = state.getEndPosition(x); + if (end <= start) { + // work around https://bugs.openjdk.org/browse/JDK-8324736 + end = start + 1; + } + fixBuilder.replace(start, end, ""); + }); return describeMatch(toDelete.get(0), fixBuilder.build()); } } diff --git a/core/src/test/java/com/google/errorprone/bugpatterns/EmptyTopLevelDeclarationTest.java b/core/src/test/java/com/google/errorprone/bugpatterns/EmptyTopLevelDeclarationTest.java index cfc534685c9..d69211cca73 100644 --- a/core/src/test/java/com/google/errorprone/bugpatterns/EmptyTopLevelDeclarationTest.java +++ b/core/src/test/java/com/google/errorprone/bugpatterns/EmptyTopLevelDeclarationTest.java @@ -43,4 +43,17 @@ public void positive() { "class One {};") .doTest(); } + + // https://github.com/google/error-prone/issues/4245 + @Test + public void noImports() { + compilationHelper + .addSourceLines( + "ReproFile.java", // + "package errorpronecrash;", + "// BUG: Diagnostic contains: Did you mean to remove this line?", + ";", + "public class ReproFile {}") + .doTest(); + } }