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