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