Skip to content

Commit

Permalink
[clang-format] Fix bugs in annotating r_paren as C-style cast
Browse files Browse the repository at this point in the history
Don't annotate r_paren as TT_CastRParen if it's followed by an amp/star and
either the line is in a macro definition or a numeric_constant follows the
amp/star.

Fixes #59634.

Differential Revision: https://reviews.llvm.org/D153745
  • Loading branch information
owenca committed Jun 27, 2023
1 parent 420a204 commit 7a4cdbe
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
10 changes: 7 additions & 3 deletions clang/lib/Format/TokenAnnotator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2428,12 +2428,16 @@ class AnnotatingParser {
// If the next token after the parenthesis is a unary operator, assume
// that this is cast, unless there are unexpected tokens inside the
// parenthesis.
bool NextIsUnary =
Tok.Next->isUnaryOperator() || Tok.Next->isOneOf(tok::amp, tok::star);
if (!NextIsUnary || Tok.Next->is(tok::plus) ||
const bool NextIsAmpOrStar = Tok.Next->isOneOf(tok::amp, tok::star);
if (!(Tok.Next->isUnaryOperator() || NextIsAmpOrStar) ||
Tok.Next->is(tok::plus) ||
!Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant)) {
return false;
}
if (NextIsAmpOrStar &&
(Tok.Next->Next->is(tok::numeric_constant) || Line.InPPDirective)) {
return false;
}
// Search for unexpected tokens.
for (FormatToken *Prev = Tok.Previous; Prev != Tok.MatchingParen;
Prev = Prev->Previous) {
Expand Down
11 changes: 11 additions & 0 deletions clang/unittests/Format/TokenAnnotatorTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -554,6 +554,17 @@ TEST_F(TokenAnnotatorTest, UnderstandsCasts) {
Tokens = annotate("throw (Foo)p;");
EXPECT_EQ(Tokens.size(), 7u) << Tokens;
EXPECT_TOKEN(Tokens[3], tok::r_paren, TT_CastRParen);

Tokens = annotate("#define FOO(x) (((uint64_t)(x) * BAR) / 100)");
EXPECT_EQ(Tokens.size(), 21u) << Tokens;
EXPECT_TOKEN(Tokens[10], tok::r_paren, TT_CastRParen);
EXPECT_TOKEN(Tokens[13], tok::r_paren, TT_Unknown);
EXPECT_TOKEN(Tokens[14], tok::star, TT_BinaryOperator);

Tokens = annotate("return (Foo) & 10;");
EXPECT_EQ(Tokens.size(), 8u) << Tokens;
EXPECT_TOKEN(Tokens[3], tok::r_paren, TT_Unknown);
EXPECT_TOKEN(Tokens[4], tok::amp, TT_BinaryOperator);
}

TEST_F(TokenAnnotatorTest, UnderstandsDynamicExceptionSpecifier) {
Expand Down

0 comments on commit 7a4cdbe

Please sign in to comment.