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