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 
917     // Remove empty lines after "{".
918     if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
919         PreviousLine->Last->is(tok::l_brace) &&
920         PreviousLine->First->isNot(tok::kw_namespace))
921       Newlines = 1;
922 
923     // Insert extra new line before access specifiers.
924     if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
925         RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
926       ++Newlines;
927 
928     // Remove empty lines after access specifiers.
929     if (PreviousLine && PreviousLine->First->isAccessSpecifier())
930       Newlines = std::min(1u, Newlines);
931 
932     Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
933                                    Indent, InPPDirective &&
934                                                !RootToken.HasUnescapedNewline);
935   }
936 
937   /// \brief Get the indent of \p Level from \p IndentForLevel.
938   ///
939   /// \p IndentForLevel must contain the indent for the level \c l
940   /// at \p IndentForLevel[l], or a value < 0 if the indent for
941   /// that level is unknown.
942   unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
943     if (IndentForLevel[Level] != -1)
944       return IndentForLevel[Level];
945     if (Level == 0)
946       return 0;
947     return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
948   }
949 
950   void join(AnnotatedLine &A, const AnnotatedLine &B) {
951     assert(!A.Last->Next);
952     assert(!B.First->Previous);
953     if (B.Affected)
954       A.Affected = true;
955     A.Last->Next = B.First;
956     B.First->Previous = A.Last;
957     B.First->CanBreakBefore = true;
958     unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
959     for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
960       Tok->TotalLength += LengthA;
961       A.Last = Tok;
962     }
963   }
964 
965   unsigned getColumnLimit(bool InPPDirective) const {
966     // In preprocessor directives reserve two chars for trailing " \"
967     return Style.ColumnLimit - (InPPDirective ? 2 : 0);
968   }
969 
970   /// \brief Analyze the entire solution space starting from \p InitialState.
971   ///
972   /// This implements a variant of Dijkstra's algorithm on the graph that spans
973   /// the solution space (\c LineStates are the nodes). The algorithm tries to
974   /// find the shortest path (the one with lowest penalty) from \p InitialState
975   /// to a state where all tokens are placed. Returns the penalty.
976   ///
977   /// If \p DryRun is \c false, directly applies the changes.
978   unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
979     std::set<LineState> Seen;
980 
981     // Increasing count of \c StateNode items we have created. This is used to
982     // create a deterministic order independent of the container.
983     unsigned Count = 0;
984     QueueType Queue;
985 
986     // Insert start element into queue.
987     StateNode *Node =
988         new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
989     Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
990     ++Count;
991 
992     unsigned Penalty = 0;
993 
994     // While not empty, take first element and follow edges.
995     while (!Queue.empty()) {
996       Penalty = Queue.top().first.first;
997       StateNode *Node = Queue.top().second;
998       if (Node->State.NextToken == NULL) {
999         DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
1000         break;
1001       }
1002       Queue.pop();
1003 
1004       // Cut off the analysis of certain solutions if the analysis gets too
1005       // complex. See description of IgnoreStackForComparison.
1006       if (Count > 10000)
1007         Node->State.IgnoreStackForComparison = true;
1008 
1009       if (!Seen.insert(Node->State).second)
1010         // State already examined with lower penalty.
1011         continue;
1012 
1013       FormatDecision LastFormat = Node->State.NextToken->Decision;
1014       if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
1015         addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
1016       if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
1017         addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
1018     }
1019 
1020     if (Queue.empty()) {
1021       // We were unable to find a solution, do nothing.
1022       // FIXME: Add diagnostic?
1023       DEBUG(llvm::dbgs() << "Could not find a solution.\n");
1024       return 0;
1025     }
1026 
1027     // Reconstruct the solution.
1028     if (!DryRun)
1029       reconstructPath(InitialState, Queue.top().second);
1030 
1031     DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
1032     DEBUG(llvm::dbgs() << "---\n");
1033 
1034     return Penalty;
1035   }
1036 
1037   void reconstructPath(LineState &State, StateNode *Current) {
1038     std::deque<StateNode *> Path;
1039     // We do not need a break before the initial token.
1040     while (Current->Previous) {
1041       Path.push_front(Current);
1042       Current = Current->Previous;
1043     }
1044     for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1045          I != E; ++I) {
1046       unsigned Penalty = 0;
1047       formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
1048       Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
1049 
1050       DEBUG({
1051         if ((*I)->NewLine) {
1052           llvm::dbgs() << "Penalty for placing "
1053                        << (*I)->Previous->State.NextToken->Tok.getName() << ": "
1054                        << Penalty << "\n";
1055         }
1056       });
1057     }
1058   }
1059 
1060   /// \brief Add the following state to the analysis queue \c Queue.
1061   ///
1062   /// Assume the current state is \p PreviousNode and has been reached with a
1063   /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
1064   void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
1065                            bool NewLine, unsigned *Count, QueueType *Queue) {
1066     if (NewLine && !Indenter->canBreak(PreviousNode->State))
1067       return;
1068     if (!NewLine && Indenter->mustBreak(PreviousNode->State))
1069       return;
1070 
1071     StateNode *Node = new (Allocator.Allocate())
1072         StateNode(PreviousNode->State, NewLine, PreviousNode);
1073     if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1074       return;
1075 
1076     Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
1077 
1078     Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1079     ++(*Count);
1080   }
1081 
1082   /// \brief If the \p State's next token is an r_brace closing a nested block,
1083   /// format the nested block before it.
1084   ///
1085   /// Returns \c true if all children could be placed successfully and adapts
1086   /// \p Penalty as well as \p State. If \p DryRun is false, also directly
1087   /// creates changes using \c Whitespaces.
1088   ///
1089   /// The crucial idea here is that children always get formatted upon
1090   /// encountering the closing brace right after the nested block. Now, if we
1091   /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1092   /// \c false), the entire block has to be kept on the same line (which is only
1093   /// possible if it fits on the line, only contains a single statement, etc.
1094   ///
1095   /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1096   /// break after the "{", format all lines with correct indentation and the put
1097   /// the closing "}" on yet another new line.
1098   ///
1099   /// This enables us to keep the simple structure of the
1100   /// \c UnwrappedLineFormatter, where we only have two options for each token:
1101   /// break or don't break.
1102   bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1103                       unsigned &Penalty) {
1104     FormatToken &Previous = *State.NextToken->Previous;
1105     const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1106     if (!LBrace || LBrace->isNot(tok::l_brace) ||
1107         LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
1108       // The previous token does not open a block. Nothing to do. We don't
1109       // assert so that we can simply call this function for all tokens.
1110       return true;
1111 
1112     if (NewLine) {
1113       int AdditionalIndent = State.Stack.back().Indent -
1114                              Previous.Children[0]->Level * Style.IndentWidth;
1115       Penalty += format(Previous.Children, DryRun, AdditionalIndent,
1116                         /*FixBadIndentation=*/true);
1117       return true;
1118     }
1119 
1120     // Cannot merge multiple statements into a single line.
1121     if (Previous.Children.size() > 1)
1122       return false;
1123 
1124     // Cannot merge into one line if this line ends on a comment.
1125     if (Previous.is(tok::comment))
1126       return false;
1127 
1128     // We can't put the closing "}" on a line with a trailing comment.
1129     if (Previous.Children[0]->Last->isTrailingComment())
1130       return false;
1131 
1132     if (!DryRun) {
1133       Whitespaces->replaceWhitespace(
1134           *Previous.Children[0]->First,
1135           /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
1136           /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
1137     }
1138     Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
1139 
1140     State.Column += 1 + Previous.Children[0]->Last->TotalLength;
1141     return true;
1142   }
1143 
1144   ContinuationIndenter *Indenter;
1145   WhitespaceManager *Whitespaces;
1146   FormatStyle Style;
1147   LineJoiner Joiner;
1148 
1149   llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1150 };
1151 
1152 class FormatTokenLexer {
1153 public:
1154   FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style,
1155                    encoding::Encoding Encoding)
1156       : FormatTok(NULL), IsFirstToken(true), GreaterStashed(false), Column(0),
1157         TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr), Style(Style),
1158         IdentTable(getFormattingLangOpts()), Encoding(Encoding) {
1159     Lex.SetKeepWhitespaceMode(true);
1160 
1161     for (const std::string& ForEachMacro : Style.ForEachMacros)
1162       ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
1163     std::sort(ForEachMacros.begin(), ForEachMacros.end());
1164   }
1165 
1166   ArrayRef<FormatToken *> lex() {
1167     assert(Tokens.empty());
1168     do {
1169       Tokens.push_back(getNextToken());
1170       tryMergePreviousTokens();
1171     } while (Tokens.back()->Tok.isNot(tok::eof));
1172     return Tokens;
1173   }
1174 
1175   IdentifierTable &getIdentTable() { return IdentTable; }
1176 
1177 private:
1178   void tryMergePreviousTokens() {
1179     if (tryMerge_TMacro())
1180       return;
1181 
1182     if (Style.Language == FormatStyle::LK_JavaScript) {
1183       static tok::TokenKind JSIdentity[] = { tok::equalequal, tok::equal };
1184       static tok::TokenKind JSNotIdentity[] = { tok::exclaimequal, tok::equal };
1185       static tok::TokenKind JSShiftEqual[] = { tok::greater, tok::greater,
1186                                                tok::greaterequal };
1187       // FIXME: We probably need to change token type to mimic operator with the
1188       // correct priority.
1189       if (tryMergeTokens(JSIdentity))
1190         return;
1191       if (tryMergeTokens(JSNotIdentity))
1192         return;
1193       if (tryMergeTokens(JSShiftEqual))
1194         return;
1195     }
1196   }
1197 
1198   bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
1199     if (Tokens.size() < Kinds.size())
1200       return false;
1201 
1202     SmallVectorImpl<FormatToken *>::const_iterator First =
1203         Tokens.end() - Kinds.size();
1204     if (!First[0]->is(Kinds[0]))
1205       return false;
1206     unsigned AddLength = 0;
1207     for (unsigned i = 1; i < Kinds.size(); ++i) {
1208       if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
1209                                          First[i]->WhitespaceRange.getEnd())
1210         return false;
1211       AddLength += First[i]->TokenText.size();
1212     }
1213     Tokens.resize(Tokens.size() - Kinds.size() + 1);
1214     First[0]->TokenText = StringRef(First[0]->TokenText.data(),
1215                                     First[0]->TokenText.size() + AddLength);
1216     First[0]->ColumnWidth += AddLength;
1217     return true;
1218   }
1219 
1220   bool tryMerge_TMacro() {
1221     if (Tokens.size() < 4)
1222       return false;
1223     FormatToken *Last = Tokens.back();
1224     if (!Last->is(tok::r_paren))
1225       return false;
1226 
1227     FormatToken *String = Tokens[Tokens.size() - 2];
1228     if (!String->is(tok::string_literal) || String->IsMultiline)
1229       return false;
1230 
1231     if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
1232       return false;
1233 
1234     FormatToken *Macro = Tokens[Tokens.size() - 4];
1235     if (Macro->TokenText != "_T")
1236       return false;
1237 
1238     const char *Start = Macro->TokenText.data();
1239     const char *End = Last->TokenText.data() + Last->TokenText.size();
1240     String->TokenText = StringRef(Start, End - Start);
1241     String->IsFirst = Macro->IsFirst;
1242     String->LastNewlineOffset = Macro->LastNewlineOffset;
1243     String->WhitespaceRange = Macro->WhitespaceRange;
1244     String->OriginalColumn = Macro->OriginalColumn;
1245     String->ColumnWidth = encoding::columnWidthWithTabs(
1246         String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1247 
1248     Tokens.pop_back();
1249     Tokens.pop_back();
1250     Tokens.pop_back();
1251     Tokens.back() = String;
1252     return true;
1253   }
1254 
1255   FormatToken *getNextToken() {
1256     if (GreaterStashed) {
1257       // Create a synthesized second '>' token.
1258       // FIXME: Increment Column and set OriginalColumn.
1259       Token Greater = FormatTok->Tok;
1260       FormatTok = new (Allocator.Allocate()) FormatToken;
1261       FormatTok->Tok = Greater;
1262       SourceLocation GreaterLocation =
1263           FormatTok->Tok.getLocation().getLocWithOffset(1);
1264       FormatTok->WhitespaceRange =
1265           SourceRange(GreaterLocation, GreaterLocation);
1266       FormatTok->TokenText = ">";
1267       FormatTok->ColumnWidth = 1;
1268       GreaterStashed = false;
1269       return FormatTok;
1270     }
1271 
1272     FormatTok = new (Allocator.Allocate()) FormatToken;
1273     readRawToken(*FormatTok);
1274     SourceLocation WhitespaceStart =
1275         FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
1276     FormatTok->IsFirst = IsFirstToken;
1277     IsFirstToken = false;
1278 
1279     // Consume and record whitespace until we find a significant token.
1280     unsigned WhitespaceLength = TrailingWhitespace;
1281     while (FormatTok->Tok.is(tok::unknown)) {
1282       for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1283         switch (FormatTok->TokenText[i]) {
1284         case '\n':
1285           ++FormatTok->NewlinesBefore;
1286           // FIXME: This is technically incorrect, as it could also
1287           // be a literal backslash at the end of the line.
1288           if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1289                          (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1290                           FormatTok->TokenText[i - 2] != '\\')))
1291             FormatTok->HasUnescapedNewline = true;
1292           FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1293           Column = 0;
1294           break;
1295         case '\r':
1296         case '\f':
1297         case '\v':
1298           Column = 0;
1299           break;
1300         case ' ':
1301           ++Column;
1302           break;
1303         case '\t':
1304           Column += Style.TabWidth - Column % Style.TabWidth;
1305           break;
1306         case '\\':
1307           ++Column;
1308           if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1309                              FormatTok->TokenText[i + 1] != '\n'))
1310             FormatTok->Type = TT_ImplicitStringLiteral;
1311           break;
1312         default:
1313           FormatTok->Type = TT_ImplicitStringLiteral;
1314           ++Column;
1315           break;
1316         }
1317       }
1318 
1319       if (FormatTok->Type == TT_ImplicitStringLiteral)
1320         break;
1321       WhitespaceLength += FormatTok->Tok.getLength();
1322 
1323       readRawToken(*FormatTok);
1324     }
1325 
1326     // In case the token starts with escaped newlines, we want to
1327     // take them into account as whitespace - this pattern is quite frequent
1328     // in macro definitions.
1329     // FIXME: Add a more explicit test.
1330     while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1331            FormatTok->TokenText[1] == '\n') {
1332       // FIXME: ++FormatTok->NewlinesBefore is missing...
1333       WhitespaceLength += 2;
1334       Column = 0;
1335       FormatTok->TokenText = FormatTok->TokenText.substr(2);
1336     }
1337 
1338     FormatTok->WhitespaceRange = SourceRange(
1339         WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1340 
1341     FormatTok->OriginalColumn = Column;
1342 
1343     TrailingWhitespace = 0;
1344     if (FormatTok->Tok.is(tok::comment)) {
1345       // FIXME: Add the trimmed whitespace to Column.
1346       StringRef UntrimmedText = FormatTok->TokenText;
1347       FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
1348       TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
1349     } else if (FormatTok->Tok.is(tok::raw_identifier)) {
1350       IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
1351       FormatTok->Tok.setIdentifierInfo(&Info);
1352       FormatTok->Tok.setKind(Info.getTokenID());
1353     } else if (FormatTok->Tok.is(tok::greatergreater)) {
1354       FormatTok->Tok.setKind(tok::greater);
1355       FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1356       GreaterStashed = true;
1357     }
1358 
1359     // Now FormatTok is the next non-whitespace token.
1360 
1361     StringRef Text = FormatTok->TokenText;
1362     size_t FirstNewlinePos = Text.find('\n');
1363     if (FirstNewlinePos == StringRef::npos) {
1364       // FIXME: ColumnWidth actually depends on the start column, we need to
1365       // take this into account when the token is moved.
1366       FormatTok->ColumnWidth =
1367           encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1368       Column += FormatTok->ColumnWidth;
1369     } else {
1370       FormatTok->IsMultiline = true;
1371       // FIXME: ColumnWidth actually depends on the start column, we need to
1372       // take this into account when the token is moved.
1373       FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1374           Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1375 
1376       // The last line of the token always starts in column 0.
1377       // Thus, the length can be precomputed even in the presence of tabs.
1378       FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1379           Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1380           Encoding);
1381       Column = FormatTok->LastLineColumnWidth;
1382     }
1383 
1384     FormatTok->IsForEachMacro =
1385         std::binary_search(ForEachMacros.begin(), ForEachMacros.end(),
1386                            FormatTok->Tok.getIdentifierInfo());
1387 
1388     return FormatTok;
1389   }
1390 
1391   FormatToken *FormatTok;
1392   bool IsFirstToken;
1393   bool GreaterStashed;
1394   unsigned Column;
1395   unsigned TrailingWhitespace;
1396   Lexer &Lex;
1397   SourceManager &SourceMgr;
1398   FormatStyle &Style;
1399   IdentifierTable IdentTable;
1400   encoding::Encoding Encoding;
1401   llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
1402   SmallVector<FormatToken *, 16> Tokens;
1403   SmallVector<IdentifierInfo*, 8> ForEachMacros;
1404 
1405   void readRawToken(FormatToken &Tok) {
1406     Lex.LexFromRawLexer(Tok.Tok);
1407     Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1408                               Tok.Tok.getLength());
1409     // For formatting, treat unterminated string literals like normal string
1410     // literals.
1411     if (Tok.is(tok::unknown)) {
1412       if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1413         Tok.Tok.setKind(tok::string_literal);
1414         Tok.IsUnterminatedLiteral = true;
1415       } else if (Style.Language == FormatStyle::LK_JavaScript &&
1416                  Tok.TokenText == "''") {
1417         Tok.Tok.setKind(tok::char_constant);
1418       }
1419     }
1420   }
1421 };
1422 
1423 static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1424   switch (Language) {
1425   case FormatStyle::LK_Cpp:
1426     return "C++";
1427   case FormatStyle::LK_JavaScript:
1428     return "JavaScript";
1429   case FormatStyle::LK_Proto:
1430     return "Proto";
1431   default:
1432     return "Unknown";
1433   }
1434 }
1435 
1436 class Formatter : public UnwrappedLineConsumer {
1437 public:
1438   Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1439             const std::vector<CharSourceRange> &Ranges)
1440       : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
1441         Whitespaces(SourceMgr, Style, inputUsesCRLF(Lex.getBuffer())),
1442         Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
1443         Encoding(encoding::detectEncoding(Lex.getBuffer())) {
1444     DEBUG(llvm::dbgs() << "File encoding: "
1445                        << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1446                                                                : "unknown")
1447                        << "\n");
1448     DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1449                        << "\n");
1450   }
1451 
1452   tooling::Replacements format() {
1453     tooling::Replacements Result;
1454     FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding);
1455 
1456     UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
1457     bool StructuralError = Parser.parse();
1458     assert(UnwrappedLines.rbegin()->empty());
1459     for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1460          ++Run) {
1461       DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1462       SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1463       for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1464         AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1465       }
1466       tooling::Replacements RunResult =
1467           format(AnnotatedLines, StructuralError, Tokens);
1468       DEBUG({
1469         llvm::dbgs() << "Replacements for run " << Run << ":\n";
1470         for (tooling::Replacements::iterator I = RunResult.begin(),
1471                                              E = RunResult.end();
1472              I != E; ++I) {
1473           llvm::dbgs() << I->toString() << "\n";
1474         }
1475       });
1476       for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1477         delete AnnotatedLines[i];
1478       }
1479       Result.insert(RunResult.begin(), RunResult.end());
1480       Whitespaces.reset();
1481     }
1482     return Result;
1483   }
1484 
1485   tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1486                                bool StructuralError, FormatTokenLexer &Tokens) {
1487     TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
1488     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1489       Annotator.annotate(*AnnotatedLines[i]);
1490     }
1491     deriveLocalStyle(AnnotatedLines);
1492     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1493       Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
1494     }
1495     computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
1496 
1497     Annotator.setCommentLineLevels(AnnotatedLines);
1498     ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
1499                                   BinPackInconclusiveFunctions);
1500     UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style);
1501     Formatter.format(AnnotatedLines, /*DryRun=*/false);
1502     return Whitespaces.generateReplacements();
1503   }
1504 
1505 private:
1506   // Determines which lines are affected by the SourceRanges given as input.
1507   // Returns \c true if at least one line between I and E or one of their
1508   // children is affected.
1509   bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1510                             SmallVectorImpl<AnnotatedLine *>::iterator E) {
1511     bool SomeLineAffected = false;
1512     const AnnotatedLine *PreviousLine = NULL;
1513     while (I != E) {
1514       AnnotatedLine *Line = *I;
1515       Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1516 
1517       // If a line is part of a preprocessor directive, it needs to be formatted
1518       // if any token within the directive is affected.
1519       if (Line->InPPDirective) {
1520         FormatToken *Last = Line->Last;
1521         SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1522         while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1523           Last = (*PPEnd)->Last;
1524           ++PPEnd;
1525         }
1526 
1527         if (affectsTokenRange(*Line->First, *Last,
1528                               /*IncludeLeadingNewlines=*/false)) {
1529           SomeLineAffected = true;
1530           markAllAsAffected(I, PPEnd);
1531         }
1532         I = PPEnd;
1533         continue;
1534       }
1535 
1536       if (nonPPLineAffected(Line, PreviousLine))
1537         SomeLineAffected = true;
1538 
1539       PreviousLine = Line;
1540       ++I;
1541     }
1542     return SomeLineAffected;
1543   }
1544 
1545   // Determines whether 'Line' is affected by the SourceRanges given as input.
1546   // Returns \c true if line or one if its children is affected.
1547   bool nonPPLineAffected(AnnotatedLine *Line,
1548                          const AnnotatedLine *PreviousLine) {
1549     bool SomeLineAffected = false;
1550     Line->ChildrenAffected =
1551         computeAffectedLines(Line->Children.begin(), Line->Children.end());
1552     if (Line->ChildrenAffected)
1553       SomeLineAffected = true;
1554 
1555     // Stores whether one of the line's tokens is directly affected.
1556     bool SomeTokenAffected = false;
1557     // Stores whether we need to look at the leading newlines of the next token
1558     // in order to determine whether it was affected.
1559     bool IncludeLeadingNewlines = false;
1560 
1561     // Stores whether the first child line of any of this line's tokens is
1562     // affected.
1563     bool SomeFirstChildAffected = false;
1564 
1565     for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1566       // Determine whether 'Tok' was affected.
1567       if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1568         SomeTokenAffected = true;
1569 
1570       // Determine whether the first child of 'Tok' was affected.
1571       if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1572         SomeFirstChildAffected = true;
1573 
1574       IncludeLeadingNewlines = Tok->Children.empty();
1575     }
1576 
1577     // Was this line moved, i.e. has it previously been on the same line as an
1578     // affected line?
1579     bool LineMoved = PreviousLine && PreviousLine->Affected &&
1580                      Line->First->NewlinesBefore == 0;
1581 
1582     bool IsContinuedComment = Line->First->is(tok::comment) &&
1583                               Line->First->Next == NULL &&
1584                               Line->First->NewlinesBefore < 2 && PreviousLine &&
1585                               PreviousLine->Affected &&
1586                               PreviousLine->Last->is(tok::comment);
1587 
1588     if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1589         IsContinuedComment) {
1590       Line->Affected = true;
1591       SomeLineAffected = true;
1592     }
1593     return SomeLineAffected;
1594   }
1595 
1596   // Marks all lines between I and E as well as all their children as affected.
1597   void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1598                          SmallVectorImpl<AnnotatedLine *>::iterator E) {
1599     while (I != E) {
1600       (*I)->Affected = true;
1601       markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1602       ++I;
1603     }
1604   }
1605 
1606   // Returns true if the range from 'First' to 'Last' intersects with one of the
1607   // input ranges.
1608   bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1609                          bool IncludeLeadingNewlines) {
1610     SourceLocation Start = First.WhitespaceRange.getBegin();
1611     if (!IncludeLeadingNewlines)
1612       Start = Start.getLocWithOffset(First.LastNewlineOffset);
1613     SourceLocation End = Last.getStartOfNonWhitespace();
1614     if (Last.TokenText.size() > 0)
1615       End = End.getLocWithOffset(Last.TokenText.size() - 1);
1616     CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1617     return affectsCharSourceRange(Range);
1618   }
1619 
1620   // Returns true if one of the input ranges intersect the leading empty lines
1621   // before 'Tok'.
1622   bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1623     CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1624         Tok.WhitespaceRange.getBegin(),
1625         Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1626     return affectsCharSourceRange(EmptyLineRange);
1627   }
1628 
1629   // Returns true if 'Range' intersects with one of the input ranges.
1630   bool affectsCharSourceRange(const CharSourceRange &Range) {
1631     for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1632                                                           E = Ranges.end();
1633          I != E; ++I) {
1634       if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1635           !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1636         return true;
1637     }
1638     return false;
1639   }
1640 
1641   static bool inputUsesCRLF(StringRef Text) {
1642     return Text.count('\r') * 2 > Text.count('\n');
1643   }
1644 
1645   void
1646   deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
1647     unsigned CountBoundToVariable = 0;
1648     unsigned CountBoundToType = 0;
1649     bool HasCpp03IncompatibleFormat = false;
1650     bool HasBinPackedFunction = false;
1651     bool HasOnePerLineFunction = false;
1652     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1653       if (!AnnotatedLines[i]->First->Next)
1654         continue;
1655       FormatToken *Tok = AnnotatedLines[i]->First->Next;
1656       while (Tok->Next) {
1657         if (Tok->Type == TT_PointerOrReference) {
1658           bool SpacesBefore =
1659               Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1660           bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1661                              Tok->Next->WhitespaceRange.getEnd();
1662           if (SpacesBefore && !SpacesAfter)
1663             ++CountBoundToVariable;
1664           else if (!SpacesBefore && SpacesAfter)
1665             ++CountBoundToType;
1666         }
1667 
1668         if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1669           if (Tok->is(tok::coloncolon) &&
1670               Tok->Previous->Type == TT_TemplateOpener)
1671             HasCpp03IncompatibleFormat = true;
1672           if (Tok->Type == TT_TemplateCloser &&
1673               Tok->Previous->Type == TT_TemplateCloser)
1674             HasCpp03IncompatibleFormat = true;
1675         }
1676 
1677         if (Tok->PackingKind == PPK_BinPacked)
1678           HasBinPackedFunction = true;
1679         if (Tok->PackingKind == PPK_OnePerLine)
1680           HasOnePerLineFunction = true;
1681 
1682         Tok = Tok->Next;
1683       }
1684     }
1685     if (Style.DerivePointerBinding) {
1686       if (CountBoundToType > CountBoundToVariable)
1687         Style.PointerBindsToType = true;
1688       else if (CountBoundToType < CountBoundToVariable)
1689         Style.PointerBindsToType = false;
1690     }
1691     if (Style.Standard == FormatStyle::LS_Auto) {
1692       Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1693                                                   : FormatStyle::LS_Cpp03;
1694     }
1695     BinPackInconclusiveFunctions =
1696         HasBinPackedFunction || !HasOnePerLineFunction;
1697   }
1698 
1699   void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
1700     assert(!UnwrappedLines.empty());
1701     UnwrappedLines.back().push_back(TheLine);
1702   }
1703 
1704   void finishRun() override {
1705     UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
1706   }
1707 
1708   FormatStyle Style;
1709   Lexer &Lex;
1710   SourceManager &SourceMgr;
1711   WhitespaceManager Whitespaces;
1712   SmallVector<CharSourceRange, 8> Ranges;
1713   SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
1714 
1715   encoding::Encoding Encoding;
1716   bool BinPackInconclusiveFunctions;
1717 };
1718 
1719 } // end anonymous namespace
1720 
1721 tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1722                                SourceManager &SourceMgr,
1723                                std::vector<CharSourceRange> Ranges) {
1724   Formatter formatter(Style, Lex, SourceMgr, Ranges);
1725   return formatter.format();
1726 }
1727 
1728 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1729                                std::vector<tooling::Range> Ranges,
1730                                StringRef FileName) {
1731   FileManager Files((FileSystemOptions()));
1732   DiagnosticsEngine Diagnostics(
1733       IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1734       new DiagnosticOptions);
1735   SourceManager SourceMgr(Diagnostics, Files);
1736   llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1737   const clang::FileEntry *Entry =
1738       Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1739   SourceMgr.overrideFileContents(Entry, Buf);
1740   FileID ID =
1741       SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
1742   Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1743             getFormattingLangOpts(Style.Standard));
1744   SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1745   std::vector<CharSourceRange> CharRanges;
1746   for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1747     SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1748     SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1749     CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1750   }
1751   return reformat(Style, Lex, SourceMgr, CharRanges);
1752 }
1753 
1754 LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
1755   LangOptions LangOpts;
1756   LangOpts.CPlusPlus = 1;
1757   LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
1758   LangOpts.LineComment = 1;
1759   LangOpts.Bool = 1;
1760   LangOpts.ObjC1 = 1;
1761   LangOpts.ObjC2 = 1;
1762   return LangOpts;
1763 }
1764 
1765 const char *StyleOptionHelpDescription =
1766     "Coding style, currently supports:\n"
1767     "  LLVM, Google, Chromium, Mozilla, WebKit.\n"
1768     "Use -style=file to load style configuration from\n"
1769     ".clang-format file located in one of the parent\n"
1770     "directories of the source file (or current\n"
1771     "directory for stdin).\n"
1772     "Use -style=\"{key: value, ...}\" to set specific\n"
1773     "parameters, e.g.:\n"
1774     "  -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1775 
1776 static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
1777   if (FileName.endswith_lower(".js")) {
1778     return FormatStyle::LK_JavaScript;
1779   } else if (FileName.endswith_lower(".proto") ||
1780              FileName.endswith_lower(".protodevel")) {
1781     return FormatStyle::LK_Proto;
1782   }
1783   return FormatStyle::LK_Cpp;
1784 }
1785 
1786 FormatStyle getStyle(StringRef StyleName, StringRef FileName,
1787                      StringRef FallbackStyle) {
1788   FormatStyle Style = getLLVMStyle();
1789   Style.Language = getLanguageByFileName(FileName);
1790   if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
1791     llvm::errs() << "Invalid fallback style \"" << FallbackStyle
1792                  << "\" using LLVM style\n";
1793     return Style;
1794   }
1795 
1796   if (StyleName.startswith("{")) {
1797     // Parse YAML/JSON style from the command line.
1798     if (llvm::error_code ec = parseConfiguration(StyleName, &Style)) {
1799       llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
1800                    << FallbackStyle << " style\n";
1801     }
1802     return Style;
1803   }
1804 
1805   if (!StyleName.equals_lower("file")) {
1806     if (!getPredefinedStyle(StyleName, Style.Language, &Style))
1807       llvm::errs() << "Invalid value for -style, using " << FallbackStyle
1808                    << " style\n";
1809     return Style;
1810   }
1811 
1812   // Look for .clang-format/_clang-format file in the file's parent directories.
1813   SmallString<128> UnsuitableConfigFiles;
1814   SmallString<128> Path(FileName);
1815   llvm::sys::fs::make_absolute(Path);
1816   for (StringRef Directory = Path; !Directory.empty();
1817        Directory = llvm::sys::path::parent_path(Directory)) {
1818     if (!llvm::sys::fs::is_directory(Directory))
1819       continue;
1820     SmallString<128> ConfigFile(Directory);
1821 
1822     llvm::sys::path::append(ConfigFile, ".clang-format");
1823     DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1824     bool IsFile = false;
1825     // Ignore errors from is_regular_file: we only need to know if we can read
1826     // the file or not.
1827     llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1828 
1829     if (!IsFile) {
1830       // Try _clang-format too, since dotfiles are not commonly used on Windows.
1831       ConfigFile = Directory;
1832       llvm::sys::path::append(ConfigFile, "_clang-format");
1833       DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1834       llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1835     }
1836 
1837     if (IsFile) {
1838       std::unique_ptr<llvm::MemoryBuffer> Text;
1839       if (llvm::error_code ec =
1840               llvm::MemoryBuffer::getFile(ConfigFile.c_str(), Text)) {
1841         llvm::errs() << ec.message() << "\n";
1842         break;
1843       }
1844       if (llvm::error_code ec = parseConfiguration(Text->getBuffer(), &Style)) {
1845         if (ec == llvm::errc::not_supported) {
1846           if (!UnsuitableConfigFiles.empty())
1847             UnsuitableConfigFiles.append(", ");
1848           UnsuitableConfigFiles.append(ConfigFile);
1849           continue;
1850         }
1851         llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
1852                      << "\n";
1853         break;
1854       }
1855       DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
1856       return Style;
1857     }
1858   }
1859   llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
1860                << " style\n";
1861   if (!UnsuitableConfigFiles.empty()) {
1862     llvm::errs() << "Configuration file(s) do(es) not support "
1863                  << getLanguageName(Style.Language) << ": "
1864                  << UnsuitableConfigFiles << "\n";
1865   }
1866   return Style;
1867 }
1868 
1869 } // namespace format
1870 } // namespace clang
1871