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