[clang] [clang-format] Fix InsertBraces rebinding an else in a preprocessor branch (PR #239414)

Andre Sun via cfe-commits cfe-commits at lists.llvm.org
Sun Nov 22 19:43:50 PST 2026


================
@@ -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;
+
----------------
and2049 wrote:

Skipping insertion whenever a preprocessor conditional follows would also suppress braces before an unrelated `#if`, where main currently inserts them. I'd prefer to preserve that behavior by checking for a possible `else`.

Much of the complexity comes from excluding unreachable branches, such as an `else` under `#if 0` / `#elif 0`. Preserving insertion in those cases requires tracking reachability across nested conditionals and checking the whole condition so that `#if 0 || A` isn't treated as unreachable.

I'd lean towards keeping that tracking so the output matches main in those cases, but they are rarer than an unrelated `#if`, so if complexity is a concern, I can drop the tracking and skip insertion whenever an `else` directly follows a directive.

https://github.com/llvm/llvm-project/pull/239414


More information about the cfe-commits mailing list