[clang] [clang-format] Fix InsertBraces rebinding an else in a preprocessor branch (PR #239414)
via cfe-commits
cfe-commits at lists.llvm.org
Thu Nov 5 14:58:31 PST 2026
llvmorg-github-actions[bot] wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-clang-format
Author: Andre Sun (and2049)
<details>
<summary>Changes</summary>
Don't insert braces around a body ending in an `if` whose `else` may appear in a preprocessor branch skipped in the current formatting pass. Inserting those braces can attach the `else` to a different `if` or leave it without a matching `if`.
Fixes #<!-- -->239332.
---
Full diff: https://github.com/llvm/llvm-project/pull/239414.diff
3 Files Affected:
- (modified) clang/lib/Format/UnwrappedLineParser.cpp (+98-1)
- (modified) clang/lib/Format/UnwrappedLineParser.h (+4)
- (modified) clang/unittests/Format/BracesInserterTest.cpp (+206)
``````````diff
diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp
index ae507a0e96a57..84a7a8efbc966 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -178,6 +178,7 @@ void UnwrappedLineParser::reset() {
PP.IncludeGuard = getIncludeGuardState(Style.IndentPPDirectives);
PP.IncludeGuardToken = nullptr;
ParsedPPDirectives.clear();
+ TokenAfterIfWithConditionalElse = nullptr;
Line.reset(new UnwrappedLine);
CommentsBeforeNextToken.clear();
FormatTok = nullptr;
@@ -2933,6 +2934,100 @@ static bool containsPPDirective(const UnwrappedLine &Line) {
[](const UnwrappedLineNode &Node) { return Node.Tok->FirstAfterPPLine; });
}
+// Returns whether an `else` in a skipped preprocessor branch may follow.
+bool UnwrappedLineParser::isFollowedByConditionalElse() const {
+ const FormatToken *Last = nullptr;
+ if (!Line->Tokens.empty()) {
+ Last = Line->Tokens.back().Tok;
+ } else {
+ for (const auto &PreviousLine : llvm::reverse(*CurrentLines)) {
+ if (!PreviousLine.InPPDirective && !PreviousLine.Tokens.empty()) {
+ Last = PreviousLine.Tokens.back().Tok;
+ break;
+ }
+ }
+ }
+ if (!Last)
+ return false;
+
+ const auto *It =
+ llvm::lower_bound(AllTokens, Last->Tok.getLocation(),
+ [](const FormatToken *Tok, SourceLocation Loc) {
+ return Tok->Tok.getLocation() < Loc;
+ });
+ if (It == AllTokens.end() || *It != Last)
+ return false;
+
+ // Whether a branch is always taken, for each conditional entered since Last.
+ SmallVector<bool, 4> Conditionals;
+ size_t UnreachableDepth = 0;
+ bool IsFirstOnLine = false;
+ bool IsFirstAfterDirective = false;
+ for (++It; It != AllTokens.end(); ++It) {
+ const auto &Tok = **It;
+ if (Tok.HasUnescapedNewline)
+ IsFirstOnLine = true;
+ if (Tok.is(tok::comment))
+ continue;
+ if (Tok.is(tok::hash) && IsFirstOnLine) {
+ SmallVector<const FormatToken *, 4> Directive;
+ for (const auto *Next = std::next(It);
+ Next != AllTokens.end() && !(*Next)->HasUnescapedNewline; ++Next) {
+ if ((*Next)->isNot(tok::comment))
+ Directive.push_back(*Next);
+ It = Next;
+ }
+ if (!Directive.empty()) {
+ const auto &Keyword = *Directive.front();
+ const auto IsLiteral = [&](bool Value) {
+ if (Keyword.isNoneOf(tok::pp_if, tok::pp_elif) ||
+ Directive.size() != 2) {
+ return false;
+ }
+ const auto &Condition = *Directive[1];
+ return Value
+ ? Condition.is(tok::kw_true) || Condition.TokenText == "1"
+ : Condition.is(tok::kw_false) ||
+ Condition.TokenText == "0";
+ };
+ if (Keyword.isOneOf(tok::pp_if, tok::pp_ifdef, tok::pp_ifndef)) {
+ Conditionals.push_back(IsLiteral(true));
+ if (UnreachableDepth == 0 && IsLiteral(false))
+ UnreachableDepth = Conditionals.size();
+ } else if (Keyword.is(tok::pp_endif)) {
+ if (Conditionals.size() == UnreachableDepth)
+ UnreachableDepth = 0;
+ if (!Conditionals.empty())
+ Conditionals.pop_back();
+ } else if (Keyword.isOneOf(tok::pp_else, tok::pp_elif, tok::pp_elifdef,
+ tok::pp_elifndef)) {
+ if (Conditionals.size() == UnreachableDepth)
+ UnreachableDepth = 0;
+ if (Conditionals.empty())
+ Conditionals.push_back(false);
+ if (UnreachableDepth == 0 &&
+ (Conditionals.back() || IsLiteral(false))) {
+ UnreachableDepth = Conditionals.size();
+ } else if (IsLiteral(true)) {
+ Conditionals.back() = true;
+ }
+ }
+ }
+ IsFirstAfterDirective = true;
+ continue;
+ }
+ IsFirstOnLine = false;
+ if (UnreachableDepth > 0)
+ continue;
+ if (IsFirstAfterDirective && Tok.is(tok::kw_else))
+ return true;
+ if (Conditionals.empty())
+ return false;
+ IsFirstAfterDirective = false;
+ }
+ return false;
+}
+
void UnwrappedLineParser::parseUnbracedBody(bool CheckEOF) {
FormatToken *Tok = nullptr;
@@ -2980,7 +3075,7 @@ void UnwrappedLineParser::parseUnbracedBody(bool CheckEOF) {
return Node.Tok->FirstAfterPPLine;
});
}
- if (EnclosesPPDirective)
+ if (EnclosesPPDirective || FormatTok == TokenAfterIfWithConditionalElse)
LBraceTok->BraceCount = 0;
else
++Tok->BraceCount;
@@ -3175,6 +3270,8 @@ FormatToken *UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
parseUnbracedBody(/*CheckEOF=*/true);
}
} else {
+ if (Style.InsertBraces && isFollowedByConditionalElse())
+ TokenAfterIfWithConditionalElse = FormatTok;
KeepIfBraces = KeepIfBraces || IfBlockKind == IfStmtKind::IfElse;
if (NeedsUnwrappedLine)
addUnwrappedLine();
diff --git a/clang/lib/Format/UnwrappedLineParser.h b/clang/lib/Format/UnwrappedLineParser.h
index 4a47f8158a0fe..fb55cfb2d5b91 100644
--- a/clang/lib/Format/UnwrappedLineParser.h
+++ b/clang/lib/Format/UnwrappedLineParser.h
@@ -161,6 +161,7 @@ class UnwrappedLineParser {
void parseSquare(bool SkipLambda = false);
void keepAncestorBraces();
void parseUnbracedBody(bool CheckEOF = false);
+ bool isFollowedByConditionalElse() const;
void handleAttributes();
bool handleCppAttributes();
bool isBlockBegin(const FormatToken &Tok) const;
@@ -439,6 +440,9 @@ class UnwrappedLineParser {
// readToken().
llvm::SmallPtrSet<const FormatToken *, 16> ParsedPPDirectives;
+ // Follows an if statement whose else may be in a skipped preprocessor branch.
+ const FormatToken *TokenAfterIfWithConditionalElse = nullptr;
+
// Contains the first start column where the source begins. This is zero for
// normal source code and may be nonzero when formatting a code fragment that
// does not start at the beginning of the file.
diff --git a/clang/unittests/Format/BracesInserterTest.cpp b/clang/unittests/Format/BracesInserterTest.cpp
index 6244ed5508654..f720739b04905 100644
--- a/clang/unittests/Format/BracesInserterTest.cpp
+++ b/clang/unittests/Format/BracesInserterTest.cpp
@@ -402,6 +402,212 @@ TEST_F(BracesInserterTest, InsertBraces) {
Style);
}
+TEST_F(BracesInserterTest, ConditionalElse) {
+ FormatStyle Style = getLLVMStyle();
+ Style.InsertBraces = true;
+
+ verifyFormat("if (a)\n"
+ " if (b) {\n"
+ " f();\n"
+ " }\n"
+ "#if A\n"
+ "g();\n"
+ "#else\n"
+ " else {\n"
+ " h();\n"
+ " }\n"
+ "#endif",
+ "if (a)\n"
+ " if (b)\n"
+ " f();\n"
+ "#if A\n"
+ "g();\n"
+ "#else\n"
+ " else\n"
+ " h();\n"
+ "#endif",
+ Style);
+
+ verifyFormat("auto l = [&] {\n"
+ " while (a)\n"
+ " if (b) {\n"
+ " f();\n"
+ " }\n"
+ "#if A\n"
+ " else {\n"
+ " h();\n"
+ " }\n"
+ "#else\n"
+ " g();\n"
+ "#endif\n"
+ "};",
+ "auto l = [&] {\n"
+ " while (a)\n"
+ " if (b)\n"
+ " f();\n"
+ "#if A\n"
+ " else\n"
+ " h();\n"
+ "#else\n"
+ " g();\n"
+ "#endif\n"
+ "};",
+ Style);
+
+ verifyFormat("if (a) {\n"
+ " f();\n"
+ "}\n"
+ "#if A\n"
+ "g();\n"
+ "#else\n"
+ "else {\n"
+ " h();\n"
+ "}\n"
+ "#endif",
+ "if (a)\n"
+ " f();\n"
+ "#if A\n"
+ "g();\n"
+ "#else\n"
+ "else\n"
+ " h();\n"
+ "#endif",
+ Style);
+
+ verifyFormat("if (a) {\n"
+ " if (b) {\n"
+ " f();\n"
+ " }\n"
+ "}\n"
+ "#if 0\n"
+ "#define Q 1\n"
+ "#if B\n"
+ "#endif\n"
+ "else\n"
+ " g();\n"
+ "#endif",
+ "if (a)\n"
+ " if (b)\n"
+ " f();\n"
+ "#if 0\n"
+ "#define Q 1\n"
+ "#if B\n"
+ "#endif\n"
+ "else\n"
+ " g();\n"
+ "#endif",
+ Style);
+
+ verifyFormat("if (a)\n"
+ " if (b) {\n"
+ " f();\n"
+ " }\n"
+ "#if 0 || A\n"
+ "else g();\n"
+ "#endif",
+ "if (a)\n"
+ " if (b)\n"
+ " f();\n"
+ "#if 0 || A\n"
+ "else g();\n"
+ "#endif",
+ Style);
+
+ verifyFormat("if (a)\n"
+ " if (b) {\n"
+ " f();\n"
+ " }\n"
+ "#if A\n"
+ "g();\n"
+ "#else\n"
+ "#if 0\n"
+ "h();\n"
+ "#elif B\n"
+ " else {\n"
+ " h();\n"
+ " }\n"
+ "#else\n"
+ "k();\n"
+ "#endif\n"
+ "#endif",
+ "if (a)\n"
+ " if (b)\n"
+ " f();\n"
+ "#if A\n"
+ "g();\n"
+ "#else\n"
+ "#if 0\n"
+ "h();\n"
+ "#elif B\n"
+ "else h();\n"
+ "#else\n"
+ "k();\n"
+ "#endif\n"
+ "#endif",
+ Style);
+
+ verifyFormat("if (a) {\n"
+ " if (b) {\n"
+ " f();\n"
+ " }\n"
+ "}\n"
+ "#if A\n"
+ "g();\n"
+ "#elif 0\n"
+ "else {\n"
+ " h();\n"
+ "}\n"
+ "#elif 1\n"
+ "k();\n"
+ "#else\n"
+ "else {\n"
+ " m();\n"
+ "}\n"
+ "#endif",
+ "if (a)\n"
+ " if (b)\n"
+ " f();\n"
+ "#if A\n"
+ "g();\n"
+ "#elif 0\n"
+ "else\n"
+ " h();\n"
+ "#elif 1\n"
+ "k();\n"
+ "#else\n"
+ "else\n"
+ " m();\n"
+ "#endif",
+ Style);
+
+ verifyFormat("if (a) {\n"
+ " if (b) {\n"
+ " f();\n"
+ " }\n"
+ "}\n"
+ "#if 1\n"
+ "#if 1\n"
+ "g();\n"
+ "#else\n"
+ "else {\n"
+ " h();\n"
+ "}\n"
+ "#endif\n"
+ "#endif",
+ "if (a)\n"
+ " if (b)\n"
+ " f();\n"
+ "#if 1\n"
+ "#if 1\n"
+ "g();\n"
+ "#else\n"
+ "else\n"
+ " h();\n"
+ "#endif\n"
+ "#endif",
+ Style);
+}
+
TEST_F(BracesInserterTest, InsertBracesRange) {
FormatStyle Style = getLLVMStyle();
Style.InsertBraces = true;
``````````
</details>
https://github.com/llvm/llvm-project/pull/239414
More information about the cfe-commits
mailing list