[clang] [clang-format] Skip line splices when sorting C++ includes (PR #120680)
via cfe-commits
cfe-commits at lists.llvm.org
Thu Dec 19 20:06:50 PST 2024
llvmbot wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-clang-format
Author: Owen Pan (owenca)
<details>
<summary>Changes</summary>
Fixes #<!-- -->109864.
---
Full diff: https://github.com/llvm/llvm-project/pull/120680.diff
2 Files Affected:
- (modified) clang/lib/Format/Format.cpp (+8-1)
- (modified) clang/unittests/Format/SortIncludesTest.cpp (+12)
``````````diff
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index dcaac4b0d42cc5..f79f9cb1ecdd22 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -3247,7 +3247,14 @@ tooling::Replacements sortCppIncludes(const FormatStyle &Style, StringRef Code,
std::string RawStringTermination = ")\"";
for (;;) {
- auto Pos = Code.find('\n', SearchFrom);
+ size_t Pos = SearchFrom;
+ if (Code[SearchFrom] != '\n') {
+ do { // Search for the first newline while skipping line splices.
+ ++Pos;
+ Pos = Code.find('\n', Pos);
+ } while (Pos != StringRef::npos && Code[Pos - 1] == '\\');
+ }
+
StringRef Line =
Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
diff --git a/clang/unittests/Format/SortIncludesTest.cpp b/clang/unittests/Format/SortIncludesTest.cpp
index 31753825646373..cb3f8c73a04871 100644
--- a/clang/unittests/Format/SortIncludesTest.cpp
+++ b/clang/unittests/Format/SortIncludesTest.cpp
@@ -984,6 +984,18 @@ TEST_F(SortIncludesTest, SortAndDeduplicateIncludes) {
"#include <c>\n"
"#include <b>"));
+ verifyFormat("/* COPYRIGHT *\\\n"
+ "\\* (C) 2024 */\n"
+ "\n"
+ "#include <a>\n"
+ "#include <b>",
+ sort("/* COPYRIGHT *\\\n"
+ "\\* (C) 2024 */\n"
+ "\n"
+ "#include <b>\n"
+ "#include <a>\n"
+ "#include <b>"));
+
Style.IncludeBlocks = tooling::IncludeStyle::IBS_Merge;
verifyFormat("#include <a>\n"
"#include <b>\n"
``````````
</details>
https://github.com/llvm/llvm-project/pull/120680
More information about the cfe-commits
mailing list