1 //===--- Format.cpp - Format C++ code -------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// \brief This file implements functions declared in Format.h. This will be
12 /// split into separate files as we go.
13 ///
14 //===----------------------------------------------------------------------===//
15 
16 #include "clang/Format/Format.h"
17 #include "AffectedRangeManager.h"
18 #include "ContinuationIndenter.h"
19 #include "FormatTokenLexer.h"
20 #include "NamespaceEndCommentsFixer.h"
21 #include "SortJavaScriptImports.h"
22 #include "TokenAnalyzer.h"
23 #include "TokenAnnotator.h"
24 #include "UnwrappedLineFormatter.h"
25 #include "UnwrappedLineParser.h"
26 #include "WhitespaceManager.h"
27 #include "clang/Basic/Diagnostic.h"
28 #include "clang/Basic/DiagnosticOptions.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/VirtualFileSystem.h"
31 #include "clang/Lex/Lexer.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/Support/Allocator.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/Path.h"
36 #include "llvm/Support/Regex.h"
37 #include "llvm/Support/YAMLTraits.h"
38 #include <algorithm>
39 #include <memory>
40 #include <string>
41 
42 #define DEBUG_TYPE "format-formatter"
43 
44 using clang::format::FormatStyle;
45 
46 LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(std::string)
47 LLVM_YAML_IS_SEQUENCE_VECTOR(clang::format::FormatStyle::IncludeCategory)
48 
49 namespace llvm {
50 namespace yaml {
51 template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
52   static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
53     IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
54     IO.enumCase(Value, "Java", FormatStyle::LK_Java);
55     IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
56     IO.enumCase(Value, "ObjC", FormatStyle::LK_ObjC);
57     IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
58     IO.enumCase(Value, "TableGen", FormatStyle::LK_TableGen);
59   }
60 };
61 
62 template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
63   static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
64     IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
65     IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
66     IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
67     IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
68     IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
69   }
70 };
71 
72 template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
73   static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
74     IO.enumCase(Value, "Never", FormatStyle::UT_Never);
75     IO.enumCase(Value, "false", FormatStyle::UT_Never);
76     IO.enumCase(Value, "Always", FormatStyle::UT_Always);
77     IO.enumCase(Value, "true", FormatStyle::UT_Always);
78     IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
79     IO.enumCase(Value, "ForContinuationAndIndentation",
80                 FormatStyle::UT_ForContinuationAndIndentation);
81   }
82 };
83 
84 template <> struct ScalarEnumerationTraits<FormatStyle::JavaScriptQuoteStyle> {
85   static void enumeration(IO &IO, FormatStyle::JavaScriptQuoteStyle &Value) {
86     IO.enumCase(Value, "Leave", FormatStyle::JSQS_Leave);
87     IO.enumCase(Value, "Single", FormatStyle::JSQS_Single);
88     IO.enumCase(Value, "Double", FormatStyle::JSQS_Double);
89   }
90 };
91 
92 template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
93   static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
94     IO.enumCase(Value, "None", FormatStyle::SFS_None);
95     IO.enumCase(Value, "false", FormatStyle::SFS_None);
96     IO.enumCase(Value, "All", FormatStyle::SFS_All);
97     IO.enumCase(Value, "true", FormatStyle::SFS_All);
98     IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
99     IO.enumCase(Value, "Empty", FormatStyle::SFS_Empty);
100   }
101 };
102 
103 template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
104   static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
105     IO.enumCase(Value, "All", FormatStyle::BOS_All);
106     IO.enumCase(Value, "true", FormatStyle::BOS_All);
107     IO.enumCase(Value, "None", FormatStyle::BOS_None);
108     IO.enumCase(Value, "false", FormatStyle::BOS_None);
109     IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
110   }
111 };
112 
113 template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
114   static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
115     IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
116     IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
117     IO.enumCase(Value, "Mozilla", FormatStyle::BS_Mozilla);
118     IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
119     IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
120     IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
121     IO.enumCase(Value, "WebKit", FormatStyle::BS_WebKit);
122     IO.enumCase(Value, "Custom", FormatStyle::BS_Custom);
123   }
124 };
125 
126 template <>
127 struct ScalarEnumerationTraits<FormatStyle::ReturnTypeBreakingStyle> {
128   static void enumeration(IO &IO, FormatStyle::ReturnTypeBreakingStyle &Value) {
129     IO.enumCase(Value, "None", FormatStyle::RTBS_None);
130     IO.enumCase(Value, "All", FormatStyle::RTBS_All);
131     IO.enumCase(Value, "TopLevel", FormatStyle::RTBS_TopLevel);
132     IO.enumCase(Value, "TopLevelDefinitions",
133                 FormatStyle::RTBS_TopLevelDefinitions);
134     IO.enumCase(Value, "AllDefinitions", FormatStyle::RTBS_AllDefinitions);
135   }
136 };
137 
138 template <>
139 struct ScalarEnumerationTraits<FormatStyle::DefinitionReturnTypeBreakingStyle> {
140   static void
141   enumeration(IO &IO, FormatStyle::DefinitionReturnTypeBreakingStyle &Value) {
142     IO.enumCase(Value, "None", FormatStyle::DRTBS_None);
143     IO.enumCase(Value, "All", FormatStyle::DRTBS_All);
144     IO.enumCase(Value, "TopLevel", FormatStyle::DRTBS_TopLevel);
145 
146     // For backward compatibility.
147     IO.enumCase(Value, "false", FormatStyle::DRTBS_None);
148     IO.enumCase(Value, "true", FormatStyle::DRTBS_All);
149   }
150 };
151 
152 template <>
153 struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
154   static void enumeration(IO &IO,
155                           FormatStyle::NamespaceIndentationKind &Value) {
156     IO.enumCase(Value, "None", FormatStyle::NI_None);
157     IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
158     IO.enumCase(Value, "All", FormatStyle::NI_All);
159   }
160 };
161 
162 template <> struct ScalarEnumerationTraits<FormatStyle::BracketAlignmentStyle> {
163   static void enumeration(IO &IO, FormatStyle::BracketAlignmentStyle &Value) {
164     IO.enumCase(Value, "Align", FormatStyle::BAS_Align);
165     IO.enumCase(Value, "DontAlign", FormatStyle::BAS_DontAlign);
166     IO.enumCase(Value, "AlwaysBreak", FormatStyle::BAS_AlwaysBreak);
167 
168     // For backward compatibility.
169     IO.enumCase(Value, "true", FormatStyle::BAS_Align);
170     IO.enumCase(Value, "false", FormatStyle::BAS_DontAlign);
171   }
172 };
173 
174 template <> struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
175   static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value) {
176     IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
177     IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
178     IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
179 
180     // For backward compatibility.
181     IO.enumCase(Value, "true", FormatStyle::PAS_Left);
182     IO.enumCase(Value, "false", FormatStyle::PAS_Right);
183   }
184 };
185 
186 template <>
187 struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
188   static void enumeration(IO &IO,
189                           FormatStyle::SpaceBeforeParensOptions &Value) {
190     IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
191     IO.enumCase(Value, "ControlStatements",
192                 FormatStyle::SBPO_ControlStatements);
193     IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
194 
195     // For backward compatibility.
196     IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
197     IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
198   }
199 };
200 
201 template <> struct MappingTraits<FormatStyle> {
202   static void mapping(IO &IO, FormatStyle &Style) {
203     // When reading, read the language first, we need it for getPredefinedStyle.
204     IO.mapOptional("Language", Style.Language);
205 
206     if (IO.outputting()) {
207       StringRef StylesArray[] = {"LLVM",    "Google", "Chromium",
208                                  "Mozilla", "WebKit", "GNU"};
209       ArrayRef<StringRef> Styles(StylesArray);
210       for (size_t i = 0, e = Styles.size(); i < e; ++i) {
211         StringRef StyleName(Styles[i]);
212         FormatStyle PredefinedStyle;
213         if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
214             Style == PredefinedStyle) {
215           IO.mapOptional("# BasedOnStyle", StyleName);
216           break;
217         }
218       }
219     } else {
220       StringRef BasedOnStyle;
221       IO.mapOptional("BasedOnStyle", BasedOnStyle);
222       if (!BasedOnStyle.empty()) {
223         FormatStyle::LanguageKind OldLanguage = Style.Language;
224         FormatStyle::LanguageKind Language =
225             ((FormatStyle *)IO.getContext())->Language;
226         if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
227           IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
228           return;
229         }
230         Style.Language = OldLanguage;
231       }
232     }
233 
234     // For backward compatibility.
235     if (!IO.outputting()) {
236       IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
237       IO.mapOptional("IndentFunctionDeclarationAfterType",
238                      Style.IndentWrappedFunctionNames);
239       IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
240       IO.mapOptional("SpaceAfterControlStatementKeyword",
241                      Style.SpaceBeforeParens);
242     }
243 
244     IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
245     IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
246     IO.mapOptional("AlignConsecutiveAssignments",
247                    Style.AlignConsecutiveAssignments);
248     IO.mapOptional("AlignConsecutiveDeclarations",
249                    Style.AlignConsecutiveDeclarations);
250     IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
251     IO.mapOptional("AlignOperands", Style.AlignOperands);
252     IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
253     IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
254                    Style.AllowAllParametersOfDeclarationOnNextLine);
255     IO.mapOptional("AllowShortBlocksOnASingleLine",
256                    Style.AllowShortBlocksOnASingleLine);
257     IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
258                    Style.AllowShortCaseLabelsOnASingleLine);
259     IO.mapOptional("AllowShortFunctionsOnASingleLine",
260                    Style.AllowShortFunctionsOnASingleLine);
261     IO.mapOptional("AllowShortIfStatementsOnASingleLine",
262                    Style.AllowShortIfStatementsOnASingleLine);
263     IO.mapOptional("AllowShortLoopsOnASingleLine",
264                    Style.AllowShortLoopsOnASingleLine);
265     IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
266                    Style.AlwaysBreakAfterDefinitionReturnType);
267     IO.mapOptional("AlwaysBreakAfterReturnType",
268                    Style.AlwaysBreakAfterReturnType);
269     // If AlwaysBreakAfterDefinitionReturnType was specified but
270     // AlwaysBreakAfterReturnType was not, initialize the latter from the
271     // former for backwards compatibility.
272     if (Style.AlwaysBreakAfterDefinitionReturnType != FormatStyle::DRTBS_None &&
273         Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None) {
274       if (Style.AlwaysBreakAfterDefinitionReturnType == FormatStyle::DRTBS_All)
275         Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
276       else if (Style.AlwaysBreakAfterDefinitionReturnType ==
277                FormatStyle::DRTBS_TopLevel)
278         Style.AlwaysBreakAfterReturnType =
279             FormatStyle::RTBS_TopLevelDefinitions;
280     }
281 
282     IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
283                    Style.AlwaysBreakBeforeMultilineStrings);
284     IO.mapOptional("AlwaysBreakTemplateDeclarations",
285                    Style.AlwaysBreakTemplateDeclarations);
286     IO.mapOptional("BinPackArguments", Style.BinPackArguments);
287     IO.mapOptional("BinPackParameters", Style.BinPackParameters);
288     IO.mapOptional("BraceWrapping", Style.BraceWrapping);
289     IO.mapOptional("BreakBeforeBinaryOperators",
290                    Style.BreakBeforeBinaryOperators);
291     IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
292     IO.mapOptional("BreakBeforeTernaryOperators",
293                    Style.BreakBeforeTernaryOperators);
294     IO.mapOptional("BreakConstructorInitializersBeforeComma",
295                    Style.BreakConstructorInitializersBeforeComma);
296     IO.mapOptional("BreakAfterJavaFieldAnnotations",
297                    Style.BreakAfterJavaFieldAnnotations);
298     IO.mapOptional("BreakStringLiterals", Style.BreakStringLiterals);
299     IO.mapOptional("ColumnLimit", Style.ColumnLimit);
300     IO.mapOptional("CommentPragmas", Style.CommentPragmas);
301     IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
302                    Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
303     IO.mapOptional("ConstructorInitializerIndentWidth",
304                    Style.ConstructorInitializerIndentWidth);
305     IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
306     IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
307     IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
308     IO.mapOptional("DisableFormat", Style.DisableFormat);
309     IO.mapOptional("ExperimentalAutoDetectBinPacking",
310                    Style.ExperimentalAutoDetectBinPacking);
311     IO.mapOptional("FixNamespaceComments", Style.FixNamespaceComments);
312     IO.mapOptional("ForEachMacros", Style.ForEachMacros);
313     IO.mapOptional("IncludeCategories", Style.IncludeCategories);
314     IO.mapOptional("IncludeIsMainRegex", Style.IncludeIsMainRegex);
315     IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
316     IO.mapOptional("IndentWidth", Style.IndentWidth);
317     IO.mapOptional("IndentWrappedFunctionNames",
318                    Style.IndentWrappedFunctionNames);
319     IO.mapOptional("JavaScriptQuotes", Style.JavaScriptQuotes);
320     IO.mapOptional("JavaScriptWrapImports", Style.JavaScriptWrapImports);
321     IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
322                    Style.KeepEmptyLinesAtTheStartOfBlocks);
323     IO.mapOptional("MacroBlockBegin", Style.MacroBlockBegin);
324     IO.mapOptional("MacroBlockEnd", Style.MacroBlockEnd);
325     IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
326     IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
327     IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
328     IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
329     IO.mapOptional("ObjCSpaceBeforeProtocolList",
330                    Style.ObjCSpaceBeforeProtocolList);
331     IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
332                    Style.PenaltyBreakBeforeFirstCallParameter);
333     IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
334     IO.mapOptional("PenaltyBreakFirstLessLess",
335                    Style.PenaltyBreakFirstLessLess);
336     IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
337     IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
338     IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
339                    Style.PenaltyReturnTypeOnItsOwnLine);
340     IO.mapOptional("PointerAlignment", Style.PointerAlignment);
341     IO.mapOptional("ReflowComments", Style.ReflowComments);
342     IO.mapOptional("SortIncludes", Style.SortIncludes);
343     IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
344     IO.mapOptional("SpaceAfterTemplateKeyword", Style.SpaceAfterTemplateKeyword);
345     IO.mapOptional("SpaceBeforeAssignmentOperators",
346                    Style.SpaceBeforeAssignmentOperators);
347     IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
348     IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
349     IO.mapOptional("SpacesBeforeTrailingComments",
350                    Style.SpacesBeforeTrailingComments);
351     IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
352     IO.mapOptional("SpacesInContainerLiterals",
353                    Style.SpacesInContainerLiterals);
354     IO.mapOptional("SpacesInCStyleCastParentheses",
355                    Style.SpacesInCStyleCastParentheses);
356     IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
357     IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
358     IO.mapOptional("Standard", Style.Standard);
359     IO.mapOptional("TabWidth", Style.TabWidth);
360     IO.mapOptional("UseTab", Style.UseTab);
361   }
362 };
363 
364 template <> struct MappingTraits<FormatStyle::BraceWrappingFlags> {
365   static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping) {
366     IO.mapOptional("AfterClass", Wrapping.AfterClass);
367     IO.mapOptional("AfterControlStatement", Wrapping.AfterControlStatement);
368     IO.mapOptional("AfterEnum", Wrapping.AfterEnum);
369     IO.mapOptional("AfterFunction", Wrapping.AfterFunction);
370     IO.mapOptional("AfterNamespace", Wrapping.AfterNamespace);
371     IO.mapOptional("AfterObjCDeclaration", Wrapping.AfterObjCDeclaration);
372     IO.mapOptional("AfterStruct", Wrapping.AfterStruct);
373     IO.mapOptional("AfterUnion", Wrapping.AfterUnion);
374     IO.mapOptional("BeforeCatch", Wrapping.BeforeCatch);
375     IO.mapOptional("BeforeElse", Wrapping.BeforeElse);
376     IO.mapOptional("IndentBraces", Wrapping.IndentBraces);
377   }
378 };
379 
380 template <> struct MappingTraits<FormatStyle::IncludeCategory> {
381   static void mapping(IO &IO, FormatStyle::IncludeCategory &Category) {
382     IO.mapOptional("Regex", Category.Regex);
383     IO.mapOptional("Priority", Category.Priority);
384   }
385 };
386 
387 // Allows to read vector<FormatStyle> while keeping default values.
388 // IO.getContext() should contain a pointer to the FormatStyle structure, that
389 // will be used to get default values for missing keys.
390 // If the first element has no Language specified, it will be treated as the
391 // default one for the following elements.
392 template <> struct DocumentListTraits<std::vector<FormatStyle>> {
393   static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
394     return Seq.size();
395   }
396   static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
397                               size_t Index) {
398     if (Index >= Seq.size()) {
399       assert(Index == Seq.size());
400       FormatStyle Template;
401       if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
402         Template = Seq[0];
403       } else {
404         Template = *((const FormatStyle *)IO.getContext());
405         Template.Language = FormatStyle::LK_None;
406       }
407       Seq.resize(Index + 1, Template);
408     }
409     return Seq[Index];
410   }
411 };
412 } // namespace yaml
413 } // namespace llvm
414 
415 namespace clang {
416 namespace format {
417 
418 const std::error_category &getParseCategory() {
419   static ParseErrorCategory C;
420   return C;
421 }
422 std::error_code make_error_code(ParseError e) {
423   return std::error_code(static_cast<int>(e), getParseCategory());
424 }
425 
426 inline llvm::Error make_string_error(const llvm::Twine &Message) {
427   return llvm::make_error<llvm::StringError>(Message,
428                                              llvm::inconvertibleErrorCode());
429 }
430 
431 const char *ParseErrorCategory::name() const noexcept {
432   return "clang-format.parse_error";
433 }
434 
435 std::string ParseErrorCategory::message(int EV) const {
436   switch (static_cast<ParseError>(EV)) {
437   case ParseError::Success:
438     return "Success";
439   case ParseError::Error:
440     return "Invalid argument";
441   case ParseError::Unsuitable:
442     return "Unsuitable";
443   }
444   llvm_unreachable("unexpected parse error");
445 }
446 
447 static FormatStyle expandPresets(const FormatStyle &Style) {
448   if (Style.BreakBeforeBraces == FormatStyle::BS_Custom)
449     return Style;
450   FormatStyle Expanded = Style;
451   Expanded.BraceWrapping = {false, false, false, false, false, false,
452                             false, false, false, false, false};
453   switch (Style.BreakBeforeBraces) {
454   case FormatStyle::BS_Linux:
455     Expanded.BraceWrapping.AfterClass = true;
456     Expanded.BraceWrapping.AfterFunction = true;
457     Expanded.BraceWrapping.AfterNamespace = true;
458     break;
459   case FormatStyle::BS_Mozilla:
460     Expanded.BraceWrapping.AfterClass = true;
461     Expanded.BraceWrapping.AfterEnum = true;
462     Expanded.BraceWrapping.AfterFunction = true;
463     Expanded.BraceWrapping.AfterStruct = true;
464     Expanded.BraceWrapping.AfterUnion = true;
465     break;
466   case FormatStyle::BS_Stroustrup:
467     Expanded.BraceWrapping.AfterFunction = true;
468     Expanded.BraceWrapping.BeforeCatch = true;
469     Expanded.BraceWrapping.BeforeElse = true;
470     break;
471   case FormatStyle::BS_Allman:
472     Expanded.BraceWrapping.AfterClass = true;
473     Expanded.BraceWrapping.AfterControlStatement = true;
474     Expanded.BraceWrapping.AfterEnum = true;
475     Expanded.BraceWrapping.AfterFunction = true;
476     Expanded.BraceWrapping.AfterNamespace = true;
477     Expanded.BraceWrapping.AfterObjCDeclaration = true;
478     Expanded.BraceWrapping.AfterStruct = true;
479     Expanded.BraceWrapping.BeforeCatch = true;
480     Expanded.BraceWrapping.BeforeElse = true;
481     break;
482   case FormatStyle::BS_GNU:
483     Expanded.BraceWrapping = {true, true, true, true, true, true,
484                               true, true, true, true, true};
485     break;
486   case FormatStyle::BS_WebKit:
487     Expanded.BraceWrapping.AfterFunction = true;
488     break;
489   default:
490     break;
491   }
492   return Expanded;
493 }
494 
495 FormatStyle getLLVMStyle() {
496   FormatStyle LLVMStyle;
497   LLVMStyle.Language = FormatStyle::LK_Cpp;
498   LLVMStyle.AccessModifierOffset = -2;
499   LLVMStyle.AlignEscapedNewlinesLeft = false;
500   LLVMStyle.AlignAfterOpenBracket = FormatStyle::BAS_Align;
501   LLVMStyle.AlignOperands = true;
502   LLVMStyle.AlignTrailingComments = true;
503   LLVMStyle.AlignConsecutiveAssignments = false;
504   LLVMStyle.AlignConsecutiveDeclarations = false;
505   LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
506   LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
507   LLVMStyle.AllowShortBlocksOnASingleLine = false;
508   LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
509   LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
510   LLVMStyle.AllowShortLoopsOnASingleLine = false;
511   LLVMStyle.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
512   LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
513   LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
514   LLVMStyle.AlwaysBreakTemplateDeclarations = false;
515   LLVMStyle.BinPackParameters = true;
516   LLVMStyle.BinPackArguments = true;
517   LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
518   LLVMStyle.BreakBeforeTernaryOperators = true;
519   LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
520   LLVMStyle.BraceWrapping = {false, false, false, false, false, false,
521                              false, false, false, false, false};
522   LLVMStyle.BreakAfterJavaFieldAnnotations = false;
523   LLVMStyle.BreakConstructorInitializersBeforeComma = false;
524   LLVMStyle.BreakStringLiterals = true;
525   LLVMStyle.ColumnLimit = 80;
526   LLVMStyle.CommentPragmas = "^ IWYU pragma:";
527   LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
528   LLVMStyle.ConstructorInitializerIndentWidth = 4;
529   LLVMStyle.ContinuationIndentWidth = 4;
530   LLVMStyle.Cpp11BracedListStyle = true;
531   LLVMStyle.DerivePointerAlignment = false;
532   LLVMStyle.ExperimentalAutoDetectBinPacking = false;
533   LLVMStyle.FixNamespaceComments = true;
534   LLVMStyle.ForEachMacros.push_back("foreach");
535   LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
536   LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
537   LLVMStyle.IncludeCategories = {{"^\"(llvm|llvm-c|clang|clang-c)/", 2},
538                                  {"^(<|\"(gtest|isl|json)/)", 3},
539                                  {".*", 1}};
540   LLVMStyle.IncludeIsMainRegex = "$";
541   LLVMStyle.IndentCaseLabels = false;
542   LLVMStyle.IndentWrappedFunctionNames = false;
543   LLVMStyle.IndentWidth = 2;
544   LLVMStyle.JavaScriptQuotes = FormatStyle::JSQS_Leave;
545   LLVMStyle.JavaScriptWrapImports = true;
546   LLVMStyle.TabWidth = 8;
547   LLVMStyle.MaxEmptyLinesToKeep = 1;
548   LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
549   LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
550   LLVMStyle.ObjCBlockIndentWidth = 2;
551   LLVMStyle.ObjCSpaceAfterProperty = false;
552   LLVMStyle.ObjCSpaceBeforeProtocolList = true;
553   LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
554   LLVMStyle.SpacesBeforeTrailingComments = 1;
555   LLVMStyle.Standard = FormatStyle::LS_Cpp11;
556   LLVMStyle.UseTab = FormatStyle::UT_Never;
557   LLVMStyle.ReflowComments = true;
558   LLVMStyle.SpacesInParentheses = false;
559   LLVMStyle.SpacesInSquareBrackets = false;
560   LLVMStyle.SpaceInEmptyParentheses = false;
561   LLVMStyle.SpacesInContainerLiterals = true;
562   LLVMStyle.SpacesInCStyleCastParentheses = false;
563   LLVMStyle.SpaceAfterCStyleCast = false;
564   LLVMStyle.SpaceAfterTemplateKeyword = true;
565   LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
566   LLVMStyle.SpaceBeforeAssignmentOperators = true;
567   LLVMStyle.SpacesInAngles = false;
568 
569   LLVMStyle.PenaltyBreakComment = 300;
570   LLVMStyle.PenaltyBreakFirstLessLess = 120;
571   LLVMStyle.PenaltyBreakString = 1000;
572   LLVMStyle.PenaltyExcessCharacter = 1000000;
573   LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
574   LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
575 
576   LLVMStyle.DisableFormat = false;
577   LLVMStyle.SortIncludes = true;
578 
579   return LLVMStyle;
580 }
581 
582 FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
583   FormatStyle GoogleStyle = getLLVMStyle();
584   GoogleStyle.Language = Language;
585 
586   GoogleStyle.AccessModifierOffset = -1;
587   GoogleStyle.AlignEscapedNewlinesLeft = true;
588   GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
589   GoogleStyle.AllowShortLoopsOnASingleLine = true;
590   GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
591   GoogleStyle.AlwaysBreakTemplateDeclarations = true;
592   GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
593   GoogleStyle.DerivePointerAlignment = true;
594   GoogleStyle.IncludeCategories = {{"^<.*\\.h>", 1}, {"^<.*", 2}, {".*", 3}};
595   GoogleStyle.IncludeIsMainRegex = "([-_](test|unittest))?$";
596   GoogleStyle.IndentCaseLabels = true;
597   GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
598   GoogleStyle.ObjCSpaceAfterProperty = false;
599   GoogleStyle.ObjCSpaceBeforeProtocolList = false;
600   GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
601   GoogleStyle.SpacesBeforeTrailingComments = 2;
602   GoogleStyle.Standard = FormatStyle::LS_Auto;
603 
604   GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
605   GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
606 
607   if (Language == FormatStyle::LK_Java) {
608     GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
609     GoogleStyle.AlignOperands = false;
610     GoogleStyle.AlignTrailingComments = false;
611     GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
612     GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
613     GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
614     GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
615     GoogleStyle.ColumnLimit = 100;
616     GoogleStyle.SpaceAfterCStyleCast = true;
617     GoogleStyle.SpacesBeforeTrailingComments = 1;
618   } else if (Language == FormatStyle::LK_JavaScript) {
619     GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
620     GoogleStyle.AlignOperands = false;
621     GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
622     GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
623     GoogleStyle.BreakBeforeTernaryOperators = false;
624     // taze:, and @tag followed by { for a lot of JSDoc tags.
625     GoogleStyle.CommentPragmas = "(taze:|(@[A-Za-z_0-9-]+[ \\t]*{))";
626     GoogleStyle.MaxEmptyLinesToKeep = 3;
627     GoogleStyle.NamespaceIndentation = FormatStyle::NI_All;
628     GoogleStyle.SpacesInContainerLiterals = false;
629     GoogleStyle.JavaScriptQuotes = FormatStyle::JSQS_Single;
630     GoogleStyle.JavaScriptWrapImports = false;
631   } else if (Language == FormatStyle::LK_Proto) {
632     GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
633     GoogleStyle.SpacesInContainerLiterals = false;
634   } else if (Language == FormatStyle::LK_ObjC) {
635     GoogleStyle.ColumnLimit = 100;
636   }
637 
638   return GoogleStyle;
639 }
640 
641 FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
642   FormatStyle ChromiumStyle = getGoogleStyle(Language);
643   if (Language == FormatStyle::LK_Java) {
644     ChromiumStyle.AllowShortIfStatementsOnASingleLine = true;
645     ChromiumStyle.BreakAfterJavaFieldAnnotations = true;
646     ChromiumStyle.ContinuationIndentWidth = 8;
647     ChromiumStyle.IndentWidth = 4;
648   } else if (Language == FormatStyle::LK_JavaScript) {
649     ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
650     ChromiumStyle.AllowShortLoopsOnASingleLine = false;
651   } else {
652     ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
653     ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
654     ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
655     ChromiumStyle.AllowShortLoopsOnASingleLine = false;
656     ChromiumStyle.BinPackParameters = false;
657     ChromiumStyle.DerivePointerAlignment = false;
658     if (Language == FormatStyle::LK_ObjC)
659       ChromiumStyle.ColumnLimit = 80;
660   }
661   return ChromiumStyle;
662 }
663 
664 FormatStyle getMozillaStyle() {
665   FormatStyle MozillaStyle = getLLVMStyle();
666   MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
667   MozillaStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
668   MozillaStyle.AlwaysBreakAfterReturnType =
669       FormatStyle::RTBS_TopLevel;
670   MozillaStyle.AlwaysBreakAfterDefinitionReturnType =
671       FormatStyle::DRTBS_TopLevel;
672   MozillaStyle.AlwaysBreakTemplateDeclarations = true;
673   MozillaStyle.BinPackParameters = false;
674   MozillaStyle.BinPackArguments = false;
675   MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
676   MozillaStyle.BreakConstructorInitializersBeforeComma = true;
677   MozillaStyle.ConstructorInitializerIndentWidth = 2;
678   MozillaStyle.ContinuationIndentWidth = 2;
679   MozillaStyle.Cpp11BracedListStyle = false;
680   MozillaStyle.FixNamespaceComments = false;
681   MozillaStyle.IndentCaseLabels = true;
682   MozillaStyle.ObjCSpaceAfterProperty = true;
683   MozillaStyle.ObjCSpaceBeforeProtocolList = false;
684   MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
685   MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
686   MozillaStyle.SpaceAfterTemplateKeyword = false;
687   return MozillaStyle;
688 }
689 
690 FormatStyle getWebKitStyle() {
691   FormatStyle Style = getLLVMStyle();
692   Style.AccessModifierOffset = -4;
693   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
694   Style.AlignOperands = false;
695   Style.AlignTrailingComments = false;
696   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
697   Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
698   Style.BreakConstructorInitializersBeforeComma = true;
699   Style.Cpp11BracedListStyle = false;
700   Style.ColumnLimit = 0;
701   Style.FixNamespaceComments = false;
702   Style.IndentWidth = 4;
703   Style.NamespaceIndentation = FormatStyle::NI_Inner;
704   Style.ObjCBlockIndentWidth = 4;
705   Style.ObjCSpaceAfterProperty = true;
706   Style.PointerAlignment = FormatStyle::PAS_Left;
707   return Style;
708 }
709 
710 FormatStyle getGNUStyle() {
711   FormatStyle Style = getLLVMStyle();
712   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
713   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
714   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
715   Style.BreakBeforeBraces = FormatStyle::BS_GNU;
716   Style.BreakBeforeTernaryOperators = true;
717   Style.Cpp11BracedListStyle = false;
718   Style.ColumnLimit = 79;
719   Style.FixNamespaceComments = false;
720   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
721   Style.Standard = FormatStyle::LS_Cpp03;
722   return Style;
723 }
724 
725 FormatStyle getNoStyle() {
726   FormatStyle NoStyle = getLLVMStyle();
727   NoStyle.DisableFormat = true;
728   NoStyle.SortIncludes = false;
729   return NoStyle;
730 }
731 
732 bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
733                         FormatStyle *Style) {
734   if (Name.equals_lower("llvm")) {
735     *Style = getLLVMStyle();
736   } else if (Name.equals_lower("chromium")) {
737     *Style = getChromiumStyle(Language);
738   } else if (Name.equals_lower("mozilla")) {
739     *Style = getMozillaStyle();
740   } else if (Name.equals_lower("google")) {
741     *Style = getGoogleStyle(Language);
742   } else if (Name.equals_lower("webkit")) {
743     *Style = getWebKitStyle();
744   } else if (Name.equals_lower("gnu")) {
745     *Style = getGNUStyle();
746   } else if (Name.equals_lower("none")) {
747     *Style = getNoStyle();
748   } else {
749     return false;
750   }
751 
752   Style->Language = Language;
753   return true;
754 }
755 
756 std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
757   assert(Style);
758   FormatStyle::LanguageKind Language = Style->Language;
759   assert(Language != FormatStyle::LK_None);
760   if (Text.trim().empty())
761     return make_error_code(ParseError::Error);
762 
763   std::vector<FormatStyle> Styles;
764   llvm::yaml::Input Input(Text);
765   // DocumentListTraits<vector<FormatStyle>> uses the context to get default
766   // values for the fields, keys for which are missing from the configuration.
767   // Mapping also uses the context to get the language to find the correct
768   // base style.
769   Input.setContext(Style);
770   Input >> Styles;
771   if (Input.error())
772     return Input.error();
773 
774   for (unsigned i = 0; i < Styles.size(); ++i) {
775     // Ensures that only the first configuration can skip the Language option.
776     if (Styles[i].Language == FormatStyle::LK_None && i != 0)
777       return make_error_code(ParseError::Error);
778     // Ensure that each language is configured at most once.
779     for (unsigned j = 0; j < i; ++j) {
780       if (Styles[i].Language == Styles[j].Language) {
781         DEBUG(llvm::dbgs()
782               << "Duplicate languages in the config file on positions " << j
783               << " and " << i << "\n");
784         return make_error_code(ParseError::Error);
785       }
786     }
787   }
788   // Look for a suitable configuration starting from the end, so we can
789   // find the configuration for the specific language first, and the default
790   // configuration (which can only be at slot 0) after it.
791   for (int i = Styles.size() - 1; i >= 0; --i) {
792     if (Styles[i].Language == Language ||
793         Styles[i].Language == FormatStyle::LK_None) {
794       *Style = Styles[i];
795       Style->Language = Language;
796       return make_error_code(ParseError::Success);
797     }
798   }
799   return make_error_code(ParseError::Unsuitable);
800 }
801 
802 std::string configurationAsText(const FormatStyle &Style) {
803   std::string Text;
804   llvm::raw_string_ostream Stream(Text);
805   llvm::yaml::Output Output(Stream);
806   // We use the same mapping method for input and output, so we need a non-const
807   // reference here.
808   FormatStyle NonConstStyle = expandPresets(Style);
809   Output << NonConstStyle;
810   return Stream.str();
811 }
812 
813 namespace {
814 
815 class JavaScriptRequoter : public TokenAnalyzer {
816 public:
817   JavaScriptRequoter(const Environment &Env, const FormatStyle &Style)
818       : TokenAnalyzer(Env, Style) {}
819 
820   tooling::Replacements
821   analyze(TokenAnnotator &Annotator,
822           SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
823           FormatTokenLexer &Tokens) override {
824     AffectedRangeMgr.computeAffectedLines(AnnotatedLines.begin(),
825                                           AnnotatedLines.end());
826     tooling::Replacements Result;
827     requoteJSStringLiteral(AnnotatedLines, Result);
828     return Result;
829   }
830 
831 private:
832   // Replaces double/single-quoted string literal as appropriate, re-escaping
833   // the contents in the process.
834   void requoteJSStringLiteral(SmallVectorImpl<AnnotatedLine *> &Lines,
835                               tooling::Replacements &Result) {
836     for (AnnotatedLine *Line : Lines) {
837       requoteJSStringLiteral(Line->Children, Result);
838       if (!Line->Affected)
839         continue;
840       for (FormatToken *FormatTok = Line->First; FormatTok;
841            FormatTok = FormatTok->Next) {
842         StringRef Input = FormatTok->TokenText;
843         if (FormatTok->Finalized || !FormatTok->isStringLiteral() ||
844             // NB: testing for not starting with a double quote to avoid
845             // breaking `template strings`.
846             (Style.JavaScriptQuotes == FormatStyle::JSQS_Single &&
847              !Input.startswith("\"")) ||
848             (Style.JavaScriptQuotes == FormatStyle::JSQS_Double &&
849              !Input.startswith("\'")))
850           continue;
851 
852         // Change start and end quote.
853         bool IsSingle = Style.JavaScriptQuotes == FormatStyle::JSQS_Single;
854         SourceLocation Start = FormatTok->Tok.getLocation();
855         auto Replace = [&](SourceLocation Start, unsigned Length,
856                            StringRef ReplacementText) {
857           auto Err = Result.add(tooling::Replacement(
858               Env.getSourceManager(), Start, Length, ReplacementText));
859           // FIXME: handle error. For now, print error message and skip the
860           // replacement for release version.
861           if (Err) {
862             llvm::errs() << llvm::toString(std::move(Err)) << "\n";
863             assert(false);
864           }
865         };
866         Replace(Start, 1, IsSingle ? "'" : "\"");
867         Replace(FormatTok->Tok.getEndLoc().getLocWithOffset(-1), 1,
868                 IsSingle ? "'" : "\"");
869 
870         // Escape internal quotes.
871         bool Escaped = false;
872         for (size_t i = 1; i < Input.size() - 1; i++) {
873           switch (Input[i]) {
874           case '\\':
875             if (!Escaped && i + 1 < Input.size() &&
876                 ((IsSingle && Input[i + 1] == '"') ||
877                  (!IsSingle && Input[i + 1] == '\''))) {
878               // Remove this \, it's escaping a " or ' that no longer needs
879               // escaping
880               Replace(Start.getLocWithOffset(i), 1, "");
881               continue;
882             }
883             Escaped = !Escaped;
884             break;
885           case '\"':
886           case '\'':
887             if (!Escaped && IsSingle == (Input[i] == '\'')) {
888               // Escape the quote.
889               Replace(Start.getLocWithOffset(i), 0, "\\");
890             }
891             Escaped = false;
892             break;
893           default:
894             Escaped = false;
895             break;
896           }
897         }
898       }
899     }
900   }
901 };
902 
903 class Formatter : public TokenAnalyzer {
904 public:
905   Formatter(const Environment &Env, const FormatStyle &Style,
906             bool *IncompleteFormat)
907       : TokenAnalyzer(Env, Style), IncompleteFormat(IncompleteFormat) {}
908 
909   tooling::Replacements
910   analyze(TokenAnnotator &Annotator,
911           SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
912           FormatTokenLexer &Tokens) override {
913     tooling::Replacements Result;
914     deriveLocalStyle(AnnotatedLines);
915     AffectedRangeMgr.computeAffectedLines(AnnotatedLines.begin(),
916                                           AnnotatedLines.end());
917     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
918       Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
919     }
920     Annotator.setCommentLineLevels(AnnotatedLines);
921 
922     WhitespaceManager Whitespaces(
923         Env.getSourceManager(), Style,
924         inputUsesCRLF(Env.getSourceManager().getBufferData(Env.getFileID())));
925     ContinuationIndenter Indenter(Style, Tokens.getKeywords(),
926                                   Env.getSourceManager(), Whitespaces, Encoding,
927                                   BinPackInconclusiveFunctions);
928     UnwrappedLineFormatter(&Indenter, &Whitespaces, Style, Tokens.getKeywords(),
929                            IncompleteFormat)
930         .format(AnnotatedLines);
931     for (const auto &R : Whitespaces.generateReplacements())
932       if (Result.add(R))
933         return Result;
934     return Result;
935   }
936 
937 private:
938 
939   static bool inputUsesCRLF(StringRef Text) {
940     return Text.count('\r') * 2 > Text.count('\n');
941   }
942 
943   bool
944   hasCpp03IncompatibleFormat(const SmallVectorImpl<AnnotatedLine *> &Lines) {
945     for (const AnnotatedLine *Line : Lines) {
946       if (hasCpp03IncompatibleFormat(Line->Children))
947         return true;
948       for (FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next) {
949         if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
950           if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
951             return true;
952           if (Tok->is(TT_TemplateCloser) &&
953               Tok->Previous->is(TT_TemplateCloser))
954             return true;
955         }
956       }
957     }
958     return false;
959   }
960 
961   int countVariableAlignments(const SmallVectorImpl<AnnotatedLine *> &Lines) {
962     int AlignmentDiff = 0;
963     for (const AnnotatedLine *Line : Lines) {
964       AlignmentDiff += countVariableAlignments(Line->Children);
965       for (FormatToken *Tok = Line->First; Tok && Tok->Next; Tok = Tok->Next) {
966         if (!Tok->is(TT_PointerOrReference))
967           continue;
968         bool SpaceBefore =
969             Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
970         bool SpaceAfter = Tok->Next->WhitespaceRange.getBegin() !=
971                           Tok->Next->WhitespaceRange.getEnd();
972         if (SpaceBefore && !SpaceAfter)
973           ++AlignmentDiff;
974         if (!SpaceBefore && SpaceAfter)
975           --AlignmentDiff;
976       }
977     }
978     return AlignmentDiff;
979   }
980 
981   void
982   deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
983     bool HasBinPackedFunction = false;
984     bool HasOnePerLineFunction = false;
985     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
986       if (!AnnotatedLines[i]->First->Next)
987         continue;
988       FormatToken *Tok = AnnotatedLines[i]->First->Next;
989       while (Tok->Next) {
990         if (Tok->PackingKind == PPK_BinPacked)
991           HasBinPackedFunction = true;
992         if (Tok->PackingKind == PPK_OnePerLine)
993           HasOnePerLineFunction = true;
994 
995         Tok = Tok->Next;
996       }
997     }
998     if (Style.DerivePointerAlignment)
999       Style.PointerAlignment = countVariableAlignments(AnnotatedLines) <= 0
1000                                    ? FormatStyle::PAS_Left
1001                                    : FormatStyle::PAS_Right;
1002     if (Style.Standard == FormatStyle::LS_Auto)
1003       Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
1004                            ? FormatStyle::LS_Cpp11
1005                            : FormatStyle::LS_Cpp03;
1006     BinPackInconclusiveFunctions =
1007         HasBinPackedFunction || !HasOnePerLineFunction;
1008   }
1009 
1010   bool BinPackInconclusiveFunctions;
1011   bool *IncompleteFormat;
1012 };
1013 
1014 // This class clean up the erroneous/redundant code around the given ranges in
1015 // file.
1016 class Cleaner : public TokenAnalyzer {
1017 public:
1018   Cleaner(const Environment &Env, const FormatStyle &Style)
1019       : TokenAnalyzer(Env, Style),
1020         DeletedTokens(FormatTokenLess(Env.getSourceManager())) {}
1021 
1022   // FIXME: eliminate unused parameters.
1023   tooling::Replacements
1024   analyze(TokenAnnotator &Annotator,
1025           SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1026           FormatTokenLexer &Tokens) override {
1027     // FIXME: in the current implementation the granularity of affected range
1028     // is an annotated line. However, this is not sufficient. Furthermore,
1029     // redundant code introduced by replacements does not necessarily
1030     // intercept with ranges of replacements that result in the redundancy.
1031     // To determine if some redundant code is actually introduced by
1032     // replacements(e.g. deletions), we need to come up with a more
1033     // sophisticated way of computing affected ranges.
1034     AffectedRangeMgr.computeAffectedLines(AnnotatedLines.begin(),
1035                                           AnnotatedLines.end());
1036 
1037     checkEmptyNamespace(AnnotatedLines);
1038 
1039     for (auto &Line : AnnotatedLines) {
1040       if (Line->Affected) {
1041         cleanupRight(Line->First, tok::comma, tok::comma);
1042         cleanupRight(Line->First, TT_CtorInitializerColon, tok::comma);
1043         cleanupRight(Line->First, tok::l_paren, tok::comma);
1044         cleanupLeft(Line->First, tok::comma, tok::r_paren);
1045         cleanupLeft(Line->First, TT_CtorInitializerComma, tok::l_brace);
1046         cleanupLeft(Line->First, TT_CtorInitializerColon, tok::l_brace);
1047         cleanupLeft(Line->First, TT_CtorInitializerColon, tok::equal);
1048       }
1049     }
1050 
1051     return generateFixes();
1052   }
1053 
1054 private:
1055   bool containsOnlyComments(const AnnotatedLine &Line) {
1056     for (FormatToken *Tok = Line.First; Tok != nullptr; Tok = Tok->Next) {
1057       if (Tok->isNot(tok::comment))
1058         return false;
1059     }
1060     return true;
1061   }
1062 
1063   // Iterate through all lines and remove any empty (nested) namespaces.
1064   void checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
1065     std::set<unsigned> DeletedLines;
1066     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1067       auto &Line = *AnnotatedLines[i];
1068       if (Line.startsWith(tok::kw_namespace) ||
1069           Line.startsWith(tok::kw_inline, tok::kw_namespace)) {
1070         checkEmptyNamespace(AnnotatedLines, i, i, DeletedLines);
1071       }
1072     }
1073 
1074     for (auto Line : DeletedLines) {
1075       FormatToken *Tok = AnnotatedLines[Line]->First;
1076       while (Tok) {
1077         deleteToken(Tok);
1078         Tok = Tok->Next;
1079       }
1080     }
1081   }
1082 
1083   // The function checks if the namespace, which starts from \p CurrentLine, and
1084   // its nested namespaces are empty and delete them if they are empty. It also
1085   // sets \p NewLine to the last line checked.
1086   // Returns true if the current namespace is empty.
1087   bool checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1088                            unsigned CurrentLine, unsigned &NewLine,
1089                            std::set<unsigned> &DeletedLines) {
1090     unsigned InitLine = CurrentLine, End = AnnotatedLines.size();
1091     if (Style.BraceWrapping.AfterNamespace) {
1092       // If the left brace is in a new line, we should consume it first so that
1093       // it does not make the namespace non-empty.
1094       // FIXME: error handling if there is no left brace.
1095       if (!AnnotatedLines[++CurrentLine]->startsWith(tok::l_brace)) {
1096         NewLine = CurrentLine;
1097         return false;
1098       }
1099     } else if (!AnnotatedLines[CurrentLine]->endsWith(tok::l_brace)) {
1100       return false;
1101     }
1102     while (++CurrentLine < End) {
1103       if (AnnotatedLines[CurrentLine]->startsWith(tok::r_brace))
1104         break;
1105 
1106       if (AnnotatedLines[CurrentLine]->startsWith(tok::kw_namespace) ||
1107           AnnotatedLines[CurrentLine]->startsWith(tok::kw_inline,
1108                                                   tok::kw_namespace)) {
1109         if (!checkEmptyNamespace(AnnotatedLines, CurrentLine, NewLine,
1110                                  DeletedLines))
1111           return false;
1112         CurrentLine = NewLine;
1113         continue;
1114       }
1115 
1116       if (containsOnlyComments(*AnnotatedLines[CurrentLine]))
1117         continue;
1118 
1119       // If there is anything other than comments or nested namespaces in the
1120       // current namespace, the namespace cannot be empty.
1121       NewLine = CurrentLine;
1122       return false;
1123     }
1124 
1125     NewLine = CurrentLine;
1126     if (CurrentLine >= End)
1127       return false;
1128 
1129     // Check if the empty namespace is actually affected by changed ranges.
1130     if (!AffectedRangeMgr.affectsCharSourceRange(CharSourceRange::getCharRange(
1131             AnnotatedLines[InitLine]->First->Tok.getLocation(),
1132             AnnotatedLines[CurrentLine]->Last->Tok.getEndLoc())))
1133       return false;
1134 
1135     for (unsigned i = InitLine; i <= CurrentLine; ++i) {
1136       DeletedLines.insert(i);
1137     }
1138 
1139     return true;
1140   }
1141 
1142   // Checks pairs {start, start->next},..., {end->previous, end} and deletes one
1143   // of the token in the pair if the left token has \p LK token kind and the
1144   // right token has \p RK token kind. If \p DeleteLeft is true, the left token
1145   // is deleted on match; otherwise, the right token is deleted.
1146   template <typename LeftKind, typename RightKind>
1147   void cleanupPair(FormatToken *Start, LeftKind LK, RightKind RK,
1148                    bool DeleteLeft) {
1149     auto NextNotDeleted = [this](const FormatToken &Tok) -> FormatToken * {
1150       for (auto *Res = Tok.Next; Res; Res = Res->Next)
1151         if (!Res->is(tok::comment) &&
1152             DeletedTokens.find(Res) == DeletedTokens.end())
1153           return Res;
1154       return nullptr;
1155     };
1156     for (auto *Left = Start; Left;) {
1157       auto *Right = NextNotDeleted(*Left);
1158       if (!Right)
1159         break;
1160       if (Left->is(LK) && Right->is(RK)) {
1161         deleteToken(DeleteLeft ? Left : Right);
1162         for (auto *Tok = Left->Next; Tok && Tok != Right; Tok = Tok->Next)
1163           deleteToken(Tok);
1164         // If the right token is deleted, we should keep the left token
1165         // unchanged and pair it with the new right token.
1166         if (!DeleteLeft)
1167           continue;
1168       }
1169       Left = Right;
1170     }
1171   }
1172 
1173   template <typename LeftKind, typename RightKind>
1174   void cleanupLeft(FormatToken *Start, LeftKind LK, RightKind RK) {
1175     cleanupPair(Start, LK, RK, /*DeleteLeft=*/true);
1176   }
1177 
1178   template <typename LeftKind, typename RightKind>
1179   void cleanupRight(FormatToken *Start, LeftKind LK, RightKind RK) {
1180     cleanupPair(Start, LK, RK, /*DeleteLeft=*/false);
1181   }
1182 
1183   // Delete the given token.
1184   inline void deleteToken(FormatToken *Tok) {
1185     if (Tok)
1186       DeletedTokens.insert(Tok);
1187   }
1188 
1189   tooling::Replacements generateFixes() {
1190     tooling::Replacements Fixes;
1191     std::vector<FormatToken *> Tokens;
1192     std::copy(DeletedTokens.begin(), DeletedTokens.end(),
1193               std::back_inserter(Tokens));
1194 
1195     // Merge multiple continuous token deletions into one big deletion so that
1196     // the number of replacements can be reduced. This makes computing affected
1197     // ranges more efficient when we run reformat on the changed code.
1198     unsigned Idx = 0;
1199     while (Idx < Tokens.size()) {
1200       unsigned St = Idx, End = Idx;
1201       while ((End + 1) < Tokens.size() &&
1202              Tokens[End]->Next == Tokens[End + 1]) {
1203         End++;
1204       }
1205       auto SR = CharSourceRange::getCharRange(Tokens[St]->Tok.getLocation(),
1206                                               Tokens[End]->Tok.getEndLoc());
1207       auto Err =
1208           Fixes.add(tooling::Replacement(Env.getSourceManager(), SR, ""));
1209       // FIXME: better error handling. for now just print error message and skip
1210       // for the release version.
1211       if (Err) {
1212         llvm::errs() << llvm::toString(std::move(Err)) << "\n";
1213         assert(false && "Fixes must not conflict!");
1214       }
1215       Idx = End + 1;
1216     }
1217 
1218     return Fixes;
1219   }
1220 
1221   // Class for less-than inequality comparason for the set `RedundantTokens`.
1222   // We store tokens in the order they appear in the translation unit so that
1223   // we do not need to sort them in `generateFixes()`.
1224   struct FormatTokenLess {
1225     FormatTokenLess(const SourceManager &SM) : SM(SM) {}
1226 
1227     bool operator()(const FormatToken *LHS, const FormatToken *RHS) const {
1228       return SM.isBeforeInTranslationUnit(LHS->Tok.getLocation(),
1229                                           RHS->Tok.getLocation());
1230     }
1231     const SourceManager &SM;
1232   };
1233 
1234   // Tokens to be deleted.
1235   std::set<FormatToken *, FormatTokenLess> DeletedTokens;
1236 };
1237 
1238 struct IncludeDirective {
1239   StringRef Filename;
1240   StringRef Text;
1241   unsigned Offset;
1242   int Category;
1243 };
1244 
1245 } // end anonymous namespace
1246 
1247 // Determines whether 'Ranges' intersects with ('Start', 'End').
1248 static bool affectsRange(ArrayRef<tooling::Range> Ranges, unsigned Start,
1249                          unsigned End) {
1250   for (auto Range : Ranges) {
1251     if (Range.getOffset() < End &&
1252         Range.getOffset() + Range.getLength() > Start)
1253       return true;
1254   }
1255   return false;
1256 }
1257 
1258 // Returns a pair (Index, OffsetToEOL) describing the position of the cursor
1259 // before sorting/deduplicating. Index is the index of the include under the
1260 // cursor in the original set of includes. If this include has duplicates, it is
1261 // the index of the first of the duplicates as the others are going to be
1262 // removed. OffsetToEOL describes the cursor's position relative to the end of
1263 // its current line.
1264 // If `Cursor` is not on any #include, `Index` will be UINT_MAX.
1265 static std::pair<unsigned, unsigned>
1266 FindCursorIndex(const SmallVectorImpl<IncludeDirective> &Includes,
1267                 const SmallVectorImpl<unsigned> &Indices, unsigned Cursor) {
1268   unsigned CursorIndex = UINT_MAX;
1269   unsigned OffsetToEOL = 0;
1270   for (int i = 0, e = Includes.size(); i != e; ++i) {
1271     unsigned Start = Includes[Indices[i]].Offset;
1272     unsigned End = Start + Includes[Indices[i]].Text.size();
1273     if (!(Cursor >= Start && Cursor < End))
1274       continue;
1275     CursorIndex = Indices[i];
1276     OffsetToEOL = End - Cursor;
1277     // Put the cursor on the only remaining #include among the duplicate
1278     // #includes.
1279     while (--i >= 0 && Includes[CursorIndex].Text == Includes[Indices[i]].Text)
1280       CursorIndex = i;
1281     break;
1282   }
1283   return std::make_pair(CursorIndex, OffsetToEOL);
1284 }
1285 
1286 // Sorts and deduplicate a block of includes given by 'Includes' alphabetically
1287 // adding the necessary replacement to 'Replaces'. 'Includes' must be in strict
1288 // source order.
1289 // #include directives with the same text will be deduplicated, and only the
1290 // first #include in the duplicate #includes remains. If the `Cursor` is
1291 // provided and put on a deleted #include, it will be moved to the remaining
1292 // #include in the duplicate #includes.
1293 static void sortCppIncludes(const FormatStyle &Style,
1294                             const SmallVectorImpl<IncludeDirective> &Includes,
1295                             ArrayRef<tooling::Range> Ranges, StringRef FileName,
1296                             tooling::Replacements &Replaces, unsigned *Cursor) {
1297   unsigned IncludesBeginOffset = Includes.front().Offset;
1298   unsigned IncludesEndOffset =
1299       Includes.back().Offset + Includes.back().Text.size();
1300   unsigned IncludesBlockSize = IncludesEndOffset - IncludesBeginOffset;
1301   if (!affectsRange(Ranges, IncludesBeginOffset, IncludesEndOffset))
1302     return;
1303   SmallVector<unsigned, 16> Indices;
1304   for (unsigned i = 0, e = Includes.size(); i != e; ++i)
1305     Indices.push_back(i);
1306   std::stable_sort(
1307       Indices.begin(), Indices.end(), [&](unsigned LHSI, unsigned RHSI) {
1308         return std::tie(Includes[LHSI].Category, Includes[LHSI].Filename) <
1309                std::tie(Includes[RHSI].Category, Includes[RHSI].Filename);
1310       });
1311   // The index of the include on which the cursor will be put after
1312   // sorting/deduplicating.
1313   unsigned CursorIndex;
1314   // The offset from cursor to the end of line.
1315   unsigned CursorToEOLOffset;
1316   if (Cursor)
1317     std::tie(CursorIndex, CursorToEOLOffset) =
1318         FindCursorIndex(Includes, Indices, *Cursor);
1319 
1320   // Deduplicate #includes.
1321   Indices.erase(std::unique(Indices.begin(), Indices.end(),
1322                             [&](unsigned LHSI, unsigned RHSI) {
1323                               return Includes[LHSI].Text == Includes[RHSI].Text;
1324                             }),
1325                 Indices.end());
1326 
1327   // If the #includes are out of order, we generate a single replacement fixing
1328   // the entire block. Otherwise, no replacement is generated.
1329   if (Indices.size() == Includes.size() &&
1330       std::is_sorted(Indices.begin(), Indices.end()))
1331     return;
1332 
1333   std::string result;
1334   for (unsigned Index : Indices) {
1335     if (!result.empty())
1336       result += "\n";
1337     result += Includes[Index].Text;
1338     if (Cursor && CursorIndex == Index)
1339       *Cursor = IncludesBeginOffset + result.size() - CursorToEOLOffset;
1340   }
1341 
1342   auto Err = Replaces.add(tooling::Replacement(
1343       FileName, Includes.front().Offset, IncludesBlockSize, result));
1344   // FIXME: better error handling. For now, just skip the replacement for the
1345   // release version.
1346   if (Err) {
1347     llvm::errs() << llvm::toString(std::move(Err)) << "\n";
1348     assert(false);
1349   }
1350 }
1351 
1352 namespace {
1353 
1354 // This class manages priorities of #include categories and calculates
1355 // priorities for headers.
1356 class IncludeCategoryManager {
1357 public:
1358   IncludeCategoryManager(const FormatStyle &Style, StringRef FileName)
1359       : Style(Style), FileName(FileName) {
1360     FileStem = llvm::sys::path::stem(FileName);
1361     for (const auto &Category : Style.IncludeCategories)
1362       CategoryRegexs.emplace_back(Category.Regex);
1363     IsMainFile = FileName.endswith(".c") || FileName.endswith(".cc") ||
1364                  FileName.endswith(".cpp") || FileName.endswith(".c++") ||
1365                  FileName.endswith(".cxx") || FileName.endswith(".m") ||
1366                  FileName.endswith(".mm");
1367   }
1368 
1369   // Returns the priority of the category which \p IncludeName belongs to.
1370   // If \p CheckMainHeader is true and \p IncludeName is a main header, returns
1371   // 0. Otherwise, returns the priority of the matching category or INT_MAX.
1372   int getIncludePriority(StringRef IncludeName, bool CheckMainHeader) {
1373     int Ret = INT_MAX;
1374     for (unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i)
1375       if (CategoryRegexs[i].match(IncludeName)) {
1376         Ret = Style.IncludeCategories[i].Priority;
1377         break;
1378       }
1379     if (CheckMainHeader && IsMainFile && Ret > 0 && isMainHeader(IncludeName))
1380       Ret = 0;
1381     return Ret;
1382   }
1383 
1384 private:
1385   bool isMainHeader(StringRef IncludeName) const {
1386     if (!IncludeName.startswith("\""))
1387       return false;
1388     StringRef HeaderStem =
1389         llvm::sys::path::stem(IncludeName.drop_front(1).drop_back(1));
1390     if (FileStem.startswith(HeaderStem)) {
1391       llvm::Regex MainIncludeRegex(
1392           (HeaderStem + Style.IncludeIsMainRegex).str());
1393       if (MainIncludeRegex.match(FileStem))
1394         return true;
1395     }
1396     return false;
1397   }
1398 
1399   const FormatStyle &Style;
1400   bool IsMainFile;
1401   StringRef FileName;
1402   StringRef FileStem;
1403   SmallVector<llvm::Regex, 4> CategoryRegexs;
1404 };
1405 
1406 const char IncludeRegexPattern[] =
1407     R"(^[\t\ ]*#[\t\ ]*(import|include)[^"<]*(["<][^">]*[">]))";
1408 
1409 } // anonymous namespace
1410 
1411 tooling::Replacements sortCppIncludes(const FormatStyle &Style, StringRef Code,
1412                                       ArrayRef<tooling::Range> Ranges,
1413                                       StringRef FileName,
1414                                       tooling::Replacements &Replaces,
1415                                       unsigned *Cursor) {
1416   unsigned Prev = 0;
1417   unsigned SearchFrom = 0;
1418   llvm::Regex IncludeRegex(IncludeRegexPattern);
1419   SmallVector<StringRef, 4> Matches;
1420   SmallVector<IncludeDirective, 16> IncludesInBlock;
1421 
1422   // In compiled files, consider the first #include to be the main #include of
1423   // the file if it is not a system #include. This ensures that the header
1424   // doesn't have hidden dependencies
1425   // (http://llvm.org/docs/CodingStandards.html#include-style).
1426   //
1427   // FIXME: Do some sanity checking, e.g. edit distance of the base name, to fix
1428   // cases where the first #include is unlikely to be the main header.
1429   IncludeCategoryManager Categories(Style, FileName);
1430   bool FirstIncludeBlock = true;
1431   bool MainIncludeFound = false;
1432   bool FormattingOff = false;
1433 
1434   for (;;) {
1435     auto Pos = Code.find('\n', SearchFrom);
1436     StringRef Line =
1437         Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
1438 
1439     StringRef Trimmed = Line.trim();
1440     if (Trimmed == "// clang-format off")
1441       FormattingOff = true;
1442     else if (Trimmed == "// clang-format on")
1443       FormattingOff = false;
1444 
1445     if (!FormattingOff && !Line.endswith("\\")) {
1446       if (IncludeRegex.match(Line, &Matches)) {
1447         StringRef IncludeName = Matches[2];
1448         int Category = Categories.getIncludePriority(
1449             IncludeName,
1450             /*CheckMainHeader=*/!MainIncludeFound && FirstIncludeBlock);
1451         if (Category == 0)
1452           MainIncludeFound = true;
1453         IncludesInBlock.push_back({IncludeName, Line, Prev, Category});
1454       } else if (!IncludesInBlock.empty()) {
1455         sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces,
1456                         Cursor);
1457         IncludesInBlock.clear();
1458         FirstIncludeBlock = false;
1459       }
1460       Prev = Pos + 1;
1461     }
1462     if (Pos == StringRef::npos || Pos + 1 == Code.size())
1463       break;
1464     SearchFrom = Pos + 1;
1465   }
1466   if (!IncludesInBlock.empty())
1467     sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces, Cursor);
1468   return Replaces;
1469 }
1470 
1471 bool isMpegTS(StringRef Code) {
1472   // MPEG transport streams use the ".ts" file extension. clang-format should
1473   // not attempt to format those. MPEG TS' frame format starts with 0x47 every
1474   // 189 bytes - detect that and return.
1475   return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47;
1476 }
1477 
1478 tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
1479                                    ArrayRef<tooling::Range> Ranges,
1480                                    StringRef FileName, unsigned *Cursor) {
1481   tooling::Replacements Replaces;
1482   if (!Style.SortIncludes)
1483     return Replaces;
1484   if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&
1485       isMpegTS(Code))
1486     return Replaces;
1487   if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript)
1488     return sortJavaScriptImports(Style, Code, Ranges, FileName);
1489   sortCppIncludes(Style, Code, Ranges, FileName, Replaces, Cursor);
1490   return Replaces;
1491 }
1492 
1493 template <typename T>
1494 static llvm::Expected<tooling::Replacements>
1495 processReplacements(T ProcessFunc, StringRef Code,
1496                     const tooling::Replacements &Replaces,
1497                     const FormatStyle &Style) {
1498   if (Replaces.empty())
1499     return tooling::Replacements();
1500 
1501   auto NewCode = applyAllReplacements(Code, Replaces);
1502   if (!NewCode)
1503     return NewCode.takeError();
1504   std::vector<tooling::Range> ChangedRanges = Replaces.getAffectedRanges();
1505   StringRef FileName = Replaces.begin()->getFilePath();
1506 
1507   tooling::Replacements FormatReplaces =
1508       ProcessFunc(Style, *NewCode, ChangedRanges, FileName);
1509 
1510   return Replaces.merge(FormatReplaces);
1511 }
1512 
1513 llvm::Expected<tooling::Replacements>
1514 formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
1515                    const FormatStyle &Style) {
1516   // We need to use lambda function here since there are two versions of
1517   // `sortIncludes`.
1518   auto SortIncludes = [](const FormatStyle &Style, StringRef Code,
1519                          std::vector<tooling::Range> Ranges,
1520                          StringRef FileName) -> tooling::Replacements {
1521     return sortIncludes(Style, Code, Ranges, FileName);
1522   };
1523   auto SortedReplaces =
1524       processReplacements(SortIncludes, Code, Replaces, Style);
1525   if (!SortedReplaces)
1526     return SortedReplaces.takeError();
1527 
1528   // We need to use lambda function here since there are two versions of
1529   // `reformat`.
1530   auto Reformat = [](const FormatStyle &Style, StringRef Code,
1531                      std::vector<tooling::Range> Ranges,
1532                      StringRef FileName) -> tooling::Replacements {
1533     return reformat(Style, Code, Ranges, FileName);
1534   };
1535   return processReplacements(Reformat, Code, *SortedReplaces, Style);
1536 }
1537 
1538 namespace {
1539 
1540 inline bool isHeaderInsertion(const tooling::Replacement &Replace) {
1541   return Replace.getOffset() == UINT_MAX && Replace.getLength() == 0 &&
1542          llvm::Regex(IncludeRegexPattern).match(Replace.getReplacementText());
1543 }
1544 
1545 inline bool isHeaderDeletion(const tooling::Replacement &Replace) {
1546   return Replace.getOffset() == UINT_MAX && Replace.getLength() == 1;
1547 }
1548 
1549 // Returns the offset after skipping a sequence of tokens, matched by \p
1550 // GetOffsetAfterSequence, from the start of the code.
1551 // \p GetOffsetAfterSequence should be a function that matches a sequence of
1552 // tokens and returns an offset after the sequence.
1553 unsigned getOffsetAfterTokenSequence(
1554     StringRef FileName, StringRef Code, const FormatStyle &Style,
1555     std::function<unsigned(const SourceManager &, Lexer &, Token &)>
1556         GetOffsetAfterSequense) {
1557   std::unique_ptr<Environment> Env =
1558       Environment::CreateVirtualEnvironment(Code, FileName, /*Ranges=*/{});
1559   const SourceManager &SourceMgr = Env->getSourceManager();
1560   Lexer Lex(Env->getFileID(), SourceMgr.getBuffer(Env->getFileID()), SourceMgr,
1561             getFormattingLangOpts(Style));
1562   Token Tok;
1563   // Get the first token.
1564   Lex.LexFromRawLexer(Tok);
1565   return GetOffsetAfterSequense(SourceMgr, Lex, Tok);
1566 }
1567 
1568 // Check if a sequence of tokens is like "#<Name> <raw_identifier>". If it is,
1569 // \p Tok will be the token after this directive; otherwise, it can be any token
1570 // after the given \p Tok (including \p Tok).
1571 bool checkAndConsumeDirectiveWithName(Lexer &Lex, StringRef Name, Token &Tok) {
1572   bool Matched = Tok.is(tok::hash) && !Lex.LexFromRawLexer(Tok) &&
1573                  Tok.is(tok::raw_identifier) &&
1574                  Tok.getRawIdentifier() == Name && !Lex.LexFromRawLexer(Tok) &&
1575                  Tok.is(tok::raw_identifier);
1576   if (Matched)
1577     Lex.LexFromRawLexer(Tok);
1578   return Matched;
1579 }
1580 
1581 void skipComments(Lexer &Lex, Token &Tok) {
1582   while (Tok.is(tok::comment))
1583     if (Lex.LexFromRawLexer(Tok))
1584       return;
1585 }
1586 
1587 // Returns the offset after header guard directives and any comments
1588 // before/after header guards. If no header guard presents in the code, this
1589 // will returns the offset after skipping all comments from the start of the
1590 // code.
1591 unsigned getOffsetAfterHeaderGuardsAndComments(StringRef FileName,
1592                                                StringRef Code,
1593                                                const FormatStyle &Style) {
1594   return getOffsetAfterTokenSequence(
1595       FileName, Code, Style,
1596       [](const SourceManager &SM, Lexer &Lex, Token Tok) {
1597         skipComments(Lex, Tok);
1598         unsigned InitialOffset = SM.getFileOffset(Tok.getLocation());
1599         if (checkAndConsumeDirectiveWithName(Lex, "ifndef", Tok)) {
1600           skipComments(Lex, Tok);
1601           if (checkAndConsumeDirectiveWithName(Lex, "define", Tok))
1602             return SM.getFileOffset(Tok.getLocation());
1603         }
1604         return InitialOffset;
1605       });
1606 }
1607 
1608 // Check if a sequence of tokens is like
1609 //    "#include ("header.h" | <header.h>)".
1610 // If it is, \p Tok will be the token after this directive; otherwise, it can be
1611 // any token after the given \p Tok (including \p Tok).
1612 bool checkAndConsumeInclusiveDirective(Lexer &Lex, Token &Tok) {
1613   auto Matched = [&]() {
1614     Lex.LexFromRawLexer(Tok);
1615     return true;
1616   };
1617   if (Tok.is(tok::hash) && !Lex.LexFromRawLexer(Tok) &&
1618       Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "include") {
1619     if (Lex.LexFromRawLexer(Tok))
1620       return false;
1621     if (Tok.is(tok::string_literal))
1622       return Matched();
1623     if (Tok.is(tok::less)) {
1624       while (!Lex.LexFromRawLexer(Tok) && Tok.isNot(tok::greater)) {
1625       }
1626       if (Tok.is(tok::greater))
1627         return Matched();
1628     }
1629   }
1630   return false;
1631 }
1632 
1633 // Returns the offset of the last #include directive after which a new
1634 // #include can be inserted. This ignores #include's after the #include block(s)
1635 // in the beginning of a file to avoid inserting headers into code sections
1636 // where new #include's should not be added by default.
1637 // These code sections include:
1638 //      - raw string literals (containing #include).
1639 //      - #if blocks.
1640 //      - Special #include's among declarations (e.g. functions).
1641 //
1642 // If no #include after which a new #include can be inserted, this returns the
1643 // offset after skipping all comments from the start of the code.
1644 // Inserting after an #include is not allowed if it comes after code that is not
1645 // #include (e.g. pre-processing directive that is not #include, declarations).
1646 unsigned getMaxHeaderInsertionOffset(StringRef FileName, StringRef Code,
1647                                      const FormatStyle &Style) {
1648   return getOffsetAfterTokenSequence(
1649       FileName, Code, Style,
1650       [](const SourceManager &SM, Lexer &Lex, Token Tok) {
1651         skipComments(Lex, Tok);
1652         unsigned MaxOffset = SM.getFileOffset(Tok.getLocation());
1653         while (checkAndConsumeInclusiveDirective(Lex, Tok))
1654           MaxOffset = SM.getFileOffset(Tok.getLocation());
1655         return MaxOffset;
1656       });
1657 }
1658 
1659 bool isDeletedHeader(llvm::StringRef HeaderName,
1660                      const std::set<llvm::StringRef> &HeadersToDelete) {
1661   return HeadersToDelete.count(HeaderName) ||
1662          HeadersToDelete.count(HeaderName.trim("\"<>"));
1663 }
1664 
1665 // FIXME: insert empty lines between newly created blocks.
1666 tooling::Replacements
1667 fixCppIncludeInsertions(StringRef Code, const tooling::Replacements &Replaces,
1668                         const FormatStyle &Style) {
1669   if (!Style.IsCpp())
1670     return Replaces;
1671 
1672   tooling::Replacements HeaderInsertions;
1673   std::set<llvm::StringRef> HeadersToDelete;
1674   tooling::Replacements Result;
1675   for (const auto &R : Replaces) {
1676     if (isHeaderInsertion(R)) {
1677       // Replacements from \p Replaces must be conflict-free already, so we can
1678       // simply consume the error.
1679       llvm::consumeError(HeaderInsertions.add(R));
1680     } else if (isHeaderDeletion(R)) {
1681       HeadersToDelete.insert(R.getReplacementText());
1682     } else if (R.getOffset() == UINT_MAX) {
1683       llvm::errs() << "Insertions other than header #include insertion are "
1684                       "not supported! "
1685                    << R.getReplacementText() << "\n";
1686     } else {
1687       llvm::consumeError(Result.add(R));
1688     }
1689   }
1690   if (HeaderInsertions.empty() && HeadersToDelete.empty())
1691     return Replaces;
1692 
1693   llvm::Regex IncludeRegex(IncludeRegexPattern);
1694   llvm::Regex DefineRegex(R"(^[\t\ ]*#[\t\ ]*define[\t\ ]*[^\\]*$)");
1695   SmallVector<StringRef, 4> Matches;
1696 
1697   StringRef FileName = Replaces.begin()->getFilePath();
1698   IncludeCategoryManager Categories(Style, FileName);
1699 
1700   // Record the offset of the end of the last include in each category.
1701   std::map<int, int> CategoryEndOffsets;
1702   // All possible priorities.
1703   // Add 0 for main header and INT_MAX for headers that are not in any category.
1704   std::set<int> Priorities = {0, INT_MAX};
1705   for (const auto &Category : Style.IncludeCategories)
1706     Priorities.insert(Category.Priority);
1707   int FirstIncludeOffset = -1;
1708   // All new headers should be inserted after this offset.
1709   unsigned MinInsertOffset =
1710       getOffsetAfterHeaderGuardsAndComments(FileName, Code, Style);
1711   StringRef TrimmedCode = Code.drop_front(MinInsertOffset);
1712   // Max insertion offset in the original code.
1713   unsigned MaxInsertOffset =
1714       MinInsertOffset +
1715       getMaxHeaderInsertionOffset(FileName, TrimmedCode, Style);
1716   SmallVector<StringRef, 32> Lines;
1717   TrimmedCode.split(Lines, '\n');
1718   unsigned Offset = MinInsertOffset;
1719   unsigned NextLineOffset;
1720   std::set<StringRef> ExistingIncludes;
1721   for (auto Line : Lines) {
1722     NextLineOffset = std::min(Code.size(), Offset + Line.size() + 1);
1723     if (IncludeRegex.match(Line, &Matches)) {
1724       // The header name with quotes or angle brackets.
1725       StringRef IncludeName = Matches[2];
1726       ExistingIncludes.insert(IncludeName);
1727       // Only record the offset of current #include if we can insert after it.
1728       if (Offset <= MaxInsertOffset) {
1729         int Category = Categories.getIncludePriority(
1730             IncludeName, /*CheckMainHeader=*/FirstIncludeOffset < 0);
1731         CategoryEndOffsets[Category] = NextLineOffset;
1732         if (FirstIncludeOffset < 0)
1733           FirstIncludeOffset = Offset;
1734       }
1735       if (isDeletedHeader(IncludeName, HeadersToDelete)) {
1736         // If this is the last line without trailing newline, we need to make
1737         // sure we don't delete across the file boundary.
1738         unsigned Length = std::min(Line.size() + 1, Code.size() - Offset);
1739         llvm::Error Err =
1740             Result.add(tooling::Replacement(FileName, Offset, Length, ""));
1741         if (Err) {
1742           // Ignore the deletion on conflict.
1743           llvm::errs() << "Failed to add header deletion replacement for "
1744                        << IncludeName << ": " << llvm::toString(std::move(Err))
1745                        << "\n";
1746         }
1747       }
1748     }
1749     Offset = NextLineOffset;
1750   }
1751 
1752   // Populate CategoryEndOfssets:
1753   // - Ensure that CategoryEndOffset[Highest] is always populated.
1754   // - If CategoryEndOffset[Priority] isn't set, use the next higher value that
1755   //   is set, up to CategoryEndOffset[Highest].
1756   auto Highest = Priorities.begin();
1757   if (CategoryEndOffsets.find(*Highest) == CategoryEndOffsets.end()) {
1758     if (FirstIncludeOffset >= 0)
1759       CategoryEndOffsets[*Highest] = FirstIncludeOffset;
1760     else
1761       CategoryEndOffsets[*Highest] = MinInsertOffset;
1762   }
1763   // By this point, CategoryEndOffset[Highest] is always set appropriately:
1764   //  - to an appropriate location before/after existing #includes, or
1765   //  - to right after the header guard, or
1766   //  - to the beginning of the file.
1767   for (auto I = ++Priorities.begin(), E = Priorities.end(); I != E; ++I)
1768     if (CategoryEndOffsets.find(*I) == CategoryEndOffsets.end())
1769       CategoryEndOffsets[*I] = CategoryEndOffsets[*std::prev(I)];
1770 
1771   bool NeedNewLineAtEnd = !Code.empty() && Code.back() != '\n';
1772   for (const auto &R : HeaderInsertions) {
1773     auto IncludeDirective = R.getReplacementText();
1774     bool Matched = IncludeRegex.match(IncludeDirective, &Matches);
1775     assert(Matched && "Header insertion replacement must have replacement text "
1776                       "'#include ...'");
1777     (void)Matched;
1778     auto IncludeName = Matches[2];
1779     if (ExistingIncludes.find(IncludeName) != ExistingIncludes.end()) {
1780       DEBUG(llvm::dbgs() << "Skip adding existing include : " << IncludeName
1781                          << "\n");
1782       continue;
1783     }
1784     int Category =
1785         Categories.getIncludePriority(IncludeName, /*CheckMainHeader=*/true);
1786     Offset = CategoryEndOffsets[Category];
1787     std::string NewInclude = !IncludeDirective.endswith("\n")
1788                                  ? (IncludeDirective + "\n").str()
1789                                  : IncludeDirective.str();
1790     // When inserting headers at end of the code, also append '\n' to the code
1791     // if it does not end with '\n'.
1792     if (NeedNewLineAtEnd && Offset == Code.size()) {
1793       NewInclude = "\n" + NewInclude;
1794       NeedNewLineAtEnd = false;
1795     }
1796     auto NewReplace = tooling::Replacement(FileName, Offset, 0, NewInclude);
1797     auto Err = Result.add(NewReplace);
1798     if (Err) {
1799       llvm::consumeError(std::move(Err));
1800       unsigned NewOffset = Result.getShiftedCodePosition(Offset);
1801       NewReplace = tooling::Replacement(FileName, NewOffset, 0, NewInclude);
1802       Result = Result.merge(tooling::Replacements(NewReplace));
1803     }
1804   }
1805   return Result;
1806 }
1807 
1808 } // anonymous namespace
1809 
1810 llvm::Expected<tooling::Replacements>
1811 cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
1812                           const FormatStyle &Style) {
1813   // We need to use lambda function here since there are two versions of
1814   // `cleanup`.
1815   auto Cleanup = [](const FormatStyle &Style, StringRef Code,
1816                     std::vector<tooling::Range> Ranges,
1817                     StringRef FileName) -> tooling::Replacements {
1818     return cleanup(Style, Code, Ranges, FileName);
1819   };
1820   // Make header insertion replacements insert new headers into correct blocks.
1821   tooling::Replacements NewReplaces =
1822       fixCppIncludeInsertions(Code, Replaces, Style);
1823   return processReplacements(Cleanup, Code, NewReplaces, Style);
1824 }
1825 
1826 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1827                                ArrayRef<tooling::Range> Ranges,
1828                                StringRef FileName, bool *IncompleteFormat) {
1829   FormatStyle Expanded = expandPresets(Style);
1830   if (Expanded.DisableFormat)
1831     return tooling::Replacements();
1832   if (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code))
1833     return tooling::Replacements();
1834   auto Env = Environment::CreateVirtualEnvironment(Code, FileName, Ranges);
1835 
1836   auto reformatAfterApplying = [&] (TokenAnalyzer& Fixer) {
1837     tooling::Replacements Fixes = Fixer.process();
1838     if (!Fixes.empty()) {
1839       auto NewCode = applyAllReplacements(Code, Fixes);
1840       if (NewCode) {
1841         auto NewEnv = Environment::CreateVirtualEnvironment(
1842             *NewCode, FileName,
1843             tooling::calculateRangesAfterReplacements(Fixes, Ranges));
1844         Formatter Format(*NewEnv, Expanded, IncompleteFormat);
1845         return Fixes.merge(Format.process());
1846       }
1847     }
1848     Formatter Format(*Env, Expanded, IncompleteFormat);
1849     return Format.process();
1850   };
1851 
1852   if (Style.Language == FormatStyle::LK_Cpp &&
1853       Style.FixNamespaceComments) {
1854     NamespaceEndCommentsFixer CommentsFixer(*Env, Expanded);
1855     return reformatAfterApplying(CommentsFixer);
1856   }
1857 
1858   if (Style.Language == FormatStyle::LK_JavaScript &&
1859       Style.JavaScriptQuotes != FormatStyle::JSQS_Leave) {
1860     JavaScriptRequoter Requoter(*Env, Expanded);
1861     return reformatAfterApplying(Requoter);
1862   }
1863 
1864   Formatter Format(*Env, Expanded, IncompleteFormat);
1865   return Format.process();
1866 }
1867 
1868 tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
1869                               ArrayRef<tooling::Range> Ranges,
1870                               StringRef FileName) {
1871   std::unique_ptr<Environment> Env =
1872       Environment::CreateVirtualEnvironment(Code, FileName, Ranges);
1873   Cleaner Clean(*Env, Style);
1874   return Clean.process();
1875 }
1876 
1877 tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style,
1878                                               StringRef Code,
1879                                               ArrayRef<tooling::Range> Ranges,
1880                                               StringRef FileName) {
1881   std::unique_ptr<Environment> Env =
1882       Environment::CreateVirtualEnvironment(Code, FileName, Ranges);
1883   NamespaceEndCommentsFixer Fix(*Env, Style);
1884   return Fix.process();
1885 }
1886 
1887 LangOptions getFormattingLangOpts(const FormatStyle &Style) {
1888   LangOptions LangOpts;
1889   LangOpts.CPlusPlus = 1;
1890   LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
1891   LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
1892   LangOpts.LineComment = 1;
1893   bool AlternativeOperators = Style.IsCpp();
1894   LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
1895   LangOpts.Bool = 1;
1896   LangOpts.ObjC1 = 1;
1897   LangOpts.ObjC2 = 1;
1898   LangOpts.MicrosoftExt = 1;    // To get kw___try, kw___finally.
1899   LangOpts.DeclSpecKeyword = 1; // To get __declspec.
1900   return LangOpts;
1901 }
1902 
1903 const char *StyleOptionHelpDescription =
1904     "Coding style, currently supports:\n"
1905     "  LLVM, Google, Chromium, Mozilla, WebKit.\n"
1906     "Use -style=file to load style configuration from\n"
1907     ".clang-format file located in one of the parent\n"
1908     "directories of the source file (or current\n"
1909     "directory for stdin).\n"
1910     "Use -style=\"{key: value, ...}\" to set specific\n"
1911     "parameters, e.g.:\n"
1912     "  -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1913 
1914 static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
1915   if (FileName.endswith(".java"))
1916     return FormatStyle::LK_Java;
1917   if (FileName.endswith_lower(".js") || FileName.endswith_lower(".ts"))
1918     return FormatStyle::LK_JavaScript; // JavaScript or TypeScript.
1919   if (FileName.endswith(".m") || FileName.endswith(".mm"))
1920     return FormatStyle::LK_ObjC;
1921   if (FileName.endswith_lower(".proto") ||
1922       FileName.endswith_lower(".protodevel"))
1923     return FormatStyle::LK_Proto;
1924   if (FileName.endswith_lower(".td"))
1925     return FormatStyle::LK_TableGen;
1926   return FormatStyle::LK_Cpp;
1927 }
1928 
1929 llvm::Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName,
1930                                      StringRef FallbackStyleName,
1931                                      StringRef Code, vfs::FileSystem *FS) {
1932   if (!FS) {
1933     FS = vfs::getRealFileSystem().get();
1934   }
1935   FormatStyle Style = getLLVMStyle();
1936   Style.Language = getLanguageByFileName(FileName);
1937 
1938   // This is a very crude detection of whether a header contains ObjC code that
1939   // should be improved over time and probably be done on tokens, not one the
1940   // bare content of the file.
1941   if (Style.Language == FormatStyle::LK_Cpp && FileName.endswith(".h") &&
1942       (Code.contains("\n- (") || Code.contains("\n+ (")))
1943     Style.Language = FormatStyle::LK_ObjC;
1944 
1945   FormatStyle FallbackStyle = getNoStyle();
1946   if (!getPredefinedStyle(FallbackStyleName, Style.Language, &FallbackStyle))
1947     return make_string_error("Invalid fallback style \"" + FallbackStyleName);
1948 
1949   if (StyleName.startswith("{")) {
1950     // Parse YAML/JSON style from the command line.
1951     if (std::error_code ec = parseConfiguration(StyleName, &Style))
1952       return make_string_error("Error parsing -style: " + ec.message());
1953     return Style;
1954   }
1955 
1956   if (!StyleName.equals_lower("file")) {
1957     if (!getPredefinedStyle(StyleName, Style.Language, &Style))
1958       return make_string_error("Invalid value for -style");
1959     return Style;
1960   }
1961 
1962   // Look for .clang-format/_clang-format file in the file's parent directories.
1963   SmallString<128> UnsuitableConfigFiles;
1964   SmallString<128> Path(FileName);
1965   if (std::error_code EC = FS->makeAbsolute(Path))
1966     return make_string_error(EC.message());
1967 
1968   for (StringRef Directory = Path; !Directory.empty();
1969        Directory = llvm::sys::path::parent_path(Directory)) {
1970 
1971     auto Status = FS->status(Directory);
1972     if (!Status ||
1973         Status->getType() != llvm::sys::fs::file_type::directory_file) {
1974       continue;
1975     }
1976 
1977     SmallString<128> ConfigFile(Directory);
1978 
1979     llvm::sys::path::append(ConfigFile, ".clang-format");
1980     DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1981 
1982     Status = FS->status(ConfigFile.str());
1983     bool FoundConfigFile =
1984         Status && (Status->getType() == llvm::sys::fs::file_type::regular_file);
1985     if (!FoundConfigFile) {
1986       // Try _clang-format too, since dotfiles are not commonly used on Windows.
1987       ConfigFile = Directory;
1988       llvm::sys::path::append(ConfigFile, "_clang-format");
1989       DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1990       Status = FS->status(ConfigFile.str());
1991       FoundConfigFile = Status && (Status->getType() ==
1992                                    llvm::sys::fs::file_type::regular_file);
1993     }
1994 
1995     if (FoundConfigFile) {
1996       llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
1997           FS->getBufferForFile(ConfigFile.str());
1998       if (std::error_code EC = Text.getError())
1999         return make_string_error(EC.message());
2000       if (std::error_code ec =
2001               parseConfiguration(Text.get()->getBuffer(), &Style)) {
2002         if (ec == ParseError::Unsuitable) {
2003           if (!UnsuitableConfigFiles.empty())
2004             UnsuitableConfigFiles.append(", ");
2005           UnsuitableConfigFiles.append(ConfigFile);
2006           continue;
2007         }
2008         return make_string_error("Error reading " + ConfigFile + ": " +
2009                                  ec.message());
2010       }
2011       DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
2012       return Style;
2013     }
2014   }
2015   if (!UnsuitableConfigFiles.empty())
2016     return make_string_error("Configuration file(s) do(es) not support " +
2017                              getLanguageName(Style.Language) + ": " +
2018                              UnsuitableConfigFiles);
2019   return FallbackStyle;
2020 }
2021 
2022 } // namespace format
2023 } // namespace clang
2024