[clang] f3b7710 - [clang-format] Correctly annotate C compound literal braces (#173771)
via cfe-commits
cfe-commits at lists.llvm.org
Sat Jan 10 20:27:09 PST 2026
Author: Lane0218
Date: 2026-01-11T04:27:04Z
New Revision: f3b7710b6b9d619a8afea49c648b340faede8707
URL: https://github.com/llvm/llvm-project/commit/f3b7710b6b9d619a8afea49c648b340faede8707
DIFF: https://github.com/llvm/llvm-project/commit/f3b7710b6b9d619a8afea49c648b340faede8707.diff
LOG: [clang-format] Correctly annotate C compound literal braces (#173771)
Fixes https://github.com/llvm/llvm-project/issues/173583
clang-format mis-formats C compound literals used in macro bodies, e.g.
`#define getAddr(v, type) &(type){v}`, treating `{...}` as a
block/function body
and reflowing the macro with backslashes and spaces.
This change:
- Recognizes `&( ... ){ ... }` patterns in macro bodies and marks the
brace as a braced-init.
- Improves parsing stability for braced lists in macro bodies.
Tests:
- FormatTests
---------
Co-authored-by: owenca <owenpiano at gmail.com>
Added:
Modified:
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/TokenAnnotatorTest.cpp
Removed:
################################################################################
diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp
index 5503df481b557..f57ef1328eac7 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2666,6 +2666,9 @@ bool UnwrappedLineParser::parseParens(TokenType AmpAmpTokenType,
RParen->setFinalizedType(TT_TypeDeclarationParen);
} else if (Prev->is(tok::greater) && RParen->Previous == LParen) {
Prev->setFinalizedType(TT_TemplateCloser);
+ } else if (FormatTok->is(tok::l_brace) && Prev->is(tok::amp) &&
+ !Prev->Previous) {
+ FormatTok->setBlockKind(BK_BracedInit);
}
}
return SeenEqual;
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 69c2c2f17b376..a04c6bea4d050 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -3943,6 +3943,10 @@ TEST_F(TokenAnnotatorTest, BraceKind) {
// Not TT_FunctionDeclarationName.
EXPECT_TOKEN(Tokens[6], tok::kw_operator, TT_Unknown);
EXPECT_BRACE_KIND(Tokens[9], BK_BracedInit);
+
+ Tokens = annotate("&(type){v}");
+ ASSERT_EQ(Tokens.size(), 8u) << Tokens;
+ EXPECT_BRACE_KIND(Tokens[4], BK_BracedInit);
}
TEST_F(TokenAnnotatorTest, UnderstandsElaboratedTypeSpecifier) {
More information about the cfe-commits
mailing list