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(); + } }