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