[clang] [clang-format] Fix designated initializer detection (PR #169228)
Daan De Meyer via cfe-commits
cfe-commits at lists.llvm.org
Mon Nov 24 02:04:37 PST 2025
https://github.com/DaanDeMeyer updated https://github.com/llvm/llvm-project/pull/169228
>From f578078b252a513d5c039828be3263f5dcbe1577 Mon Sep 17 00:00:00 2001
From: Daan De Meyer <daan.j.demeyer at gmail.com>
Date: Sun, 23 Nov 2025 19:20:25 +0100
Subject: [PATCH] [clang-format] Fix designated initializer detection
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};
```
---
clang/lib/Format/TokenAnnotator.cpp | 5 +++++
clang/unittests/Format/TokenAnnotatorTest.cpp | 5 +++++
2 files changed, 10 insertions(+)
diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp
index cb41756c56bf7..ac9ecd4aeea0c 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -708,6 +708,11 @@ class AnnotatingParser {
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) ||
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 815c79e68dac9..a6fa9cf9d18de 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -3361,6 +3361,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) {
More information about the cfe-commits
mailing list