[clang] 2e2aa8b - [clang-format] Fix a bug in DerivePointerAlignment fallback

Owen Pan via cfe-commits cfe-commits at lists.llvm.org
Fri Jan 13 12:58:45 PST 2023


Author: Owen Pan
Date: 2023-01-13T12:58:33-08:00
New Revision: 2e2aa8bb6dea365e972528ad330f575b6b6e254b

URL: https://github.com/llvm/llvm-project/commit/2e2aa8bb6dea365e972528ad330f575b6b6e254b
DIFF: https://github.com/llvm/llvm-project/commit/2e2aa8bb6dea365e972528ad330f575b6b6e254b.diff

LOG: [clang-format] Fix a bug in DerivePointerAlignment fallback

Fixes #59953.

Differential Revision: https://reviews.llvm.org/D141563

Added: 
    

Modified: 
    clang/lib/Format/Format.cpp
    clang/unittests/Format/FormatTest.cpp

Removed: 
    


################################################################################
diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 68f24fa8596a1..6b374077c602c 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -2282,9 +2282,11 @@ class Formatter : public TokenAnalyzer {
       }
     }
     if (Style.DerivePointerAlignment) {
-      Style.PointerAlignment = countVariableAlignments(AnnotatedLines) <= 0
-                                   ? FormatStyle::PAS_Left
-                                   : FormatStyle::PAS_Right;
+      const auto NetRightCount = countVariableAlignments(AnnotatedLines);
+      if (NetRightCount > 0)
+        Style.PointerAlignment = FormatStyle::PAS_Right;
+      else if (NetRightCount < 0)
+        Style.PointerAlignment = FormatStyle::PAS_Left;
       Style.ReferenceAlignment = FormatStyle::RAS_Pointer;
     }
     if (Style.Standard == FormatStyle::LS_Auto) {

diff  --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp
index 4c7c949f378a5..6fc538c4af1b9 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -10781,6 +10781,33 @@ TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
             format(Prefix + "int* x;", DerivePointerAlignment));
 }
 
+TEST_F(FormatTest, PointerAlignmentFallback) {
+  FormatStyle Style = getLLVMStyle();
+  Style.DerivePointerAlignment = true;
+
+  const StringRef Code("int* p;\n"
+                       "int *q;\n"
+                       "int * r;");
+
+  EXPECT_EQ(Style.PointerAlignment, FormatStyle::PAS_Right);
+  verifyFormat("int *p;\n"
+               "int *q;\n"
+               "int *r;",
+               Code, Style);
+
+  Style.PointerAlignment = FormatStyle::PAS_Left;
+  verifyFormat("int* p;\n"
+               "int* q;\n"
+               "int* r;",
+               Code, Style);
+
+  Style.PointerAlignment = FormatStyle::PAS_Middle;
+  verifyFormat("int * p;\n"
+               "int * q;\n"
+               "int * r;",
+               Code, Style);
+}
+
 TEST_F(FormatTest, UnderstandsNewAndDelete) {
   verifyFormat("void f() {\n"
                "  A *a = new A;\n"


        


More information about the cfe-commits mailing list