Skip to content

Commit

Permalink
[clang-format] Make formatReplacements() also sort #includes.
Browse files Browse the repository at this point in the history
Summary: [clang-format] Make formatReplacements() also sort #includes.

Reviewers: bkramer, djasper

Subscribers: klimek, cfe-commits

Differential Revision: http://reviews.llvm.org/D20362

llvm-svn: 269924
  • Loading branch information
Eric Liu committed May 18, 2016
1 parent 6b5160a commit baf58c2
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
12 changes: 11 additions & 1 deletion clang/lib/Format/Format.cpp
Expand Up @@ -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<tooling::Range> 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<tooling::Range> 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
Expand Down
25 changes: 25 additions & 0 deletions clang/unittests/Format/FormatTest.cpp
Expand Up @@ -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

0 comments on commit baf58c2

Please sign in to comment.