[clang] 9512d6d - [clang-format] Fix parsing of `operator<() {}` (#75144)

via cfe-commits cfe-commits at lists.llvm.org
Wed Dec 13 11:58:01 PST 2023


Author: XDeme
Date: 2023-12-13T11:57:56-08:00
New Revision: 9512d6d2133a15a3e6272cbadd7fbb479011ccdb

URL: https://github.com/llvm/llvm-project/commit/9512d6d2133a15a3e6272cbadd7fbb479011ccdb
DIFF: https://github.com/llvm/llvm-project/commit/9512d6d2133a15a3e6272cbadd7fbb479011ccdb.diff

LOG: [clang-format] Fix parsing of `operator<() {}` (#75144)

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`.

Added: 
    

Modified: 
    clang/lib/Format/TokenAnnotator.cpp
    clang/unittests/Format/TokenAnnotatorTest.cpp

Removed: 
    


################################################################################
diff  --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp
index febd6830eca1e2..f3551af3424396 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -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;

diff  --git a/clang/unittests/Format/TokenAnnotatorTest.cpp b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 65b1f0f4b57659..8e6935319b2f3d 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -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) {


        


More information about the cfe-commits mailing list