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