Skip to content

Commit 95bf0a9

Browse files
committed
[clang-format] Don't break block comments when sorting includes.
Fixes llvm#34626. Before, the include sorter would break the code: ``` #include <stdio.h> #include <stdint.h> /* long comment */ ``` and change it into: ``` #include <stdint.h> /* long #include <stdio.h> comment */ ``` This commit handles only the most basic case of a single block comment on an include line, but does not try to handle all the possible edge cases with multiple comments. Reviewed By: HazardyKnusperkeks Differential Revision: https://reviews.llvm.org/D118627
1 parent a265cf2 commit 95bf0a9

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

clang/lib/Format/Format.cpp

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2678,6 +2678,15 @@ tooling::Replacements sortCppIncludes(const FormatStyle &Style, StringRef Code,
26782678
if (!FormattingOff && !MergeWithNextLine) {
26792679
if (IncludeRegex.match(Line, &Matches)) {
26802680
StringRef IncludeName = Matches[2];
2681+
if (Line.contains("/*") && !Line.contains("*/")) {
2682+
// #include with a start of a block comment, but without the end.
2683+
// Need to keep all the lines until the end of the comment together.
2684+
// FIXME: This is somehow simplified check that probably does not work
2685+
// correctly if there are multiple comments on a line.
2686+
Pos = Code.find("*/", SearchFrom);
2687+
Line = Code.substr(
2688+
Prev, (Pos != StringRef::npos ? Pos + 2 : Code.size()) - Prev);
2689+
}
26812690
int Category = Categories.getIncludePriority(
26822691
IncludeName,
26832692
/*CheckMainHeader=*/!MainIncludeFound && FirstIncludeBlock);

clang/unittests/Format/SortIncludesTest.cpp

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,21 @@ TEST_F(SortIncludesTest, BasicSorting) {
7070
{tooling::Range(25, 1)}));
7171
}
7272

73+
TEST_F(SortIncludesTest, TrailingComments) {
74+
EXPECT_EQ("#include \"a.h\"\n"
75+
"#include \"b.h\" /* long\n"
76+
" * long\n"
77+
" * comment*/\n"
78+
"#include \"c.h\"\n"
79+
"#include \"d.h\"\n",
80+
sort("#include \"a.h\"\n"
81+
"#include \"c.h\"\n"
82+
"#include \"b.h\" /* long\n"
83+
" * long\n"
84+
" * comment*/\n"
85+
"#include \"d.h\"\n"));
86+
}
87+
7388
TEST_F(SortIncludesTest, SortedIncludesUsingSortPriorityAttribute) {
7489
FmtStyle.IncludeStyle.IncludeBlocks = tooling::IncludeStyle::IBS_Regroup;
7590
FmtStyle.IncludeStyle.IncludeCategories = {

0 commit comments

Comments
 (0)