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