From: Daniel Jasper Date: Thu, 3 Mar 2016 17:34:14 +0000 (+0000) Subject: clang-format: Use stable_sort when sorting #includes. X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=df46d8aa75582ec9cdffbc33fc5b640a79364f67;p=clang clang-format: Use stable_sort when sorting #includes. Otherwise, clang-format can output useless replacements in the presence of identical #includes git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@262630 91177308-0d34-0410-b5e6-96231b3b80d8 --- diff --git a/lib/Format/Format.cpp b/lib/Format/Format.cpp index c8f5ec9259..91eac1328a 100644 --- a/lib/Format/Format.cpp +++ b/lib/Format/Format.cpp @@ -1844,10 +1844,11 @@ static void sortIncludes(const FormatStyle &Style, SmallVector Indices; for (unsigned i = 0, e = Includes.size(); i != e; ++i) Indices.push_back(i); - std::sort(Indices.begin(), Indices.end(), [&](unsigned LHSI, unsigned RHSI) { - return std::tie(Includes[LHSI].Category, Includes[LHSI].Filename) < - std::tie(Includes[RHSI].Category, Includes[RHSI].Filename); - }); + std::stable_sort( + Indices.begin(), Indices.end(), [&](unsigned LHSI, unsigned RHSI) { + return std::tie(Includes[LHSI].Category, Includes[LHSI].Filename) < + std::tie(Includes[RHSI].Category, Includes[RHSI].Filename); + }); // If the #includes are out of order, we generate a single replacement fixing // the entire block. Otherwise, no replacement is generated. diff --git a/unittests/Format/SortIncludesTest.cpp b/unittests/Format/SortIncludesTest.cpp index dbe1174957..9e5f2675f0 100644 --- a/unittests/Format/SortIncludesTest.cpp +++ b/unittests/Format/SortIncludesTest.cpp @@ -20,8 +20,12 @@ namespace { class SortIncludesTest : public ::testing::Test { protected: - std::string sort(llvm::StringRef Code, StringRef FileName = "input.cpp") { - std::vector Ranges(1, tooling::Range(0, Code.size())); + std::vector GetCodeRange(StringRef Code) { + return std::vector(1, tooling::Range(0, Code.size())); + } + + std::string sort(StringRef Code, StringRef FileName = "input.cpp") { + auto Ranges = GetCodeRange(Code); std::string Sorted = applyAllReplacements(Code, sortIncludes(Style, Code, Ranges, FileName)); return applyAllReplacements(Sorted, @@ -29,8 +33,7 @@ protected: } unsigned newCursor(llvm::StringRef Code, unsigned Cursor) { - std::vector Ranges(1, tooling::Range(0, Code.size())); - sortIncludes(Style, Code, Ranges, "input.cpp", &Cursor); + sortIncludes(Style, Code, GetCodeRange(Code), "input.cpp", &Cursor); return Cursor; } @@ -47,6 +50,17 @@ TEST_F(SortIncludesTest, BasicSorting) { "#include \"b.h\"\n")); } +TEST_F(SortIncludesTest, NoReplacementsForValidIncludes) { + // Identical #includes have led to a failure with an unstable sort. + std::string Code = "#include \n" + "#include \n" + "#include \n" + "#include \n" + "#include \n" + "#include \n"; + EXPECT_TRUE(sortIncludes(Style, Code, GetCodeRange(Code), "a.cc").empty()); +} + TEST_F(SortIncludesTest, SupportClangFormatOff) { EXPECT_EQ("#include \n" "#include \n"