From 05d771021ad9de12f3e657d464d18731a13578ab Mon Sep 17 00:00:00 2001 From: owenca Date: Fri, 10 Jun 2022 13:01:27 -0700 Subject: [PATCH] [clang-format] Fix a bug in RemoveBracesLLVM Remove the braces of an else block only if the r_brace of the block is followed by an if. Differential Revision: https://reviews.llvm.org/D127532 --- clang/lib/Format/UnwrappedLineParser.cpp | 3 ++- clang/unittests/Format/FormatTest.cpp | 11 +++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp index d2d69aa..2721949 100644 --- a/clang/lib/Format/UnwrappedLineParser.cpp +++ b/clang/lib/Format/UnwrappedLineParser.cpp @@ -2610,6 +2610,7 @@ FormatToken *UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind, nextToken(); handleAttributes(); if (FormatTok->is(tok::l_brace)) { + const bool FollowedByIf = Tokens->peekNextToken()->is(tok::kw_if); FormatTok->setFinalizedType(TT_ElseLBrace); ElseLeftBrace = FormatTok; CompoundStatementIndenter Indenter(this, Style, Line->Level); @@ -2621,7 +2622,7 @@ FormatToken *UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind, KeepElseBraces = KeepElseBraces || ElseBlockKind == IfStmtKind::IfOnly || ElseBlockKind == IfStmtKind::IfElseIf; - } else if (IfLBrace && !IfLBrace->Optional) { + } else if (FollowedByIf && IfLBrace && !IfLBrace->Optional) { KeepElseBraces = true; assert(ElseLeftBrace->MatchingParen); markOptionalBraces(ElseLeftBrace); diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp index 14b169e..27984ec 100644 --- a/clang/unittests/Format/FormatTest.cpp +++ b/clang/unittests/Format/FormatTest.cpp @@ -25576,6 +25576,17 @@ TEST_F(FormatTest, RemoveBraces) { " g;", Style); + verifyFormat("if (a) {\n" + " b;\n" + " c;\n" + "} else { // comment\n" + " if (d) {\n" + " e;\n" + " f;\n" + " }\n" + "}", + Style); + verifyFormat("if (a)\n" " b;\n" "else if (c)\n" -- 2.7.4