[clang] [clang-format] Fix a crash in UseBreakAfter on an unmatched brace (PR #240744)

Yash Aggarwal via cfe-commits cfe-commits at lists.llvm.org
Mon Nov 9 23:56:27 PST 2026


https://github.com/yashaggarwal85d created https://github.com/llvm/llvm-project/pull/240744

With `BinPack: UseBreakAfter`, the loop that adds breaks between arguments skips nested brackets by jumping to their `MatchingParen`. When a nested bracket isn't closed on the same line, for example because a `;` in an inactive `#else` branch splits the line, `MatchingParen` is null and the loop dereferences it.

Stop the loop in that case. The tokens after the unclosed bracket are nested inside it, so they aren't arguments of the outer bracket anyway.

Fixes #233301

AI-assisted; I reviewed and tested the change.

>From 940bbe1605dc24f60cff1847f4ab2d70de463ec7 Mon Sep 17 00:00:00 2001
From: Yash Aggarwal <68061195+yashaggarwal85d at users.noreply.github.com>
Date: Tue, 27 Oct 2026 10:56:02 +0000
Subject: [PATCH] [clang-format] Fix a crash in UseBreakAfter on an unmatched
 brace

---
 clang/lib/Format/TokenAnnotator.cpp   |  5 ++++-
 clang/unittests/Format/FormatTest.cpp | 10 ++++++++++
 2 files changed, 14 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp
index 9bbce9552bb9de..e4caddf8fca798 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -4364,8 +4364,11 @@ void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) const {
           ParamTok->MustBreakBefore = true;
           ParamTok->CanBreakBefore = true;
         }
-        if (ParamTok->opensScope())
+        if (ParamTok->opensScope()) {
           ParamTok = ParamTok->MatchingParen;
+          if (!ParamTok)
+            break;
+        }
       }
     }
 
diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp
index f38287757ffba1..85c506b1c6fde9 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -8439,6 +8439,16 @@ TEST_F(FormatTest, BreakFunctionDefinitionParameters) {
                "         d);\n"
                "}",
                Style);
+
+  Style.PackArguments.BreakAfter = 0;
+  verifyFormat("int x[] = {{\n"
+               "#if 1\n"
+               "    0\n"
+               "#else\n"
+               "    ;\n"
+               "#endif\n"
+               "}};",
+               Style);
 }
 
 TEST_F(FormatTest, BreakBeforeInlineASMColon) {



More information about the cfe-commits mailing list