Skip to content

[clang-format] Improve function pointer CastRParen detection. #126019

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions clang/lib/Format/TokenAnnotator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2915,14 +2915,27 @@ class AnnotatingParser {
if (Prev->is(tok::r_paren)) {
if (Prev->is(TT_CastRParen))
return false;

// Check for the second pair of parentheses.
Prev = Prev->MatchingParen;
if (!Prev)
return false;

// Now check for the first pair of parentheses.
Prev = Prev->Previous;
if (!Prev || Prev->isNot(tok::r_paren))
return false;
Prev = Prev->MatchingParen;
return Prev && Prev->is(TT_FunctionTypeLParen);
const auto *PrevMatchingParen = Prev->MatchingParen;
if (!PrevMatchingParen)
return false;

// We can quickly tell it is a function pointer type if the paren is the
// right type.
if (PrevMatchingParen->isNot(TT_Unknown))
return PrevMatchingParen->is(TT_FunctionTypeLParen);

// Otherwise check for the trailing * in the parentheses.
return Prev->Previous && Prev->Previous->is(tok::star);
}

// Search for unexpected tokens.
Expand Down
5 changes: 5 additions & 0 deletions clang/unittests/Format/TokenAnnotatorTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -874,6 +874,11 @@ TEST_F(TokenAnnotatorTest, UnderstandsCasts) {
EXPECT_TOKEN(Tokens[14], tok::r_paren, TT_CastRParen);
EXPECT_TOKEN(Tokens[15], tok::amp, TT_UnaryOperator);

Tokens = annotate("func((foo(bar::*)(void))&bar::a);");
ASSERT_EQ(Tokens.size(), 20u) << Tokens;
EXPECT_TOKEN(Tokens[12], tok::r_paren, TT_CastRParen);
EXPECT_TOKEN(Tokens[13], tok::amp, TT_UnaryOperator);

auto Style = getLLVMStyle();
Style.TypeNames.push_back("Foo");
Tokens = annotate("#define FOO(bar) foo((Foo)&bar)", Style);
Expand Down