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