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