[clang-format] distinguish multiplication after brace-init from pointer

After b646f09555,
the added regression test started being formatted as-if the
multiplication `*` was a pointer. This adapts the heuristic to
distinguish between these two cases.

Reviewed By: jackhong12, curdeius, HazardyKnusperkeks, owenpan

Differential Revision: https://reviews.llvm.org/D129771
This commit is contained in:
Krasimir Georgiev 2022-07-15 11:36:08 +02:00
parent 8a519b3c21
commit 8dd2ef2130
3 changed files with 15 additions and 1 deletions

View file

@ -2317,7 +2317,15 @@ private:
// After right braces, star tokens are likely to be pointers to struct,
// union, or class.
// struct {} *ptr;
if (PrevToken->is(tok::r_brace) && Tok.is(tok::star))
// This by itself is not sufficient to distinguish from multiplication
// following a brace-initialized expression, as in:
// int i = int{42} * 2;
// In the struct case, the part of the struct declaration until the `{` and
// the `}` are put on separate unwrapped lines; in the brace-initialized
// case, the matching `{` is on the same unwrapped line, so check for the
// presence of the matching brace to distinguish between those.
if (PrevToken->is(tok::r_brace) && Tok.is(tok::star) &&
!PrevToken->MatchingParen)
return TT_PointerOrReference;
// For "} &&"

View file

@ -10458,6 +10458,9 @@ TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
verifyFormat("class {\n"
"}* ptr;",
Style);
// Don't confuse a multiplication after a brace-initialized expression with
// a class pointer.
verifyFormat("int i = int{42} * 34;", Style);
verifyFormat("struct {\n"
"}&& ptr = {};",
Style);

View file

@ -111,6 +111,9 @@ TEST_F(TokenAnnotatorTest, UnderstandsUsesOfStarAndAmp) {
"} &&ptr = {};");
EXPECT_EQ(Tokens.size(), 10u) << Tokens;
EXPECT_TOKEN(Tokens[3], tok::ampamp, TT_PointerOrReference);
Tokens = annotate("int i = int{42} * 2;");
EXPECT_EQ(Tokens.size(), 11u) << Tokens;
EXPECT_TOKEN(Tokens[7], tok::star, TT_BinaryOperator);
}
TEST_F(TokenAnnotatorTest, UnderstandsUsesOfPlusAndMinus) {