clang-format: Only consider the first #include that looks right to be
authorDaniel Jasper <djasper@google.com>
Mon, 21 Dec 2015 17:28:24 +0000 (17:28 +0000)
committerDaniel Jasper <djasper@google.com>
Mon, 21 Dec 2015 17:28:24 +0000 (17:28 +0000)
the main #include.

llvm-svn: 256170

clang/lib/Format/Format.cpp
clang/unittests/Format/SortIncludesTest.cpp

index b997486..d86fccf 100644 (file)
@@ -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<llvm::Regex, 4> 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()) {
index d96227d..dbe1174 100644 (file)
@@ -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) {