From 9635a67e3c7b5dfde83429adaf7ef39c9b0a0ee3 Mon Sep 17 00:00:00 2001 From: Eric Liu Date: Wed, 18 May 2016 13:43:48 +0000 Subject: [PATCH] [clang-format] Make formatReplacements() also sort #includes. Summary: [clang-format] Make formatReplacements() also sort #includes. Reviewers: bkramer, djasper Subscribers: klimek, cfe-commits Differential Revision: http://reviews.llvm.org/D20362 git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@269924 91177308-0d34-0410-b5e6-96231b3b80d8 --- lib/Format/Format.cpp | 12 +++++++++++- unittests/Format/FormatTest.cpp | 25 +++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/lib/Format/Format.cpp b/lib/Format/Format.cpp index c31e618520..a70a7ef2a3 100644 --- a/lib/Format/Format.cpp +++ b/lib/Format/Format.cpp @@ -2140,13 +2140,23 @@ tooling::Replacements formatReplacements(StringRef Code, const tooling::Replacements &Replaces, const FormatStyle &Style) { // We need to use lambda function here since there are two versions of + // `sortIncludes`. + auto SortIncludes = [](const FormatStyle &Style, StringRef Code, + std::vector Ranges, + StringRef FileName) -> tooling::Replacements { + return sortIncludes(Style, Code, Ranges, FileName); + }; + tooling::Replacements SortedReplaces = + processReplacements(SortIncludes, Code, Replaces, Style); + + // We need to use lambda function here since there are two versions of // `reformat`. auto Reformat = [](const FormatStyle &Style, StringRef Code, std::vector Ranges, StringRef FileName) -> tooling::Replacements { return reformat(Style, Code, Ranges, FileName); }; - return processReplacements(Reformat, Code, Replaces, Style); + return processReplacements(Reformat, Code, SortedReplaces, Style); } tooling::Replacements diff --git a/unittests/Format/FormatTest.cpp b/unittests/Format/FormatTest.cpp index 3c72a13bf1..1b434eb8c9 100644 --- a/unittests/Format/FormatTest.cpp +++ b/unittests/Format/FormatTest.cpp @@ -11559,6 +11559,31 @@ TEST_F(ReplacementTest, FixOnlyAffectedCodeAfterReplacements) { EXPECT_EQ(Expected, applyAllReplacements(Code, FinalReplaces)); } +TEST_F(ReplacementTest, SortIncludesAfterReplacement) { + std::string Code = "#include \"a.h\"\n" + "#include \"c.h\"\n" + "\n" + "int main() {\n" + " return 0;\n" + "}"; + std::string Expected = "#include \"a.h\"\n" + "#include \"b.h\"\n" + "#include \"c.h\"\n" + "\n" + "int main() {\n" + " return 0;\n" + "}"; + FileID ID = Context.createInMemoryFile("fix.cpp", Code); + tooling::Replacements Replaces; + Replaces.insert(tooling::Replacement( + Context.Sources, Context.getLocation(ID, 1, 1), 0, "#include \"b.h\"\n")); + + format::FormatStyle Style = format::getLLVMStyle(); + Style.SortIncludes = true; + auto FinalReplaces = formatReplacements(Code, Replaces, Style); + EXPECT_EQ(Expected, applyAllReplacements(Code, FinalReplaces)); +} + } // end namespace } // end namespace format } // end namespace clang -- 2.40.0