]> granicus.if.org Git - clang/commitdiff
clang-format: Enable #include sorting by default.
authorDaniel Jasper <djasper@google.com>
Mon, 16 Nov 2015 12:38:56 +0000 (12:38 +0000)
committerDaniel Jasper <djasper@google.com>
Mon, 16 Nov 2015 12:38:56 +0000 (12:38 +0000)
This has seen quite some usage and I am not aware of any issues. Also
add a style option to enable/disable include sorting. The existing
command line flag can from now on be used to override whatever is set
in the style.

git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@253202 91177308-0d34-0410-b5e6-96231b3b80d8

include/clang/Format/Format.h
lib/Format/Format.cpp
test/Format/disable-include-sorting.cpp [new file with mode: 0644]
tools/clang-format/ClangFormat.cpp
tools/clang-format/clang-format-sublime.py
tools/clang-format/clang-format.el
tools/clang-format/clang-format.py
unittests/Format/FormatTest.cpp
unittests/Format/SortIncludesTest.cpp

index d4f1d7bb6039d47e46f29beb0d0e94f9a3f2bc9f..4c326dec6dc4e31b7d1ba2a9826c890c6e0e3ac3 100644 (file)
@@ -469,6 +469,9 @@ struct FormatStyle {
   /// Pointer and reference alignment style.
   PointerAlignmentStyle PointerAlignment;
 
+  /// \brief If true, clang-format will sort #includes.
+  bool SortIncludes;
+
   /// \brief If \c true, a space may be inserted after C style casts.
   bool SpaceAfterCStyleCast;
 
index c1a3019415302d92130d9a68678edad95be626b8..4bc12f88cb00ba4a88c6cb3b7b8c5f2ed07aa4cf 100644 (file)
@@ -284,6 +284,7 @@ template <> struct MappingTraits<FormatStyle> {
     IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
     IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
                    Style.PenaltyReturnTypeOnItsOwnLine);
+    IO.mapOptional("SortIncludes", Style.SortIncludes);
     IO.mapOptional("PointerAlignment", Style.PointerAlignment);
     IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
     IO.mapOptional("SpaceBeforeAssignmentOperators",
@@ -507,6 +508,7 @@ FormatStyle getLLVMStyle() {
   LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
 
   LLVMStyle.DisableFormat = false;
+  LLVMStyle.SortIncludes = true;
 
   return LLVMStyle;
 }
@@ -635,6 +637,7 @@ FormatStyle getGNUStyle() {
 FormatStyle getNoStyle() {
   FormatStyle NoStyle = getLLVMStyle();
   NoStyle.DisableFormat = true;
+  NoStyle.SortIncludes = false;
   return NoStyle;
 }
 
@@ -1743,6 +1746,9 @@ tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
                                    ArrayRef<tooling::Range> Ranges,
                                    StringRef FileName) {
   tooling::Replacements Replaces;
+  if (!Style.SortIncludes)
+    return Replaces;
+
   unsigned Prev = 0;
   unsigned SearchFrom = 0;
   llvm::Regex IncludeRegex(
diff --git a/test/Format/disable-include-sorting.cpp b/test/Format/disable-include-sorting.cpp
new file mode 100644 (file)
index 0000000..875a0af
--- /dev/null
@@ -0,0 +1,10 @@
+// RUN: clang-format %s | FileCheck %s
+// RUN: clang-format %s -sort-includes -style="{SortIncludes: false}" | FileCheck %s
+// RUN: clang-format %s -sort-includes=false | FileCheck %s -check-prefix=NOT-SORTED
+
+#include <b>
+#include <a>
+// CHECK: <a>
+// CHECK-NEXT: <b>
+// NOT-SORTED: <b>
+// NOT-SORTED-NEXT: <a>
index 7cdb823f367437894916669ad7ada9d65a0c5712..43eded20fab49cbfaf7aa46c68e94cdfa1aeee61 100644 (file)
@@ -98,9 +98,11 @@ static cl::opt<unsigned>
                     "clang-format from an editor integration"),
            cl::init(0), cl::cat(ClangFormatCategory));
 
-static cl::opt<bool> SortIncludes("sort-includes",
-                                  cl::desc("Sort touched include lines"),
-                                  cl::cat(ClangFormatCategory));
+static cl::opt<bool> SortIncludes(
+    "sort-includes",
+    cl::desc("If set, overrides the include sorting behavior determined by the "
+             "SortIncludes style flag"),
+    cl::cat(ClangFormatCategory));
 
 static cl::list<std::string> FileNames(cl::Positional, cl::desc("[<file> ...]"),
                                        cl::cat(ClangFormatCategory));
@@ -252,17 +254,14 @@ static bool format(StringRef FileName) {
     return true;
   StringRef AssumedFileName = (FileName == "-") ? AssumeFileName : FileName;
   FormatStyle FormatStyle = getStyle(Style, AssumedFileName, FallbackStyle);
-  Replacements Replaces;
-  std::string ChangedCode;
-  if (SortIncludes) {
-    Replaces =
-        sortIncludes(FormatStyle, Code->getBuffer(), Ranges, AssumedFileName);
-    ChangedCode = tooling::applyAllReplacements(Code->getBuffer(), Replaces);
-    for (const auto &R : Replaces)
-      Ranges.push_back({R.getOffset(), R.getLength()});
-  } else {
-    ChangedCode = Code->getBuffer().str();
-  }
+  if (SortIncludes.getNumOccurrences() != 0)
+    FormatStyle.SortIncludes = SortIncludes;
+  Replacements Replaces =
+      sortIncludes(FormatStyle, Code->getBuffer(), Ranges, AssumedFileName);
+  std::string ChangedCode =
+      tooling::applyAllReplacements(Code->getBuffer(), Replaces);
+  for (const auto &R : Replaces)
+    Ranges.push_back({R.getOffset(), R.getLength()});
 
   bool IncompleteFormat = false;
   Replaces = tooling::mergeReplacements(
index 1cffcecc3946c92738ab4a9845fb6276957bc682..16ff56e502c66f71c1cbeb06c49cdbd50a8fc6df 100644 (file)
@@ -32,7 +32,7 @@ class ClangFormatCommand(sublime_plugin.TextCommand):
     if encoding == 'Undefined':
       encoding = 'utf-8'
     regions = []
-    command = [binary, '-sort-includes', '-style', style]
+    command = [binary, '-style', style]
     for region in self.view.sel():
       regions.append(region)
       region_offset = min(region.a, region.b)
index 6de45de70a651e825192cbdcae3f9fc1b6d30562..ca461444e22684186ed64aa16d10b226fce881a6 100644 (file)
@@ -126,7 +126,6 @@ is no active region.  If no style is given uses `clang-format-style'."
                  nil `(,temp-buffer ,temp-file) nil
 
                  "-output-replacements-xml"
-                 "-sort-includes"
                  "-assume-filename" (or (buffer-file-name) "")
                  "-style" style
                  "-offset" (number-to-string start)
index 1725e8659ad38706bd6b6c9d15d2cc9385eeb473..5cb41fcfa371a5c6e8ad8920ea03dc405824d5aa 100644 (file)
@@ -72,7 +72,7 @@ def main():
     startupinfo.wShowWindow = subprocess.SW_HIDE
 
   # Call formatter.
-  command = [binary, '-style', style, '-cursor', str(cursor), '-sort-includes']
+  command = [binary, '-style', style, '-cursor', str(cursor)]
   if lines != 'all':
     command.extend(['-lines', lines])
   if fallback_style:
index 1c68d67956ca9c724b69483bd2b04b882f753a2f..1c5e63b3e081b0d8eae45ae94bbb0005116e6641 100644 (file)
@@ -9563,12 +9563,14 @@ TEST_F(FormatTest, ParsesConfigurationBools) {
   CHECK_PARSE_BOOL(ConstructorInitializerAllOnOneLineOrOnePerLine);
   CHECK_PARSE_BOOL(DerivePointerAlignment);
   CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
+  CHECK_PARSE_BOOL(DisableFormat);
   CHECK_PARSE_BOOL(IndentCaseLabels);
   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
+  CHECK_PARSE_BOOL(SortIncludes);
   CHECK_PARSE_BOOL(SpacesInParentheses);
   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
   CHECK_PARSE_BOOL(SpacesInAngles);
index 84bc554edd11aef1627f04db1d21c251534f1d8b..30109ffb728fb3ca3e0aae9ef12b35b37bcc7b4d 100644 (file)
@@ -40,6 +40,16 @@ TEST_F(SortIncludesTest, BasicSorting) {
                  "#include \"b.h\"\n"));
 }
 
+TEST_F(SortIncludesTest, IncludeSortingCanBeDisabled) {
+  Style.SortIncludes = false;
+  EXPECT_EQ("#include \"a.h\"\n"
+            "#include \"c.h\"\n"
+            "#include \"b.h\"\n",
+            sort("#include \"a.h\"\n"
+                 "#include \"c.h\"\n"
+                 "#include \"b.h\"\n"));
+}
+
 TEST_F(SortIncludesTest, MixIncludeAndImport) {
   EXPECT_EQ("#include \"a.h\"\n"
             "#import \"b.h\"\n"