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