[clang-format] Correctly limit formatted ranges when specifying qualifier alignment
authorColin Ogilvie <colin.ogilvie@kdab.com>
Thu, 4 May 2023 09:48:51 +0000 (02:48 -0700)
committerOwen Pan <owenpiano@gmail.com>
Thu, 4 May 2023 09:59:05 +0000 (02:59 -0700)
The qualifier alignment fixer appeared to ignore any ranges specified for limiting formatting.
This change ensures that it only formats affected lines to avoid unexpected changes.

Fixes #54888.

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

clang/lib/Format/QualifierAlignmentFixer.cpp
clang/unittests/Format/QualifierFixerTest.cpp

index 5142a83efdd45428d61c8a35b232fe10194118e1..ff54fb75b3dd98fb29f99a65317a971967435ab7 100644 (file)
@@ -587,7 +587,7 @@ LeftRightQualifierAlignmentFixer::analyze(
   assert(QualifierToken != tok::identifier && "Unrecognised Qualifier");
 
   for (AnnotatedLine *Line : AnnotatedLines) {
-    if (Line->InPPDirective)
+    if (!Line->Affected || Line->InPPDirective)
       continue;
     FormatToken *First = Line->First;
     assert(First);
index 76800b3fc8e375d836ae03aeddb2c80d0b8d7692..9760c80dcc61983f3c5f48cdb80721b2e9caabe4 100755 (executable)
@@ -1343,6 +1343,29 @@ TEST_F(QualifierFixerTest, TemplatesLeft) {
                "TemplateType<Container const> t;", Style);
 }
 
+TEST_F(QualifierFixerTest, Ranges) {
+  FormatStyle Style = getLLVMStyle();
+  Style.QualifierAlignment = FormatStyle::QAS_Custom;
+  Style.QualifierOrder = {"const", "volatile", "type"};
+
+  // Only the first line should be formatted; the second should remain as is.
+  verifyFormat("template <typename T> const Foo f();\n"
+               "template <typename T> Foo const f();",
+               "template <typename T> Foo const f();\n"
+               "template <typename T> Foo const f();",
+               Style, {tooling::Range(0, 36)});
+
+  // Only the middle line should be formatted; the first and last should remain
+  // as is.
+  verifyFormat("template <typename T> Foo const f();\n"
+               "template <typename T> const Foo f();\n"
+               "template <typename T> Foo const f();",
+               "template <typename T> Foo const f();\n"
+               "template <typename T> Foo const f();\n"
+               "template <typename T> Foo const f();",
+               Style, {tooling::Range(37, 36)});
+}
+
 } // namespace
 } // namespace test
 } // namespace format