[clang] [clang-format] Fix a bug in annotating operator functions (PR #165351)

via cfe-commits cfe-commits at lists.llvm.org
Mon Oct 27 21:49:27 PDT 2025


https://github.com/owenca created https://github.com/llvm/llvm-project/pull/165351

Fixes #164866

>From 85036b258697d6c279d9b8150530ef8d2f6e29b6 Mon Sep 17 00:00:00 2001
From: Owen Pan <owenpiano at gmail.com>
Date: Mon, 27 Oct 2025 21:42:03 -0700
Subject: [PATCH] [clang-format] Fix a bug in annotating operator functions

Fixes #164866
---
 clang/lib/Format/TokenAnnotator.cpp           | 11 +++++++----
 clang/unittests/Format/TokenAnnotatorTest.cpp |  5 +++++
 2 files changed, 12 insertions(+), 4 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp
index 1d0dfd0b9c151..f4ea3948c14c4 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2646,9 +2646,9 @@ class AnnotatingParser {
         return false;
     }
 
-    bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
-                       PreviousNotConst->Previous &&
-                       PreviousNotConst->Previous->is(tok::hash);
+    const auto *PrevPrev = PreviousNotConst->Previous;
+    const bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
+                             PrevPrev && PrevPrev->is(tok::hash);
 
     if (PreviousNotConst->is(TT_TemplateCloser)) {
       return PreviousNotConst && PreviousNotConst->MatchingParen &&
@@ -2674,8 +2674,11 @@ class AnnotatingParser {
     }
 
     // *a or &a or &&a.
-    if (PreviousNotConst->is(TT_PointerOrReference))
+    if (PreviousNotConst->is(TT_PointerOrReference) ||
+        (PreviousNotConst->is(tok::coloncolon) && PrevPrev &&
+         PrevPrev->is(TT_PointerOrReference))) {
       return true;
+    }
 
     // MyClass a;
     if (PreviousNotConst->isTypeName(LangOpts))
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp b/clang/unittests/Format/TokenAnnotatorTest.cpp
index ca99940890984..86e21775ad9ed 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -2344,6 +2344,11 @@ TEST_F(TokenAnnotatorTest, UnderstandsFunctionDeclarationNames) {
   EXPECT_TOKEN(Tokens[2], tok::identifier, TT_FunctionDeclarationName);
   EXPECT_TOKEN(Tokens[3], tok::l_paren, TT_FunctionDeclarationLParen);
 
+  Tokens = annotate("::foo::bar& ::foo::bar::operator=(::foo::bar& other);");
+  ASSERT_EQ(Tokens.size(), 22u) << Tokens;
+  EXPECT_TOKEN(Tokens[6], tok::identifier, TT_FunctionDeclarationName);
+  EXPECT_TOKEN(Tokens[17], tok::amp, TT_PointerOrReference);
+
   Tokens = annotate("int iso_time(time_t);");
   ASSERT_EQ(Tokens.size(), 7u) << Tokens;
   EXPECT_TOKEN(Tokens[1], tok::identifier, TT_FunctionDeclarationName);



More information about the cfe-commits mailing list