[clang-format] Fix RAS reference alignment when PAS is left or middle
authorGedare Bloom <gedare@rtems.org>
Thu, 6 Jul 2023 08:36:31 +0000 (01:36 -0700)
committerOwen Pan <owenpiano@gmail.com>
Thu, 6 Jul 2023 08:41:16 +0000 (01:41 -0700)
Fixes a bug with the handling of right aligned references with left/middle
alignment pointers.

Fixes #63452.

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

clang/lib/Format/WhitespaceManager.cpp
clang/unittests/Format/FormatTest.cpp

index 2425552..18e9e04 100644 (file)
@@ -445,12 +445,24 @@ AlignTokenSequence(const FormatStyle &Style, unsigned Start, unsigned End,
       Changes[i + 1].PreviousEndOfTokenColumn += Shift;
 
     // If PointerAlignment is PAS_Right, keep *s or &s next to the token
-    if (Style.PointerAlignment == FormatStyle::PAS_Right &&
+    if ((Style.PointerAlignment == FormatStyle::PAS_Right ||
+         Style.ReferenceAlignment == FormatStyle::RAS_Right) &&
         Changes[i].Spaces != 0) {
+      const bool ReferenceNotRightAligned =
+          Style.ReferenceAlignment != FormatStyle::RAS_Right &&
+          Style.ReferenceAlignment != FormatStyle::RAS_Pointer;
       for (int Previous = i - 1;
            Previous >= 0 &&
            Changes[Previous].Tok->getType() == TT_PointerOrReference;
            --Previous) {
+        assert(
+            Changes[Previous].Tok->isOneOf(tok::star, tok::amp, tok::ampamp));
+        if (Changes[Previous].Tok->isNot(tok::star)) {
+          if (ReferenceNotRightAligned)
+            continue;
+        } else if (Style.PointerAlignment != FormatStyle::PAS_Right) {
+          continue;
+        }
         Changes[Previous + 1].Spaces -= Shift;
         Changes[Previous].Spaces += Shift;
         Changes[Previous].StartOfTokenColumn += Shift;
index a4f2b83..e0a0a0d 100644 (file)
@@ -2189,6 +2189,15 @@ TEST_F(FormatTest, SeparatePointerReferenceAlignment) {
   verifyFormat("for (int a = 0, b = 0; const Foo * c : {1, 2, 3})", Style);
   verifyFormat("for (int a = 0, b++; const Foo * c : {1, 2, 3})", Style);
 
+  Style.AlignConsecutiveDeclarations.Enabled = true;
+  verifyFormat("Const unsigned int * c;\n"
+               "const unsigned int * d;\n"
+               "Const unsigned int  &e;\n"
+               "const unsigned int  &f;\n"
+               "const unsigned     &&g;\n"
+               "Const unsigned       h;",
+               Style);
+
   // FIXME: we don't handle this yet, so output may be arbitrary until it's
   // specifically handled
   // verifyFormat("int Add2(BTree * &Root, char * szToAdd)", Style);