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 "ContinuationIndenter.h"
18 #include "TokenAnnotator.h"
19 #include "UnwrappedLineFormatter.h"
20 #include "UnwrappedLineParser.h"
21 #include "WhitespaceManager.h"
22 #include "clang/Basic/Diagnostic.h"
23 #include "clang/Basic/DiagnosticOptions.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/Lex/Lexer.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/Support/Allocator.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/Path.h"
30 #include "llvm/Support/Regex.h"
31 #include "llvm/Support/YAMLTraits.h"
32 #include <queue>
33 #include <string>
34 
35 #define DEBUG_TYPE "format-formatter"
36 
37 using clang::format::FormatStyle;
38 
39 LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(std::string)
40 LLVM_YAML_IS_SEQUENCE_VECTOR(clang::format::FormatStyle::IncludeCategory)
41 
42 namespace llvm {
43 namespace yaml {
44 template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
45   static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
46     IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
47     IO.enumCase(Value, "Java", FormatStyle::LK_Java);
48     IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
49     IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
50   }
51 };
52 
53 template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
54   static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
55     IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
56     IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
57     IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
58     IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
59     IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
60   }
61 };
62 
63 template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
64   static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
65     IO.enumCase(Value, "Never", FormatStyle::UT_Never);
66     IO.enumCase(Value, "false", FormatStyle::UT_Never);
67     IO.enumCase(Value, "Always", FormatStyle::UT_Always);
68     IO.enumCase(Value, "true", FormatStyle::UT_Always);
69     IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
70   }
71 };
72 
73 template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
74   static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
75     IO.enumCase(Value, "None", FormatStyle::SFS_None);
76     IO.enumCase(Value, "false", FormatStyle::SFS_None);
77     IO.enumCase(Value, "All", FormatStyle::SFS_All);
78     IO.enumCase(Value, "true", FormatStyle::SFS_All);
79     IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
80     IO.enumCase(Value, "Empty", FormatStyle::SFS_Empty);
81   }
82 };
83 
84 template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
85   static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
86     IO.enumCase(Value, "All", FormatStyle::BOS_All);
87     IO.enumCase(Value, "true", FormatStyle::BOS_All);
88     IO.enumCase(Value, "None", FormatStyle::BOS_None);
89     IO.enumCase(Value, "false", FormatStyle::BOS_None);
90     IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
91   }
92 };
93 
94 template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
95   static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
96     IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
97     IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
98     IO.enumCase(Value, "Mozilla", FormatStyle::BS_Mozilla);
99     IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
100     IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
101     IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
102     IO.enumCase(Value, "WebKit", FormatStyle::BS_WebKit);
103     IO.enumCase(Value, "Custom", FormatStyle::BS_Custom);
104   }
105 };
106 
107 template <>
108 struct ScalarEnumerationTraits<FormatStyle::DefinitionReturnTypeBreakingStyle> {
109   static void
110   enumeration(IO &IO, FormatStyle::DefinitionReturnTypeBreakingStyle &Value) {
111     IO.enumCase(Value, "None", FormatStyle::DRTBS_None);
112     IO.enumCase(Value, "All", FormatStyle::DRTBS_All);
113     IO.enumCase(Value, "TopLevel", FormatStyle::DRTBS_TopLevel);
114 
115     // For backward compatibility.
116     IO.enumCase(Value, "false", FormatStyle::DRTBS_None);
117     IO.enumCase(Value, "true", FormatStyle::DRTBS_All);
118   }
119 };
120 
121 template <>
122 struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
123   static void enumeration(IO &IO,
124                           FormatStyle::NamespaceIndentationKind &Value) {
125     IO.enumCase(Value, "None", FormatStyle::NI_None);
126     IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
127     IO.enumCase(Value, "All", FormatStyle::NI_All);
128   }
129 };
130 
131 template <> struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
132   static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value) {
133     IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
134     IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
135     IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
136 
137     // For backward compatibility.
138     IO.enumCase(Value, "true", FormatStyle::PAS_Left);
139     IO.enumCase(Value, "false", FormatStyle::PAS_Right);
140   }
141 };
142 
143 template <>
144 struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
145   static void enumeration(IO &IO,
146                           FormatStyle::SpaceBeforeParensOptions &Value) {
147     IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
148     IO.enumCase(Value, "ControlStatements",
149                 FormatStyle::SBPO_ControlStatements);
150     IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
151 
152     // For backward compatibility.
153     IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
154     IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
155   }
156 };
157 
158 template <> struct MappingTraits<FormatStyle> {
159   static void mapping(IO &IO, FormatStyle &Style) {
160     // When reading, read the language first, we need it for getPredefinedStyle.
161     IO.mapOptional("Language", Style.Language);
162 
163     if (IO.outputting()) {
164       StringRef StylesArray[] = {"LLVM",    "Google", "Chromium",
165                                  "Mozilla", "WebKit", "GNU"};
166       ArrayRef<StringRef> Styles(StylesArray);
167       for (size_t i = 0, e = Styles.size(); i < e; ++i) {
168         StringRef StyleName(Styles[i]);
169         FormatStyle PredefinedStyle;
170         if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
171             Style == PredefinedStyle) {
172           IO.mapOptional("# BasedOnStyle", StyleName);
173           break;
174         }
175       }
176     } else {
177       StringRef BasedOnStyle;
178       IO.mapOptional("BasedOnStyle", BasedOnStyle);
179       if (!BasedOnStyle.empty()) {
180         FormatStyle::LanguageKind OldLanguage = Style.Language;
181         FormatStyle::LanguageKind Language =
182             ((FormatStyle *)IO.getContext())->Language;
183         if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
184           IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
185           return;
186         }
187         Style.Language = OldLanguage;
188       }
189     }
190 
191     // For backward compatibility.
192     if (!IO.outputting()) {
193       IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
194       IO.mapOptional("IndentFunctionDeclarationAfterType",
195                      Style.IndentWrappedFunctionNames);
196       IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
197       IO.mapOptional("SpaceAfterControlStatementKeyword",
198                      Style.SpaceBeforeParens);
199     }
200 
201     IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
202     IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
203     IO.mapOptional("AlignConsecutiveAssignments",
204                    Style.AlignConsecutiveAssignments);
205     IO.mapOptional("AlignConsecutiveDeclarations",
206                    Style.AlignConsecutiveDeclarations);
207     IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
208     IO.mapOptional("AlignOperands", Style.AlignOperands);
209     IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
210     IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
211                    Style.AllowAllParametersOfDeclarationOnNextLine);
212     IO.mapOptional("AllowShortBlocksOnASingleLine",
213                    Style.AllowShortBlocksOnASingleLine);
214     IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
215                    Style.AllowShortCaseLabelsOnASingleLine);
216     IO.mapOptional("AllowShortFunctionsOnASingleLine",
217                    Style.AllowShortFunctionsOnASingleLine);
218     IO.mapOptional("AllowShortIfStatementsOnASingleLine",
219                    Style.AllowShortIfStatementsOnASingleLine);
220     IO.mapOptional("AllowShortLoopsOnASingleLine",
221                    Style.AllowShortLoopsOnASingleLine);
222     IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
223                    Style.AlwaysBreakAfterDefinitionReturnType);
224     IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
225                    Style.AlwaysBreakBeforeMultilineStrings);
226     IO.mapOptional("AlwaysBreakTemplateDeclarations",
227                    Style.AlwaysBreakTemplateDeclarations);
228     IO.mapOptional("BinPackArguments", Style.BinPackArguments);
229     IO.mapOptional("BinPackParameters", Style.BinPackParameters);
230     IO.mapOptional("BraceWrapping", Style.BraceWrapping);
231     IO.mapOptional("BreakBeforeBinaryOperators",
232                    Style.BreakBeforeBinaryOperators);
233     IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
234     IO.mapOptional("BreakBeforeTernaryOperators",
235                    Style.BreakBeforeTernaryOperators);
236     IO.mapOptional("BreakConstructorInitializersBeforeComma",
237                    Style.BreakConstructorInitializersBeforeComma);
238     IO.mapOptional("ColumnLimit", Style.ColumnLimit);
239     IO.mapOptional("CommentPragmas", Style.CommentPragmas);
240     IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
241                    Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
242     IO.mapOptional("ConstructorInitializerIndentWidth",
243                    Style.ConstructorInitializerIndentWidth);
244     IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
245     IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
246     IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
247     IO.mapOptional("DisableFormat", Style.DisableFormat);
248     IO.mapOptional("ExperimentalAutoDetectBinPacking",
249                    Style.ExperimentalAutoDetectBinPacking);
250     IO.mapOptional("ForEachMacros", Style.ForEachMacros);
251     IO.mapOptional("IncludeCategories", Style.IncludeCategories);
252     IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
253     IO.mapOptional("IndentWidth", Style.IndentWidth);
254     IO.mapOptional("IndentWrappedFunctionNames",
255                    Style.IndentWrappedFunctionNames);
256     IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
257                    Style.KeepEmptyLinesAtTheStartOfBlocks);
258     IO.mapOptional("MacroBlockBegin", Style.MacroBlockBegin);
259     IO.mapOptional("MacroBlockEnd", Style.MacroBlockEnd);
260     IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
261     IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
262     IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
263     IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
264     IO.mapOptional("ObjCSpaceBeforeProtocolList",
265                    Style.ObjCSpaceBeforeProtocolList);
266     IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
267                    Style.PenaltyBreakBeforeFirstCallParameter);
268     IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
269     IO.mapOptional("PenaltyBreakFirstLessLess",
270                    Style.PenaltyBreakFirstLessLess);
271     IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
272     IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
273     IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
274                    Style.PenaltyReturnTypeOnItsOwnLine);
275     IO.mapOptional("PointerAlignment", Style.PointerAlignment);
276     IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
277     IO.mapOptional("SpaceBeforeAssignmentOperators",
278                    Style.SpaceBeforeAssignmentOperators);
279     IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
280     IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
281     IO.mapOptional("SpacesBeforeTrailingComments",
282                    Style.SpacesBeforeTrailingComments);
283     IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
284     IO.mapOptional("SpacesInContainerLiterals",
285                    Style.SpacesInContainerLiterals);
286     IO.mapOptional("SpacesInCStyleCastParentheses",
287                    Style.SpacesInCStyleCastParentheses);
288     IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
289     IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
290     IO.mapOptional("Standard", Style.Standard);
291     IO.mapOptional("TabWidth", Style.TabWidth);
292     IO.mapOptional("UseTab", Style.UseTab);
293   }
294 };
295 
296 template <> struct MappingTraits<FormatStyle::BraceWrappingFlags> {
297   static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping) {
298     IO.mapOptional("AfterClass", Wrapping.AfterClass);
299     IO.mapOptional("AfterControlStatement", Wrapping.AfterControlStatement);
300     IO.mapOptional("AfterEnum", Wrapping.AfterEnum);
301     IO.mapOptional("AfterFunction", Wrapping.AfterFunction);
302     IO.mapOptional("AfterNamespace", Wrapping.AfterNamespace);
303     IO.mapOptional("AfterObjCDeclaration", Wrapping.AfterObjCDeclaration);
304     IO.mapOptional("AfterStruct", Wrapping.AfterStruct);
305     IO.mapOptional("AfterUnion", Wrapping.AfterUnion);
306     IO.mapOptional("BeforeCatch", Wrapping.BeforeCatch);
307     IO.mapOptional("BeforeElse", Wrapping.BeforeElse);
308     IO.mapOptional("IndentBraces", Wrapping.IndentBraces);
309   }
310 };
311 
312 template <> struct MappingTraits<FormatStyle::IncludeCategory> {
313   static void mapping(IO &IO, FormatStyle::IncludeCategory &Category) {
314     IO.mapOptional("Regex", Category.Regex);
315     IO.mapOptional("Priority", Category.Priority);
316   }
317 };
318 
319 // Allows to read vector<FormatStyle> while keeping default values.
320 // IO.getContext() should contain a pointer to the FormatStyle structure, that
321 // will be used to get default values for missing keys.
322 // If the first element has no Language specified, it will be treated as the
323 // default one for the following elements.
324 template <> struct DocumentListTraits<std::vector<FormatStyle>> {
325   static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
326     return Seq.size();
327   }
328   static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
329                               size_t Index) {
330     if (Index >= Seq.size()) {
331       assert(Index == Seq.size());
332       FormatStyle Template;
333       if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
334         Template = Seq[0];
335       } else {
336         Template = *((const FormatStyle *)IO.getContext());
337         Template.Language = FormatStyle::LK_None;
338       }
339       Seq.resize(Index + 1, Template);
340     }
341     return Seq[Index];
342   }
343 };
344 } // namespace yaml
345 } // namespace llvm
346 
347 namespace clang {
348 namespace format {
349 
350 const std::error_category &getParseCategory() {
351   static ParseErrorCategory C;
352   return C;
353 }
354 std::error_code make_error_code(ParseError e) {
355   return std::error_code(static_cast<int>(e), getParseCategory());
356 }
357 
358 const char *ParseErrorCategory::name() const LLVM_NOEXCEPT {
359   return "clang-format.parse_error";
360 }
361 
362 std::string ParseErrorCategory::message(int EV) const {
363   switch (static_cast<ParseError>(EV)) {
364   case ParseError::Success:
365     return "Success";
366   case ParseError::Error:
367     return "Invalid argument";
368   case ParseError::Unsuitable:
369     return "Unsuitable";
370   }
371   llvm_unreachable("unexpected parse error");
372 }
373 
374 static FormatStyle expandPresets(const FormatStyle &Style) {
375   FormatStyle Expanded = Style;
376   Expanded.BraceWrapping = {false, false, false, false, false, false,
377                             false, false, false, false, false};
378   switch (Style.BreakBeforeBraces) {
379   case FormatStyle::BS_Linux:
380     Expanded.BraceWrapping.AfterClass = true;
381     Expanded.BraceWrapping.AfterFunction = true;
382     Expanded.BraceWrapping.AfterNamespace = true;
383     Expanded.BraceWrapping.BeforeElse = true;
384     break;
385   case FormatStyle::BS_Mozilla:
386     Expanded.BraceWrapping.AfterClass = true;
387     Expanded.BraceWrapping.AfterEnum = true;
388     Expanded.BraceWrapping.AfterFunction = true;
389     Expanded.BraceWrapping.AfterStruct = true;
390     Expanded.BraceWrapping.AfterUnion = true;
391     break;
392   case FormatStyle::BS_Stroustrup:
393     Expanded.BraceWrapping.AfterFunction = true;
394     Expanded.BraceWrapping.BeforeCatch = true;
395     Expanded.BraceWrapping.BeforeElse = true;
396     break;
397   case FormatStyle::BS_Allman:
398     Expanded.BraceWrapping.AfterClass = true;
399     Expanded.BraceWrapping.AfterControlStatement = true;
400     Expanded.BraceWrapping.AfterEnum = true;
401     Expanded.BraceWrapping.AfterFunction = true;
402     Expanded.BraceWrapping.AfterNamespace = true;
403     Expanded.BraceWrapping.AfterObjCDeclaration = true;
404     Expanded.BraceWrapping.AfterStruct = true;
405     Expanded.BraceWrapping.BeforeCatch = true;
406     Expanded.BraceWrapping.BeforeElse = true;
407     break;
408   case FormatStyle::BS_GNU:
409     Expanded.BraceWrapping = {true, true, true, true, true, true,
410                               true, true, true, true, true};
411     break;
412   case FormatStyle::BS_WebKit:
413     Expanded.BraceWrapping.AfterFunction = true;
414     break;
415   default:
416     break;
417   }
418   return Expanded;
419 }
420 
421 FormatStyle getLLVMStyle() {
422   FormatStyle LLVMStyle;
423   LLVMStyle.Language = FormatStyle::LK_Cpp;
424   LLVMStyle.AccessModifierOffset = -2;
425   LLVMStyle.AlignEscapedNewlinesLeft = false;
426   LLVMStyle.AlignAfterOpenBracket = true;
427   LLVMStyle.AlignOperands = true;
428   LLVMStyle.AlignTrailingComments = true;
429   LLVMStyle.AlignConsecutiveAssignments = false;
430   LLVMStyle.AlignConsecutiveDeclarations = false;
431   LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
432   LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
433   LLVMStyle.AllowShortBlocksOnASingleLine = false;
434   LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
435   LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
436   LLVMStyle.AllowShortLoopsOnASingleLine = false;
437   LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
438   LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
439   LLVMStyle.AlwaysBreakTemplateDeclarations = false;
440   LLVMStyle.BinPackParameters = true;
441   LLVMStyle.BinPackArguments = true;
442   LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
443   LLVMStyle.BreakBeforeTernaryOperators = true;
444   LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
445   LLVMStyle.BreakConstructorInitializersBeforeComma = false;
446   LLVMStyle.ColumnLimit = 80;
447   LLVMStyle.CommentPragmas = "^ IWYU pragma:";
448   LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
449   LLVMStyle.ConstructorInitializerIndentWidth = 4;
450   LLVMStyle.ContinuationIndentWidth = 4;
451   LLVMStyle.Cpp11BracedListStyle = true;
452   LLVMStyle.DerivePointerAlignment = false;
453   LLVMStyle.ExperimentalAutoDetectBinPacking = false;
454   LLVMStyle.ForEachMacros.push_back("foreach");
455   LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
456   LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
457   LLVMStyle.IncludeCategories = {{"^\"(llvm|llvm-c|clang|clang-c)/", 2},
458                                  {"^(<|\"(gtest|isl|json)/)", 3},
459                                  {".*", 1}};
460   LLVMStyle.IndentCaseLabels = false;
461   LLVMStyle.IndentWrappedFunctionNames = false;
462   LLVMStyle.IndentWidth = 2;
463   LLVMStyle.TabWidth = 8;
464   LLVMStyle.MaxEmptyLinesToKeep = 1;
465   LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
466   LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
467   LLVMStyle.ObjCBlockIndentWidth = 2;
468   LLVMStyle.ObjCSpaceAfterProperty = false;
469   LLVMStyle.ObjCSpaceBeforeProtocolList = true;
470   LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
471   LLVMStyle.SpacesBeforeTrailingComments = 1;
472   LLVMStyle.Standard = FormatStyle::LS_Cpp11;
473   LLVMStyle.UseTab = FormatStyle::UT_Never;
474   LLVMStyle.SpacesInParentheses = false;
475   LLVMStyle.SpacesInSquareBrackets = false;
476   LLVMStyle.SpaceInEmptyParentheses = false;
477   LLVMStyle.SpacesInContainerLiterals = true;
478   LLVMStyle.SpacesInCStyleCastParentheses = false;
479   LLVMStyle.SpaceAfterCStyleCast = false;
480   LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
481   LLVMStyle.SpaceBeforeAssignmentOperators = true;
482   LLVMStyle.SpacesInAngles = false;
483 
484   LLVMStyle.PenaltyBreakComment = 300;
485   LLVMStyle.PenaltyBreakFirstLessLess = 120;
486   LLVMStyle.PenaltyBreakString = 1000;
487   LLVMStyle.PenaltyExcessCharacter = 1000000;
488   LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
489   LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
490 
491   LLVMStyle.DisableFormat = false;
492 
493   return LLVMStyle;
494 }
495 
496 FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
497   FormatStyle GoogleStyle = getLLVMStyle();
498   GoogleStyle.Language = Language;
499 
500   GoogleStyle.AccessModifierOffset = -1;
501   GoogleStyle.AlignEscapedNewlinesLeft = true;
502   GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
503   GoogleStyle.AllowShortLoopsOnASingleLine = true;
504   GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
505   GoogleStyle.AlwaysBreakTemplateDeclarations = true;
506   GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
507   GoogleStyle.DerivePointerAlignment = true;
508   GoogleStyle.IncludeCategories = {{"^<.*\\.h>", 1}, {"^<.*", 2}, {".*", 3}};
509   GoogleStyle.IndentCaseLabels = true;
510   GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
511   GoogleStyle.ObjCSpaceAfterProperty = false;
512   GoogleStyle.ObjCSpaceBeforeProtocolList = false;
513   GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
514   GoogleStyle.SpacesBeforeTrailingComments = 2;
515   GoogleStyle.Standard = FormatStyle::LS_Auto;
516 
517   GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
518   GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
519 
520   if (Language == FormatStyle::LK_Java) {
521     GoogleStyle.AlignAfterOpenBracket = false;
522     GoogleStyle.AlignOperands = false;
523     GoogleStyle.AlignTrailingComments = false;
524     GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
525     GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
526     GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
527     GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
528     GoogleStyle.ColumnLimit = 100;
529     GoogleStyle.SpaceAfterCStyleCast = true;
530     GoogleStyle.SpacesBeforeTrailingComments = 1;
531   } else if (Language == FormatStyle::LK_JavaScript) {
532     GoogleStyle.BreakBeforeTernaryOperators = false;
533     GoogleStyle.MaxEmptyLinesToKeep = 3;
534     GoogleStyle.SpacesInContainerLiterals = false;
535     GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
536     GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
537   } else if (Language == FormatStyle::LK_Proto) {
538     GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
539     GoogleStyle.SpacesInContainerLiterals = false;
540   }
541 
542   return GoogleStyle;
543 }
544 
545 FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
546   FormatStyle ChromiumStyle = getGoogleStyle(Language);
547   if (Language == FormatStyle::LK_Java) {
548     ChromiumStyle.AllowShortIfStatementsOnASingleLine = true;
549     ChromiumStyle.IndentWidth = 4;
550     ChromiumStyle.ContinuationIndentWidth = 8;
551   } else {
552     ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
553     ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
554     ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
555     ChromiumStyle.AllowShortLoopsOnASingleLine = false;
556     ChromiumStyle.BinPackParameters = false;
557     ChromiumStyle.DerivePointerAlignment = false;
558   }
559   return ChromiumStyle;
560 }
561 
562 FormatStyle getMozillaStyle() {
563   FormatStyle MozillaStyle = getLLVMStyle();
564   MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
565   MozillaStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
566   MozillaStyle.AlwaysBreakAfterDefinitionReturnType =
567       FormatStyle::DRTBS_TopLevel;
568   MozillaStyle.AlwaysBreakTemplateDeclarations = true;
569   MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
570   MozillaStyle.BreakConstructorInitializersBeforeComma = true;
571   MozillaStyle.ConstructorInitializerIndentWidth = 2;
572   MozillaStyle.ContinuationIndentWidth = 2;
573   MozillaStyle.Cpp11BracedListStyle = false;
574   MozillaStyle.IndentCaseLabels = true;
575   MozillaStyle.ObjCSpaceAfterProperty = true;
576   MozillaStyle.ObjCSpaceBeforeProtocolList = false;
577   MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
578   MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
579   return MozillaStyle;
580 }
581 
582 FormatStyle getWebKitStyle() {
583   FormatStyle Style = getLLVMStyle();
584   Style.AccessModifierOffset = -4;
585   Style.AlignAfterOpenBracket = false;
586   Style.AlignOperands = false;
587   Style.AlignTrailingComments = false;
588   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
589   Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
590   Style.BreakConstructorInitializersBeforeComma = true;
591   Style.Cpp11BracedListStyle = false;
592   Style.ColumnLimit = 0;
593   Style.IndentWidth = 4;
594   Style.NamespaceIndentation = FormatStyle::NI_Inner;
595   Style.ObjCBlockIndentWidth = 4;
596   Style.ObjCSpaceAfterProperty = true;
597   Style.PointerAlignment = FormatStyle::PAS_Left;
598   Style.Standard = FormatStyle::LS_Cpp03;
599   return Style;
600 }
601 
602 FormatStyle getGNUStyle() {
603   FormatStyle Style = getLLVMStyle();
604   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
605   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
606   Style.BreakBeforeBraces = FormatStyle::BS_GNU;
607   Style.BreakBeforeTernaryOperators = true;
608   Style.Cpp11BracedListStyle = false;
609   Style.ColumnLimit = 79;
610   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
611   Style.Standard = FormatStyle::LS_Cpp03;
612   return Style;
613 }
614 
615 FormatStyle getNoStyle() {
616   FormatStyle NoStyle = getLLVMStyle();
617   NoStyle.DisableFormat = true;
618   return NoStyle;
619 }
620 
621 bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
622                         FormatStyle *Style) {
623   if (Name.equals_lower("llvm")) {
624     *Style = getLLVMStyle();
625   } else if (Name.equals_lower("chromium")) {
626     *Style = getChromiumStyle(Language);
627   } else if (Name.equals_lower("mozilla")) {
628     *Style = getMozillaStyle();
629   } else if (Name.equals_lower("google")) {
630     *Style = getGoogleStyle(Language);
631   } else if (Name.equals_lower("webkit")) {
632     *Style = getWebKitStyle();
633   } else if (Name.equals_lower("gnu")) {
634     *Style = getGNUStyle();
635   } else if (Name.equals_lower("none")) {
636     *Style = getNoStyle();
637   } else {
638     return false;
639   }
640 
641   Style->Language = Language;
642   return true;
643 }
644 
645 std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
646   assert(Style);
647   FormatStyle::LanguageKind Language = Style->Language;
648   assert(Language != FormatStyle::LK_None);
649   if (Text.trim().empty())
650     return make_error_code(ParseError::Error);
651 
652   std::vector<FormatStyle> Styles;
653   llvm::yaml::Input Input(Text);
654   // DocumentListTraits<vector<FormatStyle>> uses the context to get default
655   // values for the fields, keys for which are missing from the configuration.
656   // Mapping also uses the context to get the language to find the correct
657   // base style.
658   Input.setContext(Style);
659   Input >> Styles;
660   if (Input.error())
661     return Input.error();
662 
663   for (unsigned i = 0; i < Styles.size(); ++i) {
664     // Ensures that only the first configuration can skip the Language option.
665     if (Styles[i].Language == FormatStyle::LK_None && i != 0)
666       return make_error_code(ParseError::Error);
667     // Ensure that each language is configured at most once.
668     for (unsigned j = 0; j < i; ++j) {
669       if (Styles[i].Language == Styles[j].Language) {
670         DEBUG(llvm::dbgs()
671               << "Duplicate languages in the config file on positions " << j
672               << " and " << i << "\n");
673         return make_error_code(ParseError::Error);
674       }
675     }
676   }
677   // Look for a suitable configuration starting from the end, so we can
678   // find the configuration for the specific language first, and the default
679   // configuration (which can only be at slot 0) after it.
680   for (int i = Styles.size() - 1; i >= 0; --i) {
681     if (Styles[i].Language == Language ||
682         Styles[i].Language == FormatStyle::LK_None) {
683       *Style = Styles[i];
684       Style->Language = Language;
685       return make_error_code(ParseError::Success);
686     }
687   }
688   return make_error_code(ParseError::Unsuitable);
689 }
690 
691 std::string configurationAsText(const FormatStyle &Style) {
692   std::string Text;
693   llvm::raw_string_ostream Stream(Text);
694   llvm::yaml::Output Output(Stream);
695   // We use the same mapping method for input and output, so we need a non-const
696   // reference here.
697   FormatStyle NonConstStyle = expandPresets(Style);
698   Output << NonConstStyle;
699   return Stream.str();
700 }
701 
702 namespace {
703 
704 class FormatTokenLexer {
705 public:
706   FormatTokenLexer(SourceManager &SourceMgr, FileID ID, FormatStyle &Style,
707                    encoding::Encoding Encoding)
708       : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
709         LessStashed(false), Column(0), TrailingWhitespace(0),
710         SourceMgr(SourceMgr), ID(ID), Style(Style),
711         IdentTable(getFormattingLangOpts(Style)), Keywords(IdentTable),
712         Encoding(Encoding), FirstInLineIndex(0), FormattingDisabled(false),
713         MacroBlockBeginRegex(Style.MacroBlockBegin),
714         MacroBlockEndRegex(Style.MacroBlockEnd) {
715     Lex.reset(new Lexer(ID, SourceMgr.getBuffer(ID), SourceMgr,
716                         getFormattingLangOpts(Style)));
717     Lex->SetKeepWhitespaceMode(true);
718 
719     for (const std::string &ForEachMacro : Style.ForEachMacros)
720       ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
721     std::sort(ForEachMacros.begin(), ForEachMacros.end());
722   }
723 
724   ArrayRef<FormatToken *> lex() {
725     assert(Tokens.empty());
726     assert(FirstInLineIndex == 0);
727     do {
728       Tokens.push_back(getNextToken());
729       tryMergePreviousTokens();
730       if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
731         FirstInLineIndex = Tokens.size() - 1;
732     } while (Tokens.back()->Tok.isNot(tok::eof));
733     return Tokens;
734   }
735 
736   const AdditionalKeywords &getKeywords() { return Keywords; }
737 
738 private:
739   void tryMergePreviousTokens() {
740     if (tryMerge_TMacro())
741       return;
742     if (tryMergeConflictMarkers())
743       return;
744     if (tryMergeLessLess())
745       return;
746 
747     if (Style.Language == FormatStyle::LK_JavaScript) {
748       if (tryMergeJSRegexLiteral())
749         return;
750       if (tryMergeEscapeSequence())
751         return;
752       if (tryMergeTemplateString())
753         return;
754 
755       static const tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
756       static const tok::TokenKind JSNotIdentity[] = {tok::exclaimequal,
757                                                      tok::equal};
758       static const tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
759                                                     tok::greaterequal};
760       static const tok::TokenKind JSRightArrow[] = {tok::equal, tok::greater};
761       // FIXME: Investigate what token type gives the correct operator priority.
762       if (tryMergeTokens(JSIdentity, TT_BinaryOperator))
763         return;
764       if (tryMergeTokens(JSNotIdentity, TT_BinaryOperator))
765         return;
766       if (tryMergeTokens(JSShiftEqual, TT_BinaryOperator))
767         return;
768       if (tryMergeTokens(JSRightArrow, TT_JsFatArrow))
769         return;
770     }
771   }
772 
773   bool tryMergeLessLess() {
774     // Merge X,less,less,Y into X,lessless,Y unless X or Y is less.
775     if (Tokens.size() < 3)
776       return false;
777 
778     bool FourthTokenIsLess = false;
779     if (Tokens.size() > 3)
780       FourthTokenIsLess = (Tokens.end() - 4)[0]->is(tok::less);
781 
782     auto First = Tokens.end() - 3;
783     if (First[2]->is(tok::less) || First[1]->isNot(tok::less) ||
784         First[0]->isNot(tok::less) || FourthTokenIsLess)
785       return false;
786 
787     // Only merge if there currently is no whitespace between the two "<".
788     if (First[1]->WhitespaceRange.getBegin() !=
789         First[1]->WhitespaceRange.getEnd())
790       return false;
791 
792     First[0]->Tok.setKind(tok::lessless);
793     First[0]->TokenText = "<<";
794     First[0]->ColumnWidth += 1;
795     Tokens.erase(Tokens.end() - 2);
796     return true;
797   }
798 
799   bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds, TokenType NewType) {
800     if (Tokens.size() < Kinds.size())
801       return false;
802 
803     SmallVectorImpl<FormatToken *>::const_iterator First =
804         Tokens.end() - Kinds.size();
805     if (!First[0]->is(Kinds[0]))
806       return false;
807     unsigned AddLength = 0;
808     for (unsigned i = 1; i < Kinds.size(); ++i) {
809       if (!First[i]->is(Kinds[i]) ||
810           First[i]->WhitespaceRange.getBegin() !=
811               First[i]->WhitespaceRange.getEnd())
812         return false;
813       AddLength += First[i]->TokenText.size();
814     }
815     Tokens.resize(Tokens.size() - Kinds.size() + 1);
816     First[0]->TokenText = StringRef(First[0]->TokenText.data(),
817                                     First[0]->TokenText.size() + AddLength);
818     First[0]->ColumnWidth += AddLength;
819     First[0]->Type = NewType;
820     return true;
821   }
822 
823   // Tries to merge an escape sequence, i.e. a "\\" and the following
824   // character. Use e.g. inside JavaScript regex literals.
825   bool tryMergeEscapeSequence() {
826     if (Tokens.size() < 2)
827       return false;
828     FormatToken *Previous = Tokens[Tokens.size() - 2];
829     if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\")
830       return false;
831     ++Previous->ColumnWidth;
832     StringRef Text = Previous->TokenText;
833     Previous->TokenText = StringRef(Text.data(), Text.size() + 1);
834     resetLexer(SourceMgr.getFileOffset(Tokens.back()->Tok.getLocation()) + 1);
835     Tokens.resize(Tokens.size() - 1);
836     Column = Previous->OriginalColumn + Previous->ColumnWidth;
837     return true;
838   }
839 
840   // Try to determine whether the current token ends a JavaScript regex literal.
841   // We heuristically assume that this is a regex literal if we find two
842   // unescaped slashes on a line and the token before the first slash is one of
843   // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
844   // a division.
845   bool tryMergeJSRegexLiteral() {
846     if (Tokens.size() < 2)
847       return false;
848 
849     // If this is a string literal with a slash inside, compute the slash's
850     // offset and try to find the beginning of the regex literal.
851     // Also look at tok::unknown, as it can be an unterminated char literal.
852     size_t SlashInStringPos = StringRef::npos;
853     if (Tokens.back()->isOneOf(tok::string_literal, tok::char_constant,
854                                tok::unknown)) {
855       // Start search from position 1 as otherwise, this is an unknown token
856       // for an unterminated /*-comment which is handled elsewhere.
857       SlashInStringPos = Tokens.back()->TokenText.find('/', 1);
858       if (SlashInStringPos == StringRef::npos)
859         return false;
860     }
861 
862     // If a regex literal ends in "\//", this gets represented by an unknown
863     // token "\" and a comment.
864     bool MightEndWithEscapedSlash =
865         Tokens.back()->is(tok::comment) &&
866         Tokens.back()->TokenText.startswith("//") &&
867         Tokens[Tokens.size() - 2]->TokenText == "\\";
868     if (!MightEndWithEscapedSlash && SlashInStringPos == StringRef::npos &&
869         (Tokens.back()->isNot(tok::slash) ||
870          (Tokens[Tokens.size() - 2]->is(tok::unknown) &&
871           Tokens[Tokens.size() - 2]->TokenText == "\\")))
872       return false;
873 
874     unsigned TokenCount = 0;
875     for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
876       ++TokenCount;
877       auto Prev = I + 1;
878       while (Prev != E && Prev[0]->is(tok::comment))
879         ++Prev;
880       if (I[0]->isOneOf(tok::slash, tok::slashequal) &&
881           (Prev == E ||
882            ((Prev[0]->isOneOf(tok::l_paren, tok::semi, tok::l_brace,
883                               tok::r_brace, tok::exclaim, tok::l_square,
884                               tok::colon, tok::comma, tok::question,
885                               tok::kw_return) ||
886              Prev[0]->isBinaryOperator())))) {
887         unsigned LastColumn = Tokens.back()->OriginalColumn;
888         SourceLocation Loc = Tokens.back()->Tok.getLocation();
889         if (MightEndWithEscapedSlash) {
890           // This regex literal ends in '\//'. Skip past the '//' of the last
891           // token and re-start lexing from there.
892           resetLexer(SourceMgr.getFileOffset(Loc) + 2);
893         } else if (SlashInStringPos != StringRef::npos) {
894           // This regex literal ends in a string_literal with a slash inside.
895           // Calculate end column and reset lexer appropriately.
896           resetLexer(SourceMgr.getFileOffset(Loc) + SlashInStringPos + 1);
897           LastColumn += SlashInStringPos;
898         }
899         Tokens.resize(Tokens.size() - TokenCount);
900         Tokens.back()->Tok.setKind(tok::unknown);
901         Tokens.back()->Type = TT_RegexLiteral;
902         // Treat regex literals like other string_literals.
903         Tokens.back()->Tok.setKind(tok::string_literal);
904         Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
905         return true;
906       }
907 
908       // There can't be a newline inside a regex literal.
909       if (I[0]->NewlinesBefore > 0)
910         return false;
911     }
912     return false;
913   }
914 
915   bool tryMergeTemplateString() {
916     if (Tokens.size() < 2)
917       return false;
918 
919     FormatToken *EndBacktick = Tokens.back();
920     // Backticks get lexed as tok::unknown tokens. If a template string contains
921     // a comment start, it gets lexed as a tok::comment, or tok::unknown if
922     // unterminated.
923     if (!EndBacktick->isOneOf(tok::comment, tok::string_literal,
924                               tok::char_constant, tok::unknown))
925       return false;
926     size_t CommentBacktickPos = EndBacktick->TokenText.find('`');
927     // Unknown token that's not actually a backtick, or a comment that doesn't
928     // contain a backtick.
929     if (CommentBacktickPos == StringRef::npos)
930       return false;
931 
932     unsigned TokenCount = 0;
933     bool IsMultiline = false;
934     unsigned EndColumnInFirstLine =
935         EndBacktick->OriginalColumn + EndBacktick->ColumnWidth;
936     for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; I++) {
937       ++TokenCount;
938       if (I[0]->IsMultiline)
939         IsMultiline = true;
940 
941       // If there was a preceding template string, this must be the start of a
942       // template string, not the end.
943       if (I[0]->is(TT_TemplateString))
944         return false;
945 
946       if (I[0]->isNot(tok::unknown) || I[0]->TokenText != "`") {
947         // Keep track of the rhs offset of the last token to wrap across lines -
948         // its the rhs offset of the first line of the template string, used to
949         // determine its width.
950         if (I[0]->IsMultiline)
951           EndColumnInFirstLine = I[0]->OriginalColumn + I[0]->ColumnWidth;
952         // If the token has newlines, the token before it (if it exists) is the
953         // rhs end of the previous line.
954         if (I[0]->NewlinesBefore > 0 && (I + 1 != E)) {
955           EndColumnInFirstLine = I[1]->OriginalColumn + I[1]->ColumnWidth;
956           IsMultiline = true;
957         }
958         continue;
959       }
960 
961       Tokens.resize(Tokens.size() - TokenCount);
962       Tokens.back()->Type = TT_TemplateString;
963       const char *EndOffset =
964           EndBacktick->TokenText.data() + 1 + CommentBacktickPos;
965       if (CommentBacktickPos != 0) {
966         // If the backtick was not the first character (e.g. in a comment),
967         // re-lex after the backtick position.
968         SourceLocation Loc = EndBacktick->Tok.getLocation();
969         resetLexer(SourceMgr.getFileOffset(Loc) + CommentBacktickPos + 1);
970       }
971       Tokens.back()->TokenText =
972           StringRef(Tokens.back()->TokenText.data(),
973                     EndOffset - Tokens.back()->TokenText.data());
974 
975       unsigned EndOriginalColumn = EndBacktick->OriginalColumn;
976       if (EndOriginalColumn == 0) {
977         SourceLocation Loc = EndBacktick->Tok.getLocation();
978         EndOriginalColumn = SourceMgr.getSpellingColumnNumber(Loc);
979       }
980       // If the ` is further down within the token (e.g. in a comment).
981       EndOriginalColumn += CommentBacktickPos;
982 
983       if (IsMultiline) {
984         // ColumnWidth is from backtick to last token in line.
985         // LastLineColumnWidth is 0 to backtick.
986         // x = `some content
987         //     until here`;
988         Tokens.back()->ColumnWidth =
989             EndColumnInFirstLine - Tokens.back()->OriginalColumn;
990         // +1 for the ` itself.
991         Tokens.back()->LastLineColumnWidth = EndOriginalColumn + 1;
992         Tokens.back()->IsMultiline = true;
993       } else {
994         // Token simply spans from start to end, +1 for the ` itself.
995         Tokens.back()->ColumnWidth =
996             EndOriginalColumn - Tokens.back()->OriginalColumn + 1;
997       }
998       return true;
999     }
1000     return false;
1001   }
1002 
1003   bool tryMerge_TMacro() {
1004     if (Tokens.size() < 4)
1005       return false;
1006     FormatToken *Last = Tokens.back();
1007     if (!Last->is(tok::r_paren))
1008       return false;
1009 
1010     FormatToken *String = Tokens[Tokens.size() - 2];
1011     if (!String->is(tok::string_literal) || String->IsMultiline)
1012       return false;
1013 
1014     if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
1015       return false;
1016 
1017     FormatToken *Macro = Tokens[Tokens.size() - 4];
1018     if (Macro->TokenText != "_T")
1019       return false;
1020 
1021     const char *Start = Macro->TokenText.data();
1022     const char *End = Last->TokenText.data() + Last->TokenText.size();
1023     String->TokenText = StringRef(Start, End - Start);
1024     String->IsFirst = Macro->IsFirst;
1025     String->LastNewlineOffset = Macro->LastNewlineOffset;
1026     String->WhitespaceRange = Macro->WhitespaceRange;
1027     String->OriginalColumn = Macro->OriginalColumn;
1028     String->ColumnWidth = encoding::columnWidthWithTabs(
1029         String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1030     String->NewlinesBefore = Macro->NewlinesBefore;
1031     String->HasUnescapedNewline = Macro->HasUnescapedNewline;
1032 
1033     Tokens.pop_back();
1034     Tokens.pop_back();
1035     Tokens.pop_back();
1036     Tokens.back() = String;
1037     return true;
1038   }
1039 
1040   bool tryMergeConflictMarkers() {
1041     if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1042       return false;
1043 
1044     // Conflict lines look like:
1045     // <marker> <text from the vcs>
1046     // For example:
1047     // >>>>>>> /file/in/file/system at revision 1234
1048     //
1049     // We merge all tokens in a line that starts with a conflict marker
1050     // into a single token with a special token type that the unwrapped line
1051     // parser will use to correctly rebuild the underlying code.
1052 
1053     FileID ID;
1054     // Get the position of the first token in the line.
1055     unsigned FirstInLineOffset;
1056     std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1057         Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1058     StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1059     // Calculate the offset of the start of the current line.
1060     auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1061     if (LineOffset == StringRef::npos) {
1062       LineOffset = 0;
1063     } else {
1064       ++LineOffset;
1065     }
1066 
1067     auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1068     StringRef LineStart;
1069     if (FirstSpace == StringRef::npos) {
1070       LineStart = Buffer.substr(LineOffset);
1071     } else {
1072       LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1073     }
1074 
1075     TokenType Type = TT_Unknown;
1076     if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1077       Type = TT_ConflictStart;
1078     } else if (LineStart == "|||||||" || LineStart == "=======" ||
1079                LineStart == "====") {
1080       Type = TT_ConflictAlternative;
1081     } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1082       Type = TT_ConflictEnd;
1083     }
1084 
1085     if (Type != TT_Unknown) {
1086       FormatToken *Next = Tokens.back();
1087 
1088       Tokens.resize(FirstInLineIndex + 1);
1089       // We do not need to build a complete token here, as we will skip it
1090       // during parsing anyway (as we must not touch whitespace around conflict
1091       // markers).
1092       Tokens.back()->Type = Type;
1093       Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1094 
1095       Tokens.push_back(Next);
1096       return true;
1097     }
1098 
1099     return false;
1100   }
1101 
1102   FormatToken *getStashedToken() {
1103     // Create a synthesized second '>' or '<' token.
1104     Token Tok = FormatTok->Tok;
1105     StringRef TokenText = FormatTok->TokenText;
1106 
1107     unsigned OriginalColumn = FormatTok->OriginalColumn;
1108     FormatTok = new (Allocator.Allocate()) FormatToken;
1109     FormatTok->Tok = Tok;
1110     SourceLocation TokLocation =
1111         FormatTok->Tok.getLocation().getLocWithOffset(Tok.getLength() - 1);
1112     FormatTok->Tok.setLocation(TokLocation);
1113     FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
1114     FormatTok->TokenText = TokenText;
1115     FormatTok->ColumnWidth = 1;
1116     FormatTok->OriginalColumn = OriginalColumn + 1;
1117 
1118     return FormatTok;
1119   }
1120 
1121   FormatToken *getNextToken() {
1122     if (GreaterStashed) {
1123       GreaterStashed = false;
1124       return getStashedToken();
1125     }
1126     if (LessStashed) {
1127       LessStashed = false;
1128       return getStashedToken();
1129     }
1130 
1131     FormatTok = new (Allocator.Allocate()) FormatToken;
1132     readRawToken(*FormatTok);
1133     SourceLocation WhitespaceStart =
1134         FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
1135     FormatTok->IsFirst = IsFirstToken;
1136     IsFirstToken = false;
1137 
1138     // Consume and record whitespace until we find a significant token.
1139     unsigned WhitespaceLength = TrailingWhitespace;
1140     while (FormatTok->Tok.is(tok::unknown)) {
1141       StringRef Text = FormatTok->TokenText;
1142       auto EscapesNewline = [&](int pos) {
1143         // A '\r' here is just part of '\r\n'. Skip it.
1144         if (pos >= 0 && Text[pos] == '\r')
1145           --pos;
1146         // See whether there is an odd number of '\' before this.
1147         unsigned count = 0;
1148         for (; pos >= 0; --pos, ++count)
1149           if (Text[pos] != '\\')
1150             break;
1151         return count & 1;
1152       };
1153       // FIXME: This miscounts tok:unknown tokens that are not just
1154       // whitespace, e.g. a '`' character.
1155       for (int i = 0, e = Text.size(); i != e; ++i) {
1156         switch (Text[i]) {
1157         case '\n':
1158           ++FormatTok->NewlinesBefore;
1159           FormatTok->HasUnescapedNewline = !EscapesNewline(i - 1);
1160           FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1161           Column = 0;
1162           break;
1163         case '\r':
1164           FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1165           Column = 0;
1166           break;
1167         case '\f':
1168         case '\v':
1169           Column = 0;
1170           break;
1171         case ' ':
1172           ++Column;
1173           break;
1174         case '\t':
1175           Column += Style.TabWidth - Column % Style.TabWidth;
1176           break;
1177         case '\\':
1178           if (i + 1 == e || (Text[i + 1] != '\r' && Text[i + 1] != '\n'))
1179             FormatTok->Type = TT_ImplicitStringLiteral;
1180           break;
1181         default:
1182           FormatTok->Type = TT_ImplicitStringLiteral;
1183           break;
1184         }
1185       }
1186 
1187       if (FormatTok->is(TT_ImplicitStringLiteral))
1188         break;
1189       WhitespaceLength += FormatTok->Tok.getLength();
1190 
1191       readRawToken(*FormatTok);
1192     }
1193 
1194     // In case the token starts with escaped newlines, we want to
1195     // take them into account as whitespace - this pattern is quite frequent
1196     // in macro definitions.
1197     // FIXME: Add a more explicit test.
1198     while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1199            FormatTok->TokenText[1] == '\n') {
1200       ++FormatTok->NewlinesBefore;
1201       WhitespaceLength += 2;
1202       FormatTok->LastNewlineOffset = 2;
1203       Column = 0;
1204       FormatTok->TokenText = FormatTok->TokenText.substr(2);
1205     }
1206 
1207     FormatTok->WhitespaceRange = SourceRange(
1208         WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1209 
1210     FormatTok->OriginalColumn = Column;
1211 
1212     TrailingWhitespace = 0;
1213     if (FormatTok->Tok.is(tok::comment)) {
1214       // FIXME: Add the trimmed whitespace to Column.
1215       StringRef UntrimmedText = FormatTok->TokenText;
1216       FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
1217       TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
1218     } else if (FormatTok->Tok.is(tok::raw_identifier)) {
1219       IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
1220       FormatTok->Tok.setIdentifierInfo(&Info);
1221       FormatTok->Tok.setKind(Info.getTokenID());
1222       if (Style.Language == FormatStyle::LK_Java &&
1223           FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete)) {
1224         FormatTok->Tok.setKind(tok::identifier);
1225         FormatTok->Tok.setIdentifierInfo(nullptr);
1226       }
1227     } else if (FormatTok->Tok.is(tok::greatergreater)) {
1228       FormatTok->Tok.setKind(tok::greater);
1229       FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1230       GreaterStashed = true;
1231     } else if (FormatTok->Tok.is(tok::lessless)) {
1232       FormatTok->Tok.setKind(tok::less);
1233       FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1234       LessStashed = true;
1235     }
1236 
1237     // Now FormatTok is the next non-whitespace token.
1238 
1239     StringRef Text = FormatTok->TokenText;
1240     size_t FirstNewlinePos = Text.find('\n');
1241     if (FirstNewlinePos == StringRef::npos) {
1242       // FIXME: ColumnWidth actually depends on the start column, we need to
1243       // take this into account when the token is moved.
1244       FormatTok->ColumnWidth =
1245           encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1246       Column += FormatTok->ColumnWidth;
1247     } else {
1248       FormatTok->IsMultiline = true;
1249       // FIXME: ColumnWidth actually depends on the start column, we need to
1250       // take this into account when the token is moved.
1251       FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1252           Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1253 
1254       // The last line of the token always starts in column 0.
1255       // Thus, the length can be precomputed even in the presence of tabs.
1256       FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1257           Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1258           Encoding);
1259       Column = FormatTok->LastLineColumnWidth;
1260     }
1261 
1262     if (Style.Language == FormatStyle::LK_Cpp) {
1263       if (!(Tokens.size() > 0 && Tokens.back()->Tok.getIdentifierInfo() &&
1264             Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() ==
1265                 tok::pp_define) &&
1266           std::find(ForEachMacros.begin(), ForEachMacros.end(),
1267                     FormatTok->Tok.getIdentifierInfo()) != ForEachMacros.end()) {
1268         FormatTok->Type = TT_ForEachMacro;
1269       } else if (FormatTok->is(tok::identifier)) {
1270         if (MacroBlockBeginRegex.match(Text)) {
1271           FormatTok->Type = TT_MacroBlockBegin;
1272         } else if (MacroBlockEndRegex.match(Text)) {
1273           FormatTok->Type = TT_MacroBlockEnd;
1274         }
1275       }
1276     }
1277 
1278     return FormatTok;
1279   }
1280 
1281   FormatToken *FormatTok;
1282   bool IsFirstToken;
1283   bool GreaterStashed, LessStashed;
1284   unsigned Column;
1285   unsigned TrailingWhitespace;
1286   std::unique_ptr<Lexer> Lex;
1287   SourceManager &SourceMgr;
1288   FileID ID;
1289   FormatStyle &Style;
1290   IdentifierTable IdentTable;
1291   AdditionalKeywords Keywords;
1292   encoding::Encoding Encoding;
1293   llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
1294   // Index (in 'Tokens') of the last token that starts a new line.
1295   unsigned FirstInLineIndex;
1296   SmallVector<FormatToken *, 16> Tokens;
1297   SmallVector<IdentifierInfo *, 8> ForEachMacros;
1298 
1299   bool FormattingDisabled;
1300 
1301   llvm::Regex MacroBlockBeginRegex;
1302   llvm::Regex MacroBlockEndRegex;
1303 
1304   void readRawToken(FormatToken &Tok) {
1305     Lex->LexFromRawLexer(Tok.Tok);
1306     Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1307                               Tok.Tok.getLength());
1308     // For formatting, treat unterminated string literals like normal string
1309     // literals.
1310     if (Tok.is(tok::unknown)) {
1311       if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1312         Tok.Tok.setKind(tok::string_literal);
1313         Tok.IsUnterminatedLiteral = true;
1314       } else if (Style.Language == FormatStyle::LK_JavaScript &&
1315                  Tok.TokenText == "''") {
1316         Tok.Tok.setKind(tok::char_constant);
1317       }
1318     }
1319 
1320     if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
1321                                  Tok.TokenText == "/* clang-format on */")) {
1322       FormattingDisabled = false;
1323     }
1324 
1325     Tok.Finalized = FormattingDisabled;
1326 
1327     if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
1328                                  Tok.TokenText == "/* clang-format off */")) {
1329       FormattingDisabled = true;
1330     }
1331   }
1332 
1333   void resetLexer(unsigned Offset) {
1334     StringRef Buffer = SourceMgr.getBufferData(ID);
1335     Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
1336                         getFormattingLangOpts(Style), Buffer.begin(),
1337                         Buffer.begin() + Offset, Buffer.end()));
1338     Lex->SetKeepWhitespaceMode(true);
1339     TrailingWhitespace = 0;
1340   }
1341 };
1342 
1343 static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1344   switch (Language) {
1345   case FormatStyle::LK_Cpp:
1346     return "C++";
1347   case FormatStyle::LK_Java:
1348     return "Java";
1349   case FormatStyle::LK_JavaScript:
1350     return "JavaScript";
1351   case FormatStyle::LK_Proto:
1352     return "Proto";
1353   default:
1354     return "Unknown";
1355   }
1356 }
1357 
1358 class Formatter : public UnwrappedLineConsumer {
1359 public:
1360   Formatter(const FormatStyle &Style, SourceManager &SourceMgr, FileID ID,
1361             ArrayRef<CharSourceRange> Ranges)
1362       : Style(Style), ID(ID), SourceMgr(SourceMgr),
1363         Whitespaces(SourceMgr, Style,
1364                     inputUsesCRLF(SourceMgr.getBufferData(ID))),
1365         Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
1366         Encoding(encoding::detectEncoding(SourceMgr.getBufferData(ID))) {
1367     DEBUG(llvm::dbgs() << "File encoding: "
1368                        << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1369                                                                : "unknown")
1370                        << "\n");
1371     DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1372                        << "\n");
1373   }
1374 
1375   tooling::Replacements format(bool *IncompleteFormat) {
1376     tooling::Replacements Result;
1377     FormatTokenLexer Tokens(SourceMgr, ID, Style, Encoding);
1378 
1379     UnwrappedLineParser Parser(Style, Tokens.getKeywords(), Tokens.lex(),
1380                                *this);
1381     Parser.parse();
1382     assert(UnwrappedLines.rbegin()->empty());
1383     for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1384          ++Run) {
1385       DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1386       SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1387       for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1388         AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1389       }
1390       tooling::Replacements RunResult =
1391           format(AnnotatedLines, Tokens, IncompleteFormat);
1392       DEBUG({
1393         llvm::dbgs() << "Replacements for run " << Run << ":\n";
1394         for (tooling::Replacements::iterator I = RunResult.begin(),
1395                                              E = RunResult.end();
1396              I != E; ++I) {
1397           llvm::dbgs() << I->toString() << "\n";
1398         }
1399       });
1400       for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1401         delete AnnotatedLines[i];
1402       }
1403       Result.insert(RunResult.begin(), RunResult.end());
1404       Whitespaces.reset();
1405     }
1406     return Result;
1407   }
1408 
1409   tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1410                                FormatTokenLexer &Tokens,
1411                                bool *IncompleteFormat) {
1412     TokenAnnotator Annotator(Style, Tokens.getKeywords());
1413     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1414       Annotator.annotate(*AnnotatedLines[i]);
1415     }
1416     deriveLocalStyle(AnnotatedLines);
1417     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1418       Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
1419     }
1420     computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
1421 
1422     Annotator.setCommentLineLevels(AnnotatedLines);
1423     ContinuationIndenter Indenter(Style, Tokens.getKeywords(), SourceMgr,
1424                                   Whitespaces, Encoding,
1425                                   BinPackInconclusiveFunctions);
1426     UnwrappedLineFormatter(&Indenter, &Whitespaces, Style, Tokens.getKeywords(),
1427                            IncompleteFormat)
1428         .format(AnnotatedLines);
1429     return Whitespaces.generateReplacements();
1430   }
1431 
1432 private:
1433   // Determines which lines are affected by the SourceRanges given as input.
1434   // Returns \c true if at least one line between I and E or one of their
1435   // children is affected.
1436   bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1437                             SmallVectorImpl<AnnotatedLine *>::iterator E) {
1438     bool SomeLineAffected = false;
1439     const AnnotatedLine *PreviousLine = nullptr;
1440     while (I != E) {
1441       AnnotatedLine *Line = *I;
1442       Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1443 
1444       // If a line is part of a preprocessor directive, it needs to be formatted
1445       // if any token within the directive is affected.
1446       if (Line->InPPDirective) {
1447         FormatToken *Last = Line->Last;
1448         SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1449         while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1450           Last = (*PPEnd)->Last;
1451           ++PPEnd;
1452         }
1453 
1454         if (affectsTokenRange(*Line->First, *Last,
1455                               /*IncludeLeadingNewlines=*/false)) {
1456           SomeLineAffected = true;
1457           markAllAsAffected(I, PPEnd);
1458         }
1459         I = PPEnd;
1460         continue;
1461       }
1462 
1463       if (nonPPLineAffected(Line, PreviousLine))
1464         SomeLineAffected = true;
1465 
1466       PreviousLine = Line;
1467       ++I;
1468     }
1469     return SomeLineAffected;
1470   }
1471 
1472   // Determines whether 'Line' is affected by the SourceRanges given as input.
1473   // Returns \c true if line or one if its children is affected.
1474   bool nonPPLineAffected(AnnotatedLine *Line,
1475                          const AnnotatedLine *PreviousLine) {
1476     bool SomeLineAffected = false;
1477     Line->ChildrenAffected =
1478         computeAffectedLines(Line->Children.begin(), Line->Children.end());
1479     if (Line->ChildrenAffected)
1480       SomeLineAffected = true;
1481 
1482     // Stores whether one of the line's tokens is directly affected.
1483     bool SomeTokenAffected = false;
1484     // Stores whether we need to look at the leading newlines of the next token
1485     // in order to determine whether it was affected.
1486     bool IncludeLeadingNewlines = false;
1487 
1488     // Stores whether the first child line of any of this line's tokens is
1489     // affected.
1490     bool SomeFirstChildAffected = false;
1491 
1492     for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1493       // Determine whether 'Tok' was affected.
1494       if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1495         SomeTokenAffected = true;
1496 
1497       // Determine whether the first child of 'Tok' was affected.
1498       if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1499         SomeFirstChildAffected = true;
1500 
1501       IncludeLeadingNewlines = Tok->Children.empty();
1502     }
1503 
1504     // Was this line moved, i.e. has it previously been on the same line as an
1505     // affected line?
1506     bool LineMoved = PreviousLine && PreviousLine->Affected &&
1507                      Line->First->NewlinesBefore == 0;
1508 
1509     bool IsContinuedComment =
1510         Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1511         Line->First->NewlinesBefore < 2 && PreviousLine &&
1512         PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
1513 
1514     if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1515         IsContinuedComment) {
1516       Line->Affected = true;
1517       SomeLineAffected = true;
1518     }
1519     return SomeLineAffected;
1520   }
1521 
1522   // Marks all lines between I and E as well as all their children as affected.
1523   void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1524                          SmallVectorImpl<AnnotatedLine *>::iterator E) {
1525     while (I != E) {
1526       (*I)->Affected = true;
1527       markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1528       ++I;
1529     }
1530   }
1531 
1532   // Returns true if the range from 'First' to 'Last' intersects with one of the
1533   // input ranges.
1534   bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1535                          bool IncludeLeadingNewlines) {
1536     SourceLocation Start = First.WhitespaceRange.getBegin();
1537     if (!IncludeLeadingNewlines)
1538       Start = Start.getLocWithOffset(First.LastNewlineOffset);
1539     SourceLocation End = Last.getStartOfNonWhitespace();
1540     End = End.getLocWithOffset(Last.TokenText.size());
1541     CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1542     return affectsCharSourceRange(Range);
1543   }
1544 
1545   // Returns true if one of the input ranges intersect the leading empty lines
1546   // before 'Tok'.
1547   bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1548     CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1549         Tok.WhitespaceRange.getBegin(),
1550         Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1551     return affectsCharSourceRange(EmptyLineRange);
1552   }
1553 
1554   // Returns true if 'Range' intersects with one of the input ranges.
1555   bool affectsCharSourceRange(const CharSourceRange &Range) {
1556     for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1557                                                           E = Ranges.end();
1558          I != E; ++I) {
1559       if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1560           !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1561         return true;
1562     }
1563     return false;
1564   }
1565 
1566   static bool inputUsesCRLF(StringRef Text) {
1567     return Text.count('\r') * 2 > Text.count('\n');
1568   }
1569 
1570   bool
1571   hasCpp03IncompatibleFormat(const SmallVectorImpl<AnnotatedLine *> &Lines) {
1572     for (const AnnotatedLine* Line : Lines) {
1573       if (hasCpp03IncompatibleFormat(Line->Children))
1574         return true;
1575       for (FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next) {
1576         if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1577           if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
1578             return true;
1579           if (Tok->is(TT_TemplateCloser) &&
1580               Tok->Previous->is(TT_TemplateCloser))
1581             return true;
1582         }
1583       }
1584     }
1585     return false;
1586   }
1587 
1588   int countVariableAlignments(const SmallVectorImpl<AnnotatedLine *> &Lines) {
1589     int AlignmentDiff = 0;
1590     for (const AnnotatedLine* Line : Lines) {
1591       AlignmentDiff += countVariableAlignments(Line->Children);
1592       for (FormatToken *Tok = Line->First; Tok && Tok->Next; Tok = Tok->Next) {
1593         if (!Tok->is(TT_PointerOrReference))
1594           continue;
1595         bool SpaceBefore =
1596             Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1597         bool SpaceAfter = Tok->Next->WhitespaceRange.getBegin() !=
1598                           Tok->Next->WhitespaceRange.getEnd();
1599         if (SpaceBefore && !SpaceAfter)
1600           ++AlignmentDiff;
1601         if (!SpaceBefore && SpaceAfter)
1602           --AlignmentDiff;
1603       }
1604     }
1605     return AlignmentDiff;
1606   }
1607 
1608   void
1609   deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
1610     bool HasBinPackedFunction = false;
1611     bool HasOnePerLineFunction = false;
1612     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1613       if (!AnnotatedLines[i]->First->Next)
1614         continue;
1615       FormatToken *Tok = AnnotatedLines[i]->First->Next;
1616       while (Tok->Next) {
1617         if (Tok->PackingKind == PPK_BinPacked)
1618           HasBinPackedFunction = true;
1619         if (Tok->PackingKind == PPK_OnePerLine)
1620           HasOnePerLineFunction = true;
1621 
1622         Tok = Tok->Next;
1623       }
1624     }
1625     if (Style.DerivePointerAlignment)
1626       Style.PointerAlignment = countVariableAlignments(AnnotatedLines) <= 0
1627                                    ? FormatStyle::PAS_Left
1628                                    : FormatStyle::PAS_Right;
1629     if (Style.Standard == FormatStyle::LS_Auto)
1630       Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
1631                            ? FormatStyle::LS_Cpp11
1632                            : FormatStyle::LS_Cpp03;
1633     BinPackInconclusiveFunctions =
1634         HasBinPackedFunction || !HasOnePerLineFunction;
1635   }
1636 
1637   void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
1638     assert(!UnwrappedLines.empty());
1639     UnwrappedLines.back().push_back(TheLine);
1640   }
1641 
1642   void finishRun() override {
1643     UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
1644   }
1645 
1646   FormatStyle Style;
1647   FileID ID;
1648   SourceManager &SourceMgr;
1649   WhitespaceManager Whitespaces;
1650   SmallVector<CharSourceRange, 8> Ranges;
1651   SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
1652 
1653   encoding::Encoding Encoding;
1654   bool BinPackInconclusiveFunctions;
1655 };
1656 
1657 struct IncludeDirective {
1658   StringRef Filename;
1659   StringRef Text;
1660   unsigned Offset;
1661   unsigned Category;
1662 };
1663 
1664 } // end anonymous namespace
1665 
1666 // Determines whether 'Ranges' intersects with ('Start', 'End').
1667 static bool affectsRange(ArrayRef<tooling::Range> Ranges, unsigned Start,
1668                          unsigned End) {
1669   for (auto Range : Ranges) {
1670     if (Range.getOffset() < End &&
1671         Range.getOffset() + Range.getLength() > Start)
1672       return true;
1673   }
1674   return false;
1675 }
1676 
1677 // Sorts a block of includes given by 'Includes' alphabetically adding the
1678 // necessary replacement to 'Replaces'. 'Includes' must be in strict source
1679 // order.
1680 static void sortIncludes(const FormatStyle &Style,
1681                          const SmallVectorImpl<IncludeDirective> &Includes,
1682                          ArrayRef<tooling::Range> Ranges, StringRef FileName,
1683                          tooling::Replacements &Replaces) {
1684   if (!affectsRange(Ranges, Includes.front().Offset,
1685                     Includes.back().Offset + Includes.back().Text.size()))
1686     return;
1687   SmallVector<unsigned, 16> Indices;
1688   for (unsigned i = 0, e = Includes.size(); i != e; ++i)
1689     Indices.push_back(i);
1690   std::sort(Indices.begin(), Indices.end(), [&](unsigned LHSI, unsigned RHSI) {
1691     return std::tie(Includes[LHSI].Category, Includes[LHSI].Filename) <
1692            std::tie(Includes[RHSI].Category, Includes[RHSI].Filename);
1693   });
1694 
1695   // If the #includes are out of order, we generate a single replacement fixing
1696   // the entire block. Otherwise, no replacement is generated.
1697   bool OutOfOrder = false;
1698   for (unsigned i = 1, e = Indices.size(); i != e; ++i) {
1699     if (Indices[i] != i) {
1700       OutOfOrder = true;
1701       break;
1702     }
1703   }
1704   if (!OutOfOrder)
1705     return;
1706 
1707   std::string result = Includes[Indices[0]].Text;
1708   for (unsigned i = 1, e = Indices.size(); i != e; ++i) {
1709     result += "\n";
1710     result += Includes[Indices[i]].Text;
1711   }
1712 
1713   // Sorting #includes shouldn't change their total number of characters.
1714   // This would otherwise mess up 'Ranges'.
1715   assert(result.size() ==
1716          Includes.back().Offset + Includes.back().Text.size() -
1717              Includes.front().Offset);
1718 
1719   Replaces.insert(tooling::Replacement(FileName, Includes.front().Offset,
1720                                        result.size(), result));
1721 }
1722 
1723 tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
1724                                    ArrayRef<tooling::Range> Ranges,
1725                                    StringRef FileName) {
1726   tooling::Replacements Replaces;
1727   unsigned Prev = 0;
1728   unsigned SearchFrom = 0;
1729   llvm::Regex IncludeRegex(
1730       R"(^[\t\ ]*#[\t\ ]*include[^"<]*(["<][^">]*[">]))");
1731   SmallVector<StringRef, 4> Matches;
1732   SmallVector<IncludeDirective, 16> IncludesInBlock;
1733 
1734   // In compiled files, consider the first #include to be the main #include of
1735   // the file if it is not a system #include. This ensures that the header
1736   // doesn't have hidden dependencies
1737   // (http://llvm.org/docs/CodingStandards.html#include-style).
1738   //
1739   // FIXME: Do some sanity checking, e.g. edit distance of the base name, to fix
1740   // cases where the first #include is unlikely to be the main header.
1741   bool LookForMainHeader = FileName.endswith(".c") ||
1742                            FileName.endswith(".cc") ||
1743                            FileName.endswith(".cpp")||
1744                            FileName.endswith(".c++")||
1745                            FileName.endswith(".cxx");
1746 
1747   // Create pre-compiled regular expressions for the #include categories.
1748   SmallVector<llvm::Regex, 4> CategoryRegexs;
1749   for (const auto &Category : Style.IncludeCategories)
1750     CategoryRegexs.emplace_back(Category.Regex);
1751 
1752   for (;;) {
1753     auto Pos = Code.find('\n', SearchFrom);
1754     StringRef Line =
1755         Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
1756     if (!Line.endswith("\\")) {
1757       if (IncludeRegex.match(Line, &Matches)) {
1758         unsigned Category;
1759         if (LookForMainHeader && !Matches[1].startswith("<")) {
1760           Category = 0;
1761         } else {
1762           Category = UINT_MAX;
1763           for (unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i) {
1764             if (CategoryRegexs[i].match(Matches[1])) {
1765               Category = Style.IncludeCategories[i].Priority;
1766               break;
1767             }
1768           }
1769         }
1770         LookForMainHeader = false;
1771         IncludesInBlock.push_back({Matches[1], Line, Prev, Category});
1772       } else if (!IncludesInBlock.empty()) {
1773         sortIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces);
1774         IncludesInBlock.clear();
1775       }
1776       Prev = Pos + 1;
1777     }
1778     if (Pos == StringRef::npos || Pos + 1 == Code.size())
1779       break;
1780     SearchFrom = Pos + 1;
1781   }
1782   if (!IncludesInBlock.empty())
1783     sortIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces);
1784   return Replaces;
1785 }
1786 
1787 tooling::Replacements reformat(const FormatStyle &Style,
1788                                SourceManager &SourceMgr, FileID ID,
1789                                ArrayRef<CharSourceRange> Ranges,
1790                                bool *IncompleteFormat) {
1791   FormatStyle Expanded = expandPresets(Style);
1792   if (Expanded.DisableFormat)
1793     return tooling::Replacements();
1794   Formatter formatter(Expanded, SourceMgr, ID, Ranges);
1795   return formatter.format(IncompleteFormat);
1796 }
1797 
1798 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1799                                ArrayRef<tooling::Range> Ranges,
1800                                StringRef FileName, bool *IncompleteFormat) {
1801   if (Style.DisableFormat)
1802     return tooling::Replacements();
1803 
1804   IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
1805       new vfs::InMemoryFileSystem);
1806   FileManager Files(FileSystemOptions(), InMemoryFileSystem);
1807   DiagnosticsEngine Diagnostics(
1808       IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1809       new DiagnosticOptions);
1810   SourceManager SourceMgr(Diagnostics, Files);
1811   InMemoryFileSystem->addFile(FileName, 0,
1812                               llvm::MemoryBuffer::getMemBuffer(Code, FileName));
1813   FileID ID = SourceMgr.createFileID(Files.getFile(FileName), SourceLocation(),
1814                                      clang::SrcMgr::C_User);
1815   SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1816   std::vector<CharSourceRange> CharRanges;
1817   for (const tooling::Range &Range : Ranges) {
1818     SourceLocation Start = StartOfFile.getLocWithOffset(Range.getOffset());
1819     SourceLocation End = Start.getLocWithOffset(Range.getLength());
1820     CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1821   }
1822   return reformat(Style, SourceMgr, ID, CharRanges, IncompleteFormat);
1823 }
1824 
1825 LangOptions getFormattingLangOpts(const FormatStyle &Style) {
1826   LangOptions LangOpts;
1827   LangOpts.CPlusPlus = 1;
1828   LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
1829   LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
1830   LangOpts.LineComment = 1;
1831   bool AlternativeOperators = Style.Language == FormatStyle::LK_Cpp;
1832   LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
1833   LangOpts.Bool = 1;
1834   LangOpts.ObjC1 = 1;
1835   LangOpts.ObjC2 = 1;
1836   LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally.
1837   LangOpts.DeclSpecKeyword = 1; // To get __declspec.
1838   return LangOpts;
1839 }
1840 
1841 const char *StyleOptionHelpDescription =
1842     "Coding style, currently supports:\n"
1843     "  LLVM, Google, Chromium, Mozilla, WebKit.\n"
1844     "Use -style=file to load style configuration from\n"
1845     ".clang-format file located in one of the parent\n"
1846     "directories of the source file (or current\n"
1847     "directory for stdin).\n"
1848     "Use -style=\"{key: value, ...}\" to set specific\n"
1849     "parameters, e.g.:\n"
1850     "  -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1851 
1852 static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
1853   if (FileName.endswith(".java")) {
1854     return FormatStyle::LK_Java;
1855   } else if (FileName.endswith_lower(".js") || FileName.endswith_lower(".ts")) {
1856     // JavaScript or TypeScript.
1857     return FormatStyle::LK_JavaScript;
1858   } else if (FileName.endswith_lower(".proto") ||
1859              FileName.endswith_lower(".protodevel")) {
1860     return FormatStyle::LK_Proto;
1861   }
1862   return FormatStyle::LK_Cpp;
1863 }
1864 
1865 FormatStyle getStyle(StringRef StyleName, StringRef FileName,
1866                      StringRef FallbackStyle) {
1867   FormatStyle Style = getLLVMStyle();
1868   Style.Language = getLanguageByFileName(FileName);
1869   if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
1870     llvm::errs() << "Invalid fallback style \"" << FallbackStyle
1871                  << "\" using LLVM style\n";
1872     return Style;
1873   }
1874 
1875   if (StyleName.startswith("{")) {
1876     // Parse YAML/JSON style from the command line.
1877     if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
1878       llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
1879                    << FallbackStyle << " style\n";
1880     }
1881     return Style;
1882   }
1883 
1884   if (!StyleName.equals_lower("file")) {
1885     if (!getPredefinedStyle(StyleName, Style.Language, &Style))
1886       llvm::errs() << "Invalid value for -style, using " << FallbackStyle
1887                    << " style\n";
1888     return Style;
1889   }
1890 
1891   // Look for .clang-format/_clang-format file in the file's parent directories.
1892   SmallString<128> UnsuitableConfigFiles;
1893   SmallString<128> Path(FileName);
1894   llvm::sys::fs::make_absolute(Path);
1895   for (StringRef Directory = Path; !Directory.empty();
1896        Directory = llvm::sys::path::parent_path(Directory)) {
1897     if (!llvm::sys::fs::is_directory(Directory))
1898       continue;
1899     SmallString<128> ConfigFile(Directory);
1900 
1901     llvm::sys::path::append(ConfigFile, ".clang-format");
1902     DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1903     bool IsFile = false;
1904     // Ignore errors from is_regular_file: we only need to know if we can read
1905     // the file or not.
1906     llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1907 
1908     if (!IsFile) {
1909       // Try _clang-format too, since dotfiles are not commonly used on Windows.
1910       ConfigFile = Directory;
1911       llvm::sys::path::append(ConfigFile, "_clang-format");
1912       DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1913       llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1914     }
1915 
1916     if (IsFile) {
1917       llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
1918           llvm::MemoryBuffer::getFile(ConfigFile.c_str());
1919       if (std::error_code EC = Text.getError()) {
1920         llvm::errs() << EC.message() << "\n";
1921         break;
1922       }
1923       if (std::error_code ec =
1924               parseConfiguration(Text.get()->getBuffer(), &Style)) {
1925         if (ec == ParseError::Unsuitable) {
1926           if (!UnsuitableConfigFiles.empty())
1927             UnsuitableConfigFiles.append(", ");
1928           UnsuitableConfigFiles.append(ConfigFile);
1929           continue;
1930         }
1931         llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
1932                      << "\n";
1933         break;
1934       }
1935       DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
1936       return Style;
1937     }
1938   }
1939   if (!UnsuitableConfigFiles.empty()) {
1940     llvm::errs() << "Configuration file(s) do(es) not support "
1941                  << getLanguageName(Style.Language) << ": "
1942                  << UnsuitableConfigFiles << "\n";
1943   }
1944   return Style;
1945 }
1946 
1947 } // namespace format
1948 } // namespace clang
1949