From: Daniel Jasper Date: Mon, 21 Dec 2015 17:28:24 +0000 (+0000) Subject: clang-format: Only consider the first #include that looks right to be X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=a45fac502a87ad6569e67e1b1691f7270791694f;p=clang clang-format: Only consider the first #include that looks right to be the main #include. git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@256170 91177308-0d34-0410-b5e6-96231b3b80d8 --- diff --git a/lib/Format/Format.cpp b/lib/Format/Format.cpp index b997486f97..d86fccf416 100644 --- a/lib/Format/Format.cpp +++ b/lib/Format/Format.cpp @@ -1816,6 +1816,7 @@ tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code, FileName.endswith(".mm"); StringRef FileStem = llvm::sys::path::stem(FileName); bool FirstIncludeBlock = true; + bool MainIncludeFound = false; // Create pre-compiled regular expressions for the #include categories. SmallVector CategoryRegexs; @@ -1845,12 +1846,14 @@ tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code, break; } } - if (IsSource && Category > 0 && FirstIncludeBlock && - IncludeName.startswith("\"")) { + if (IsSource && !MainIncludeFound && Category > 0 && + FirstIncludeBlock && IncludeName.startswith("\"")) { StringRef HeaderStem = llvm::sys::path::stem(IncludeName.drop_front(1).drop_back(1)); - if (FileStem.startswith(HeaderStem)) + if (FileStem.startswith(HeaderStem)) { Category = 0; + MainIncludeFound = true; + } } IncludesInBlock.push_back({IncludeName, Line, Prev, Category}); } else if (!IncludesInBlock.empty()) { diff --git a/unittests/Format/SortIncludesTest.cpp b/unittests/Format/SortIncludesTest.cpp index d96227d13e..dbe1174957 100644 --- a/unittests/Format/SortIncludesTest.cpp +++ b/unittests/Format/SortIncludesTest.cpp @@ -204,6 +204,17 @@ TEST_F(SortIncludesTest, LeavesMainHeaderFirst) { "#include \"c.h\"\n" "#include \"b.h\"\n", "a.cc")); + + // Only recognize the first #include with a matching basename as main include. + EXPECT_EQ("#include \"a.h\"\n" + "#include \"b.h\"\n" + "#include \"c.h\"\n" + "#include \"llvm/a.h\"\n", + sort("#include \"b.h\"\n" + "#include \"a.h\"\n" + "#include \"c.h\"\n" + "#include \"llvm/a.h\"\n", + "a.cc")); } TEST_F(SortIncludesTest, NegativePriorities) {