From e217acab66a45cb61e1e22b7dc3d1470fb18e62c Mon Sep 17 00:00:00 2001 From: Alex Lorenz Date: Thu, 24 Jan 2019 23:07:58 +0000 Subject: [PATCH] [clang-format] square parens with one token are not Objective-C message sends The commit r322690 introduced support for ObjC detection in header files. Unfortunately some C headers that use designated initializers are now incorrectly detected as Objective-C. This commit fixes it by ensuring that `[ token ]` is not annotated as an Objective-C message send. rdar://45504376 Differential Revision: https://reviews.llvm.org/D56226 git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@352125 91177308-0d34-0410-b5e6-96231b3b80d8 --- lib/Format/TokenAnnotator.cpp | 9 +++++++-- unittests/Format/FormatTestObjC.cpp | 14 ++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/lib/Format/TokenAnnotator.cpp b/lib/Format/TokenAnnotator.cpp index bd824f1e17..1c93c8c6cc 100644 --- a/lib/Format/TokenAnnotator.cpp +++ b/lib/Format/TokenAnnotator.cpp @@ -494,9 +494,14 @@ private: if (CurrentToken->is(tok::r_square)) { if (IsCpp11AttributeSpecifier) CurrentToken->Type = TT_AttributeSquare; - else if (CurrentToken->Next && CurrentToken->Next->is(tok::l_paren) && + else if (((CurrentToken->Next && + CurrentToken->Next->is(tok::l_paren)) || + (CurrentToken->Previous && + CurrentToken->Previous->Previous == Left)) && Left->is(TT_ObjCMethodExpr)) { - // An ObjC method call is rarely followed by an open parenthesis. + // An ObjC method call is rarely followed by an open parenthesis. It + // also can't be composed of just one token, unless it's a macro that + // will be expanded to more tokens. // FIXME: Do we incorrectly label ":" with this? StartsObjCMethodExpr = false; Left->Type = TT_Unknown; diff --git a/unittests/Format/FormatTestObjC.cpp b/unittests/Format/FormatTestObjC.cpp index 2cb3f9f111..0d3a5d85bb 100644 --- a/unittests/Format/FormatTestObjC.cpp +++ b/unittests/Format/FormatTestObjC.cpp @@ -165,6 +165,20 @@ TEST(FormatTestObjCStyle, DetectsObjCInHeaders) { EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language); } +TEST(FormatTestObjCStyle, AvoidDetectingDesignatedInitializersAsObjCInHeaders) { + auto Style = getStyle("LLVM", "a.h", "none", + "static const char *names[] = {[0] = \"foo\",\n" + "[kBar] = \"bar\"};"); + ASSERT_TRUE((bool)Style); + EXPECT_EQ(FormatStyle::LK_Cpp, Style->Language); + + Style = getStyle("LLVM", "a.h", "none", + "static const char *names[] = {[0] EQ \"foo\",\n" + "[kBar] EQ \"bar\"};"); + ASSERT_TRUE((bool)Style); + EXPECT_EQ(FormatStyle::LK_Cpp, Style->Language); +} + TEST_F(FormatTestObjC, FormatObjCTryCatch) { verifyFormat("@try {\n" " f();\n" -- 2.50.1