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       // Check for Limit <= 2 to account for the " {".
669       if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
670         return 0;
671       Limit -= 2;
672 
673       unsigned MergedLines = 0;
674       if (MergeShortFunctions) {
675         MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
676         // If we managed to merge the block, count the function header, which is
677         // on a separate line.
678         if (MergedLines > 0)
679           ++MergedLines;
680       }
681       return MergedLines;
682     }
683     if (TheLine->First->is(tok::kw_if)) {
684       return Style.AllowShortIfStatementsOnASingleLine
685                  ? tryMergeSimpleControlStatement(I, E, Limit)
686                  : 0;
687     }
688     if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
689       return Style.AllowShortLoopsOnASingleLine
690                  ? tryMergeSimpleControlStatement(I, E, Limit)
691                  : 0;
692     }
693     if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
694       return Style.AllowShortCaseLabelsOnASingleLine
695                  ? tryMergeShortCaseLabels(I, E, Limit)
696                  : 0;
697     }
698     if (TheLine->InPPDirective &&
699         (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
700       return tryMergeSimplePPDirective(I, E, Limit);
701     }
702     return 0;
703   }
704 
705 private:
706   unsigned
707   tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
708                             SmallVectorImpl<AnnotatedLine *>::const_iterator E,
709                             unsigned Limit) {
710     if (Limit == 0)
711       return 0;
712     if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
713       return 0;
714     if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
715       return 0;
716     if (1 + I[1]->Last->TotalLength > Limit)
717       return 0;
718     return 1;
719   }
720 
721   unsigned tryMergeSimpleControlStatement(
722       SmallVectorImpl<AnnotatedLine *>::const_iterator I,
723       SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
724     if (Limit == 0)
725       return 0;
726     if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
727          Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
728         (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
729       return 0;
730     if (I[1]->InPPDirective != (*I)->InPPDirective ||
731         (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
732       return 0;
733     Limit = limitConsideringMacros(I + 1, E, Limit);
734     AnnotatedLine &Line = **I;
735     if (Line.Last->isNot(tok::r_paren))
736       return 0;
737     if (1 + I[1]->Last->TotalLength > Limit)
738       return 0;
739     if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
740                              tok::kw_while, TT_LineComment))
741       return 0;
742     // Only inline simple if's (no nested if or else).
743     if (I + 2 != E && Line.First->is(tok::kw_if) &&
744         I[2]->First->is(tok::kw_else))
745       return 0;
746     return 1;
747   }
748 
749   unsigned tryMergeShortCaseLabels(
750       SmallVectorImpl<AnnotatedLine *>::const_iterator I,
751       SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
752     if (Limit == 0 || I + 1 == E ||
753         I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
754       return 0;
755     unsigned NumStmts = 0;
756     unsigned Length = 0;
757     bool InPPDirective = I[0]->InPPDirective;
758     for (; NumStmts < 3; ++NumStmts) {
759       if (I + 1 + NumStmts == E)
760         break;
761       const AnnotatedLine *Line = I[1 + NumStmts];
762       if (Line->InPPDirective != InPPDirective)
763         break;
764       if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
765         break;
766       if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
767                                tok::kw_while, tok::comment))
768         return 0;
769       Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
770     }
771     if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
772       return 0;
773     return NumStmts;
774   }
775 
776   unsigned
777   tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
778                       SmallVectorImpl<AnnotatedLine *>::const_iterator E,
779                       unsigned Limit) {
780     AnnotatedLine &Line = **I;
781 
782     // Don't merge ObjC @ keywords and methods.
783     if (Style.Language != FormatStyle::LK_Java &&
784         Line.First->isOneOf(tok::at, tok::minus, tok::plus))
785       return 0;
786 
787     // Check that the current line allows merging. This depends on whether we
788     // are in a control flow statements as well as several style flags.
789     if (Line.First->isOneOf(tok::kw_else, tok::kw_case))
790       return 0;
791     if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
792                             tok::kw_catch, tok::kw_for, tok::r_brace)) {
793       if (!Style.AllowShortBlocksOnASingleLine)
794         return 0;
795       if (!Style.AllowShortIfStatementsOnASingleLine &&
796           Line.First->is(tok::kw_if))
797         return 0;
798       if (!Style.AllowShortLoopsOnASingleLine &&
799           Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
800         return 0;
801       // FIXME: Consider an option to allow short exception handling clauses on
802       // a single line.
803       if (Line.First->isOneOf(tok::kw_try, tok::kw_catch))
804         return 0;
805     }
806 
807     FormatToken *Tok = I[1]->First;
808     if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
809         (Tok->getNextNonComment() == nullptr ||
810          Tok->getNextNonComment()->is(tok::semi))) {
811       // We merge empty blocks even if the line exceeds the column limit.
812       Tok->SpacesRequiredBefore = 0;
813       Tok->CanBreakBefore = true;
814       return 1;
815     } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace) &&
816                !startsExternCBlock(Line)) {
817       // We don't merge short records.
818       if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct))
819         return 0;
820 
821       // Check that we still have three lines and they fit into the limit.
822       if (I + 2 == E || I[2]->Type == LT_Invalid)
823         return 0;
824       Limit = limitConsideringMacros(I + 2, E, Limit);
825 
826       if (!nextTwoLinesFitInto(I, Limit))
827         return 0;
828 
829       // Second, check that the next line does not contain any braces - if it
830       // does, readability declines when putting it into a single line.
831       if (I[1]->Last->is(TT_LineComment))
832         return 0;
833       do {
834         if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
835           return 0;
836         Tok = Tok->Next;
837       } while (Tok);
838 
839       // Last, check that the third line starts with a closing brace.
840       Tok = I[2]->First;
841       if (Tok->isNot(tok::r_brace))
842         return 0;
843 
844       return 2;
845     }
846     return 0;
847   }
848 
849   /// Returns the modified column limit for \p I if it is inside a macro and
850   /// needs a trailing '\'.
851   unsigned
852   limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
853                          SmallVectorImpl<AnnotatedLine *>::const_iterator E,
854                          unsigned Limit) {
855     if (I[0]->InPPDirective && I + 1 != E &&
856         !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
857       return Limit < 2 ? 0 : Limit - 2;
858     }
859     return Limit;
860   }
861 
862   bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
863                            unsigned Limit) {
864     if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
865       return false;
866     return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
867   }
868 
869   bool containsMustBreak(const AnnotatedLine *Line) {
870     for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
871       if (Tok->MustBreakBefore)
872         return true;
873     }
874     return false;
875   }
876 
877   const FormatStyle &Style;
878 };
879 
880 class UnwrappedLineFormatter {
881 public:
882   UnwrappedLineFormatter(ContinuationIndenter *Indenter,
883                          WhitespaceManager *Whitespaces,
884                          const FormatStyle &Style)
885       : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
886         Joiner(Style) {}
887 
888   unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
889                   int AdditionalIndent = 0, bool FixBadIndentation = false) {
890     // Try to look up already computed penalty in DryRun-mode.
891     std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
892         &Lines, AdditionalIndent);
893     auto CacheIt = PenaltyCache.find(CacheKey);
894     if (DryRun && CacheIt != PenaltyCache.end())
895       return CacheIt->second;
896 
897     assert(!Lines.empty());
898     unsigned Penalty = 0;
899     std::vector<int> IndentForLevel;
900     for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
901       IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
902     const AnnotatedLine *PreviousLine = nullptr;
903     for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
904                                                           E = Lines.end();
905          I != E; ++I) {
906       const AnnotatedLine &TheLine = **I;
907       const FormatToken *FirstTok = TheLine.First;
908       int Offset = getIndentOffset(*FirstTok);
909 
910       // Determine indent and try to merge multiple unwrapped lines.
911       unsigned Indent;
912       if (TheLine.InPPDirective) {
913         Indent = TheLine.Level * Style.IndentWidth;
914       } else {
915         while (IndentForLevel.size() <= TheLine.Level)
916           IndentForLevel.push_back(-1);
917         IndentForLevel.resize(TheLine.Level + 1);
918         Indent = getIndent(IndentForLevel, TheLine.Level);
919       }
920       unsigned LevelIndent = Indent;
921       if (static_cast<int>(Indent) + Offset >= 0)
922         Indent += Offset;
923 
924       // Merge multiple lines if possible.
925       unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
926       if (MergedLines > 0 && Style.ColumnLimit == 0) {
927         // Disallow line merging if there is a break at the start of one of the
928         // input lines.
929         for (unsigned i = 0; i < MergedLines; ++i) {
930           if (I[i + 1]->First->NewlinesBefore > 0)
931             MergedLines = 0;
932         }
933       }
934       if (!DryRun) {
935         for (unsigned i = 0; i < MergedLines; ++i) {
936           join(*I[i], *I[i + 1]);
937         }
938       }
939       I += MergedLines;
940 
941       bool FixIndentation =
942           FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
943       if (TheLine.First->is(tok::eof)) {
944         if (PreviousLine && PreviousLine->Affected && !DryRun) {
945           // Remove the file's trailing whitespace.
946           unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
947           Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
948                                          /*IndentLevel=*/0, /*Spaces=*/0,
949                                          /*TargetColumn=*/0);
950         }
951       } else if (TheLine.Type != LT_Invalid &&
952                  (TheLine.Affected || FixIndentation)) {
953         if (FirstTok->WhitespaceRange.isValid()) {
954           if (!DryRun)
955             formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
956                              Indent, TheLine.InPPDirective);
957         } else {
958           Indent = LevelIndent = FirstTok->OriginalColumn;
959         }
960 
961         // If everything fits on a single line, just put it there.
962         unsigned ColumnLimit = Style.ColumnLimit;
963         if (I + 1 != E) {
964           AnnotatedLine *NextLine = I[1];
965           if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
966             ColumnLimit = getColumnLimit(TheLine.InPPDirective);
967         }
968 
969         if (TheLine.Last->TotalLength + Indent <= ColumnLimit ||
970             TheLine.Type == LT_ImportStatement) {
971           LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
972           while (State.NextToken) {
973             formatChildren(State, /*Newline=*/false, /*DryRun=*/false, Penalty);
974             Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
975           }
976         } else if (Style.ColumnLimit == 0) {
977           // FIXME: Implement nested blocks for ColumnLimit = 0.
978           NoColumnLimitFormatter Formatter(Indenter);
979           if (!DryRun)
980             Formatter.format(Indent, &TheLine);
981         } else {
982           Penalty += format(TheLine, Indent, DryRun);
983         }
984 
985         if (!TheLine.InPPDirective)
986           IndentForLevel[TheLine.Level] = LevelIndent;
987       } else if (TheLine.ChildrenAffected) {
988         format(TheLine.Children, DryRun);
989       } else {
990         // Format the first token if necessary, and notify the WhitespaceManager
991         // about the unchanged whitespace.
992         for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
993           if (Tok == TheLine.First &&
994               (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
995             unsigned LevelIndent = Tok->OriginalColumn;
996             if (!DryRun) {
997               // Remove trailing whitespace of the previous line.
998               if ((PreviousLine && PreviousLine->Affected) ||
999                   TheLine.LeadingEmptyLinesAffected) {
1000                 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
1001                                  TheLine.InPPDirective);
1002               } else {
1003                 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
1004               }
1005             }
1006 
1007             if (static_cast<int>(LevelIndent) - Offset >= 0)
1008               LevelIndent -= Offset;
1009             if (Tok->isNot(tok::comment) && !TheLine.InPPDirective)
1010               IndentForLevel[TheLine.Level] = LevelIndent;
1011           } else if (!DryRun) {
1012             Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
1013           }
1014         }
1015       }
1016       if (!DryRun) {
1017         for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
1018           Tok->Finalized = true;
1019         }
1020       }
1021       PreviousLine = *I;
1022     }
1023     PenaltyCache[CacheKey] = Penalty;
1024     return Penalty;
1025   }
1026 
1027 private:
1028   /// \brief Formats an \c AnnotatedLine and returns the penalty.
1029   ///
1030   /// If \p DryRun is \c false, directly applies the changes.
1031   unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
1032                   bool DryRun) {
1033     LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
1034 
1035     // If the ObjC method declaration does not fit on a line, we should format
1036     // it with one arg per line.
1037     if (State.Line->Type == LT_ObjCMethodDecl)
1038       State.Stack.back().BreakBeforeParameter = true;
1039 
1040     // Find best solution in solution space.
1041     return analyzeSolutionSpace(State, DryRun);
1042   }
1043 
1044   /// \brief An edge in the solution space from \c Previous->State to \c State,
1045   /// inserting a newline dependent on the \c NewLine.
1046   struct StateNode {
1047     StateNode(const LineState &State, bool NewLine, StateNode *Previous)
1048         : State(State), NewLine(NewLine), Previous(Previous) {}
1049     LineState State;
1050     bool NewLine;
1051     StateNode *Previous;
1052   };
1053 
1054   /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
1055   ///
1056   /// In case of equal penalties, we want to prefer states that were inserted
1057   /// first. During state generation we make sure that we insert states first
1058   /// that break the line as late as possible.
1059   typedef std::pair<unsigned, unsigned> OrderedPenalty;
1060 
1061   /// \brief An item in the prioritized BFS search queue. The \c StateNode's
1062   /// \c State has the given \c OrderedPenalty.
1063   typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1064 
1065   /// \brief The BFS queue type.
1066   typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
1067                               std::greater<QueueItem> > QueueType;
1068 
1069   /// \brief Get the offset of the line relatively to the level.
1070   ///
1071   /// For example, 'public:' labels in classes are offset by 1 or 2
1072   /// characters to the left from their level.
1073   int getIndentOffset(const FormatToken &RootToken) {
1074     if (Style.Language == FormatStyle::LK_Java)
1075       return 0;
1076     if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
1077       return Style.AccessModifierOffset;
1078     return 0;
1079   }
1080 
1081   /// \brief Add a new line and the required indent before the first Token
1082   /// of the \c UnwrappedLine if there was no structural parsing error.
1083   void formatFirstToken(FormatToken &RootToken,
1084                         const AnnotatedLine *PreviousLine, unsigned IndentLevel,
1085                         unsigned Indent, bool InPPDirective) {
1086     unsigned Newlines =
1087         std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1088     // Remove empty lines before "}" where applicable.
1089     if (RootToken.is(tok::r_brace) &&
1090         (!RootToken.Next ||
1091          (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1092       Newlines = std::min(Newlines, 1u);
1093     if (Newlines == 0 && !RootToken.IsFirst)
1094       Newlines = 1;
1095     if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
1096       Newlines = 0;
1097 
1098     // Remove empty lines after "{".
1099     if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
1100         PreviousLine->Last->is(tok::l_brace) &&
1101         PreviousLine->First->isNot(tok::kw_namespace) &&
1102         !startsExternCBlock(*PreviousLine))
1103       Newlines = 1;
1104 
1105     // Insert extra new line before access specifiers.
1106     if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
1107         RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
1108       ++Newlines;
1109 
1110     // Remove empty lines after access specifiers.
1111     if (PreviousLine && PreviousLine->First->isAccessSpecifier())
1112       Newlines = std::min(1u, Newlines);
1113 
1114     Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
1115                                    Indent, InPPDirective &&
1116                                                !RootToken.HasUnescapedNewline);
1117   }
1118 
1119   /// \brief Get the indent of \p Level from \p IndentForLevel.
1120   ///
1121   /// \p IndentForLevel must contain the indent for the level \c l
1122   /// at \p IndentForLevel[l], or a value < 0 if the indent for
1123   /// that level is unknown.
1124   unsigned getIndent(ArrayRef<int> IndentForLevel, unsigned Level) {
1125     if (IndentForLevel[Level] != -1)
1126       return IndentForLevel[Level];
1127     if (Level == 0)
1128       return 0;
1129     return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
1130   }
1131 
1132   void join(AnnotatedLine &A, const AnnotatedLine &B) {
1133     assert(!A.Last->Next);
1134     assert(!B.First->Previous);
1135     if (B.Affected)
1136       A.Affected = true;
1137     A.Last->Next = B.First;
1138     B.First->Previous = A.Last;
1139     B.First->CanBreakBefore = true;
1140     unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1141     for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1142       Tok->TotalLength += LengthA;
1143       A.Last = Tok;
1144     }
1145   }
1146 
1147   unsigned getColumnLimit(bool InPPDirective) const {
1148     // In preprocessor directives reserve two chars for trailing " \"
1149     return Style.ColumnLimit - (InPPDirective ? 2 : 0);
1150   }
1151 
1152   struct CompareLineStatePointers {
1153     bool operator()(LineState *obj1, LineState *obj2) const {
1154       return *obj1 < *obj2;
1155     }
1156   };
1157 
1158   /// \brief Analyze the entire solution space starting from \p InitialState.
1159   ///
1160   /// This implements a variant of Dijkstra's algorithm on the graph that spans
1161   /// the solution space (\c LineStates are the nodes). The algorithm tries to
1162   /// find the shortest path (the one with lowest penalty) from \p InitialState
1163   /// to a state where all tokens are placed. Returns the penalty.
1164   ///
1165   /// If \p DryRun is \c false, directly applies the changes.
1166   unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
1167     std::set<LineState *, CompareLineStatePointers> Seen;
1168 
1169     // Increasing count of \c StateNode items we have created. This is used to
1170     // create a deterministic order independent of the container.
1171     unsigned Count = 0;
1172     QueueType Queue;
1173 
1174     // Insert start element into queue.
1175     StateNode *Node =
1176         new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
1177     Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1178     ++Count;
1179 
1180     unsigned Penalty = 0;
1181 
1182     // While not empty, take first element and follow edges.
1183     while (!Queue.empty()) {
1184       Penalty = Queue.top().first.first;
1185       StateNode *Node = Queue.top().second;
1186       if (!Node->State.NextToken) {
1187         DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
1188         break;
1189       }
1190       Queue.pop();
1191 
1192       // Cut off the analysis of certain solutions if the analysis gets too
1193       // complex. See description of IgnoreStackForComparison.
1194       if (Count > 10000)
1195         Node->State.IgnoreStackForComparison = true;
1196 
1197       if (!Seen.insert(&Node->State).second)
1198         // State already examined with lower penalty.
1199         continue;
1200 
1201       FormatDecision LastFormat = Node->State.NextToken->Decision;
1202       if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
1203         addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
1204       if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
1205         addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
1206     }
1207 
1208     if (Queue.empty()) {
1209       // We were unable to find a solution, do nothing.
1210       // FIXME: Add diagnostic?
1211       DEBUG(llvm::dbgs() << "Could not find a solution.\n");
1212       return 0;
1213     }
1214 
1215     // Reconstruct the solution.
1216     if (!DryRun)
1217       reconstructPath(InitialState, Queue.top().second);
1218 
1219     DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
1220     DEBUG(llvm::dbgs() << "---\n");
1221 
1222     return Penalty;
1223   }
1224 
1225   void reconstructPath(LineState &State, StateNode *Current) {
1226     std::deque<StateNode *> Path;
1227     // We do not need a break before the initial token.
1228     while (Current->Previous) {
1229       Path.push_front(Current);
1230       Current = Current->Previous;
1231     }
1232     for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1233          I != E; ++I) {
1234       unsigned Penalty = 0;
1235       formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
1236       Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
1237 
1238       DEBUG({
1239         if ((*I)->NewLine) {
1240           llvm::dbgs() << "Penalty for placing "
1241                        << (*I)->Previous->State.NextToken->Tok.getName() << ": "
1242                        << Penalty << "\n";
1243         }
1244       });
1245     }
1246   }
1247 
1248   /// \brief Add the following state to the analysis queue \c Queue.
1249   ///
1250   /// Assume the current state is \p PreviousNode and has been reached with a
1251   /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
1252   void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
1253                            bool NewLine, unsigned *Count, QueueType *Queue) {
1254     if (NewLine && !Indenter->canBreak(PreviousNode->State))
1255       return;
1256     if (!NewLine && Indenter->mustBreak(PreviousNode->State))
1257       return;
1258 
1259     StateNode *Node = new (Allocator.Allocate())
1260         StateNode(PreviousNode->State, NewLine, PreviousNode);
1261     if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1262       return;
1263 
1264     Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
1265 
1266     Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1267     ++(*Count);
1268   }
1269 
1270   /// \brief If the \p State's next token is an r_brace closing a nested block,
1271   /// format the nested block before it.
1272   ///
1273   /// Returns \c true if all children could be placed successfully and adapts
1274   /// \p Penalty as well as \p State. If \p DryRun is false, also directly
1275   /// creates changes using \c Whitespaces.
1276   ///
1277   /// The crucial idea here is that children always get formatted upon
1278   /// encountering the closing brace right after the nested block. Now, if we
1279   /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1280   /// \c false), the entire block has to be kept on the same line (which is only
1281   /// possible if it fits on the line, only contains a single statement, etc.
1282   ///
1283   /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1284   /// break after the "{", format all lines with correct indentation and the put
1285   /// the closing "}" on yet another new line.
1286   ///
1287   /// This enables us to keep the simple structure of the
1288   /// \c UnwrappedLineFormatter, where we only have two options for each token:
1289   /// break or don't break.
1290   bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1291                       unsigned &Penalty) {
1292     FormatToken &Previous = *State.NextToken->Previous;
1293     const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1294     if (!LBrace || LBrace->isNot(tok::l_brace) ||
1295         LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
1296       // The previous token does not open a block. Nothing to do. We don't
1297       // assert so that we can simply call this function for all tokens.
1298       return true;
1299 
1300     if (NewLine) {
1301       int AdditionalIndent =
1302           State.FirstIndent - State.Line->Level * Style.IndentWidth;
1303       if (State.Stack.size() < 2 ||
1304           !State.Stack[State.Stack.size() - 2].NestedBlockInlined) {
1305         AdditionalIndent = State.Stack.back().Indent -
1306                            Previous.Children[0]->Level * Style.IndentWidth;
1307       }
1308 
1309       Penalty += format(Previous.Children, DryRun, AdditionalIndent,
1310                         /*FixBadIndentation=*/true);
1311       return true;
1312     }
1313 
1314     if (Previous.Children[0]->First->MustBreakBefore)
1315       return false;
1316 
1317     // Cannot merge multiple statements into a single line.
1318     if (Previous.Children.size() > 1)
1319       return false;
1320 
1321     // Cannot merge into one line if this line ends on a comment.
1322     if (Previous.is(tok::comment))
1323       return false;
1324 
1325     // We can't put the closing "}" on a line with a trailing comment.
1326     if (Previous.Children[0]->Last->isTrailingComment())
1327       return false;
1328 
1329     // If the child line exceeds the column limit, we wouldn't want to merge it.
1330     // We add +2 for the trailing " }".
1331     if (Style.ColumnLimit > 0 &&
1332         Previous.Children[0]->Last->TotalLength + State.Column + 2 >
1333             Style.ColumnLimit)
1334       return false;
1335 
1336     if (!DryRun) {
1337       Whitespaces->replaceWhitespace(
1338           *Previous.Children[0]->First,
1339           /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
1340           /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
1341     }
1342     Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
1343 
1344     State.Column += 1 + Previous.Children[0]->Last->TotalLength;
1345     return true;
1346   }
1347 
1348   ContinuationIndenter *Indenter;
1349   WhitespaceManager *Whitespaces;
1350   FormatStyle Style;
1351   LineJoiner Joiner;
1352 
1353   llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1354 
1355   // Cache to store the penalty of formatting a vector of AnnotatedLines
1356   // starting from a specific additional offset. Improves performance if there
1357   // are many nested blocks.
1358   std::map<std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned>,
1359            unsigned> PenaltyCache;
1360 };
1361 
1362 class FormatTokenLexer {
1363 public:
1364   FormatTokenLexer(SourceManager &SourceMgr, FileID ID, FormatStyle &Style,
1365                    encoding::Encoding Encoding)
1366       : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
1367         Column(0), TrailingWhitespace(0), SourceMgr(SourceMgr), ID(ID),
1368         Style(Style), IdentTable(getFormattingLangOpts(Style)),
1369         Keywords(IdentTable), Encoding(Encoding), FirstInLineIndex(0),
1370         FormattingDisabled(false) {
1371     Lex.reset(new Lexer(ID, SourceMgr.getBuffer(ID), SourceMgr,
1372                         getFormattingLangOpts(Style)));
1373     Lex->SetKeepWhitespaceMode(true);
1374 
1375     for (const std::string &ForEachMacro : Style.ForEachMacros)
1376       ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
1377     std::sort(ForEachMacros.begin(), ForEachMacros.end());
1378   }
1379 
1380   ArrayRef<FormatToken *> lex() {
1381     assert(Tokens.empty());
1382     assert(FirstInLineIndex == 0);
1383     do {
1384       Tokens.push_back(getNextToken());
1385       tryMergePreviousTokens();
1386       if (Tokens.back()->NewlinesBefore > 0)
1387         FirstInLineIndex = Tokens.size() - 1;
1388     } while (Tokens.back()->Tok.isNot(tok::eof));
1389     return Tokens;
1390   }
1391 
1392   const AdditionalKeywords &getKeywords() { return Keywords; }
1393 
1394 private:
1395   void tryMergePreviousTokens() {
1396     if (tryMerge_TMacro())
1397       return;
1398     if (tryMergeConflictMarkers())
1399       return;
1400 
1401     if (Style.Language == FormatStyle::LK_JavaScript) {
1402       if (tryMergeJSRegexLiteral())
1403         return;
1404       if (tryMergeEscapeSequence())
1405         return;
1406 
1407       static tok::TokenKind JSIdentity[] = { tok::equalequal, tok::equal };
1408       static tok::TokenKind JSNotIdentity[] = { tok::exclaimequal, tok::equal };
1409       static tok::TokenKind JSShiftEqual[] = { tok::greater, tok::greater,
1410                                                tok::greaterequal };
1411       static tok::TokenKind JSRightArrow[] = { tok::equal, tok::greater };
1412       // FIXME: We probably need to change token type to mimic operator with the
1413       // correct priority.
1414       if (tryMergeTokens(JSIdentity))
1415         return;
1416       if (tryMergeTokens(JSNotIdentity))
1417         return;
1418       if (tryMergeTokens(JSShiftEqual))
1419         return;
1420       if (tryMergeTokens(JSRightArrow))
1421         return;
1422     }
1423   }
1424 
1425   bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
1426     if (Tokens.size() < Kinds.size())
1427       return false;
1428 
1429     SmallVectorImpl<FormatToken *>::const_iterator First =
1430         Tokens.end() - Kinds.size();
1431     if (!First[0]->is(Kinds[0]))
1432       return false;
1433     unsigned AddLength = 0;
1434     for (unsigned i = 1; i < Kinds.size(); ++i) {
1435       if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
1436                                          First[i]->WhitespaceRange.getEnd())
1437         return false;
1438       AddLength += First[i]->TokenText.size();
1439     }
1440     Tokens.resize(Tokens.size() - Kinds.size() + 1);
1441     First[0]->TokenText = StringRef(First[0]->TokenText.data(),
1442                                     First[0]->TokenText.size() + AddLength);
1443     First[0]->ColumnWidth += AddLength;
1444     return true;
1445   }
1446 
1447   // Tries to merge an escape sequence, i.e. a "\\" and the following
1448   // character. Use e.g. inside JavaScript regex literals.
1449   bool tryMergeEscapeSequence() {
1450     if (Tokens.size() < 2)
1451       return false;
1452     FormatToken *Previous = Tokens[Tokens.size() - 2];
1453     if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\")
1454       return false;
1455     ++Previous->ColumnWidth;
1456     StringRef Text = Previous->TokenText;
1457     Previous->TokenText = StringRef(Text.data(), Text.size() + 1);
1458     resetLexer(SourceMgr.getFileOffset(Tokens.back()->Tok.getLocation()) + 1);
1459     Tokens.resize(Tokens.size() - 1);
1460     Column = Previous->OriginalColumn + Previous->ColumnWidth;
1461     return true;
1462   }
1463 
1464   // Try to determine whether the current token ends a JavaScript regex literal.
1465   // We heuristically assume that this is a regex literal if we find two
1466   // unescaped slashes on a line and the token before the first slash is one of
1467   // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
1468   // a division.
1469   bool tryMergeJSRegexLiteral() {
1470     if (Tokens.size() < 2)
1471       return false;
1472     // If a regex literal ends in "\//", this gets represented by an unknown
1473     // token "\" and a comment.
1474     bool MightEndWithEscapedSlash =
1475         Tokens.back()->is(tok::comment) &&
1476         Tokens.back()->TokenText.startswith("//") &&
1477         Tokens[Tokens.size() - 2]->TokenText == "\\";
1478     if (!MightEndWithEscapedSlash &&
1479         (Tokens.back()->isNot(tok::slash) ||
1480          (Tokens[Tokens.size() - 2]->is(tok::unknown) &&
1481           Tokens[Tokens.size() - 2]->TokenText == "\\")))
1482       return false;
1483     unsigned TokenCount = 0;
1484     unsigned LastColumn = Tokens.back()->OriginalColumn;
1485     for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
1486       ++TokenCount;
1487       if (I[0]->is(tok::slash) && I + 1 != E &&
1488           (I[1]->isOneOf(tok::l_paren, tok::semi, tok::l_brace, tok::r_brace,
1489                          tok::exclaim, tok::l_square, tok::colon, tok::comma,
1490                          tok::question, tok::kw_return) ||
1491            I[1]->isBinaryOperator())) {
1492         if (MightEndWithEscapedSlash) {
1493           // This regex literal ends in '\//'. Skip past the '//' of the last
1494           // token and re-start lexing from there.
1495           SourceLocation Loc = Tokens.back()->Tok.getLocation();
1496           resetLexer(SourceMgr.getFileOffset(Loc) + 2);
1497         }
1498         Tokens.resize(Tokens.size() - TokenCount);
1499         Tokens.back()->Tok.setKind(tok::unknown);
1500         Tokens.back()->Type = TT_RegexLiteral;
1501         Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
1502         return true;
1503       }
1504 
1505       // There can't be a newline inside a regex literal.
1506       if (I[0]->NewlinesBefore > 0)
1507         return false;
1508     }
1509     return false;
1510   }
1511 
1512   bool tryMerge_TMacro() {
1513     if (Tokens.size() < 4)
1514       return false;
1515     FormatToken *Last = Tokens.back();
1516     if (!Last->is(tok::r_paren))
1517       return false;
1518 
1519     FormatToken *String = Tokens[Tokens.size() - 2];
1520     if (!String->is(tok::string_literal) || String->IsMultiline)
1521       return false;
1522 
1523     if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
1524       return false;
1525 
1526     FormatToken *Macro = Tokens[Tokens.size() - 4];
1527     if (Macro->TokenText != "_T")
1528       return false;
1529 
1530     const char *Start = Macro->TokenText.data();
1531     const char *End = Last->TokenText.data() + Last->TokenText.size();
1532     String->TokenText = StringRef(Start, End - Start);
1533     String->IsFirst = Macro->IsFirst;
1534     String->LastNewlineOffset = Macro->LastNewlineOffset;
1535     String->WhitespaceRange = Macro->WhitespaceRange;
1536     String->OriginalColumn = Macro->OriginalColumn;
1537     String->ColumnWidth = encoding::columnWidthWithTabs(
1538         String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1539 
1540     Tokens.pop_back();
1541     Tokens.pop_back();
1542     Tokens.pop_back();
1543     Tokens.back() = String;
1544     return true;
1545   }
1546 
1547   bool tryMergeConflictMarkers() {
1548     if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1549       return false;
1550 
1551     // Conflict lines look like:
1552     // <marker> <text from the vcs>
1553     // For example:
1554     // >>>>>>> /file/in/file/system at revision 1234
1555     //
1556     // We merge all tokens in a line that starts with a conflict marker
1557     // into a single token with a special token type that the unwrapped line
1558     // parser will use to correctly rebuild the underlying code.
1559 
1560     FileID ID;
1561     // Get the position of the first token in the line.
1562     unsigned FirstInLineOffset;
1563     std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1564         Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1565     StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1566     // Calculate the offset of the start of the current line.
1567     auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1568     if (LineOffset == StringRef::npos) {
1569       LineOffset = 0;
1570     } else {
1571       ++LineOffset;
1572     }
1573 
1574     auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1575     StringRef LineStart;
1576     if (FirstSpace == StringRef::npos) {
1577       LineStart = Buffer.substr(LineOffset);
1578     } else {
1579       LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1580     }
1581 
1582     TokenType Type = TT_Unknown;
1583     if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1584       Type = TT_ConflictStart;
1585     } else if (LineStart == "|||||||" || LineStart == "=======" ||
1586                LineStart == "====") {
1587       Type = TT_ConflictAlternative;
1588     } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1589       Type = TT_ConflictEnd;
1590     }
1591 
1592     if (Type != TT_Unknown) {
1593       FormatToken *Next = Tokens.back();
1594 
1595       Tokens.resize(FirstInLineIndex + 1);
1596       // We do not need to build a complete token here, as we will skip it
1597       // during parsing anyway (as we must not touch whitespace around conflict
1598       // markers).
1599       Tokens.back()->Type = Type;
1600       Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1601 
1602       Tokens.push_back(Next);
1603       return true;
1604     }
1605 
1606     return false;
1607   }
1608 
1609   FormatToken *getNextToken() {
1610     if (GreaterStashed) {
1611       // Create a synthesized second '>' token.
1612       // FIXME: Increment Column and set OriginalColumn.
1613       Token Greater = FormatTok->Tok;
1614       FormatTok = new (Allocator.Allocate()) FormatToken;
1615       FormatTok->Tok = Greater;
1616       SourceLocation GreaterLocation =
1617           FormatTok->Tok.getLocation().getLocWithOffset(1);
1618       FormatTok->WhitespaceRange =
1619           SourceRange(GreaterLocation, GreaterLocation);
1620       FormatTok->TokenText = ">";
1621       FormatTok->ColumnWidth = 1;
1622       GreaterStashed = false;
1623       return FormatTok;
1624     }
1625 
1626     FormatTok = new (Allocator.Allocate()) FormatToken;
1627     readRawToken(*FormatTok);
1628     SourceLocation WhitespaceStart =
1629         FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
1630     FormatTok->IsFirst = IsFirstToken;
1631     IsFirstToken = false;
1632 
1633     // Consume and record whitespace until we find a significant token.
1634     unsigned WhitespaceLength = TrailingWhitespace;
1635     while (FormatTok->Tok.is(tok::unknown)) {
1636       for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1637         switch (FormatTok->TokenText[i]) {
1638         case '\n':
1639           ++FormatTok->NewlinesBefore;
1640           // FIXME: This is technically incorrect, as it could also
1641           // be a literal backslash at the end of the line.
1642           if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1643                          (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1644                           FormatTok->TokenText[i - 2] != '\\')))
1645             FormatTok->HasUnescapedNewline = true;
1646           FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1647           Column = 0;
1648           break;
1649         case '\r':
1650         case '\f':
1651         case '\v':
1652           Column = 0;
1653           break;
1654         case ' ':
1655           ++Column;
1656           break;
1657         case '\t':
1658           Column += Style.TabWidth - Column % Style.TabWidth;
1659           break;
1660         case '\\':
1661           ++Column;
1662           if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1663                              FormatTok->TokenText[i + 1] != '\n'))
1664             FormatTok->Type = TT_ImplicitStringLiteral;
1665           break;
1666         default:
1667           FormatTok->Type = TT_ImplicitStringLiteral;
1668           ++Column;
1669           break;
1670         }
1671       }
1672 
1673       if (FormatTok->is(TT_ImplicitStringLiteral))
1674         break;
1675       WhitespaceLength += FormatTok->Tok.getLength();
1676 
1677       readRawToken(*FormatTok);
1678     }
1679 
1680     // In case the token starts with escaped newlines, we want to
1681     // take them into account as whitespace - this pattern is quite frequent
1682     // in macro definitions.
1683     // FIXME: Add a more explicit test.
1684     while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1685            FormatTok->TokenText[1] == '\n') {
1686       ++FormatTok->NewlinesBefore;
1687       WhitespaceLength += 2;
1688       Column = 0;
1689       FormatTok->TokenText = FormatTok->TokenText.substr(2);
1690     }
1691 
1692     FormatTok->WhitespaceRange = SourceRange(
1693         WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1694 
1695     FormatTok->OriginalColumn = Column;
1696 
1697     TrailingWhitespace = 0;
1698     if (FormatTok->Tok.is(tok::comment)) {
1699       // FIXME: Add the trimmed whitespace to Column.
1700       StringRef UntrimmedText = FormatTok->TokenText;
1701       FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
1702       TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
1703     } else if (FormatTok->Tok.is(tok::raw_identifier)) {
1704       IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
1705       FormatTok->Tok.setIdentifierInfo(&Info);
1706       FormatTok->Tok.setKind(Info.getTokenID());
1707       if (Style.Language == FormatStyle::LK_Java &&
1708           FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete)) {
1709         FormatTok->Tok.setKind(tok::identifier);
1710         FormatTok->Tok.setIdentifierInfo(nullptr);
1711       }
1712     } else if (FormatTok->Tok.is(tok::greatergreater)) {
1713       FormatTok->Tok.setKind(tok::greater);
1714       FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1715       GreaterStashed = true;
1716     }
1717 
1718     // Now FormatTok is the next non-whitespace token.
1719 
1720     StringRef Text = FormatTok->TokenText;
1721     size_t FirstNewlinePos = Text.find('\n');
1722     if (FirstNewlinePos == StringRef::npos) {
1723       // FIXME: ColumnWidth actually depends on the start column, we need to
1724       // take this into account when the token is moved.
1725       FormatTok->ColumnWidth =
1726           encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1727       Column += FormatTok->ColumnWidth;
1728     } else {
1729       FormatTok->IsMultiline = true;
1730       // FIXME: ColumnWidth actually depends on the start column, we need to
1731       // take this into account when the token is moved.
1732       FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1733           Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1734 
1735       // The last line of the token always starts in column 0.
1736       // Thus, the length can be precomputed even in the presence of tabs.
1737       FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1738           Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1739           Encoding);
1740       Column = FormatTok->LastLineColumnWidth;
1741     }
1742 
1743     FormatTok->IsForEachMacro =
1744         std::binary_search(ForEachMacros.begin(), ForEachMacros.end(),
1745                            FormatTok->Tok.getIdentifierInfo());
1746 
1747     return FormatTok;
1748   }
1749 
1750   FormatToken *FormatTok;
1751   bool IsFirstToken;
1752   bool GreaterStashed;
1753   unsigned Column;
1754   unsigned TrailingWhitespace;
1755   std::unique_ptr<Lexer> Lex;
1756   SourceManager &SourceMgr;
1757   FileID ID;
1758   FormatStyle &Style;
1759   IdentifierTable IdentTable;
1760   AdditionalKeywords Keywords;
1761   encoding::Encoding Encoding;
1762   llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
1763   // Index (in 'Tokens') of the last token that starts a new line.
1764   unsigned FirstInLineIndex;
1765   SmallVector<FormatToken *, 16> Tokens;
1766   SmallVector<IdentifierInfo *, 8> ForEachMacros;
1767 
1768   bool FormattingDisabled;
1769 
1770   void readRawToken(FormatToken &Tok) {
1771     Lex->LexFromRawLexer(Tok.Tok);
1772     Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1773                               Tok.Tok.getLength());
1774     // For formatting, treat unterminated string literals like normal string
1775     // literals.
1776     if (Tok.is(tok::unknown)) {
1777       if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1778         Tok.Tok.setKind(tok::string_literal);
1779         Tok.IsUnterminatedLiteral = true;
1780       } else if (Style.Language == FormatStyle::LK_JavaScript &&
1781                  Tok.TokenText == "''") {
1782         Tok.Tok.setKind(tok::char_constant);
1783       }
1784     }
1785 
1786     if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
1787                                  Tok.TokenText == "/* clang-format on */")) {
1788       FormattingDisabled = false;
1789     }
1790 
1791     Tok.Finalized = FormattingDisabled;
1792 
1793     if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
1794                                  Tok.TokenText == "/* clang-format off */")) {
1795       FormattingDisabled = true;
1796     }
1797   }
1798 
1799   void resetLexer(unsigned Offset) {
1800     StringRef Buffer = SourceMgr.getBufferData(ID);
1801     Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
1802                         getFormattingLangOpts(Style), Buffer.begin(),
1803                         Buffer.begin() + Offset, Buffer.end()));
1804     Lex->SetKeepWhitespaceMode(true);
1805   }
1806 };
1807 
1808 static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1809   switch (Language) {
1810   case FormatStyle::LK_Cpp:
1811     return "C++";
1812   case FormatStyle::LK_Java:
1813     return "Java";
1814   case FormatStyle::LK_JavaScript:
1815     return "JavaScript";
1816   case FormatStyle::LK_Proto:
1817     return "Proto";
1818   default:
1819     return "Unknown";
1820   }
1821 }
1822 
1823 class Formatter : public UnwrappedLineConsumer {
1824 public:
1825   Formatter(const FormatStyle &Style, SourceManager &SourceMgr, FileID ID,
1826             ArrayRef<CharSourceRange> Ranges)
1827       : Style(Style), ID(ID), SourceMgr(SourceMgr),
1828         Whitespaces(SourceMgr, Style,
1829                     inputUsesCRLF(SourceMgr.getBufferData(ID))),
1830         Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
1831         Encoding(encoding::detectEncoding(SourceMgr.getBufferData(ID))) {
1832     DEBUG(llvm::dbgs() << "File encoding: "
1833                        << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1834                                                                : "unknown")
1835                        << "\n");
1836     DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1837                        << "\n");
1838   }
1839 
1840   tooling::Replacements format() {
1841     tooling::Replacements Result;
1842     FormatTokenLexer Tokens(SourceMgr, ID, Style, Encoding);
1843 
1844     UnwrappedLineParser Parser(Style, Tokens.getKeywords(), Tokens.lex(),
1845                                *this);
1846     bool StructuralError = Parser.parse();
1847     assert(UnwrappedLines.rbegin()->empty());
1848     for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1849          ++Run) {
1850       DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1851       SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1852       for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1853         AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1854       }
1855       tooling::Replacements RunResult =
1856           format(AnnotatedLines, StructuralError, Tokens);
1857       DEBUG({
1858         llvm::dbgs() << "Replacements for run " << Run << ":\n";
1859         for (tooling::Replacements::iterator I = RunResult.begin(),
1860                                              E = RunResult.end();
1861              I != E; ++I) {
1862           llvm::dbgs() << I->toString() << "\n";
1863         }
1864       });
1865       for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1866         delete AnnotatedLines[i];
1867       }
1868       Result.insert(RunResult.begin(), RunResult.end());
1869       Whitespaces.reset();
1870     }
1871     return Result;
1872   }
1873 
1874   tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1875                                bool StructuralError, FormatTokenLexer &Tokens) {
1876     TokenAnnotator Annotator(Style, Tokens.getKeywords());
1877     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1878       Annotator.annotate(*AnnotatedLines[i]);
1879     }
1880     deriveLocalStyle(AnnotatedLines);
1881     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1882       Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
1883     }
1884     computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
1885 
1886     Annotator.setCommentLineLevels(AnnotatedLines);
1887     ContinuationIndenter Indenter(Style, Tokens.getKeywords(), SourceMgr,
1888                                   Whitespaces, Encoding,
1889                                   BinPackInconclusiveFunctions);
1890     UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style);
1891     Formatter.format(AnnotatedLines, /*DryRun=*/false);
1892     return Whitespaces.generateReplacements();
1893   }
1894 
1895 private:
1896   // Determines which lines are affected by the SourceRanges given as input.
1897   // Returns \c true if at least one line between I and E or one of their
1898   // children is affected.
1899   bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1900                             SmallVectorImpl<AnnotatedLine *>::iterator E) {
1901     bool SomeLineAffected = false;
1902     const AnnotatedLine *PreviousLine = nullptr;
1903     while (I != E) {
1904       AnnotatedLine *Line = *I;
1905       Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1906 
1907       // If a line is part of a preprocessor directive, it needs to be formatted
1908       // if any token within the directive is affected.
1909       if (Line->InPPDirective) {
1910         FormatToken *Last = Line->Last;
1911         SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1912         while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1913           Last = (*PPEnd)->Last;
1914           ++PPEnd;
1915         }
1916 
1917         if (affectsTokenRange(*Line->First, *Last,
1918                               /*IncludeLeadingNewlines=*/false)) {
1919           SomeLineAffected = true;
1920           markAllAsAffected(I, PPEnd);
1921         }
1922         I = PPEnd;
1923         continue;
1924       }
1925 
1926       if (nonPPLineAffected(Line, PreviousLine))
1927         SomeLineAffected = true;
1928 
1929       PreviousLine = Line;
1930       ++I;
1931     }
1932     return SomeLineAffected;
1933   }
1934 
1935   // Determines whether 'Line' is affected by the SourceRanges given as input.
1936   // Returns \c true if line or one if its children is affected.
1937   bool nonPPLineAffected(AnnotatedLine *Line,
1938                          const AnnotatedLine *PreviousLine) {
1939     bool SomeLineAffected = false;
1940     Line->ChildrenAffected =
1941         computeAffectedLines(Line->Children.begin(), Line->Children.end());
1942     if (Line->ChildrenAffected)
1943       SomeLineAffected = true;
1944 
1945     // Stores whether one of the line's tokens is directly affected.
1946     bool SomeTokenAffected = false;
1947     // Stores whether we need to look at the leading newlines of the next token
1948     // in order to determine whether it was affected.
1949     bool IncludeLeadingNewlines = false;
1950 
1951     // Stores whether the first child line of any of this line's tokens is
1952     // affected.
1953     bool SomeFirstChildAffected = false;
1954 
1955     for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1956       // Determine whether 'Tok' was affected.
1957       if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1958         SomeTokenAffected = true;
1959 
1960       // Determine whether the first child of 'Tok' was affected.
1961       if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1962         SomeFirstChildAffected = true;
1963 
1964       IncludeLeadingNewlines = Tok->Children.empty();
1965     }
1966 
1967     // Was this line moved, i.e. has it previously been on the same line as an
1968     // affected line?
1969     bool LineMoved = PreviousLine && PreviousLine->Affected &&
1970                      Line->First->NewlinesBefore == 0;
1971 
1972     bool IsContinuedComment =
1973         Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1974         Line->First->NewlinesBefore < 2 && PreviousLine &&
1975         PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
1976 
1977     if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1978         IsContinuedComment) {
1979       Line->Affected = true;
1980       SomeLineAffected = true;
1981     }
1982     return SomeLineAffected;
1983   }
1984 
1985   // Marks all lines between I and E as well as all their children as affected.
1986   void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1987                          SmallVectorImpl<AnnotatedLine *>::iterator E) {
1988     while (I != E) {
1989       (*I)->Affected = true;
1990       markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1991       ++I;
1992     }
1993   }
1994 
1995   // Returns true if the range from 'First' to 'Last' intersects with one of the
1996   // input ranges.
1997   bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1998                          bool IncludeLeadingNewlines) {
1999     SourceLocation Start = First.WhitespaceRange.getBegin();
2000     if (!IncludeLeadingNewlines)
2001       Start = Start.getLocWithOffset(First.LastNewlineOffset);
2002     SourceLocation End = Last.getStartOfNonWhitespace();
2003     End = End.getLocWithOffset(Last.TokenText.size());
2004     CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
2005     return affectsCharSourceRange(Range);
2006   }
2007 
2008   // Returns true if one of the input ranges intersect the leading empty lines
2009   // before 'Tok'.
2010   bool affectsLeadingEmptyLines(const FormatToken &Tok) {
2011     CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
2012         Tok.WhitespaceRange.getBegin(),
2013         Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
2014     return affectsCharSourceRange(EmptyLineRange);
2015   }
2016 
2017   // Returns true if 'Range' intersects with one of the input ranges.
2018   bool affectsCharSourceRange(const CharSourceRange &Range) {
2019     for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
2020                                                           E = Ranges.end();
2021          I != E; ++I) {
2022       if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
2023           !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
2024         return true;
2025     }
2026     return false;
2027   }
2028 
2029   static bool inputUsesCRLF(StringRef Text) {
2030     return Text.count('\r') * 2 > Text.count('\n');
2031   }
2032 
2033   void
2034   deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
2035     unsigned CountBoundToVariable = 0;
2036     unsigned CountBoundToType = 0;
2037     bool HasCpp03IncompatibleFormat = false;
2038     bool HasBinPackedFunction = false;
2039     bool HasOnePerLineFunction = false;
2040     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
2041       if (!AnnotatedLines[i]->First->Next)
2042         continue;
2043       FormatToken *Tok = AnnotatedLines[i]->First->Next;
2044       while (Tok->Next) {
2045         if (Tok->is(TT_PointerOrReference)) {
2046           bool SpacesBefore =
2047               Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
2048           bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
2049                              Tok->Next->WhitespaceRange.getEnd();
2050           if (SpacesBefore && !SpacesAfter)
2051             ++CountBoundToVariable;
2052           else if (!SpacesBefore && SpacesAfter)
2053             ++CountBoundToType;
2054         }
2055 
2056         if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
2057           if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
2058             HasCpp03IncompatibleFormat = true;
2059           if (Tok->is(TT_TemplateCloser) &&
2060               Tok->Previous->is(TT_TemplateCloser))
2061             HasCpp03IncompatibleFormat = true;
2062         }
2063 
2064         if (Tok->PackingKind == PPK_BinPacked)
2065           HasBinPackedFunction = true;
2066         if (Tok->PackingKind == PPK_OnePerLine)
2067           HasOnePerLineFunction = true;
2068 
2069         Tok = Tok->Next;
2070       }
2071     }
2072     if (Style.DerivePointerAlignment) {
2073       if (CountBoundToType > CountBoundToVariable)
2074         Style.PointerAlignment = FormatStyle::PAS_Left;
2075       else if (CountBoundToType < CountBoundToVariable)
2076         Style.PointerAlignment = FormatStyle::PAS_Right;
2077     }
2078     if (Style.Standard == FormatStyle::LS_Auto) {
2079       Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
2080                                                   : FormatStyle::LS_Cpp03;
2081     }
2082     BinPackInconclusiveFunctions =
2083         HasBinPackedFunction || !HasOnePerLineFunction;
2084   }
2085 
2086   void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
2087     assert(!UnwrappedLines.empty());
2088     UnwrappedLines.back().push_back(TheLine);
2089   }
2090 
2091   void finishRun() override {
2092     UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
2093   }
2094 
2095   FormatStyle Style;
2096   FileID ID;
2097   SourceManager &SourceMgr;
2098   WhitespaceManager Whitespaces;
2099   SmallVector<CharSourceRange, 8> Ranges;
2100   SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
2101 
2102   encoding::Encoding Encoding;
2103   bool BinPackInconclusiveFunctions;
2104 };
2105 
2106 } // end anonymous namespace
2107 
2108 tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
2109                                SourceManager &SourceMgr,
2110                                ArrayRef<CharSourceRange> Ranges) {
2111   if (Style.DisableFormat)
2112     return tooling::Replacements();
2113   return reformat(Style, SourceMgr,
2114                   SourceMgr.getFileID(Lex.getSourceLocation()), Ranges);
2115 }
2116 
2117 tooling::Replacements reformat(const FormatStyle &Style,
2118                                SourceManager &SourceMgr, FileID ID,
2119                                ArrayRef<CharSourceRange> Ranges) {
2120   if (Style.DisableFormat)
2121     return tooling::Replacements();
2122   Formatter formatter(Style, SourceMgr, ID, Ranges);
2123   return formatter.format();
2124 }
2125 
2126 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
2127                                ArrayRef<tooling::Range> Ranges,
2128                                StringRef FileName) {
2129   if (Style.DisableFormat)
2130     return tooling::Replacements();
2131 
2132   FileManager Files((FileSystemOptions()));
2133   DiagnosticsEngine Diagnostics(
2134       IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
2135       new DiagnosticOptions);
2136   SourceManager SourceMgr(Diagnostics, Files);
2137   std::unique_ptr<llvm::MemoryBuffer> Buf =
2138       llvm::MemoryBuffer::getMemBuffer(Code, FileName);
2139   const clang::FileEntry *Entry =
2140       Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
2141   SourceMgr.overrideFileContents(Entry, std::move(Buf));
2142   FileID ID =
2143       SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
2144   SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
2145   std::vector<CharSourceRange> CharRanges;
2146   for (const tooling::Range &Range : Ranges) {
2147     SourceLocation Start = StartOfFile.getLocWithOffset(Range.getOffset());
2148     SourceLocation End = Start.getLocWithOffset(Range.getLength());
2149     CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
2150   }
2151   return reformat(Style, SourceMgr, ID, CharRanges);
2152 }
2153 
2154 LangOptions getFormattingLangOpts(const FormatStyle &Style) {
2155   LangOptions LangOpts;
2156   LangOpts.CPlusPlus = 1;
2157   LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
2158   LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
2159   LangOpts.LineComment = 1;
2160   bool AlternativeOperators = Style.Language != FormatStyle::LK_JavaScript &&
2161                               Style.Language != FormatStyle::LK_Java;
2162   LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
2163   LangOpts.Bool = 1;
2164   LangOpts.ObjC1 = 1;
2165   LangOpts.ObjC2 = 1;
2166   return LangOpts;
2167 }
2168 
2169 const char *StyleOptionHelpDescription =
2170     "Coding style, currently supports:\n"
2171     "  LLVM, Google, Chromium, Mozilla, WebKit.\n"
2172     "Use -style=file to load style configuration from\n"
2173     ".clang-format file located in one of the parent\n"
2174     "directories of the source file (or current\n"
2175     "directory for stdin).\n"
2176     "Use -style=\"{key: value, ...}\" to set specific\n"
2177     "parameters, e.g.:\n"
2178     "  -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
2179 
2180 static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
2181   if (FileName.endswith(".java")) {
2182     return FormatStyle::LK_Java;
2183   } else if (FileName.endswith_lower(".js")) {
2184     return FormatStyle::LK_JavaScript;
2185   } else if (FileName.endswith_lower(".proto") ||
2186              FileName.endswith_lower(".protodevel")) {
2187     return FormatStyle::LK_Proto;
2188   }
2189   return FormatStyle::LK_Cpp;
2190 }
2191 
2192 FormatStyle getStyle(StringRef StyleName, StringRef FileName,
2193                      StringRef FallbackStyle) {
2194   FormatStyle Style = getLLVMStyle();
2195   Style.Language = getLanguageByFileName(FileName);
2196   if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
2197     llvm::errs() << "Invalid fallback style \"" << FallbackStyle
2198                  << "\" using LLVM style\n";
2199     return Style;
2200   }
2201 
2202   if (StyleName.startswith("{")) {
2203     // Parse YAML/JSON style from the command line.
2204     if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
2205       llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
2206                    << FallbackStyle << " style\n";
2207     }
2208     return Style;
2209   }
2210 
2211   if (!StyleName.equals_lower("file")) {
2212     if (!getPredefinedStyle(StyleName, Style.Language, &Style))
2213       llvm::errs() << "Invalid value for -style, using " << FallbackStyle
2214                    << " style\n";
2215     return Style;
2216   }
2217 
2218   // Look for .clang-format/_clang-format file in the file's parent directories.
2219   SmallString<128> UnsuitableConfigFiles;
2220   SmallString<128> Path(FileName);
2221   llvm::sys::fs::make_absolute(Path);
2222   for (StringRef Directory = Path; !Directory.empty();
2223        Directory = llvm::sys::path::parent_path(Directory)) {
2224     if (!llvm::sys::fs::is_directory(Directory))
2225       continue;
2226     SmallString<128> ConfigFile(Directory);
2227 
2228     llvm::sys::path::append(ConfigFile, ".clang-format");
2229     DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2230     bool IsFile = false;
2231     // Ignore errors from is_regular_file: we only need to know if we can read
2232     // the file or not.
2233     llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2234 
2235     if (!IsFile) {
2236       // Try _clang-format too, since dotfiles are not commonly used on Windows.
2237       ConfigFile = Directory;
2238       llvm::sys::path::append(ConfigFile, "_clang-format");
2239       DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2240       llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2241     }
2242 
2243     if (IsFile) {
2244       llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
2245           llvm::MemoryBuffer::getFile(ConfigFile.c_str());
2246       if (std::error_code EC = Text.getError()) {
2247         llvm::errs() << EC.message() << "\n";
2248         break;
2249       }
2250       if (std::error_code ec =
2251               parseConfiguration(Text.get()->getBuffer(), &Style)) {
2252         if (ec == ParseError::Unsuitable) {
2253           if (!UnsuitableConfigFiles.empty())
2254             UnsuitableConfigFiles.append(", ");
2255           UnsuitableConfigFiles.append(ConfigFile);
2256           continue;
2257         }
2258         llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
2259                      << "\n";
2260         break;
2261       }
2262       DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
2263       return Style;
2264     }
2265   }
2266   llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
2267                << " style\n";
2268   if (!UnsuitableConfigFiles.empty()) {
2269     llvm::errs() << "Configuration file(s) do(es) not support "
2270                  << getLanguageName(Style.Language) << ": "
2271                  << UnsuitableConfigFiles << "\n";
2272   }
2273   return Style;
2274 }
2275 
2276 } // namespace format
2277 } // namespace clang
2278