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