[clang] [clang-format] Restore InsertBraces around interior preprocessor directives (PR #239459)

Andre Sun via cfe-commits cfe-commits at lists.llvm.org
Sun Nov 29 17:57:00 PST 2026


https://github.com/and2049 updated https://github.com/llvm/llvm-project/pull/239459

>From b4039f3a70b7605065bdc553e2c00e97881317eb Mon Sep 17 00:00:00 2001
From: Andre Sun <andsun9999 at gmail.com>
Date: Thu, 5 Nov 2026 21:58:44 -0500
Subject: [PATCH 1/2] [clang-format] Restore InsertBraces around interior
 preprocessor directives

---
 clang/docs/ClangFormatStyleOptions.md         |   4 +-
 clang/include/clang/Format/Format.h           |   4 +-
 clang/lib/Format/UnwrappedLineParser.cpp      | 113 ++++++++++---
 clang/lib/Format/UnwrappedLineParser.h        |   2 +
 clang/unittests/Format/BracesInserterTest.cpp | 151 +++++++++++++++++-
 5 files changed, 252 insertions(+), 22 deletions(-)

diff --git a/clang/docs/ClangFormatStyleOptions.md b/clang/docs/ClangFormatStyleOptions.md
index c7de6fc25e1f3a..6d76ca6af604ea 100644
--- a/clang/docs/ClangFormatStyleOptions.md
+++ b/clang/docs/ClangFormatStyleOptions.md
@@ -5126,7 +5126,9 @@ the configuration (without a prefix: `Auto`).
 
 : Insert braces after control statements (`if`, `else`, `for`, `do`,
   and `while`) in C++ unless the control statements are inside macro
-  definitions or the braces would enclose preprocessor directives.
+  definitions or a preprocessor directive separates a control statement
+  from its body. Braces may enclose preprocessor directives within a body
+  when the same closing-brace position is safe in every branch.
 
   :::{warning}
   Setting this option to `true` could lead to incorrect code formatting
diff --git a/clang/include/clang/Format/Format.h b/clang/include/clang/Format/Format.h
index 1f29dd630b8020..07847543bc7cbc 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -3492,7 +3492,9 @@ struct FormatStyle {
 
   /// Insert braces after control statements (`if`, `else`, `for`, `do`,
   /// and `while`) in C++ unless the control statements are inside macro
-  /// definitions or the braces would enclose preprocessor directives.
+  /// definitions or a preprocessor directive separates a control statement
+  /// from its body. Braces may enclose preprocessor directives within a body
+  /// when the same closing-brace position is safe in every branch.
   /// \warning
   ///  Setting this option to `true` could lead to incorrect code formatting
   ///  due to clang-format's lack of complete semantic information. As such,
diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp
index 28f240553cd63c..1f6a4b2f9a9202 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -3050,6 +3050,92 @@ bool UnwrappedLineParser::isFollowedByConditionalElse() const {
   return false;
 }
 
+// Returns whether the body ends at RBraceTok in every preprocessor branch.
+bool UnwrappedLineParser::canInsertBraces(const FormatToken &LBraceTok,
+                                          const FormatToken &RBraceTok) const {
+  const auto *It =
+      llvm::lower_bound(AllTokens, LBraceTok.Tok.getLocation(),
+                        [](const FormatToken *Tok, SourceLocation Loc) {
+                          return Tok->Tok.getLocation() < Loc;
+                        });
+  if (It == AllTokens.end() || *It != &LBraceTok)
+    return false;
+
+  struct Conditional {
+    int StartDepth;
+    std::optional<int> EndDepth = std::nullopt;
+    bool HasElse = false;
+  };
+  SmallVector<Conditional, 2> Conditionals;
+  int Depth = 0;
+  bool InBody = false;
+  bool FirstNonCommentOnLine = false;
+  bool HasDirective = false;
+  bool HasMacroCall = false;
+  for (++It; It != AllTokens.end(); ++It) {
+    const auto &Tok = **It;
+    if (Tok.HasUnescapedNewline)
+      FirstNonCommentOnLine = true;
+    if (Tok.is(tok::hash) && FirstNonCommentOnLine) {
+      if (!InBody)
+        return false;
+      HasDirective = true;
+      const auto *Next = std::next(It);
+      while (Next != AllTokens.end() && (*Next)->is(tok::comment) &&
+             !(*Next)->HasUnescapedNewline) {
+        ++Next;
+      }
+      if (Next == AllTokens.end() || (*Next)->HasUnescapedNewline)
+        continue;
+      const auto &Keyword = **Next;
+      if (Keyword.isOneOf(tok::pp_if, tok::pp_ifdef, tok::pp_ifndef)) {
+        Conditionals.push_back({Depth});
+      } else if (Keyword.isOneOf(tok::pp_else, tok::pp_elif, tok::pp_elifdef,
+                                 tok::pp_elifndef, tok::pp_endif)) {
+        if (Conditionals.empty())
+          return false;
+        auto &C = Conditionals.back();
+        if (C.EndDepth && *C.EndDepth != Depth)
+          return false;
+        C.EndDepth = Depth;
+        if (Keyword.is(tok::pp_endif)) {
+          if (!C.HasElse && Depth != C.StartDepth)
+            return false;
+          Conditionals.pop_back();
+        } else {
+          C.HasElse = C.HasElse || Keyword.is(tok::pp_else);
+          Depth = C.StartDepth;
+        }
+      }
+      while (Next != AllTokens.end() && !(*Next)->HasUnescapedNewline)
+        It = Next++;
+      continue;
+    }
+    if (Tok.isNot(tok::comment)) {
+      FirstNonCommentOnLine = false;
+      InBody = true;
+      if (Tok.is(tok::identifier) && Macros.defined(Tok.TokenText))
+        HasMacroCall = true;
+      if (Tok.isOneOf(tok::l_paren, tok::l_square, tok::l_brace))
+        ++Depth;
+      else if (Tok.isOneOf(tok::r_paren, tok::r_square, tok::r_brace))
+        --Depth;
+      // A branch must not change where the statement ends.
+      if (Depth < 0 ||
+          (Depth == 0 && !Conditionals.empty() &&
+           Tok.isOneOf(tok::semi, tok::r_brace, tok::kw_if, tok::kw_else,
+                       tok::kw_for, tok::kw_while, tok::kw_do, tok::kw_switch,
+                       tok::kw_try, tok::kw_catch))) {
+        return false;
+      }
+    }
+    // Directives in a body with a configured macro call are not supported.
+    if (&Tok == &RBraceTok)
+      return Conditionals.empty() && !(HasDirective && HasMacroCall);
+  }
+  return false;
+}
+
 void UnwrappedLineParser::parseUnbracedBody(bool CheckEOF) {
   FormatToken *Tok = nullptr;
 
@@ -3068,7 +3154,6 @@ void UnwrappedLineParser::parseUnbracedBody(bool CheckEOF) {
   }
 
   addUnwrappedLine();
-  const auto BodyStart = CurrentLines->size();
   ++Line->Level;
   ++Line->UnbracedBodyLevel;
   parseStructuralElement();
@@ -3078,29 +3163,19 @@ void UnwrappedLineParser::parseUnbracedBody(bool CheckEOF) {
     assert(!Line->InPPDirective);
     FormatToken *const LBraceTok = Tok;
     Tok = nullptr;
-    auto BodyEnd = CurrentLines->size();
-    while (BodyEnd > 0) {
-      const auto &L = (*CurrentLines)[--BodyEnd];
-      if (!L.InPPDirective && getLastNonComment(L)) {
-        Tok = L.Tokens.back().Tok;
+    for (const auto &BodyLine : llvm::reverse(*CurrentLines)) {
+      if (!BodyLine.InPPDirective && getLastNonComment(BodyLine)) {
+        Tok = BodyLine.Tokens.back().Tok;
         break;
       }
     }
     assert(Tok);
-    // Don't insert the braces if they would enclose preprocessor directives.
-    bool EnclosesPPDirective = false;
-    for (size_t I = BodyStart; I <= BodyEnd && !EnclosesPPDirective; ++I) {
-      const auto &BodyLine = (*CurrentLines)[I];
-      EnclosesPPDirective =
-          BodyLine.InPPDirective ||
-          llvm::any_of(BodyLine.Tokens, [](const UnwrappedLineNode &Node) {
-            return Node.Tok->FirstAfterPPLine;
-          });
-    }
-    if (EnclosesPPDirective || FormatTok == TokenAfterIfWithConditionalElse)
-      LBraceTok->BraceCount = 0;
-    else
+    if (FormatTok != TokenAfterIfWithConditionalElse &&
+        canInsertBraces(*LBraceTok, *Tok)) {
       ++Tok->BraceCount;
+    } else {
+      LBraceTok->BraceCount = 0;
+    }
   }
 
   if (CheckEOF && eof())
diff --git a/clang/lib/Format/UnwrappedLineParser.h b/clang/lib/Format/UnwrappedLineParser.h
index fb55cfb2d5b915..e81ff06c7a560f 100644
--- a/clang/lib/Format/UnwrappedLineParser.h
+++ b/clang/lib/Format/UnwrappedLineParser.h
@@ -162,6 +162,8 @@ class UnwrappedLineParser {
   void keepAncestorBraces();
   void parseUnbracedBody(bool CheckEOF = false);
   bool isFollowedByConditionalElse() const;
+  bool canInsertBraces(const FormatToken &LBraceTok,
+                       const FormatToken &RBraceTok) const;
   void handleAttributes();
   bool handleCppAttributes();
   bool isBlockBegin(const FormatToken &Tok) const;
diff --git a/clang/unittests/Format/BracesInserterTest.cpp b/clang/unittests/Format/BracesInserterTest.cpp
index d077256af337ae..282c83a15334fe 100644
--- a/clang/unittests/Format/BracesInserterTest.cpp
+++ b/clang/unittests/Format/BracesInserterTest.cpp
@@ -214,7 +214,16 @@ TEST_F(BracesInserterTest, InsertBraces) {
                "#endif",
                Style);
 
-  verifyFormat("if (a)\n"
+  verifyFormat("if (a) {\n"
+               "  f(\n"
+               "#ifdef A\n"
+               "      1\n"
+               "#else\n"
+               "      2\n"
+               "#endif\n"
+               "  );\n"
+               "}",
+               "if (a)\n"
                "  f(\n"
                "#ifdef A\n"
                "      1\n"
@@ -224,6 +233,135 @@ TEST_F(BracesInserterTest, InsertBraces) {
                "  );",
                Style);
 
+  verifyFormat("if (a) {\n"
+               "  f(\n"
+               "#if A\n"
+               "      1\n"
+               "#else\n"
+               "#if B\n"
+               "      2\n"
+               "#else\n"
+               "      3\n"
+               "#endif\n"
+               "#endif\n"
+               "  );\n"
+               "}",
+               "if (a)\n"
+               "  f(\n"
+               "#if A\n"
+               "      1\n"
+               "#else\n"
+               "#if B\n"
+               "      2\n"
+               "#else\n"
+               "      3\n"
+               "#endif\n"
+               "#endif\n"
+               "  );",
+               Style);
+
+  verifyFormat("if (a) {\n"
+               "  if (b) {\n"
+               "#ifdef A\n"
+               "    f();\n"
+               "#endif\n"
+               "  }\n"
+               "}",
+               "if (a)\n"
+               "  if (b) {\n"
+               "#ifdef A\n"
+               "    f();\n"
+               "#endif\n"
+               "  }",
+               Style);
+
+  verifyFormat("if (a) {\n"
+               "  g([] {\n"
+               "#ifdef A\n"
+               "    f();\n"
+               "#endif\n"
+               "  });\n"
+               "}",
+               "if (a)\n"
+               "  g([] {\n"
+               "#ifdef A\n"
+               "    f();\n"
+               "#endif\n"
+               "  });",
+               Style);
+
+  verifyFormat("auto l = [] {\n"
+               "  if (a) {\n"
+               "    f(\n"
+               "#ifdef A\n"
+               "        1\n"
+               "#else\n"
+               "        2\n"
+               "#endif\n"
+               "    );\n"
+               "  }\n"
+               "};",
+               "auto l = [] {\n"
+               "  if (a)\n"
+               "    f(\n"
+               "#ifdef A\n"
+               "        1\n"
+               "#else\n"
+               "        2\n"
+               "#endif\n"
+               "    );\n"
+               "};",
+               Style);
+
+  verifyFormat("if (a)\n"
+               "  if (b)\n"
+               "#/* comment */ if A\n"
+               "    f();\n"
+               "#else\n"
+               "    g();\n"
+               "#endif",
+               Style);
+
+  verifyFormat("if (a)\n"
+               "  f(\n"
+               "#if A\n"
+               "#/* comment */\n"
+               "      endif);\n"
+               "#else\n"
+               "      2);\n"
+               "#endif",
+               Style);
+
+  verifyFormat("if (a)\n"
+               "  if (b)\n"
+               "#if A\n"
+               "    do\n"
+               "#else\n"
+               "    if (c)\n"
+               "#endif\n"
+               "      f();\n"
+               "    while (c);\n"
+               "g();",
+               Style);
+
+  verifyFormat("if (a)\n"
+               "  f(\n"
+               "#if A\n"
+               "      1\n"
+               "#else\n"
+               "      2)\n"
+               "#if B\n"
+               "      ;\n"
+               "h();\n"
+               "#else\n"
+               "      ;\n"
+               "g();\n"
+               "#endif\n"
+               "f(3\n"
+               "#endif\n"
+               "  );",
+               Style);
+
   verifyFormat("#if A\n"
                "if (a) {\n"
                "  f();\n"
@@ -369,6 +507,17 @@ TEST_F(BracesInserterTest, InsertBraces) {
                "  f();",
                Style);
 
+  Style.Macros = {"ID(x)=x"};
+  verifyFormat("if (a)\n"
+               "  ID(f(\n"
+               "#ifdef A\n"
+               "      1\n"
+               "#endif\n"
+               "      ));",
+               Style);
+
+  Style.Macros.clear();
+
   Style.RemoveBracesLLVM = true;
   verifyFormat("if (a) //\n"
                "  return b;",

>From 48663b4375d3b1c0ca840d91e24fbacc3f7c8555 Mon Sep 17 00:00:00 2001
From: Andre Sun <andsun9999 at gmail.com>
Date: Sun, 29 Nov 2026 20:56:49 -0500
Subject: [PATCH 2/2] Add comments

---
 clang/lib/Format/UnwrappedLineParser.cpp | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp
index 1f6a4b2f9a9202..00903dcb46e111 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -3050,7 +3050,8 @@ bool UnwrappedLineParser::isFollowedByConditionalElse() const {
   return false;
 }
 
-// Returns whether the body ends at RBraceTok in every preprocessor branch.
+// Scan the original tokens, including skipped branches, to check whether a
+// closing brace can follow RBraceTok in every branch.
 bool UnwrappedLineParser::canInsertBraces(const FormatToken &LBraceTok,
                                           const FormatToken &RBraceTok) const {
   const auto *It =
@@ -3067,6 +3068,7 @@ bool UnwrappedLineParser::canInsertBraces(const FormatToken &LBraceTok,
     bool HasElse = false;
   };
   SmallVector<Conditional, 2> Conditionals;
+  // Bracket nesting depth relative to the start of the body.
   int Depth = 0;
   bool InBody = false;
   bool FirstNonCommentOnLine = false;
@@ -3076,6 +3078,7 @@ bool UnwrappedLineParser::canInsertBraces(const FormatToken &LBraceTok,
     const auto &Tok = **It;
     if (Tok.HasUnescapedNewline)
       FirstNonCommentOnLine = true;
+    // All branches of a conditional must end at the same delimiter depth.
     if (Tok.is(tok::hash) && FirstNonCommentOnLine) {
       if (!InBody)
         return false;
@@ -3099,6 +3102,7 @@ bool UnwrappedLineParser::canInsertBraces(const FormatToken &LBraceTok,
           return false;
         C.EndDepth = Depth;
         if (Keyword.is(tok::pp_endif)) {
+          // Without an #else, taking no branch leaves the depth at StartDepth.
           if (!C.HasElse && Depth != C.StartDepth)
             return false;
           Conditionals.pop_back();
@@ -3120,7 +3124,8 @@ bool UnwrappedLineParser::canInsertBraces(const FormatToken &LBraceTok,
         ++Depth;
       else if (Tok.isOneOf(tok::r_paren, tok::r_square, tok::r_brace))
         --Depth;
-      // A branch must not change where the statement ends.
+      // A branch must not end or start a statement at the body's own depth, as
+      // another branch could then end the body at a different token.
       if (Depth < 0 ||
           (Depth == 0 && !Conditionals.empty() &&
            Tok.isOneOf(tok::semi, tok::r_brace, tok::kw_if, tok::kw_else,
@@ -3129,6 +3134,7 @@ bool UnwrappedLineParser::canInsertBraces(const FormatToken &LBraceTok,
         return false;
       }
     }
+    // Any conditional opened within the body must end before the closing brace.
     // Directives in a body with a configured macro call are not supported.
     if (&Tok == &RBraceTok)
       return Conditionals.empty() && !(HasDirective && HasMacroCall);



More information about the cfe-commits mailing list