[clang] [clang-format] Fix anonymous reference parameter with default value (PR #86254)

via cfe-commits cfe-commits at lists.llvm.org
Fri Mar 22 00:21:27 PDT 2024


https://github.com/rayroudc created https://github.com/llvm/llvm-project/pull/86254

When enabling alignment of consecutive declarations and reference right alignment, the needed space between `& ` and ` = ` is removed in the following use case.

Problem (does not compile)
```
int    a(const Test    &= Test());
double b();
```

Expected:
```
int    a(const Test & = Test());
double b();
```

Test command:

```
echo "int    a(const Test& = Test()); double b();"  | clang-format -style="{AlignConsecutiveDeclarations: true, ReferenceAlignment: Right}"
```

>From 3feaef98f0b47de919146e05daeb37552bfea36a Mon Sep 17 00:00:00 2001
From: "C. Rayroud" <rayroudc at gmail.com>
Date: Mon, 18 Mar 2024 06:39:26 +0000
Subject: [PATCH] [clang-format] Fix anonymous reference parameter with default
 value

---
 clang/lib/Format/WhitespaceManager.cpp | 4 ++++
 clang/unittests/Format/FormatTest.cpp  | 7 +++++++
 2 files changed, 11 insertions(+)

diff --git a/clang/lib/Format/WhitespaceManager.cpp b/clang/lib/Format/WhitespaceManager.cpp
index 6577c19cdf7978..c4a7d54e5bc8ed 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -471,6 +471,10 @@ AlignTokenSequence(const FormatStyle &Style, unsigned Start, unsigned End,
            Previous >= 0 &&
            Changes[Previous].Tok->getType() == TT_PointerOrReference;
            --Previous) {
+        // Don't align function default argument using return type maximum size
+        if (Changes[Previous + 1].Tok->is(tok::equal)) {
+          continue;
+        }
         assert(Changes[Previous].Tok->isPointerOrReference());
         if (Changes[Previous].Tok->isNot(tok::star)) {
           if (ReferenceNotRightAligned)
diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp
index a14b002c37c631..23169363542ec1 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -19056,6 +19056,9 @@ TEST_F(FormatTest, AlignConsecutiveDeclarations) {
   verifyFormat("int    a(int x);\n"
                "double b();",
                Alignment);
+  verifyFormat("int    a(const Test & = Test());\n"
+               "double b();",
+               Alignment);
   verifyFormat("struct Test {\n"
                "  Test(const Test &) = default;\n"
                "  ~Test() = default;\n"
@@ -19277,6 +19280,10 @@ TEST_F(FormatTest, AlignConsecutiveDeclarations) {
                "int    foobar;",
                AlignmentLeft);
 
+  verifyFormat("int    a(const Test& = Test());\n"
+               "double b();",
+               AlignmentLeft);
+
   // PAS_Middle
   FormatStyle AlignmentMiddle = Alignment;
   AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle;



More information about the cfe-commits mailing list