[clang-format] Find main include after block ended with #pragma hdrstop
authorRafał Jelonek <71409580+rjelonek@users.noreply.github.com>
Mon, 11 Jan 2021 08:43:30 +0000 (09:43 +0100)
committerMarek Kurdej <marek.kurdej@gmail.com>
Mon, 11 Jan 2021 08:49:34 +0000 (09:49 +0100)
Find main include in first include block not ended with #pragma hdrstop

Reviewed By: curdeius

Differential Revision: https://reviews.llvm.org/D94217

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

index 37b6c4c..fc62a34 100644 (file)
@@ -2308,7 +2308,10 @@ tooling::Replacements sortCppIncludes(const FormatStyle &Style, StringRef Code,
         sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Code,
                         Replaces, Cursor);
         IncludesInBlock.clear();
-        FirstIncludeBlock = false;
+        if (Trimmed.startswith("#pragma hdrstop")) // Precompiled headers.
+          FirstIncludeBlock = true;
+        else
+          FirstIncludeBlock = false;
       }
     }
     if (Pos == StringRef::npos || Pos + 1 == Code.size())
index f2f0e93..41ff7af 100644 (file)
@@ -900,6 +900,45 @@ TEST_F(SortIncludesTest, DoNotRegroupGroupsInGoogleObjCStyle) {
                  "#include \"a.h\""));
 }
 
+TEST_F(SortIncludesTest, DoNotTreatPrecompiledHeadersAsFirstBlock) {
+  Style.IncludeBlocks = Style.IBS_Merge;
+  std::string Code = "#include \"d.h\"\r\n"
+                     "#include \"b.h\"\r\n"
+                     "#pragma hdrstop\r\n"
+                     "\r\n"
+                     "#include \"c.h\"\r\n"
+                     "#include \"a.h\"\r\n"
+                     "#include \"e.h\"\r\n";
+
+  std::string Expected = "#include \"b.h\"\r\n"
+                         "#include \"d.h\"\r\n"
+                         "#pragma hdrstop\r\n"
+                         "\r\n"
+                         "#include \"e.h\"\r\n"
+                         "#include \"a.h\"\r\n"
+                         "#include \"c.h\"\r\n";
+
+  EXPECT_EQ(Expected, sort(Code, "e.cpp", 2));
+
+  Code = "#include \"d.h\"\n"
+         "#include \"b.h\"\n"
+         "#pragma hdrstop( \"c:\\projects\\include\\myinc.pch\" )\n"
+         "\n"
+         "#include \"c.h\"\n"
+         "#include \"a.h\"\n"
+         "#include \"e.h\"\n";
+
+  Expected = "#include \"b.h\"\n"
+             "#include \"d.h\"\n"
+             "#pragma hdrstop(\"c:\\projects\\include\\myinc.pch\")\n"
+             "\n"
+             "#include \"e.h\"\n"
+             "#include \"a.h\"\n"
+             "#include \"c.h\"\n";
+
+  EXPECT_EQ(Expected, sort(Code, "e.cpp", 2));
+}
+
 TEST_F(SortIncludesTest, skipUTF8ByteOrderMarkMerge) {
   Style.IncludeBlocks = Style.IBS_Merge;
   std::string Code = "\xEF\xBB\xBF#include \"d.h\"\r\n"