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 "ContinuationIndenter.h"
17 #include "TokenAnnotator.h"
18 #include "UnwrappedLineParser.h"
19 #include "WhitespaceManager.h"
20 #include "clang/Basic/Diagnostic.h"
21 #include "clang/Basic/DiagnosticOptions.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/Format/Format.h"
24 #include "clang/Lex/Lexer.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/Support/Allocator.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/Path.h"
29 #include "llvm/Support/YAMLTraits.h"
30 #include <queue>
31 #include <string>
32 
33 #define DEBUG_TYPE "format-formatter"
34 
35 using clang::format::FormatStyle;
36 
37 LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(std::string)
38 
39 namespace llvm {
40 namespace yaml {
41 template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
42   static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
43     IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
44     IO.enumCase(Value, "Java", FormatStyle::LK_Java);
45     IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
46     IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
47   }
48 };
49 
50 template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
51   static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
52     IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
53     IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
54     IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
55     IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
56     IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
57   }
58 };
59 
60 template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
61   static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
62     IO.enumCase(Value, "Never", FormatStyle::UT_Never);
63     IO.enumCase(Value, "false", FormatStyle::UT_Never);
64     IO.enumCase(Value, "Always", FormatStyle::UT_Always);
65     IO.enumCase(Value, "true", FormatStyle::UT_Always);
66     IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
67   }
68 };
69 
70 template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
71   static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
72     IO.enumCase(Value, "None", FormatStyle::SFS_None);
73     IO.enumCase(Value, "false", FormatStyle::SFS_None);
74     IO.enumCase(Value, "All", FormatStyle::SFS_All);
75     IO.enumCase(Value, "true", FormatStyle::SFS_All);
76     IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
77     IO.enumCase(Value, "Empty", FormatStyle::SFS_Empty);
78   }
79 };
80 
81 template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
82   static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
83     IO.enumCase(Value, "All", FormatStyle::BOS_All);
84     IO.enumCase(Value, "true", FormatStyle::BOS_All);
85     IO.enumCase(Value, "None", FormatStyle::BOS_None);
86     IO.enumCase(Value, "false", FormatStyle::BOS_None);
87     IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
88   }
89 };
90 
91 template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
92   static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
93     IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
94     IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
95     IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
96     IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
97     IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
98   }
99 };
100 
101 template <>
102 struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
103   static void enumeration(IO &IO,
104                           FormatStyle::NamespaceIndentationKind &Value) {
105     IO.enumCase(Value, "None", FormatStyle::NI_None);
106     IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
107     IO.enumCase(Value, "All", FormatStyle::NI_All);
108   }
109 };
110 
111 template <>
112 struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
113   static void enumeration(IO &IO,
114                           FormatStyle::PointerAlignmentStyle &Value) {
115     IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
116     IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
117     IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
118 
119     // For backward compatibility.
120     IO.enumCase(Value, "true", FormatStyle::PAS_Left);
121     IO.enumCase(Value, "false", FormatStyle::PAS_Right);
122   }
123 };
124 
125 template <>
126 struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
127   static void enumeration(IO &IO,
128                           FormatStyle::SpaceBeforeParensOptions &Value) {
129     IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
130     IO.enumCase(Value, "ControlStatements",
131                 FormatStyle::SBPO_ControlStatements);
132     IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
133 
134     // For backward compatibility.
135     IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
136     IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
137   }
138 };
139 
140 template <> struct MappingTraits<FormatStyle> {
141   static void mapping(IO &IO, FormatStyle &Style) {
142     // When reading, read the language first, we need it for getPredefinedStyle.
143     IO.mapOptional("Language", Style.Language);
144 
145     if (IO.outputting()) {
146       StringRef StylesArray[] = { "LLVM",    "Google", "Chromium",
147                                   "Mozilla", "WebKit", "GNU" };
148       ArrayRef<StringRef> Styles(StylesArray);
149       for (size_t i = 0, e = Styles.size(); i < e; ++i) {
150         StringRef StyleName(Styles[i]);
151         FormatStyle PredefinedStyle;
152         if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
153             Style == PredefinedStyle) {
154           IO.mapOptional("# BasedOnStyle", StyleName);
155           break;
156         }
157       }
158     } else {
159       StringRef BasedOnStyle;
160       IO.mapOptional("BasedOnStyle", BasedOnStyle);
161       if (!BasedOnStyle.empty()) {
162         FormatStyle::LanguageKind OldLanguage = Style.Language;
163         FormatStyle::LanguageKind Language =
164             ((FormatStyle *)IO.getContext())->Language;
165         if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
166           IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
167           return;
168         }
169         Style.Language = OldLanguage;
170       }
171     }
172 
173     IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
174     IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
175     IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
176     IO.mapOptional("AlignOperands", Style.AlignOperands);
177     IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
178     IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
179                    Style.AllowAllParametersOfDeclarationOnNextLine);
180     IO.mapOptional("AllowShortBlocksOnASingleLine",
181                    Style.AllowShortBlocksOnASingleLine);
182     IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
183                    Style.AllowShortCaseLabelsOnASingleLine);
184     IO.mapOptional("AllowShortIfStatementsOnASingleLine",
185                    Style.AllowShortIfStatementsOnASingleLine);
186     IO.mapOptional("AllowShortLoopsOnASingleLine",
187                    Style.AllowShortLoopsOnASingleLine);
188     IO.mapOptional("AllowShortFunctionsOnASingleLine",
189                    Style.AllowShortFunctionsOnASingleLine);
190     IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
191                    Style.AlwaysBreakAfterDefinitionReturnType);
192     IO.mapOptional("AlwaysBreakTemplateDeclarations",
193                    Style.AlwaysBreakTemplateDeclarations);
194     IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
195                    Style.AlwaysBreakBeforeMultilineStrings);
196     IO.mapOptional("BreakBeforeBinaryOperators",
197                    Style.BreakBeforeBinaryOperators);
198     IO.mapOptional("BreakBeforeTernaryOperators",
199                    Style.BreakBeforeTernaryOperators);
200     IO.mapOptional("BreakConstructorInitializersBeforeComma",
201                    Style.BreakConstructorInitializersBeforeComma);
202     IO.mapOptional("BinPackParameters", Style.BinPackParameters);
203     IO.mapOptional("BinPackArguments", Style.BinPackArguments);
204     IO.mapOptional("ColumnLimit", Style.ColumnLimit);
205     IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
206                    Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
207     IO.mapOptional("ConstructorInitializerIndentWidth",
208                    Style.ConstructorInitializerIndentWidth);
209     IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
210     IO.mapOptional("ExperimentalAutoDetectBinPacking",
211                    Style.ExperimentalAutoDetectBinPacking);
212     IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
213     IO.mapOptional("IndentWrappedFunctionNames",
214                    Style.IndentWrappedFunctionNames);
215     IO.mapOptional("IndentFunctionDeclarationAfterType",
216                    Style.IndentWrappedFunctionNames);
217     IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
218     IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
219                    Style.KeepEmptyLinesAtTheStartOfBlocks);
220     IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
221     IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
222     IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
223     IO.mapOptional("ObjCSpaceBeforeProtocolList",
224                    Style.ObjCSpaceBeforeProtocolList);
225     IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
226                    Style.PenaltyBreakBeforeFirstCallParameter);
227     IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
228     IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
229     IO.mapOptional("PenaltyBreakFirstLessLess",
230                    Style.PenaltyBreakFirstLessLess);
231     IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
232     IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
233                    Style.PenaltyReturnTypeOnItsOwnLine);
234     IO.mapOptional("PointerAlignment", Style.PointerAlignment);
235     IO.mapOptional("SpacesBeforeTrailingComments",
236                    Style.SpacesBeforeTrailingComments);
237     IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
238     IO.mapOptional("Standard", Style.Standard);
239     IO.mapOptional("IndentWidth", Style.IndentWidth);
240     IO.mapOptional("TabWidth", Style.TabWidth);
241     IO.mapOptional("UseTab", Style.UseTab);
242     IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
243     IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
244     IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
245     IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
246     IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
247     IO.mapOptional("SpacesInCStyleCastParentheses",
248                    Style.SpacesInCStyleCastParentheses);
249     IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
250     IO.mapOptional("SpacesInContainerLiterals",
251                    Style.SpacesInContainerLiterals);
252     IO.mapOptional("SpaceBeforeAssignmentOperators",
253                    Style.SpaceBeforeAssignmentOperators);
254     IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
255     IO.mapOptional("CommentPragmas", Style.CommentPragmas);
256     IO.mapOptional("ForEachMacros", Style.ForEachMacros);
257 
258     // For backward compatibility.
259     if (!IO.outputting()) {
260       IO.mapOptional("SpaceAfterControlStatementKeyword",
261                      Style.SpaceBeforeParens);
262       IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
263       IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
264     }
265     IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
266     IO.mapOptional("DisableFormat", Style.DisableFormat);
267   }
268 };
269 
270 // Allows to read vector<FormatStyle> while keeping default values.
271 // IO.getContext() should contain a pointer to the FormatStyle structure, that
272 // will be used to get default values for missing keys.
273 // If the first element has no Language specified, it will be treated as the
274 // default one for the following elements.
275 template <> struct DocumentListTraits<std::vector<FormatStyle> > {
276   static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
277     return Seq.size();
278   }
279   static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
280                               size_t Index) {
281     if (Index >= Seq.size()) {
282       assert(Index == Seq.size());
283       FormatStyle Template;
284       if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
285         Template = Seq[0];
286       } else {
287         Template = *((const FormatStyle *)IO.getContext());
288         Template.Language = FormatStyle::LK_None;
289       }
290       Seq.resize(Index + 1, Template);
291     }
292     return Seq[Index];
293   }
294 };
295 }
296 }
297 
298 namespace clang {
299 namespace format {
300 
301 const std::error_category &getParseCategory() {
302   static ParseErrorCategory C;
303   return C;
304 }
305 std::error_code make_error_code(ParseError e) {
306   return std::error_code(static_cast<int>(e), getParseCategory());
307 }
308 
309 const char *ParseErrorCategory::name() const LLVM_NOEXCEPT {
310   return "clang-format.parse_error";
311 }
312 
313 std::string ParseErrorCategory::message(int EV) const {
314   switch (static_cast<ParseError>(EV)) {
315   case ParseError::Success:
316     return "Success";
317   case ParseError::Error:
318     return "Invalid argument";
319   case ParseError::Unsuitable:
320     return "Unsuitable";
321   }
322   llvm_unreachable("unexpected parse error");
323 }
324 
325 FormatStyle getLLVMStyle() {
326   FormatStyle LLVMStyle;
327   LLVMStyle.Language = FormatStyle::LK_Cpp;
328   LLVMStyle.AccessModifierOffset = -2;
329   LLVMStyle.AlignEscapedNewlinesLeft = false;
330   LLVMStyle.AlignAfterOpenBracket = true;
331   LLVMStyle.AlignOperands = true;
332   LLVMStyle.AlignTrailingComments = true;
333   LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
334   LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
335   LLVMStyle.AllowShortBlocksOnASingleLine = false;
336   LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
337   LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
338   LLVMStyle.AllowShortLoopsOnASingleLine = false;
339   LLVMStyle.AlwaysBreakAfterDefinitionReturnType = false;
340   LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
341   LLVMStyle.AlwaysBreakTemplateDeclarations = false;
342   LLVMStyle.BinPackParameters = true;
343   LLVMStyle.BinPackArguments = true;
344   LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
345   LLVMStyle.BreakBeforeTernaryOperators = true;
346   LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
347   LLVMStyle.BreakConstructorInitializersBeforeComma = false;
348   LLVMStyle.ColumnLimit = 80;
349   LLVMStyle.CommentPragmas = "^ IWYU pragma:";
350   LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
351   LLVMStyle.ConstructorInitializerIndentWidth = 4;
352   LLVMStyle.ContinuationIndentWidth = 4;
353   LLVMStyle.Cpp11BracedListStyle = true;
354   LLVMStyle.DerivePointerAlignment = false;
355   LLVMStyle.ExperimentalAutoDetectBinPacking = false;
356   LLVMStyle.ForEachMacros.push_back("foreach");
357   LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
358   LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
359   LLVMStyle.IndentCaseLabels = false;
360   LLVMStyle.IndentWrappedFunctionNames = false;
361   LLVMStyle.IndentWidth = 2;
362   LLVMStyle.TabWidth = 8;
363   LLVMStyle.MaxEmptyLinesToKeep = 1;
364   LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
365   LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
366   LLVMStyle.ObjCBlockIndentWidth = 2;
367   LLVMStyle.ObjCSpaceAfterProperty = false;
368   LLVMStyle.ObjCSpaceBeforeProtocolList = true;
369   LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
370   LLVMStyle.SpacesBeforeTrailingComments = 1;
371   LLVMStyle.Standard = FormatStyle::LS_Cpp11;
372   LLVMStyle.UseTab = FormatStyle::UT_Never;
373   LLVMStyle.SpacesInParentheses = false;
374   LLVMStyle.SpacesInSquareBrackets = false;
375   LLVMStyle.SpaceInEmptyParentheses = false;
376   LLVMStyle.SpacesInContainerLiterals = true;
377   LLVMStyle.SpacesInCStyleCastParentheses = false;
378   LLVMStyle.SpaceAfterCStyleCast = false;
379   LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
380   LLVMStyle.SpaceBeforeAssignmentOperators = true;
381   LLVMStyle.SpacesInAngles = false;
382 
383   LLVMStyle.PenaltyBreakComment = 300;
384   LLVMStyle.PenaltyBreakFirstLessLess = 120;
385   LLVMStyle.PenaltyBreakString = 1000;
386   LLVMStyle.PenaltyExcessCharacter = 1000000;
387   LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
388   LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
389 
390   LLVMStyle.DisableFormat = false;
391 
392   return LLVMStyle;
393 }
394 
395 FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
396   FormatStyle GoogleStyle = getLLVMStyle();
397   GoogleStyle.Language = Language;
398 
399   GoogleStyle.AccessModifierOffset = -1;
400   GoogleStyle.AlignEscapedNewlinesLeft = true;
401   GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
402   GoogleStyle.AllowShortLoopsOnASingleLine = true;
403   GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
404   GoogleStyle.AlwaysBreakTemplateDeclarations = true;
405   GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
406   GoogleStyle.DerivePointerAlignment = true;
407   GoogleStyle.IndentCaseLabels = true;
408   GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
409   GoogleStyle.ObjCSpaceAfterProperty = false;
410   GoogleStyle.ObjCSpaceBeforeProtocolList = false;
411   GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
412   GoogleStyle.SpacesBeforeTrailingComments = 2;
413   GoogleStyle.Standard = FormatStyle::LS_Auto;
414 
415   GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
416   GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
417 
418   if (Language == FormatStyle::LK_Java) {
419     GoogleStyle.AlignAfterOpenBracket = false;
420     GoogleStyle.AlignOperands = false;
421     GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
422     GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
423     GoogleStyle.ColumnLimit = 100;
424     GoogleStyle.SpaceAfterCStyleCast = true;
425     GoogleStyle.SpacesBeforeTrailingComments = 1;
426   } else if (Language == FormatStyle::LK_JavaScript) {
427     GoogleStyle.BreakBeforeTernaryOperators = false;
428     GoogleStyle.MaxEmptyLinesToKeep = 3;
429     GoogleStyle.SpacesInContainerLiterals = false;
430     GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
431   } else if (Language == FormatStyle::LK_Proto) {
432     GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
433     GoogleStyle.SpacesInContainerLiterals = false;
434   }
435 
436   return GoogleStyle;
437 }
438 
439 FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
440   FormatStyle ChromiumStyle = getGoogleStyle(Language);
441   if (Language == FormatStyle::LK_Java) {
442     ChromiumStyle.IndentWidth = 4;
443     ChromiumStyle.ContinuationIndentWidth = 8;
444   } else {
445     ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
446     ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
447     ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
448     ChromiumStyle.AllowShortLoopsOnASingleLine = false;
449     ChromiumStyle.BinPackParameters = false;
450     ChromiumStyle.DerivePointerAlignment = false;
451   }
452   return ChromiumStyle;
453 }
454 
455 FormatStyle getMozillaStyle() {
456   FormatStyle MozillaStyle = getLLVMStyle();
457   MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
458   MozillaStyle.Cpp11BracedListStyle = false;
459   MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
460   MozillaStyle.DerivePointerAlignment = true;
461   MozillaStyle.IndentCaseLabels = true;
462   MozillaStyle.ObjCSpaceAfterProperty = true;
463   MozillaStyle.ObjCSpaceBeforeProtocolList = false;
464   MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
465   MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
466   MozillaStyle.Standard = FormatStyle::LS_Cpp03;
467   return MozillaStyle;
468 }
469 
470 FormatStyle getWebKitStyle() {
471   FormatStyle Style = getLLVMStyle();
472   Style.AccessModifierOffset = -4;
473   Style.AlignAfterOpenBracket = false;
474   Style.AlignOperands = false;
475   Style.AlignTrailingComments = false;
476   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
477   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
478   Style.BreakConstructorInitializersBeforeComma = true;
479   Style.Cpp11BracedListStyle = false;
480   Style.ColumnLimit = 0;
481   Style.IndentWidth = 4;
482   Style.NamespaceIndentation = FormatStyle::NI_Inner;
483   Style.ObjCBlockIndentWidth = 4;
484   Style.ObjCSpaceAfterProperty = true;
485   Style.PointerAlignment = FormatStyle::PAS_Left;
486   Style.Standard = FormatStyle::LS_Cpp03;
487   return Style;
488 }
489 
490 FormatStyle getGNUStyle() {
491   FormatStyle Style = getLLVMStyle();
492   Style.AlwaysBreakAfterDefinitionReturnType = true;
493   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
494   Style.BreakBeforeBraces = FormatStyle::BS_GNU;
495   Style.BreakBeforeTernaryOperators = true;
496   Style.Cpp11BracedListStyle = false;
497   Style.ColumnLimit = 79;
498   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
499   Style.Standard = FormatStyle::LS_Cpp03;
500   return Style;
501 }
502 
503 FormatStyle getNoStyle() {
504   FormatStyle NoStyle = getLLVMStyle();
505   NoStyle.DisableFormat = true;
506   return NoStyle;
507 }
508 
509 bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
510                         FormatStyle *Style) {
511   if (Name.equals_lower("llvm")) {
512     *Style = getLLVMStyle();
513   } else if (Name.equals_lower("chromium")) {
514     *Style = getChromiumStyle(Language);
515   } else if (Name.equals_lower("mozilla")) {
516     *Style = getMozillaStyle();
517   } else if (Name.equals_lower("google")) {
518     *Style = getGoogleStyle(Language);
519   } else if (Name.equals_lower("webkit")) {
520     *Style = getWebKitStyle();
521   } else if (Name.equals_lower("gnu")) {
522     *Style = getGNUStyle();
523   } else if (Name.equals_lower("none")) {
524     *Style = getNoStyle();
525   } else {
526     return false;
527   }
528 
529   Style->Language = Language;
530   return true;
531 }
532 
533 std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
534   assert(Style);
535   FormatStyle::LanguageKind Language = Style->Language;
536   assert(Language != FormatStyle::LK_None);
537   if (Text.trim().empty())
538     return make_error_code(ParseError::Error);
539 
540   std::vector<FormatStyle> Styles;
541   llvm::yaml::Input Input(Text);
542   // DocumentListTraits<vector<FormatStyle>> uses the context to get default
543   // values for the fields, keys for which are missing from the configuration.
544   // Mapping also uses the context to get the language to find the correct
545   // base style.
546   Input.setContext(Style);
547   Input >> Styles;
548   if (Input.error())
549     return Input.error();
550 
551   for (unsigned i = 0; i < Styles.size(); ++i) {
552     // Ensures that only the first configuration can skip the Language option.
553     if (Styles[i].Language == FormatStyle::LK_None && i != 0)
554       return make_error_code(ParseError::Error);
555     // Ensure that each language is configured at most once.
556     for (unsigned j = 0; j < i; ++j) {
557       if (Styles[i].Language == Styles[j].Language) {
558         DEBUG(llvm::dbgs()
559               << "Duplicate languages in the config file on positions " << j
560               << " and " << i << "\n");
561         return make_error_code(ParseError::Error);
562       }
563     }
564   }
565   // Look for a suitable configuration starting from the end, so we can
566   // find the configuration for the specific language first, and the default
567   // configuration (which can only be at slot 0) after it.
568   for (int i = Styles.size() - 1; i >= 0; --i) {
569     if (Styles[i].Language == Language ||
570         Styles[i].Language == FormatStyle::LK_None) {
571       *Style = Styles[i];
572       Style->Language = Language;
573       return make_error_code(ParseError::Success);
574     }
575   }
576   return make_error_code(ParseError::Unsuitable);
577 }
578 
579 std::string configurationAsText(const FormatStyle &Style) {
580   std::string Text;
581   llvm::raw_string_ostream Stream(Text);
582   llvm::yaml::Output Output(Stream);
583   // We use the same mapping method for input and output, so we need a non-const
584   // reference here.
585   FormatStyle NonConstStyle = Style;
586   Output << NonConstStyle;
587   return Stream.str();
588 }
589 
590 namespace {
591 
592 bool startsExternCBlock(const AnnotatedLine &Line) {
593   const FormatToken *Next = Line.First->getNextNonComment();
594   const FormatToken *NextNext = Next ? Next->getNextNonComment() : nullptr;
595   return Line.First->is(tok::kw_extern) && Next && Next->isStringLiteral() &&
596          NextNext && NextNext->is(tok::l_brace);
597 }
598 
599 class NoColumnLimitFormatter {
600 public:
601   NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
602 
603   /// \brief Formats the line starting at \p State, simply keeping all of the
604   /// input's line breaking decisions.
605   void format(unsigned FirstIndent, const AnnotatedLine *Line) {
606     LineState State =
607         Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
608     while (State.NextToken) {
609       bool Newline =
610           Indenter->mustBreak(State) ||
611           (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
612       Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
613     }
614   }
615 
616 private:
617   ContinuationIndenter *Indenter;
618 };
619 
620 class LineJoiner {
621 public:
622   LineJoiner(const FormatStyle &Style) : Style(Style) {}
623 
624   /// \brief Calculates how many lines can be merged into 1 starting at \p I.
625   unsigned
626   tryFitMultipleLinesInOne(unsigned Indent,
627                            SmallVectorImpl<AnnotatedLine *>::const_iterator I,
628                            SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
629     // We can never merge stuff if there are trailing line comments.
630     const AnnotatedLine *TheLine = *I;
631     if (TheLine->Last->is(TT_LineComment))
632       return 0;
633 
634     if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
635       return 0;
636 
637     unsigned Limit =
638         Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
639     // If we already exceed the column limit, we set 'Limit' to 0. The different
640     // tryMerge..() functions can then decide whether to still do merging.
641     Limit = TheLine->Last->TotalLength > Limit
642                 ? 0
643                 : Limit - TheLine->Last->TotalLength;
644 
645     if (I + 1 == E || I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
646       return 0;
647 
648     // FIXME: TheLine->Level != 0 might or might not be the right check to do.
649     // If necessary, change to something smarter.
650     bool MergeShortFunctions =
651         Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
652         (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty &&
653          I[1]->First->is(tok::r_brace)) ||
654         (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
655          TheLine->Level != 0);
656 
657     if (TheLine->Last->is(TT_FunctionLBrace) &&
658         TheLine->First != TheLine->Last) {
659       return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
660     }
661     if (TheLine->Last->is(tok::l_brace)) {
662       return Style.BreakBeforeBraces == FormatStyle::BS_Attach
663                  ? tryMergeSimpleBlock(I, E, Limit)
664                  : 0;
665     }
666     if (I[1]->First->is(TT_FunctionLBrace) &&
667         Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
668       if (I[1]->Last->is(TT_LineComment))
669         return 0;
670 
671       // Check for Limit <= 2 to account for the " {".
672       if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
673         return 0;
674       Limit -= 2;
675 
676       unsigned MergedLines = 0;
677       if (MergeShortFunctions) {
678         MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
679         // If we managed to merge the block, count the function header, which is
680         // on a separate line.
681         if (MergedLines > 0)
682           ++MergedLines;
683       }
684       return MergedLines;
685     }
686     if (TheLine->First->is(tok::kw_if)) {
687       return Style.AllowShortIfStatementsOnASingleLine
688                  ? tryMergeSimpleControlStatement(I, E, Limit)
689                  : 0;
690     }
691     if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
692       return Style.AllowShortLoopsOnASingleLine
693                  ? tryMergeSimpleControlStatement(I, E, Limit)
694                  : 0;
695     }
696     if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
697       return Style.AllowShortCaseLabelsOnASingleLine
698                  ? tryMergeShortCaseLabels(I, E, Limit)
699                  : 0;
700     }
701     if (TheLine->InPPDirective &&
702         (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
703       return tryMergeSimplePPDirective(I, E, Limit);
704     }
705     return 0;
706   }
707 
708 private:
709   unsigned
710   tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
711                             SmallVectorImpl<AnnotatedLine *>::const_iterator E,
712                             unsigned Limit) {
713     if (Limit == 0)
714       return 0;
715     if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
716       return 0;
717     if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
718       return 0;
719     if (1 + I[1]->Last->TotalLength > Limit)
720       return 0;
721     return 1;
722   }
723 
724   unsigned tryMergeSimpleControlStatement(
725       SmallVectorImpl<AnnotatedLine *>::const_iterator I,
726       SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
727     if (Limit == 0)
728       return 0;
729     if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
730          Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
731         (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
732       return 0;
733     if (I[1]->InPPDirective != (*I)->InPPDirective ||
734         (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
735       return 0;
736     Limit = limitConsideringMacros(I + 1, E, Limit);
737     AnnotatedLine &Line = **I;
738     if (Line.Last->isNot(tok::r_paren))
739       return 0;
740     if (1 + I[1]->Last->TotalLength > Limit)
741       return 0;
742     if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
743                              tok::kw_while, TT_LineComment))
744       return 0;
745     // Only inline simple if's (no nested if or else).
746     if (I + 2 != E && Line.First->is(tok::kw_if) &&
747         I[2]->First->is(tok::kw_else))
748       return 0;
749     return 1;
750   }
751 
752   unsigned tryMergeShortCaseLabels(
753       SmallVectorImpl<AnnotatedLine *>::const_iterator I,
754       SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
755     if (Limit == 0 || I + 1 == E ||
756         I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
757       return 0;
758     unsigned NumStmts = 0;
759     unsigned Length = 0;
760     bool InPPDirective = I[0]->InPPDirective;
761     for (; NumStmts < 3; ++NumStmts) {
762       if (I + 1 + NumStmts == E)
763         break;
764       const AnnotatedLine *Line = I[1 + NumStmts];
765       if (Line->InPPDirective != InPPDirective)
766         break;
767       if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
768         break;
769       if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
770                                tok::kw_while, tok::comment))
771         return 0;
772       Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
773     }
774     if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
775       return 0;
776     return NumStmts;
777   }
778 
779   unsigned
780   tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
781                       SmallVectorImpl<AnnotatedLine *>::const_iterator E,
782                       unsigned Limit) {
783     AnnotatedLine &Line = **I;
784 
785     // Don't merge ObjC @ keywords and methods.
786     if (Style.Language != FormatStyle::LK_Java &&
787         Line.First->isOneOf(tok::at, tok::minus, tok::plus))
788       return 0;
789 
790     // Check that the current line allows merging. This depends on whether we
791     // are in a control flow statements as well as several style flags.
792     if (Line.First->isOneOf(tok::kw_else, tok::kw_case))
793       return 0;
794     if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
795                             tok::kw_catch, tok::kw_for, tok::r_brace)) {
796       if (!Style.AllowShortBlocksOnASingleLine)
797         return 0;
798       if (!Style.AllowShortIfStatementsOnASingleLine &&
799           Line.First->is(tok::kw_if))
800         return 0;
801       if (!Style.AllowShortLoopsOnASingleLine &&
802           Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
803         return 0;
804       // FIXME: Consider an option to allow short exception handling clauses on
805       // a single line.
806       if (Line.First->isOneOf(tok::kw_try, tok::kw_catch))
807         return 0;
808     }
809 
810     FormatToken *Tok = I[1]->First;
811     if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
812         (Tok->getNextNonComment() == nullptr ||
813          Tok->getNextNonComment()->is(tok::semi))) {
814       // We merge empty blocks even if the line exceeds the column limit.
815       Tok->SpacesRequiredBefore = 0;
816       Tok->CanBreakBefore = true;
817       return 1;
818     } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace) &&
819                !startsExternCBlock(Line)) {
820       // We don't merge short records.
821       if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct))
822         return 0;
823 
824       // Check that we still have three lines and they fit into the limit.
825       if (I + 2 == E || I[2]->Type == LT_Invalid)
826         return 0;
827       Limit = limitConsideringMacros(I + 2, E, Limit);
828 
829       if (!nextTwoLinesFitInto(I, Limit))
830         return 0;
831 
832       // Second, check that the next line does not contain any braces - if it
833       // does, readability declines when putting it into a single line.
834       if (I[1]->Last->is(TT_LineComment))
835         return 0;
836       do {
837         if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
838           return 0;
839         Tok = Tok->Next;
840       } while (Tok);
841 
842       // Last, check that the third line starts with a closing brace.
843       Tok = I[2]->First;
844       if (Tok->isNot(tok::r_brace))
845         return 0;
846 
847       return 2;
848     }
849     return 0;
850   }
851 
852   /// Returns the modified column limit for \p I if it is inside a macro and
853   /// needs a trailing '\'.
854   unsigned
855   limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
856                          SmallVectorImpl<AnnotatedLine *>::const_iterator E,
857                          unsigned Limit) {
858     if (I[0]->InPPDirective && I + 1 != E &&
859         !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
860       return Limit < 2 ? 0 : Limit - 2;
861     }
862     return Limit;
863   }
864 
865   bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
866                            unsigned Limit) {
867     if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
868       return false;
869     return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
870   }
871 
872   bool containsMustBreak(const AnnotatedLine *Line) {
873     for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
874       if (Tok->MustBreakBefore)
875         return true;
876     }
877     return false;
878   }
879 
880   const FormatStyle &Style;
881 };
882 
883 class UnwrappedLineFormatter {
884 public:
885   UnwrappedLineFormatter(ContinuationIndenter *Indenter,
886                          WhitespaceManager *Whitespaces,
887                          const FormatStyle &Style)
888       : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
889         Joiner(Style) {}
890 
891   unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
892                   int AdditionalIndent = 0, bool FixBadIndentation = false) {
893     // Try to look up already computed penalty in DryRun-mode.
894     std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
895         &Lines, AdditionalIndent);
896     auto CacheIt = PenaltyCache.find(CacheKey);
897     if (DryRun && CacheIt != PenaltyCache.end())
898       return CacheIt->second;
899 
900     assert(!Lines.empty());
901     unsigned Penalty = 0;
902     std::vector<int> IndentForLevel;
903     for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
904       IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
905     const AnnotatedLine *PreviousLine = nullptr;
906     for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
907                                                           E = Lines.end();
908          I != E; ++I) {
909       const AnnotatedLine &TheLine = **I;
910       const FormatToken *FirstTok = TheLine.First;
911       int Offset = getIndentOffset(*FirstTok);
912 
913       // Determine indent and try to merge multiple unwrapped lines.
914       unsigned Indent;
915       if (TheLine.InPPDirective) {
916         Indent = TheLine.Level * Style.IndentWidth;
917       } else {
918         while (IndentForLevel.size() <= TheLine.Level)
919           IndentForLevel.push_back(-1);
920         IndentForLevel.resize(TheLine.Level + 1);
921         Indent = getIndent(IndentForLevel, TheLine.Level);
922       }
923       unsigned LevelIndent = Indent;
924       if (static_cast<int>(Indent) + Offset >= 0)
925         Indent += Offset;
926 
927       // Merge multiple lines if possible.
928       unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
929       if (MergedLines > 0 && Style.ColumnLimit == 0) {
930         // Disallow line merging if there is a break at the start of one of the
931         // input lines.
932         for (unsigned i = 0; i < MergedLines; ++i) {
933           if (I[i + 1]->First->NewlinesBefore > 0)
934             MergedLines = 0;
935         }
936       }
937       if (!DryRun) {
938         for (unsigned i = 0; i < MergedLines; ++i) {
939           join(*I[i], *I[i + 1]);
940         }
941       }
942       I += MergedLines;
943 
944       bool FixIndentation =
945           FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
946       if (TheLine.First->is(tok::eof)) {
947         if (PreviousLine && PreviousLine->Affected && !DryRun) {
948           // Remove the file's trailing whitespace.
949           unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
950           Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
951                                          /*IndentLevel=*/0, /*Spaces=*/0,
952                                          /*TargetColumn=*/0);
953         }
954       } else if (TheLine.Type != LT_Invalid &&
955                  (TheLine.Affected || FixIndentation)) {
956         if (FirstTok->WhitespaceRange.isValid()) {
957           if (!DryRun)
958             formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
959                              Indent, TheLine.InPPDirective);
960         } else {
961           Indent = LevelIndent = FirstTok->OriginalColumn;
962         }
963 
964         // If everything fits on a single line, just put it there.
965         unsigned ColumnLimit = Style.ColumnLimit;
966         if (I + 1 != E) {
967           AnnotatedLine *NextLine = I[1];
968           if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
969             ColumnLimit = getColumnLimit(TheLine.InPPDirective);
970         }
971 
972         if (TheLine.Last->TotalLength + Indent <= ColumnLimit ||
973             TheLine.Type == LT_ImportStatement) {
974           LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
975           while (State.NextToken) {
976             formatChildren(State, /*Newline=*/false, /*DryRun=*/false, Penalty);
977             Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
978           }
979         } else if (Style.ColumnLimit == 0) {
980           // FIXME: Implement nested blocks for ColumnLimit = 0.
981           NoColumnLimitFormatter Formatter(Indenter);
982           if (!DryRun)
983             Formatter.format(Indent, &TheLine);
984         } else {
985           Penalty += format(TheLine, Indent, DryRun);
986         }
987 
988         if (!TheLine.InPPDirective)
989           IndentForLevel[TheLine.Level] = LevelIndent;
990       } else if (TheLine.ChildrenAffected) {
991         format(TheLine.Children, DryRun);
992       } else {
993         // Format the first token if necessary, and notify the WhitespaceManager
994         // about the unchanged whitespace.
995         for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
996           if (Tok == TheLine.First &&
997               (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
998             unsigned LevelIndent = Tok->OriginalColumn;
999             if (!DryRun) {
1000               // Remove trailing whitespace of the previous line.
1001               if ((PreviousLine && PreviousLine->Affected) ||
1002                   TheLine.LeadingEmptyLinesAffected) {
1003                 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
1004                                  TheLine.InPPDirective);
1005               } else {
1006                 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
1007               }
1008             }
1009 
1010             if (static_cast<int>(LevelIndent) - Offset >= 0)
1011               LevelIndent -= Offset;
1012             if (Tok->isNot(tok::comment) && !TheLine.InPPDirective)
1013               IndentForLevel[TheLine.Level] = LevelIndent;
1014           } else if (!DryRun) {
1015             Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
1016           }
1017         }
1018       }
1019       if (!DryRun) {
1020         for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
1021           Tok->Finalized = true;
1022         }
1023       }
1024       PreviousLine = *I;
1025     }
1026     PenaltyCache[CacheKey] = Penalty;
1027     return Penalty;
1028   }
1029 
1030 private:
1031   /// \brief Formats an \c AnnotatedLine and returns the penalty.
1032   ///
1033   /// If \p DryRun is \c false, directly applies the changes.
1034   unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
1035                   bool DryRun) {
1036     LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
1037 
1038     // If the ObjC method declaration does not fit on a line, we should format
1039     // it with one arg per line.
1040     if (State.Line->Type == LT_ObjCMethodDecl)
1041       State.Stack.back().BreakBeforeParameter = true;
1042 
1043     // Find best solution in solution space.
1044     return analyzeSolutionSpace(State, DryRun);
1045   }
1046 
1047   /// \brief An edge in the solution space from \c Previous->State to \c State,
1048   /// inserting a newline dependent on the \c NewLine.
1049   struct StateNode {
1050     StateNode(const LineState &State, bool NewLine, StateNode *Previous)
1051         : State(State), NewLine(NewLine), Previous(Previous) {}
1052     LineState State;
1053     bool NewLine;
1054     StateNode *Previous;
1055   };
1056 
1057   /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
1058   ///
1059   /// In case of equal penalties, we want to prefer states that were inserted
1060   /// first. During state generation we make sure that we insert states first
1061   /// that break the line as late as possible.
1062   typedef std::pair<unsigned, unsigned> OrderedPenalty;
1063 
1064   /// \brief An item in the prioritized BFS search queue. The \c StateNode's
1065   /// \c State has the given \c OrderedPenalty.
1066   typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1067 
1068   /// \brief The BFS queue type.
1069   typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
1070                               std::greater<QueueItem> > QueueType;
1071 
1072   /// \brief Get the offset of the line relatively to the level.
1073   ///
1074   /// For example, 'public:' labels in classes are offset by 1 or 2
1075   /// characters to the left from their level.
1076   int getIndentOffset(const FormatToken &RootToken) {
1077     if (Style.Language == FormatStyle::LK_Java)
1078       return 0;
1079     if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
1080       return Style.AccessModifierOffset;
1081     return 0;
1082   }
1083 
1084   /// \brief Add a new line and the required indent before the first Token
1085   /// of the \c UnwrappedLine if there was no structural parsing error.
1086   void formatFirstToken(FormatToken &RootToken,
1087                         const AnnotatedLine *PreviousLine, unsigned IndentLevel,
1088                         unsigned Indent, bool InPPDirective) {
1089     unsigned Newlines =
1090         std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1091     // Remove empty lines before "}" where applicable.
1092     if (RootToken.is(tok::r_brace) &&
1093         (!RootToken.Next ||
1094          (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1095       Newlines = std::min(Newlines, 1u);
1096     if (Newlines == 0 && !RootToken.IsFirst)
1097       Newlines = 1;
1098     if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
1099       Newlines = 0;
1100 
1101     // Remove empty lines after "{".
1102     if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
1103         PreviousLine->Last->is(tok::l_brace) &&
1104         PreviousLine->First->isNot(tok::kw_namespace) &&
1105         !startsExternCBlock(*PreviousLine))
1106       Newlines = 1;
1107 
1108     // Insert extra new line before access specifiers.
1109     if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
1110         RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
1111       ++Newlines;
1112 
1113     // Remove empty lines after access specifiers.
1114     if (PreviousLine && PreviousLine->First->isAccessSpecifier())
1115       Newlines = std::min(1u, Newlines);
1116 
1117     Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
1118                                    Indent, InPPDirective &&
1119                                                !RootToken.HasUnescapedNewline);
1120   }
1121 
1122   /// \brief Get the indent of \p Level from \p IndentForLevel.
1123   ///
1124   /// \p IndentForLevel must contain the indent for the level \c l
1125   /// at \p IndentForLevel[l], or a value < 0 if the indent for
1126   /// that level is unknown.
1127   unsigned getIndent(ArrayRef<int> IndentForLevel, unsigned Level) {
1128     if (IndentForLevel[Level] != -1)
1129       return IndentForLevel[Level];
1130     if (Level == 0)
1131       return 0;
1132     return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
1133   }
1134 
1135   void join(AnnotatedLine &A, const AnnotatedLine &B) {
1136     assert(!A.Last->Next);
1137     assert(!B.First->Previous);
1138     if (B.Affected)
1139       A.Affected = true;
1140     A.Last->Next = B.First;
1141     B.First->Previous = A.Last;
1142     B.First->CanBreakBefore = true;
1143     unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1144     for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1145       Tok->TotalLength += LengthA;
1146       A.Last = Tok;
1147     }
1148   }
1149 
1150   unsigned getColumnLimit(bool InPPDirective) const {
1151     // In preprocessor directives reserve two chars for trailing " \"
1152     return Style.ColumnLimit - (InPPDirective ? 2 : 0);
1153   }
1154 
1155   struct CompareLineStatePointers {
1156     bool operator()(LineState *obj1, LineState *obj2) const {
1157       return *obj1 < *obj2;
1158     }
1159   };
1160 
1161   /// \brief Analyze the entire solution space starting from \p InitialState.
1162   ///
1163   /// This implements a variant of Dijkstra's algorithm on the graph that spans
1164   /// the solution space (\c LineStates are the nodes). The algorithm tries to
1165   /// find the shortest path (the one with lowest penalty) from \p InitialState
1166   /// to a state where all tokens are placed. Returns the penalty.
1167   ///
1168   /// If \p DryRun is \c false, directly applies the changes.
1169   unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
1170     std::set<LineState *, CompareLineStatePointers> Seen;
1171 
1172     // Increasing count of \c StateNode items we have created. This is used to
1173     // create a deterministic order independent of the container.
1174     unsigned Count = 0;
1175     QueueType Queue;
1176 
1177     // Insert start element into queue.
1178     StateNode *Node =
1179         new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
1180     Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1181     ++Count;
1182 
1183     unsigned Penalty = 0;
1184 
1185     // While not empty, take first element and follow edges.
1186     while (!Queue.empty()) {
1187       Penalty = Queue.top().first.first;
1188       StateNode *Node = Queue.top().second;
1189       if (!Node->State.NextToken) {
1190         DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
1191         break;
1192       }
1193       Queue.pop();
1194 
1195       // Cut off the analysis of certain solutions if the analysis gets too
1196       // complex. See description of IgnoreStackForComparison.
1197       if (Count > 10000)
1198         Node->State.IgnoreStackForComparison = true;
1199 
1200       if (!Seen.insert(&Node->State).second)
1201         // State already examined with lower penalty.
1202         continue;
1203 
1204       FormatDecision LastFormat = Node->State.NextToken->Decision;
1205       if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
1206         addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
1207       if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
1208         addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
1209     }
1210 
1211     if (Queue.empty()) {
1212       // We were unable to find a solution, do nothing.
1213       // FIXME: Add diagnostic?
1214       DEBUG(llvm::dbgs() << "Could not find a solution.\n");
1215       return 0;
1216     }
1217 
1218     // Reconstruct the solution.
1219     if (!DryRun)
1220       reconstructPath(InitialState, Queue.top().second);
1221 
1222     DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
1223     DEBUG(llvm::dbgs() << "---\n");
1224 
1225     return Penalty;
1226   }
1227 
1228   void reconstructPath(LineState &State, StateNode *Current) {
1229     std::deque<StateNode *> Path;
1230     // We do not need a break before the initial token.
1231     while (Current->Previous) {
1232       Path.push_front(Current);
1233       Current = Current->Previous;
1234     }
1235     for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1236          I != E; ++I) {
1237       unsigned Penalty = 0;
1238       formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
1239       Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
1240 
1241       DEBUG({
1242         if ((*I)->NewLine) {
1243           llvm::dbgs() << "Penalty for placing "
1244                        << (*I)->Previous->State.NextToken->Tok.getName() << ": "
1245                        << Penalty << "\n";
1246         }
1247       });
1248     }
1249   }
1250 
1251   /// \brief Add the following state to the analysis queue \c Queue.
1252   ///
1253   /// Assume the current state is \p PreviousNode and has been reached with a
1254   /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
1255   void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
1256                            bool NewLine, unsigned *Count, QueueType *Queue) {
1257     if (NewLine && !Indenter->canBreak(PreviousNode->State))
1258       return;
1259     if (!NewLine && Indenter->mustBreak(PreviousNode->State))
1260       return;
1261 
1262     StateNode *Node = new (Allocator.Allocate())
1263         StateNode(PreviousNode->State, NewLine, PreviousNode);
1264     if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1265       return;
1266 
1267     Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
1268 
1269     Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1270     ++(*Count);
1271   }
1272 
1273   /// \brief If the \p State's next token is an r_brace closing a nested block,
1274   /// format the nested block before it.
1275   ///
1276   /// Returns \c true if all children could be placed successfully and adapts
1277   /// \p Penalty as well as \p State. If \p DryRun is false, also directly
1278   /// creates changes using \c Whitespaces.
1279   ///
1280   /// The crucial idea here is that children always get formatted upon
1281   /// encountering the closing brace right after the nested block. Now, if we
1282   /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1283   /// \c false), the entire block has to be kept on the same line (which is only
1284   /// possible if it fits on the line, only contains a single statement, etc.
1285   ///
1286   /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1287   /// break after the "{", format all lines with correct indentation and the put
1288   /// the closing "}" on yet another new line.
1289   ///
1290   /// This enables us to keep the simple structure of the
1291   /// \c UnwrappedLineFormatter, where we only have two options for each token:
1292   /// break or don't break.
1293   bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1294                       unsigned &Penalty) {
1295     FormatToken &Previous = *State.NextToken->Previous;
1296     const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1297     if (!LBrace || LBrace->isNot(tok::l_brace) ||
1298         LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
1299       // The previous token does not open a block. Nothing to do. We don't
1300       // assert so that we can simply call this function for all tokens.
1301       return true;
1302 
1303     if (NewLine) {
1304       int AdditionalIndent =
1305           State.FirstIndent - State.Line->Level * Style.IndentWidth;
1306       if (State.Stack.size() < 2 ||
1307           !State.Stack[State.Stack.size() - 2].NestedBlockInlined) {
1308         AdditionalIndent = State.Stack.back().Indent -
1309                            Previous.Children[0]->Level * Style.IndentWidth;
1310       }
1311 
1312       Penalty += format(Previous.Children, DryRun, AdditionalIndent,
1313                         /*FixBadIndentation=*/true);
1314       return true;
1315     }
1316 
1317     if (Previous.Children[0]->First->MustBreakBefore)
1318       return false;
1319 
1320     // Cannot merge multiple statements into a single line.
1321     if (Previous.Children.size() > 1)
1322       return false;
1323 
1324     // Cannot merge into one line if this line ends on a comment.
1325     if (Previous.is(tok::comment))
1326       return false;
1327 
1328     // We can't put the closing "}" on a line with a trailing comment.
1329     if (Previous.Children[0]->Last->isTrailingComment())
1330       return false;
1331 
1332     // If the child line exceeds the column limit, we wouldn't want to merge it.
1333     // We add +2 for the trailing " }".
1334     if (Style.ColumnLimit > 0 &&
1335         Previous.Children[0]->Last->TotalLength + State.Column + 2 >
1336             Style.ColumnLimit)
1337       return false;
1338 
1339     if (!DryRun) {
1340       Whitespaces->replaceWhitespace(
1341           *Previous.Children[0]->First,
1342           /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
1343           /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
1344     }
1345     Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
1346 
1347     State.Column += 1 + Previous.Children[0]->Last->TotalLength;
1348     return true;
1349   }
1350 
1351   ContinuationIndenter *Indenter;
1352   WhitespaceManager *Whitespaces;
1353   FormatStyle Style;
1354   LineJoiner Joiner;
1355 
1356   llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1357 
1358   // Cache to store the penalty of formatting a vector of AnnotatedLines
1359   // starting from a specific additional offset. Improves performance if there
1360   // are many nested blocks.
1361   std::map<std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned>,
1362            unsigned> PenaltyCache;
1363 };
1364 
1365 class FormatTokenLexer {
1366 public:
1367   FormatTokenLexer(SourceManager &SourceMgr, FileID ID, FormatStyle &Style,
1368                    encoding::Encoding Encoding)
1369       : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
1370         Column(0), TrailingWhitespace(0), SourceMgr(SourceMgr), ID(ID),
1371         Style(Style), IdentTable(getFormattingLangOpts(Style)),
1372         Keywords(IdentTable), Encoding(Encoding), FirstInLineIndex(0),
1373         FormattingDisabled(false) {
1374     Lex.reset(new Lexer(ID, SourceMgr.getBuffer(ID), SourceMgr,
1375                         getFormattingLangOpts(Style)));
1376     Lex->SetKeepWhitespaceMode(true);
1377 
1378     for (const std::string &ForEachMacro : Style.ForEachMacros)
1379       ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
1380     std::sort(ForEachMacros.begin(), ForEachMacros.end());
1381   }
1382 
1383   ArrayRef<FormatToken *> lex() {
1384     assert(Tokens.empty());
1385     assert(FirstInLineIndex == 0);
1386     do {
1387       Tokens.push_back(getNextToken());
1388       tryMergePreviousTokens();
1389       if (Tokens.back()->NewlinesBefore > 0)
1390         FirstInLineIndex = Tokens.size() - 1;
1391     } while (Tokens.back()->Tok.isNot(tok::eof));
1392     return Tokens;
1393   }
1394 
1395   const AdditionalKeywords &getKeywords() { return Keywords; }
1396 
1397 private:
1398   void tryMergePreviousTokens() {
1399     if (tryMerge_TMacro())
1400       return;
1401     if (tryMergeConflictMarkers())
1402       return;
1403 
1404     if (Style.Language == FormatStyle::LK_JavaScript) {
1405       if (tryMergeJSRegexLiteral())
1406         return;
1407       if (tryMergeEscapeSequence())
1408         return;
1409 
1410       static tok::TokenKind JSIdentity[] = { tok::equalequal, tok::equal };
1411       static tok::TokenKind JSNotIdentity[] = { tok::exclaimequal, tok::equal };
1412       static tok::TokenKind JSShiftEqual[] = { tok::greater, tok::greater,
1413                                                tok::greaterequal };
1414       static tok::TokenKind JSRightArrow[] = { tok::equal, tok::greater };
1415       // FIXME: We probably need to change token type to mimic operator with the
1416       // correct priority.
1417       if (tryMergeTokens(JSIdentity))
1418         return;
1419       if (tryMergeTokens(JSNotIdentity))
1420         return;
1421       if (tryMergeTokens(JSShiftEqual))
1422         return;
1423       if (tryMergeTokens(JSRightArrow))
1424         return;
1425     }
1426   }
1427 
1428   bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
1429     if (Tokens.size() < Kinds.size())
1430       return false;
1431 
1432     SmallVectorImpl<FormatToken *>::const_iterator First =
1433         Tokens.end() - Kinds.size();
1434     if (!First[0]->is(Kinds[0]))
1435       return false;
1436     unsigned AddLength = 0;
1437     for (unsigned i = 1; i < Kinds.size(); ++i) {
1438       if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
1439                                          First[i]->WhitespaceRange.getEnd())
1440         return false;
1441       AddLength += First[i]->TokenText.size();
1442     }
1443     Tokens.resize(Tokens.size() - Kinds.size() + 1);
1444     First[0]->TokenText = StringRef(First[0]->TokenText.data(),
1445                                     First[0]->TokenText.size() + AddLength);
1446     First[0]->ColumnWidth += AddLength;
1447     return true;
1448   }
1449 
1450   // Tries to merge an escape sequence, i.e. a "\\" and the following
1451   // character. Use e.g. inside JavaScript regex literals.
1452   bool tryMergeEscapeSequence() {
1453     if (Tokens.size() < 2)
1454       return false;
1455     FormatToken *Previous = Tokens[Tokens.size() - 2];
1456     if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\")
1457       return false;
1458     ++Previous->ColumnWidth;
1459     StringRef Text = Previous->TokenText;
1460     Previous->TokenText = StringRef(Text.data(), Text.size() + 1);
1461     resetLexer(SourceMgr.getFileOffset(Tokens.back()->Tok.getLocation()) + 1);
1462     Tokens.resize(Tokens.size() - 1);
1463     Column = Previous->OriginalColumn + Previous->ColumnWidth;
1464     return true;
1465   }
1466 
1467   // Try to determine whether the current token ends a JavaScript regex literal.
1468   // We heuristically assume that this is a regex literal if we find two
1469   // unescaped slashes on a line and the token before the first slash is one of
1470   // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
1471   // a division.
1472   bool tryMergeJSRegexLiteral() {
1473     if (Tokens.size() < 2)
1474       return false;
1475     // If a regex literal ends in "\//", this gets represented by an unknown
1476     // token "\" and a comment.
1477     bool MightEndWithEscapedSlash =
1478         Tokens.back()->is(tok::comment) &&
1479         Tokens.back()->TokenText.startswith("//") &&
1480         Tokens[Tokens.size() - 2]->TokenText == "\\";
1481     if (!MightEndWithEscapedSlash &&
1482         (Tokens.back()->isNot(tok::slash) ||
1483          (Tokens[Tokens.size() - 2]->is(tok::unknown) &&
1484           Tokens[Tokens.size() - 2]->TokenText == "\\")))
1485       return false;
1486     unsigned TokenCount = 0;
1487     unsigned LastColumn = Tokens.back()->OriginalColumn;
1488     for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
1489       ++TokenCount;
1490       if (I[0]->is(tok::slash) && I + 1 != E &&
1491           (I[1]->isOneOf(tok::l_paren, tok::semi, tok::l_brace, tok::r_brace,
1492                          tok::exclaim, tok::l_square, tok::colon, tok::comma,
1493                          tok::question, tok::kw_return) ||
1494            I[1]->isBinaryOperator())) {
1495         if (MightEndWithEscapedSlash) {
1496           // This regex literal ends in '\//'. Skip past the '//' of the last
1497           // token and re-start lexing from there.
1498           SourceLocation Loc = Tokens.back()->Tok.getLocation();
1499           resetLexer(SourceMgr.getFileOffset(Loc) + 2);
1500         }
1501         Tokens.resize(Tokens.size() - TokenCount);
1502         Tokens.back()->Tok.setKind(tok::unknown);
1503         Tokens.back()->Type = TT_RegexLiteral;
1504         Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
1505         return true;
1506       }
1507 
1508       // There can't be a newline inside a regex literal.
1509       if (I[0]->NewlinesBefore > 0)
1510         return false;
1511     }
1512     return false;
1513   }
1514 
1515   bool tryMerge_TMacro() {
1516     if (Tokens.size() < 4)
1517       return false;
1518     FormatToken *Last = Tokens.back();
1519     if (!Last->is(tok::r_paren))
1520       return false;
1521 
1522     FormatToken *String = Tokens[Tokens.size() - 2];
1523     if (!String->is(tok::string_literal) || String->IsMultiline)
1524       return false;
1525 
1526     if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
1527       return false;
1528 
1529     FormatToken *Macro = Tokens[Tokens.size() - 4];
1530     if (Macro->TokenText != "_T")
1531       return false;
1532 
1533     const char *Start = Macro->TokenText.data();
1534     const char *End = Last->TokenText.data() + Last->TokenText.size();
1535     String->TokenText = StringRef(Start, End - Start);
1536     String->IsFirst = Macro->IsFirst;
1537     String->LastNewlineOffset = Macro->LastNewlineOffset;
1538     String->WhitespaceRange = Macro->WhitespaceRange;
1539     String->OriginalColumn = Macro->OriginalColumn;
1540     String->ColumnWidth = encoding::columnWidthWithTabs(
1541         String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1542 
1543     Tokens.pop_back();
1544     Tokens.pop_back();
1545     Tokens.pop_back();
1546     Tokens.back() = String;
1547     return true;
1548   }
1549 
1550   bool tryMergeConflictMarkers() {
1551     if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1552       return false;
1553 
1554     // Conflict lines look like:
1555     // <marker> <text from the vcs>
1556     // For example:
1557     // >>>>>>> /file/in/file/system at revision 1234
1558     //
1559     // We merge all tokens in a line that starts with a conflict marker
1560     // into a single token with a special token type that the unwrapped line
1561     // parser will use to correctly rebuild the underlying code.
1562 
1563     FileID ID;
1564     // Get the position of the first token in the line.
1565     unsigned FirstInLineOffset;
1566     std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1567         Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1568     StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1569     // Calculate the offset of the start of the current line.
1570     auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1571     if (LineOffset == StringRef::npos) {
1572       LineOffset = 0;
1573     } else {
1574       ++LineOffset;
1575     }
1576 
1577     auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1578     StringRef LineStart;
1579     if (FirstSpace == StringRef::npos) {
1580       LineStart = Buffer.substr(LineOffset);
1581     } else {
1582       LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1583     }
1584 
1585     TokenType Type = TT_Unknown;
1586     if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1587       Type = TT_ConflictStart;
1588     } else if (LineStart == "|||||||" || LineStart == "=======" ||
1589                LineStart == "====") {
1590       Type = TT_ConflictAlternative;
1591     } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1592       Type = TT_ConflictEnd;
1593     }
1594 
1595     if (Type != TT_Unknown) {
1596       FormatToken *Next = Tokens.back();
1597 
1598       Tokens.resize(FirstInLineIndex + 1);
1599       // We do not need to build a complete token here, as we will skip it
1600       // during parsing anyway (as we must not touch whitespace around conflict
1601       // markers).
1602       Tokens.back()->Type = Type;
1603       Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1604 
1605       Tokens.push_back(Next);
1606       return true;
1607     }
1608 
1609     return false;
1610   }
1611 
1612   FormatToken *getNextToken() {
1613     if (GreaterStashed) {
1614       // Create a synthesized second '>' token.
1615       // FIXME: Increment Column and set OriginalColumn.
1616       Token Greater = FormatTok->Tok;
1617       FormatTok = new (Allocator.Allocate()) FormatToken;
1618       FormatTok->Tok = Greater;
1619       SourceLocation GreaterLocation =
1620           FormatTok->Tok.getLocation().getLocWithOffset(1);
1621       FormatTok->WhitespaceRange =
1622           SourceRange(GreaterLocation, GreaterLocation);
1623       FormatTok->TokenText = ">";
1624       FormatTok->ColumnWidth = 1;
1625       GreaterStashed = false;
1626       return FormatTok;
1627     }
1628 
1629     FormatTok = new (Allocator.Allocate()) FormatToken;
1630     readRawToken(*FormatTok);
1631     SourceLocation WhitespaceStart =
1632         FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
1633     FormatTok->IsFirst = IsFirstToken;
1634     IsFirstToken = false;
1635 
1636     // Consume and record whitespace until we find a significant token.
1637     unsigned WhitespaceLength = TrailingWhitespace;
1638     while (FormatTok->Tok.is(tok::unknown)) {
1639       for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1640         switch (FormatTok->TokenText[i]) {
1641         case '\n':
1642           ++FormatTok->NewlinesBefore;
1643           // FIXME: This is technically incorrect, as it could also
1644           // be a literal backslash at the end of the line.
1645           if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1646                          (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1647                           FormatTok->TokenText[i - 2] != '\\')))
1648             FormatTok->HasUnescapedNewline = true;
1649           FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1650           Column = 0;
1651           break;
1652         case '\r':
1653         case '\f':
1654         case '\v':
1655           Column = 0;
1656           break;
1657         case ' ':
1658           ++Column;
1659           break;
1660         case '\t':
1661           Column += Style.TabWidth - Column % Style.TabWidth;
1662           break;
1663         case '\\':
1664           ++Column;
1665           if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1666                              FormatTok->TokenText[i + 1] != '\n'))
1667             FormatTok->Type = TT_ImplicitStringLiteral;
1668           break;
1669         default:
1670           FormatTok->Type = TT_ImplicitStringLiteral;
1671           ++Column;
1672           break;
1673         }
1674       }
1675 
1676       if (FormatTok->is(TT_ImplicitStringLiteral))
1677         break;
1678       WhitespaceLength += FormatTok->Tok.getLength();
1679 
1680       readRawToken(*FormatTok);
1681     }
1682 
1683     // In case the token starts with escaped newlines, we want to
1684     // take them into account as whitespace - this pattern is quite frequent
1685     // in macro definitions.
1686     // FIXME: Add a more explicit test.
1687     while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1688            FormatTok->TokenText[1] == '\n') {
1689       ++FormatTok->NewlinesBefore;
1690       WhitespaceLength += 2;
1691       Column = 0;
1692       FormatTok->TokenText = FormatTok->TokenText.substr(2);
1693     }
1694 
1695     FormatTok->WhitespaceRange = SourceRange(
1696         WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1697 
1698     FormatTok->OriginalColumn = Column;
1699 
1700     TrailingWhitespace = 0;
1701     if (FormatTok->Tok.is(tok::comment)) {
1702       // FIXME: Add the trimmed whitespace to Column.
1703       StringRef UntrimmedText = FormatTok->TokenText;
1704       FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
1705       TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
1706     } else if (FormatTok->Tok.is(tok::raw_identifier)) {
1707       IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
1708       FormatTok->Tok.setIdentifierInfo(&Info);
1709       FormatTok->Tok.setKind(Info.getTokenID());
1710       if (Style.Language == FormatStyle::LK_Java &&
1711           FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete)) {
1712         FormatTok->Tok.setKind(tok::identifier);
1713         FormatTok->Tok.setIdentifierInfo(nullptr);
1714       }
1715     } else if (FormatTok->Tok.is(tok::greatergreater)) {
1716       FormatTok->Tok.setKind(tok::greater);
1717       FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1718       GreaterStashed = true;
1719     }
1720 
1721     // Now FormatTok is the next non-whitespace token.
1722 
1723     StringRef Text = FormatTok->TokenText;
1724     size_t FirstNewlinePos = Text.find('\n');
1725     if (FirstNewlinePos == StringRef::npos) {
1726       // FIXME: ColumnWidth actually depends on the start column, we need to
1727       // take this into account when the token is moved.
1728       FormatTok->ColumnWidth =
1729           encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1730       Column += FormatTok->ColumnWidth;
1731     } else {
1732       FormatTok->IsMultiline = true;
1733       // FIXME: ColumnWidth actually depends on the start column, we need to
1734       // take this into account when the token is moved.
1735       FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1736           Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1737 
1738       // The last line of the token always starts in column 0.
1739       // Thus, the length can be precomputed even in the presence of tabs.
1740       FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1741           Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1742           Encoding);
1743       Column = FormatTok->LastLineColumnWidth;
1744     }
1745 
1746     FormatTok->IsForEachMacro =
1747         std::binary_search(ForEachMacros.begin(), ForEachMacros.end(),
1748                            FormatTok->Tok.getIdentifierInfo());
1749 
1750     return FormatTok;
1751   }
1752 
1753   FormatToken *FormatTok;
1754   bool IsFirstToken;
1755   bool GreaterStashed;
1756   unsigned Column;
1757   unsigned TrailingWhitespace;
1758   std::unique_ptr<Lexer> Lex;
1759   SourceManager &SourceMgr;
1760   FileID ID;
1761   FormatStyle &Style;
1762   IdentifierTable IdentTable;
1763   AdditionalKeywords Keywords;
1764   encoding::Encoding Encoding;
1765   llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
1766   // Index (in 'Tokens') of the last token that starts a new line.
1767   unsigned FirstInLineIndex;
1768   SmallVector<FormatToken *, 16> Tokens;
1769   SmallVector<IdentifierInfo *, 8> ForEachMacros;
1770 
1771   bool FormattingDisabled;
1772 
1773   void readRawToken(FormatToken &Tok) {
1774     Lex->LexFromRawLexer(Tok.Tok);
1775     Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1776                               Tok.Tok.getLength());
1777     // For formatting, treat unterminated string literals like normal string
1778     // literals.
1779     if (Tok.is(tok::unknown)) {
1780       if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1781         Tok.Tok.setKind(tok::string_literal);
1782         Tok.IsUnterminatedLiteral = true;
1783       } else if (Style.Language == FormatStyle::LK_JavaScript &&
1784                  Tok.TokenText == "''") {
1785         Tok.Tok.setKind(tok::char_constant);
1786       }
1787     }
1788 
1789     if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
1790                                  Tok.TokenText == "/* clang-format on */")) {
1791       FormattingDisabled = false;
1792     }
1793 
1794     Tok.Finalized = FormattingDisabled;
1795 
1796     if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
1797                                  Tok.TokenText == "/* clang-format off */")) {
1798       FormattingDisabled = true;
1799     }
1800   }
1801 
1802   void resetLexer(unsigned Offset) {
1803     StringRef Buffer = SourceMgr.getBufferData(ID);
1804     Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
1805                         getFormattingLangOpts(Style), Buffer.begin(),
1806                         Buffer.begin() + Offset, Buffer.end()));
1807     Lex->SetKeepWhitespaceMode(true);
1808   }
1809 };
1810 
1811 static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1812   switch (Language) {
1813   case FormatStyle::LK_Cpp:
1814     return "C++";
1815   case FormatStyle::LK_Java:
1816     return "Java";
1817   case FormatStyle::LK_JavaScript:
1818     return "JavaScript";
1819   case FormatStyle::LK_Proto:
1820     return "Proto";
1821   default:
1822     return "Unknown";
1823   }
1824 }
1825 
1826 class Formatter : public UnwrappedLineConsumer {
1827 public:
1828   Formatter(const FormatStyle &Style, SourceManager &SourceMgr, FileID ID,
1829             ArrayRef<CharSourceRange> Ranges)
1830       : Style(Style), ID(ID), SourceMgr(SourceMgr),
1831         Whitespaces(SourceMgr, Style,
1832                     inputUsesCRLF(SourceMgr.getBufferData(ID))),
1833         Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
1834         Encoding(encoding::detectEncoding(SourceMgr.getBufferData(ID))) {
1835     DEBUG(llvm::dbgs() << "File encoding: "
1836                        << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1837                                                                : "unknown")
1838                        << "\n");
1839     DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1840                        << "\n");
1841   }
1842 
1843   tooling::Replacements format() {
1844     tooling::Replacements Result;
1845     FormatTokenLexer Tokens(SourceMgr, ID, Style, Encoding);
1846 
1847     UnwrappedLineParser Parser(Style, Tokens.getKeywords(), Tokens.lex(),
1848                                *this);
1849     bool StructuralError = Parser.parse();
1850     assert(UnwrappedLines.rbegin()->empty());
1851     for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1852          ++Run) {
1853       DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1854       SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1855       for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1856         AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1857       }
1858       tooling::Replacements RunResult =
1859           format(AnnotatedLines, StructuralError, Tokens);
1860       DEBUG({
1861         llvm::dbgs() << "Replacements for run " << Run << ":\n";
1862         for (tooling::Replacements::iterator I = RunResult.begin(),
1863                                              E = RunResult.end();
1864              I != E; ++I) {
1865           llvm::dbgs() << I->toString() << "\n";
1866         }
1867       });
1868       for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1869         delete AnnotatedLines[i];
1870       }
1871       Result.insert(RunResult.begin(), RunResult.end());
1872       Whitespaces.reset();
1873     }
1874     return Result;
1875   }
1876 
1877   tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1878                                bool StructuralError, FormatTokenLexer &Tokens) {
1879     TokenAnnotator Annotator(Style, Tokens.getKeywords());
1880     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1881       Annotator.annotate(*AnnotatedLines[i]);
1882     }
1883     deriveLocalStyle(AnnotatedLines);
1884     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1885       Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
1886     }
1887     computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
1888 
1889     Annotator.setCommentLineLevels(AnnotatedLines);
1890     ContinuationIndenter Indenter(Style, Tokens.getKeywords(), SourceMgr,
1891                                   Whitespaces, Encoding,
1892                                   BinPackInconclusiveFunctions);
1893     UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style);
1894     Formatter.format(AnnotatedLines, /*DryRun=*/false);
1895     return Whitespaces.generateReplacements();
1896   }
1897 
1898 private:
1899   // Determines which lines are affected by the SourceRanges given as input.
1900   // Returns \c true if at least one line between I and E or one of their
1901   // children is affected.
1902   bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1903                             SmallVectorImpl<AnnotatedLine *>::iterator E) {
1904     bool SomeLineAffected = false;
1905     const AnnotatedLine *PreviousLine = nullptr;
1906     while (I != E) {
1907       AnnotatedLine *Line = *I;
1908       Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1909 
1910       // If a line is part of a preprocessor directive, it needs to be formatted
1911       // if any token within the directive is affected.
1912       if (Line->InPPDirective) {
1913         FormatToken *Last = Line->Last;
1914         SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1915         while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1916           Last = (*PPEnd)->Last;
1917           ++PPEnd;
1918         }
1919 
1920         if (affectsTokenRange(*Line->First, *Last,
1921                               /*IncludeLeadingNewlines=*/false)) {
1922           SomeLineAffected = true;
1923           markAllAsAffected(I, PPEnd);
1924         }
1925         I = PPEnd;
1926         continue;
1927       }
1928 
1929       if (nonPPLineAffected(Line, PreviousLine))
1930         SomeLineAffected = true;
1931 
1932       PreviousLine = Line;
1933       ++I;
1934     }
1935     return SomeLineAffected;
1936   }
1937 
1938   // Determines whether 'Line' is affected by the SourceRanges given as input.
1939   // Returns \c true if line or one if its children is affected.
1940   bool nonPPLineAffected(AnnotatedLine *Line,
1941                          const AnnotatedLine *PreviousLine) {
1942     bool SomeLineAffected = false;
1943     Line->ChildrenAffected =
1944         computeAffectedLines(Line->Children.begin(), Line->Children.end());
1945     if (Line->ChildrenAffected)
1946       SomeLineAffected = true;
1947 
1948     // Stores whether one of the line's tokens is directly affected.
1949     bool SomeTokenAffected = false;
1950     // Stores whether we need to look at the leading newlines of the next token
1951     // in order to determine whether it was affected.
1952     bool IncludeLeadingNewlines = false;
1953 
1954     // Stores whether the first child line of any of this line's tokens is
1955     // affected.
1956     bool SomeFirstChildAffected = false;
1957 
1958     for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1959       // Determine whether 'Tok' was affected.
1960       if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1961         SomeTokenAffected = true;
1962 
1963       // Determine whether the first child of 'Tok' was affected.
1964       if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1965         SomeFirstChildAffected = true;
1966 
1967       IncludeLeadingNewlines = Tok->Children.empty();
1968     }
1969 
1970     // Was this line moved, i.e. has it previously been on the same line as an
1971     // affected line?
1972     bool LineMoved = PreviousLine && PreviousLine->Affected &&
1973                      Line->First->NewlinesBefore == 0;
1974 
1975     bool IsContinuedComment =
1976         Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1977         Line->First->NewlinesBefore < 2 && PreviousLine &&
1978         PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
1979 
1980     if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1981         IsContinuedComment) {
1982       Line->Affected = true;
1983       SomeLineAffected = true;
1984     }
1985     return SomeLineAffected;
1986   }
1987 
1988   // Marks all lines between I and E as well as all their children as affected.
1989   void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1990                          SmallVectorImpl<AnnotatedLine *>::iterator E) {
1991     while (I != E) {
1992       (*I)->Affected = true;
1993       markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1994       ++I;
1995     }
1996   }
1997 
1998   // Returns true if the range from 'First' to 'Last' intersects with one of the
1999   // input ranges.
2000   bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
2001                          bool IncludeLeadingNewlines) {
2002     SourceLocation Start = First.WhitespaceRange.getBegin();
2003     if (!IncludeLeadingNewlines)
2004       Start = Start.getLocWithOffset(First.LastNewlineOffset);
2005     SourceLocation End = Last.getStartOfNonWhitespace();
2006     End = End.getLocWithOffset(Last.TokenText.size());
2007     CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
2008     return affectsCharSourceRange(Range);
2009   }
2010 
2011   // Returns true if one of the input ranges intersect the leading empty lines
2012   // before 'Tok'.
2013   bool affectsLeadingEmptyLines(const FormatToken &Tok) {
2014     CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
2015         Tok.WhitespaceRange.getBegin(),
2016         Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
2017     return affectsCharSourceRange(EmptyLineRange);
2018   }
2019 
2020   // Returns true if 'Range' intersects with one of the input ranges.
2021   bool affectsCharSourceRange(const CharSourceRange &Range) {
2022     for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
2023                                                           E = Ranges.end();
2024          I != E; ++I) {
2025       if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
2026           !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
2027         return true;
2028     }
2029     return false;
2030   }
2031 
2032   static bool inputUsesCRLF(StringRef Text) {
2033     return Text.count('\r') * 2 > Text.count('\n');
2034   }
2035 
2036   void
2037   deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
2038     unsigned CountBoundToVariable = 0;
2039     unsigned CountBoundToType = 0;
2040     bool HasCpp03IncompatibleFormat = false;
2041     bool HasBinPackedFunction = false;
2042     bool HasOnePerLineFunction = false;
2043     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
2044       if (!AnnotatedLines[i]->First->Next)
2045         continue;
2046       FormatToken *Tok = AnnotatedLines[i]->First->Next;
2047       while (Tok->Next) {
2048         if (Tok->is(TT_PointerOrReference)) {
2049           bool SpacesBefore =
2050               Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
2051           bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
2052                              Tok->Next->WhitespaceRange.getEnd();
2053           if (SpacesBefore && !SpacesAfter)
2054             ++CountBoundToVariable;
2055           else if (!SpacesBefore && SpacesAfter)
2056             ++CountBoundToType;
2057         }
2058 
2059         if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
2060           if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
2061             HasCpp03IncompatibleFormat = true;
2062           if (Tok->is(TT_TemplateCloser) &&
2063               Tok->Previous->is(TT_TemplateCloser))
2064             HasCpp03IncompatibleFormat = true;
2065         }
2066 
2067         if (Tok->PackingKind == PPK_BinPacked)
2068           HasBinPackedFunction = true;
2069         if (Tok->PackingKind == PPK_OnePerLine)
2070           HasOnePerLineFunction = true;
2071 
2072         Tok = Tok->Next;
2073       }
2074     }
2075     if (Style.DerivePointerAlignment) {
2076       if (CountBoundToType > CountBoundToVariable)
2077         Style.PointerAlignment = FormatStyle::PAS_Left;
2078       else if (CountBoundToType < CountBoundToVariable)
2079         Style.PointerAlignment = FormatStyle::PAS_Right;
2080     }
2081     if (Style.Standard == FormatStyle::LS_Auto) {
2082       Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
2083                                                   : FormatStyle::LS_Cpp03;
2084     }
2085     BinPackInconclusiveFunctions =
2086         HasBinPackedFunction || !HasOnePerLineFunction;
2087   }
2088 
2089   void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
2090     assert(!UnwrappedLines.empty());
2091     UnwrappedLines.back().push_back(TheLine);
2092   }
2093 
2094   void finishRun() override {
2095     UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
2096   }
2097 
2098   FormatStyle Style;
2099   FileID ID;
2100   SourceManager &SourceMgr;
2101   WhitespaceManager Whitespaces;
2102   SmallVector<CharSourceRange, 8> Ranges;
2103   SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
2104 
2105   encoding::Encoding Encoding;
2106   bool BinPackInconclusiveFunctions;
2107 };
2108 
2109 } // end anonymous namespace
2110 
2111 tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
2112                                SourceManager &SourceMgr,
2113                                ArrayRef<CharSourceRange> Ranges) {
2114   if (Style.DisableFormat)
2115     return tooling::Replacements();
2116   return reformat(Style, SourceMgr,
2117                   SourceMgr.getFileID(Lex.getSourceLocation()), Ranges);
2118 }
2119 
2120 tooling::Replacements reformat(const FormatStyle &Style,
2121                                SourceManager &SourceMgr, FileID ID,
2122                                ArrayRef<CharSourceRange> Ranges) {
2123   if (Style.DisableFormat)
2124     return tooling::Replacements();
2125   Formatter formatter(Style, SourceMgr, ID, Ranges);
2126   return formatter.format();
2127 }
2128 
2129 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
2130                                ArrayRef<tooling::Range> Ranges,
2131                                StringRef FileName) {
2132   if (Style.DisableFormat)
2133     return tooling::Replacements();
2134 
2135   FileManager Files((FileSystemOptions()));
2136   DiagnosticsEngine Diagnostics(
2137       IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
2138       new DiagnosticOptions);
2139   SourceManager SourceMgr(Diagnostics, Files);
2140   std::unique_ptr<llvm::MemoryBuffer> Buf =
2141       llvm::MemoryBuffer::getMemBuffer(Code, FileName);
2142   const clang::FileEntry *Entry =
2143       Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
2144   SourceMgr.overrideFileContents(Entry, std::move(Buf));
2145   FileID ID =
2146       SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
2147   SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
2148   std::vector<CharSourceRange> CharRanges;
2149   for (const tooling::Range &Range : Ranges) {
2150     SourceLocation Start = StartOfFile.getLocWithOffset(Range.getOffset());
2151     SourceLocation End = Start.getLocWithOffset(Range.getLength());
2152     CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
2153   }
2154   return reformat(Style, SourceMgr, ID, CharRanges);
2155 }
2156 
2157 LangOptions getFormattingLangOpts(const FormatStyle &Style) {
2158   LangOptions LangOpts;
2159   LangOpts.CPlusPlus = 1;
2160   LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
2161   LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
2162   LangOpts.LineComment = 1;
2163   bool AlternativeOperators = Style.Language != FormatStyle::LK_JavaScript &&
2164                               Style.Language != FormatStyle::LK_Java;
2165   LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
2166   LangOpts.Bool = 1;
2167   LangOpts.ObjC1 = 1;
2168   LangOpts.ObjC2 = 1;
2169   return LangOpts;
2170 }
2171 
2172 const char *StyleOptionHelpDescription =
2173     "Coding style, currently supports:\n"
2174     "  LLVM, Google, Chromium, Mozilla, WebKit.\n"
2175     "Use -style=file to load style configuration from\n"
2176     ".clang-format file located in one of the parent\n"
2177     "directories of the source file (or current\n"
2178     "directory for stdin).\n"
2179     "Use -style=\"{key: value, ...}\" to set specific\n"
2180     "parameters, e.g.:\n"
2181     "  -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
2182 
2183 static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
2184   if (FileName.endswith(".java")) {
2185     return FormatStyle::LK_Java;
2186   } else if (FileName.endswith_lower(".js")) {
2187     return FormatStyle::LK_JavaScript;
2188   } else if (FileName.endswith_lower(".proto") ||
2189              FileName.endswith_lower(".protodevel")) {
2190     return FormatStyle::LK_Proto;
2191   }
2192   return FormatStyle::LK_Cpp;
2193 }
2194 
2195 FormatStyle getStyle(StringRef StyleName, StringRef FileName,
2196                      StringRef FallbackStyle) {
2197   FormatStyle Style = getLLVMStyle();
2198   Style.Language = getLanguageByFileName(FileName);
2199   if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
2200     llvm::errs() << "Invalid fallback style \"" << FallbackStyle
2201                  << "\" using LLVM style\n";
2202     return Style;
2203   }
2204 
2205   if (StyleName.startswith("{")) {
2206     // Parse YAML/JSON style from the command line.
2207     if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
2208       llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
2209                    << FallbackStyle << " style\n";
2210     }
2211     return Style;
2212   }
2213 
2214   if (!StyleName.equals_lower("file")) {
2215     if (!getPredefinedStyle(StyleName, Style.Language, &Style))
2216       llvm::errs() << "Invalid value for -style, using " << FallbackStyle
2217                    << " style\n";
2218     return Style;
2219   }
2220 
2221   // Look for .clang-format/_clang-format file in the file's parent directories.
2222   SmallString<128> UnsuitableConfigFiles;
2223   SmallString<128> Path(FileName);
2224   llvm::sys::fs::make_absolute(Path);
2225   for (StringRef Directory = Path; !Directory.empty();
2226        Directory = llvm::sys::path::parent_path(Directory)) {
2227     if (!llvm::sys::fs::is_directory(Directory))
2228       continue;
2229     SmallString<128> ConfigFile(Directory);
2230 
2231     llvm::sys::path::append(ConfigFile, ".clang-format");
2232     DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2233     bool IsFile = false;
2234     // Ignore errors from is_regular_file: we only need to know if we can read
2235     // the file or not.
2236     llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2237 
2238     if (!IsFile) {
2239       // Try _clang-format too, since dotfiles are not commonly used on Windows.
2240       ConfigFile = Directory;
2241       llvm::sys::path::append(ConfigFile, "_clang-format");
2242       DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2243       llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2244     }
2245 
2246     if (IsFile) {
2247       llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
2248           llvm::MemoryBuffer::getFile(ConfigFile.c_str());
2249       if (std::error_code EC = Text.getError()) {
2250         llvm::errs() << EC.message() << "\n";
2251         break;
2252       }
2253       if (std::error_code ec =
2254               parseConfiguration(Text.get()->getBuffer(), &Style)) {
2255         if (ec == ParseError::Unsuitable) {
2256           if (!UnsuitableConfigFiles.empty())
2257             UnsuitableConfigFiles.append(", ");
2258           UnsuitableConfigFiles.append(ConfigFile);
2259           continue;
2260         }
2261         llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
2262                      << "\n";
2263         break;
2264       }
2265       DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
2266       return Style;
2267     }
2268   }
2269   llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
2270                << " style\n";
2271   if (!UnsuitableConfigFiles.empty()) {
2272     llvm::errs() << "Configuration file(s) do(es) not support "
2273                  << getLanguageName(Style.Language) << ": "
2274                  << UnsuitableConfigFiles << "\n";
2275   }
2276   return Style;
2277 }
2278 
2279 } // namespace format
2280 } // namespace clang
2281