Skip to content

Commit 7b186e4

Browse files
authored
[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}; ```
1 parent 48eb697 commit 7b186e4

File tree

2 files changed

+10
-0
lines changed

2 files changed

+10
-0
lines changed

clang/lib/Format/TokenAnnotator.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -708,6 +708,11 @@ class AnnotatingParser {
708708
IsCpp && !IsCpp11AttributeSpecifier && !IsCSharpAttributeSpecifier &&
709709
Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) &&
710710
CurrentToken->isNoneOf(tok::l_brace, tok::r_square) &&
711+
// Do not consider '[' after a comma inside a braced initializer the
712+
// start of an ObjC method expression. In braced initializer lists,
713+
// commas are list separators and should not trigger ObjC parsing.
714+
(!Parent || !Parent->is(tok::comma) ||
715+
Contexts.back().ContextKind != tok::l_brace) &&
711716
(!Parent ||
712717
Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
713718
tok::kw_return, tok::kw_throw) ||

clang/unittests/Format/TokenAnnotatorTest.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3370,6 +3370,11 @@ TEST_F(TokenAnnotatorTest, UnderstandDesignatedInitializers) {
33703370
ASSERT_EQ(Tokens.size(), 14u) << Tokens;
33713371
EXPECT_TOKEN(Tokens[6], tok::l_square, TT_DesignatedInitializerLSquare);
33723372
EXPECT_BRACE_KIND(Tokens[9], BK_BracedInit);
3373+
3374+
Tokens = annotate("Foo foo[] = {[0] = 1, [1] = 2};");
3375+
ASSERT_EQ(Tokens.size(), 20u) << Tokens;
3376+
EXPECT_TOKEN(Tokens[6], tok::l_square, TT_DesignatedInitializerLSquare);
3377+
EXPECT_TOKEN(Tokens[12], tok::l_square, TT_DesignatedInitializerLSquare);
33733378
}
33743379

33753380
TEST_F(TokenAnnotatorTest, UnderstandsJavaScript) {

0 commit comments

Comments
 (0)