[clang] [clang-format] Keep compound literals stable in macro bodies (PR #173771)

via cfe-commits cfe-commits at lists.llvm.org
Sun Dec 28 18:44:30 PST 2025


Lane0218 wrote:

> Looks like all we need is this:
> 
> ```diff
> diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp
> index c1a9161b1072..775fb9b7b3ed 100644
> --- a/clang/lib/Format/UnwrappedLineParser.cpp
> +++ b/clang/lib/Format/UnwrappedLineParser.cpp
> @@ -2664,6 +2664,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);
>          } else if (OptionalParens()) {
>            LParen->Optional = true;
>            RParen->Optional = true;
> diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp b/clang/unittests/Format/TokenAnnotatorTest.cpp
> index 69c2c2f17b37..a04c6bea4d05 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) {
> ```

Hi @owenca, thanks for the concrete suggestion.

I updated the implementation to match your proposed approach by setting the `{` following `&(type)` to `BK_BracedInit` in `UnwrappedLineParser::parseParens(...)`, and I added the `TokenAnnotatorTest` coverage for `&(type){v}` (asserting the `{` is `BK_BracedInit`). I also cleaned up the macro regression test to use `verifyFormat` and removed the `getAddr2` case since its expansion is not a meaningful C/C++ snippet.

Tests: FormatTests



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


More information about the cfe-commits mailing list