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

via cfe-commits cfe-commits at lists.llvm.org
Mon Nov 9 23:57:08 PST 2026


llvmorg-github-actions[bot] wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-clang-format

Author: Yash Aggarwal (yashaggarwal85d)

<details>
<summary>Changes</summary>

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.

---
Full diff: https://github.com/llvm/llvm-project/pull/240744.diff


2 Files Affected:

- (modified) clang/lib/Format/TokenAnnotator.cpp (+4-1) 
- (modified) clang/unittests/Format/FormatTest.cpp (+10) 


``````````diff
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) {

``````````

</details>


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


More information about the cfe-commits mailing list