Skip to content

Commit 70de684

Browse files
committed
[clang-format] Handle object instansiation in if-statements
Before this patch code like this: ``` if (Class* obj{getObject()}) { } ``` would be mis-formated since the * would be annotated as a binaryoperator. This patch changes the * to become a PointerOrReference instead and fixes the formatting issues. Reviewed By: HazardyKnusperkeks Differential Revision: https://reviews.llvm.org/D137327
1 parent 9a3b969 commit 70de684

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

clang/lib/Format/TokenAnnotator.cpp

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -362,7 +362,8 @@ class AnnotatingParser {
362362
FormatToken *Next = CurrentToken->Next;
363363
if (PrevPrev && PrevPrev->is(tok::identifier) &&
364364
Prev->isOneOf(tok::star, tok::amp, tok::ampamp) &&
365-
CurrentToken->is(tok::identifier) && Next->isNot(tok::equal)) {
365+
CurrentToken->is(tok::identifier) &&
366+
!Next->isOneOf(tok::equal, tok::l_brace)) {
366367
Prev->setType(TT_BinaryOperator);
367368
LookForDecls = false;
368369
}
@@ -2387,6 +2388,12 @@ class AnnotatingParser {
23872388
return TT_PointerOrReference;
23882389
}
23892390

2391+
// if (Class* obj { function() })
2392+
if (PrevToken->Tok.isAnyIdentifier() && NextToken->Tok.isAnyIdentifier() &&
2393+
NextToken->Next && NextToken->Next->is(tok::l_brace)) {
2394+
return TT_PointerOrReference;
2395+
}
2396+
23902397
if (PrevToken->endsSequence(tok::r_square, tok::l_square, tok::kw_delete))
23912398
return TT_UnaryOperator;
23922399

clang/unittests/Format/TokenAnnotatorTest.cpp

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,18 @@ TEST_F(TokenAnnotatorTest, UnderstandsUsesOfStarAndAmp) {
145145
EXPECT_TOKEN(Tokens[6], tok::l_paren, TT_FunctionTypeLParen);
146146
EXPECT_TOKEN(Tokens[7], tok::star, TT_UnaryOperator);
147147
EXPECT_TOKEN(Tokens[12], tok::star, TT_PointerOrReference);
148+
149+
Tokens = annotate("if (Foo * Bar / Test)");
150+
ASSERT_EQ(Tokens.size(), 9u) << Tokens;
151+
EXPECT_TOKEN(Tokens[3], tok::star, TT_BinaryOperator);
152+
153+
Tokens = annotate("if (Class* obj {getObj()})");
154+
ASSERT_EQ(Tokens.size(), 12u) << Tokens;
155+
EXPECT_TOKEN(Tokens[3], tok::star, TT_PointerOrReference);
156+
157+
Tokens = annotate("if (Foo* Bar = getObj())");
158+
ASSERT_EQ(Tokens.size(), 11u) << Tokens;
159+
EXPECT_TOKEN(Tokens[3], tok::star, TT_PointerOrReference);
148160
}
149161

150162
TEST_F(TokenAnnotatorTest, UnderstandsUsesOfPlusAndMinus) {

0 commit comments

Comments
 (0)