Skip to content

Commit

Permalink
[clang-format] Fix parsing of operator<() {} (#75144)
Browse files Browse the repository at this point in the history
Fixes #74876.

During the parsing of `operator<(Foo&) {}`, there was no handling for
the operator<, so it called `consumeToken()` again, causing the
`AnnotationParser::Scopes` to have one additional left brace each time
it tried to parse it, leaving it unbalanced.
Because of this, in the following code:
```cpp
class Foo {
  void operator<(Foo&) {}
  Foo& f;
};
```
The `&` in the reference member, was being interpreted as
`TT_BinaryOperator` instead of `TT_PointerOrReference`.
  • Loading branch information
XDeme1 committed Dec 13, 2023
1 parent ddd13b6 commit 9512d6d
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
4 changes: 4 additions & 0 deletions clang/lib/Format/TokenAnnotator.cpp
Expand Up @@ -164,6 +164,10 @@ class AnnotatingParser {
TT_OverloadedOperatorLParen))) {
return false;
}
if (Previous.Previous->is(tok::kw_operator) &&
CurrentToken->is(tok::l_paren)) {
return false;
}
}

FormatToken *Left = CurrentToken->Previous;
Expand Down
11 changes: 11 additions & 0 deletions clang/unittests/Format/TokenAnnotatorTest.cpp
Expand Up @@ -298,6 +298,17 @@ TEST_F(TokenAnnotatorTest, UnderstandsUsesOfStarAndAmp) {
ASSERT_EQ(Tokens.size(), 12u) << Tokens;
EXPECT_TOKEN(Tokens[2], tok::identifier, TT_TypeName);
EXPECT_TOKEN(Tokens[3], tok::star, TT_PointerOrReference);

Tokens = annotate("class Foo {\n"
" void operator<() {}\n"
" Foo &f;\n"
"};");
ASSERT_EQ(Tokens.size(), 17u) << Tokens;
EXPECT_TOKEN(Tokens[4], tok::kw_operator, TT_FunctionDeclarationName);
EXPECT_TOKEN(Tokens[5], tok::less, TT_OverloadedOperator);
EXPECT_TOKEN(Tokens[6], tok::l_paren, TT_OverloadedOperatorLParen);
EXPECT_TOKEN(Tokens[8], tok::l_brace, TT_FunctionLBrace);
EXPECT_TOKEN(Tokens[11], tok::amp, TT_PointerOrReference);
}

TEST_F(TokenAnnotatorTest, UnderstandsUsesOfPlusAndMinus) {
Expand Down

0 comments on commit 9512d6d

Please sign in to comment.