[clang-format] Fix designated initializer detection (#169228)

Currently, in the following snippet, the second designated initializer
is incorrectly detected as an OBJC method expr. Fix that and a test to
make sure we don't regress.

```
Foo foo[] = {[0] = 1, [1] = 2};
```
This commit is contained in:
Daan De Meyer
2025-11-24 20:26:07 +01:00
committed by GitHub
parent 48eb697441
commit 7b186e4bf0
2 changed files with 10 additions and 0 deletions

View File

@@ -708,6 +708,11 @@ private:
IsCpp && !IsCpp11AttributeSpecifier && !IsCSharpAttributeSpecifier &&
Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) &&
CurrentToken->isNoneOf(tok::l_brace, tok::r_square) &&
// Do not consider '[' after a comma inside a braced initializer the
// start of an ObjC method expression. In braced initializer lists,
// commas are list separators and should not trigger ObjC parsing.
(!Parent || !Parent->is(tok::comma) ||
Contexts.back().ContextKind != tok::l_brace) &&
(!Parent ||
Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
tok::kw_return, tok::kw_throw) ||

View File

@@ -3370,6 +3370,11 @@ TEST_F(TokenAnnotatorTest, UnderstandDesignatedInitializers) {
ASSERT_EQ(Tokens.size(), 14u) << Tokens;
EXPECT_TOKEN(Tokens[6], tok::l_square, TT_DesignatedInitializerLSquare);
EXPECT_BRACE_KIND(Tokens[9], BK_BracedInit);
Tokens = annotate("Foo foo[] = {[0] = 1, [1] = 2};");
ASSERT_EQ(Tokens.size(), 20u) << Tokens;
EXPECT_TOKEN(Tokens[6], tok::l_square, TT_DesignatedInitializerLSquare);
EXPECT_TOKEN(Tokens[12], tok::l_square, TT_DesignatedInitializerLSquare);
}
TEST_F(TokenAnnotatorTest, UnderstandsJavaScript) {