From e489a52bc2d737b70ba741990cec5f48f4bd9238 Mon Sep 17 00:00:00 2001 From: Liam Miller-Cushon Date: Sun, 3 Nov 2024 21:00:57 -0800 Subject: [PATCH] DuplicateBranches: don't crash on empty blocks PiperOrigin-RevId: 692822985 --- .../bugpatterns/DuplicateBranches.java | 8 ++++-- .../bugpatterns/DuplicateBranchesTest.java | 25 +++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) 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 3936c3fc9ad..297c57de3df 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/DuplicateBranches.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/DuplicateBranches.java @@ -76,8 +76,12 @@ private Description match(Tree tree, Tree thenTree, Tree elseTree, VisitorState if (elseTree instanceof BlockTree) { needsBraces = !state.getPath().getParentPath().getLeaf().getKind().equals(Kind.BLOCK); var statements = ((BlockTree) elseTree).getStatements(); - start = getStartPosition(statements.get(0)); - end = state.getEndPosition(getLast(statements)); + if (statements.isEmpty()) { + start = end; + } else { + start = getStartPosition(statements.get(0)); + end = state.getEndPosition(getLast(statements)); + } } String comments = ErrorProneTokens.getTokens( diff --git a/core/src/test/java/com/google/errorprone/bugpatterns/DuplicateBranchesTest.java b/core/src/test/java/com/google/errorprone/bugpatterns/DuplicateBranchesTest.java index bf9c8eb87bb..c8b0c42c124 100644 --- a/core/src/test/java/com/google/errorprone/bugpatterns/DuplicateBranchesTest.java +++ b/core/src/test/java/com/google/errorprone/bugpatterns/DuplicateBranchesTest.java @@ -215,4 +215,29 @@ boolean g(boolean a, boolean b) { """) .doTest(TestMode.TEXT_MATCH); } + + @Test + public void negativeEmpty() { + BugCheckerRefactoringTestHelper.newInstance(DuplicateBranches.class, getClass()) + .addInputLines( + "Test.java", + """ + class Test { + void f(boolean a) { + if (a) { + } else { + } + } + } + """) + .addOutputLines( + "Test.java", + """ + class Test { + void f(boolean a) { + } + } + """) + .doTest(); + } }