[clang] fix: no update cursor pos in sort includes if no replacement (PR #77456)

via cfe-commits cfe-commits at lists.llvm.org
Tue Jan 9 05:01:31 PST 2024


https://github.com/NorthBlue333 updated https://github.com/llvm/llvm-project/pull/77456

>From 48907435d55bf30ad6fb730784f4f6cdaf1be6a9 Mon Sep 17 00:00:00 2001
From: NorthBlue333 <north333 at free.fr>
Date: Tue, 9 Jan 2024 14:01:14 +0100
Subject: [PATCH] [clang-format] Do not update cursor pos if no includes
 replacement

---
 clang/lib/Format/Format.cpp | 14 ++++++++++----
 1 file changed, 10 insertions(+), 4 deletions(-)

diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index f798d555bf9929..a91f6a639fb00b 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -3119,6 +3119,7 @@ static void sortCppIncludes(const FormatStyle &Style,
     return;
   }
 
+  unsigned NewCursor = UINT_MAX;
   std::string result;
   for (unsigned Index : Indices) {
     if (!result.empty()) {
@@ -3131,13 +3132,10 @@ static void sortCppIncludes(const FormatStyle &Style,
     }
     result += Includes[Index].Text;
     if (Cursor && CursorIndex == Index)
-      *Cursor = IncludesBeginOffset + result.size() - CursorToEOLOffset;
+      NewCursor = IncludesBeginOffset + result.size() - CursorToEOLOffset;
     CurrentCategory = Includes[Index].Category;
   }
 
-  if (Cursor && *Cursor >= IncludesEndOffset)
-    *Cursor += result.size() - IncludesBlockSize;
-
   // If the #includes are out of order, we generate a single replacement fixing
   // the entire range of blocks. Otherwise, no replacement is generated.
   if (replaceCRLF(result) == replaceCRLF(std::string(Code.substr(
@@ -3145,6 +3143,14 @@ static void sortCppIncludes(const FormatStyle &Style,
     return;
   }
 
+  if (Cursor) {
+    if (UINT_MAX != NewCursor) {
+      *Cursor = NewCursor;
+    } else if (*Cursor >= IncludesEndOffset) {
+      *Cursor += result.size() - IncludesBlockSize;
+    }
+  }
+
   auto Err = Replaces.add(tooling::Replacement(
       FileName, Includes.front().Offset, IncludesBlockSize, result));
   // FIXME: better error handling. For now, just skip the replacement for the



More information about the cfe-commits mailing list