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