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 "BreakableToken.h"
19 #include "TokenAnnotator.h"
20 #include "UnwrappedLineParser.h"
21 #include "WhitespaceManager.h"
22 #include "clang/Basic/Diagnostic.h"
23 #include "clang/Basic/OperatorPrecedence.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/Format/Format.h"
26 #include "clang/Lex/Lexer.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/Support/Allocator.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/YAMLTraits.h"
31 #include <queue>
32 #include <string>
33 
34 namespace llvm {
35 namespace yaml {
36 template <>
37 struct ScalarEnumerationTraits<clang::format::FormatStyle::LanguageStandard> {
38   static void enumeration(IO &IO,
39                           clang::format::FormatStyle::LanguageStandard &Value) {
40     IO.enumCase(Value, "C++03", clang::format::FormatStyle::LS_Cpp03);
41     IO.enumCase(Value, "C++11", clang::format::FormatStyle::LS_Cpp11);
42     IO.enumCase(Value, "Auto", clang::format::FormatStyle::LS_Auto);
43   }
44 };
45 
46 template <>
47 struct ScalarEnumerationTraits<clang::format::FormatStyle::BraceBreakingStyle> {
48   static void
49   enumeration(IO &IO, clang::format::FormatStyle::BraceBreakingStyle &Value) {
50     IO.enumCase(Value, "Attach", clang::format::FormatStyle::BS_Attach);
51     IO.enumCase(Value, "Linux", clang::format::FormatStyle::BS_Linux);
52     IO.enumCase(Value, "Stroustrup", clang::format::FormatStyle::BS_Stroustrup);
53   }
54 };
55 
56 template <> struct MappingTraits<clang::format::FormatStyle> {
57   static void mapping(llvm::yaml::IO &IO, clang::format::FormatStyle &Style) {
58     if (IO.outputting()) {
59       StringRef StylesArray[] = { "LLVM", "Google", "Chromium", "Mozilla" };
60       ArrayRef<StringRef> Styles(StylesArray);
61       for (size_t i = 0, e = Styles.size(); i < e; ++i) {
62         StringRef StyleName(Styles[i]);
63         clang::format::FormatStyle PredefinedStyle;
64         if (clang::format::getPredefinedStyle(StyleName, &PredefinedStyle) &&
65             Style == PredefinedStyle) {
66           IO.mapOptional("# BasedOnStyle", StyleName);
67           break;
68         }
69       }
70     } else {
71       StringRef BasedOnStyle;
72       IO.mapOptional("BasedOnStyle", BasedOnStyle);
73       if (!BasedOnStyle.empty())
74         if (!clang::format::getPredefinedStyle(BasedOnStyle, &Style)) {
75           IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
76           return;
77         }
78     }
79 
80     IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
81     IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
82     IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
83                    Style.AllowAllParametersOfDeclarationOnNextLine);
84     IO.mapOptional("AllowShortIfStatementsOnASingleLine",
85                    Style.AllowShortIfStatementsOnASingleLine);
86     IO.mapOptional("AllowShortLoopsOnASingleLine",
87                    Style.AllowShortLoopsOnASingleLine);
88     IO.mapOptional("AlwaysBreakTemplateDeclarations",
89                    Style.AlwaysBreakTemplateDeclarations);
90     IO.mapOptional("BinPackParameters", Style.BinPackParameters);
91     IO.mapOptional("ColumnLimit", Style.ColumnLimit);
92     IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
93                    Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
94     IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
95     IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
96     IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
97     IO.mapOptional("ObjCSpaceBeforeProtocolList",
98                    Style.ObjCSpaceBeforeProtocolList);
99     IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
100     IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
101     IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
102     IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
103                    Style.PenaltyReturnTypeOnItsOwnLine);
104     IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
105     IO.mapOptional("SpacesBeforeTrailingComments",
106                    Style.SpacesBeforeTrailingComments);
107     IO.mapOptional("SpacesInBracedLists", Style.SpacesInBracedLists);
108     IO.mapOptional("Standard", Style.Standard);
109     IO.mapOptional("IndentWidth", Style.IndentWidth);
110     IO.mapOptional("UseTab", Style.UseTab);
111     IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
112   }
113 };
114 }
115 }
116 
117 namespace clang {
118 namespace format {
119 
120 FormatStyle getLLVMStyle() {
121   FormatStyle LLVMStyle;
122   LLVMStyle.AccessModifierOffset = -2;
123   LLVMStyle.AlignEscapedNewlinesLeft = false;
124   LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
125   LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
126   LLVMStyle.AllowShortLoopsOnASingleLine = false;
127   LLVMStyle.AlwaysBreakTemplateDeclarations = false;
128   LLVMStyle.BinPackParameters = true;
129   LLVMStyle.ColumnLimit = 80;
130   LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
131   LLVMStyle.DerivePointerBinding = false;
132   LLVMStyle.IndentCaseLabels = false;
133   LLVMStyle.MaxEmptyLinesToKeep = 1;
134   LLVMStyle.ObjCSpaceBeforeProtocolList = true;
135   LLVMStyle.PenaltyBreakComment = 45;
136   LLVMStyle.PenaltyBreakString = 1000;
137   LLVMStyle.PenaltyExcessCharacter = 1000000;
138   LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 75;
139   LLVMStyle.PointerBindsToType = false;
140   LLVMStyle.SpacesBeforeTrailingComments = 1;
141   LLVMStyle.SpacesInBracedLists = true;
142   LLVMStyle.Standard = FormatStyle::LS_Cpp03;
143   LLVMStyle.IndentWidth = 2;
144   LLVMStyle.UseTab = false;
145   LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
146   return LLVMStyle;
147 }
148 
149 FormatStyle getGoogleStyle() {
150   FormatStyle GoogleStyle;
151   GoogleStyle.AccessModifierOffset = -1;
152   GoogleStyle.AlignEscapedNewlinesLeft = true;
153   GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
154   GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
155   GoogleStyle.AllowShortLoopsOnASingleLine = true;
156   GoogleStyle.AlwaysBreakTemplateDeclarations = true;
157   GoogleStyle.BinPackParameters = true;
158   GoogleStyle.ColumnLimit = 80;
159   GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
160   GoogleStyle.DerivePointerBinding = true;
161   GoogleStyle.IndentCaseLabels = true;
162   GoogleStyle.MaxEmptyLinesToKeep = 1;
163   GoogleStyle.ObjCSpaceBeforeProtocolList = false;
164   GoogleStyle.PenaltyBreakComment = 45;
165   GoogleStyle.PenaltyBreakString = 1000;
166   GoogleStyle.PenaltyExcessCharacter = 1000000;
167   GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
168   GoogleStyle.PointerBindsToType = true;
169   GoogleStyle.SpacesBeforeTrailingComments = 2;
170   GoogleStyle.SpacesInBracedLists = false;
171   GoogleStyle.Standard = FormatStyle::LS_Auto;
172   GoogleStyle.IndentWidth = 2;
173   GoogleStyle.UseTab = false;
174   GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
175   return GoogleStyle;
176 }
177 
178 FormatStyle getChromiumStyle() {
179   FormatStyle ChromiumStyle = getGoogleStyle();
180   ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
181   ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
182   ChromiumStyle.AllowShortLoopsOnASingleLine = false;
183   ChromiumStyle.BinPackParameters = false;
184   ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
185   ChromiumStyle.DerivePointerBinding = false;
186   return ChromiumStyle;
187 }
188 
189 FormatStyle getMozillaStyle() {
190   FormatStyle MozillaStyle = getLLVMStyle();
191   MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
192   MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
193   MozillaStyle.DerivePointerBinding = true;
194   MozillaStyle.IndentCaseLabels = true;
195   MozillaStyle.ObjCSpaceBeforeProtocolList = false;
196   MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
197   MozillaStyle.PointerBindsToType = true;
198   return MozillaStyle;
199 }
200 
201 bool getPredefinedStyle(StringRef Name, FormatStyle *Style) {
202   if (Name.equals_lower("llvm"))
203     *Style = getLLVMStyle();
204   else if (Name.equals_lower("chromium"))
205     *Style = getChromiumStyle();
206   else if (Name.equals_lower("mozilla"))
207     *Style = getMozillaStyle();
208   else if (Name.equals_lower("google"))
209     *Style = getGoogleStyle();
210   else
211     return false;
212 
213   return true;
214 }
215 
216 llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
217   if (Text.trim().empty())
218     return llvm::make_error_code(llvm::errc::invalid_argument);
219   llvm::yaml::Input Input(Text);
220   Input >> *Style;
221   return Input.error();
222 }
223 
224 std::string configurationAsText(const FormatStyle &Style) {
225   std::string Text;
226   llvm::raw_string_ostream Stream(Text);
227   llvm::yaml::Output Output(Stream);
228   // We use the same mapping method for input and output, so we need a non-const
229   // reference here.
230   FormatStyle NonConstStyle = Style;
231   Output << NonConstStyle;
232   return Stream.str();
233 }
234 
235 // Returns the length of everything up to the first possible line break after
236 // the ), ], } or > matching \c Tok.
237 static unsigned getLengthToMatchingParen(const FormatToken &Tok) {
238   if (Tok.MatchingParen == NULL)
239     return 0;
240   FormatToken *End = Tok.MatchingParen;
241   while (End->Next && !End->Next->CanBreakBefore) {
242     End = End->Next;
243   }
244   return End->TotalLength - Tok.TotalLength + 1;
245 }
246 
247 class UnwrappedLineFormatter {
248 public:
249   UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
250                          const AnnotatedLine &Line, unsigned FirstIndent,
251                          const FormatToken *RootToken,
252                          WhitespaceManager &Whitespaces,
253                          encoding::Encoding Encoding)
254       : Style(Style), SourceMgr(SourceMgr), Line(Line),
255         FirstIndent(FirstIndent), RootToken(RootToken),
256         Whitespaces(Whitespaces), Count(0), Encoding(Encoding) {}
257 
258   /// \brief Formats an \c UnwrappedLine.
259   void format(const AnnotatedLine *NextLine) {
260     // Initialize state dependent on indent.
261     LineState State;
262     State.Column = FirstIndent;
263     State.NextToken = RootToken;
264     State.Stack.push_back(
265         ParenState(FirstIndent, FirstIndent, /*AvoidBinPacking=*/ false,
266                    /*NoLineBreak=*/ false));
267     State.LineContainsContinuedForLoopSection = false;
268     State.ParenLevel = 0;
269     State.StartOfStringLiteral = 0;
270     State.StartOfLineLevel = State.ParenLevel;
271     State.LowestCallLevel = State.ParenLevel;
272     State.IgnoreStackForComparison = false;
273 
274     // The first token has already been indented and thus consumed.
275     moveStateToNextToken(State, /*DryRun=*/ false);
276 
277     // If everything fits on a single line, just put it there.
278     unsigned ColumnLimit = Style.ColumnLimit;
279     if (NextLine && NextLine->InPPDirective &&
280         !NextLine->First->HasUnescapedNewline)
281       ColumnLimit = getColumnLimit();
282     if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
283       while (State.NextToken != NULL) {
284         addTokenToState(false, false, State);
285       }
286     }
287 
288     // If the ObjC method declaration does not fit on a line, we should format
289     // it with one arg per line.
290     if (Line.Type == LT_ObjCMethodDecl)
291       State.Stack.back().BreakBeforeParameter = true;
292 
293     // Find best solution in solution space.
294     analyzeSolutionSpace(State);
295   }
296 
297 private:
298   void DebugTokenState(const FormatToken &FormatTok) {
299     const Token &Tok = FormatTok.Tok;
300     llvm::dbgs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
301                               Tok.getLength());
302     llvm::dbgs();
303   }
304 
305   struct ParenState {
306     ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
307                bool NoLineBreak)
308         : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
309           BreakBeforeClosingBrace(false), QuestionColumn(0),
310           AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
311           NoLineBreak(NoLineBreak), ColonPos(0), StartOfFunctionCall(0),
312           NestedNameSpecifierContinuation(0), CallContinuation(0),
313           VariablePos(0), ForFakeParenthesis(false) {}
314 
315     /// \brief The position to which a specific parenthesis level needs to be
316     /// indented.
317     unsigned Indent;
318 
319     /// \brief The position of the last space on each level.
320     ///
321     /// Used e.g. to break like:
322     /// functionCall(Parameter, otherCall(
323     ///                             OtherParameter));
324     unsigned LastSpace;
325 
326     /// \brief The position the first "<<" operator encountered on each level.
327     ///
328     /// Used to align "<<" operators. 0 if no such operator has been encountered
329     /// on a level.
330     unsigned FirstLessLess;
331 
332     /// \brief Whether a newline needs to be inserted before the block's closing
333     /// brace.
334     ///
335     /// We only want to insert a newline before the closing brace if there also
336     /// was a newline after the beginning left brace.
337     bool BreakBeforeClosingBrace;
338 
339     /// \brief The column of a \c ? in a conditional expression;
340     unsigned QuestionColumn;
341 
342     /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
343     /// lines, in this context.
344     bool AvoidBinPacking;
345 
346     /// \brief Break after the next comma (or all the commas in this context if
347     /// \c AvoidBinPacking is \c true).
348     bool BreakBeforeParameter;
349 
350     /// \brief Line breaking in this context would break a formatting rule.
351     bool NoLineBreak;
352 
353     /// \brief The position of the colon in an ObjC method declaration/call.
354     unsigned ColonPos;
355 
356     /// \brief The start of the most recent function in a builder-type call.
357     unsigned StartOfFunctionCall;
358 
359     /// \brief If a nested name specifier was broken over multiple lines, this
360     /// contains the start column of the second line. Otherwise 0.
361     unsigned NestedNameSpecifierContinuation;
362 
363     /// \brief If a call expression was broken over multiple lines, this
364     /// contains the start column of the second line. Otherwise 0.
365     unsigned CallContinuation;
366 
367     /// \brief The column of the first variable name in a variable declaration.
368     ///
369     /// Used to align further variables if necessary.
370     unsigned VariablePos;
371 
372     /// \brief \c true if this \c ParenState was created for a fake parenthesis.
373     ///
374     /// Does not need to be considered for memoization / the comparison function
375     /// as otherwise identical states will have the same fake/non-fake
376     /// \c ParenStates.
377     bool ForFakeParenthesis;
378 
379     bool operator<(const ParenState &Other) const {
380       if (Indent != Other.Indent)
381         return Indent < Other.Indent;
382       if (LastSpace != Other.LastSpace)
383         return LastSpace < Other.LastSpace;
384       if (FirstLessLess != Other.FirstLessLess)
385         return FirstLessLess < Other.FirstLessLess;
386       if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
387         return BreakBeforeClosingBrace;
388       if (QuestionColumn != Other.QuestionColumn)
389         return QuestionColumn < Other.QuestionColumn;
390       if (AvoidBinPacking != Other.AvoidBinPacking)
391         return AvoidBinPacking;
392       if (BreakBeforeParameter != Other.BreakBeforeParameter)
393         return BreakBeforeParameter;
394       if (NoLineBreak != Other.NoLineBreak)
395         return NoLineBreak;
396       if (ColonPos != Other.ColonPos)
397         return ColonPos < Other.ColonPos;
398       if (StartOfFunctionCall != Other.StartOfFunctionCall)
399         return StartOfFunctionCall < Other.StartOfFunctionCall;
400       if (CallContinuation != Other.CallContinuation)
401         return CallContinuation < Other.CallContinuation;
402       if (VariablePos != Other.VariablePos)
403         return VariablePos < Other.VariablePos;
404       return false;
405     }
406   };
407 
408   /// \brief The current state when indenting a unwrapped line.
409   ///
410   /// As the indenting tries different combinations this is copied by value.
411   struct LineState {
412     /// \brief The number of used columns in the current line.
413     unsigned Column;
414 
415     /// \brief The token that needs to be next formatted.
416     const FormatToken *NextToken;
417 
418     /// \brief \c true if this line contains a continued for-loop section.
419     bool LineContainsContinuedForLoopSection;
420 
421     /// \brief The level of nesting inside (), [], <> and {}.
422     unsigned ParenLevel;
423 
424     /// \brief The \c ParenLevel at the start of this line.
425     unsigned StartOfLineLevel;
426 
427     /// \brief The lowest \c ParenLevel of "." or "->" on the current line.
428     unsigned LowestCallLevel;
429 
430     /// \brief The start column of the string literal, if we're in a string
431     /// literal sequence, 0 otherwise.
432     unsigned StartOfStringLiteral;
433 
434     /// \brief A stack keeping track of properties applying to parenthesis
435     /// levels.
436     std::vector<ParenState> Stack;
437 
438     /// \brief Ignore the stack of \c ParenStates for state comparison.
439     ///
440     /// In long and deeply nested unwrapped lines, the current algorithm can
441     /// be insufficient for finding the best formatting with a reasonable amount
442     /// of time and memory. Setting this flag will effectively lead to the
443     /// algorithm not analyzing some combinations. However, these combinations
444     /// rarely contain the optimal solution: In short, accepting a higher
445     /// penalty early would need to lead to different values in the \c
446     /// ParenState stack (in an otherwise identical state) and these different
447     /// values would need to lead to a significant amount of avoided penalty
448     /// later.
449     ///
450     /// FIXME: Come up with a better algorithm instead.
451     bool IgnoreStackForComparison;
452 
453     /// \brief Comparison operator to be able to used \c LineState in \c map.
454     bool operator<(const LineState &Other) const {
455       if (NextToken != Other.NextToken)
456         return NextToken < Other.NextToken;
457       if (Column != Other.Column)
458         return Column < Other.Column;
459       if (LineContainsContinuedForLoopSection !=
460           Other.LineContainsContinuedForLoopSection)
461         return LineContainsContinuedForLoopSection;
462       if (ParenLevel != Other.ParenLevel)
463         return ParenLevel < Other.ParenLevel;
464       if (StartOfLineLevel != Other.StartOfLineLevel)
465         return StartOfLineLevel < Other.StartOfLineLevel;
466       if (LowestCallLevel != Other.LowestCallLevel)
467         return LowestCallLevel < Other.LowestCallLevel;
468       if (StartOfStringLiteral != Other.StartOfStringLiteral)
469         return StartOfStringLiteral < Other.StartOfStringLiteral;
470       if (IgnoreStackForComparison || Other.IgnoreStackForComparison)
471         return false;
472       return Stack < Other.Stack;
473     }
474   };
475 
476   /// \brief Appends the next token to \p State and updates information
477   /// necessary for indentation.
478   ///
479   /// Puts the token on the current line if \p Newline is \c true and adds a
480   /// line break and necessary indentation otherwise.
481   ///
482   /// If \p DryRun is \c false, also creates and stores the required
483   /// \c Replacement.
484   unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
485     const FormatToken &Current = *State.NextToken;
486     const FormatToken &Previous = *State.NextToken->Previous;
487 
488     if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
489       // FIXME: Is this correct?
490       int WhitespaceLength = SourceMgr.getSpellingColumnNumber(
491                                  State.NextToken->WhitespaceRange.getEnd()) -
492                              SourceMgr.getSpellingColumnNumber(
493                                  State.NextToken->WhitespaceRange.getBegin());
494       State.Column += WhitespaceLength + State.NextToken->CodePointCount;
495       State.NextToken = State.NextToken->Next;
496       return 0;
497     }
498 
499     // If we are continuing an expression, we want to indent an extra 4 spaces.
500     unsigned ContinuationIndent =
501         std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
502     if (Newline) {
503       if (Current.is(tok::r_brace)) {
504         State.Column = Line.Level * Style.IndentWidth;
505       } else if (Current.is(tok::string_literal) &&
506                  State.StartOfStringLiteral != 0) {
507         State.Column = State.StartOfStringLiteral;
508         State.Stack.back().BreakBeforeParameter = true;
509       } else if (Current.is(tok::lessless) &&
510                  State.Stack.back().FirstLessLess != 0) {
511         State.Column = State.Stack.back().FirstLessLess;
512       } else if (Current.isOneOf(tok::period, tok::arrow) &&
513                  Current.Type != TT_DesignatedInitializerPeriod) {
514         if (State.Stack.back().CallContinuation == 0) {
515           State.Column = ContinuationIndent;
516           State.Stack.back().CallContinuation = State.Column;
517         } else {
518           State.Column = State.Stack.back().CallContinuation;
519         }
520       } else if (Current.Type == TT_ConditionalExpr) {
521         State.Column = State.Stack.back().QuestionColumn;
522       } else if (Previous.is(tok::comma) &&
523                  State.Stack.back().VariablePos != 0) {
524         State.Column = State.Stack.back().VariablePos;
525       } else if (Previous.ClosesTemplateDeclaration ||
526                  (Current.Type == TT_StartOfName && State.ParenLevel == 0 &&
527                   Line.StartsDefinition)) {
528         State.Column = State.Stack.back().Indent;
529       } else if (Current.Type == TT_ObjCSelectorName) {
530         if (State.Stack.back().ColonPos > Current.CodePointCount) {
531           State.Column = State.Stack.back().ColonPos - Current.CodePointCount;
532         } else {
533           State.Column = State.Stack.back().Indent;
534           State.Stack.back().ColonPos = State.Column + Current.CodePointCount;
535         }
536       } else if (Current.Type == TT_StartOfName ||
537                  Previous.isOneOf(tok::coloncolon, tok::equal) ||
538                  Previous.Type == TT_ObjCMethodExpr) {
539         State.Column = ContinuationIndent;
540       } else {
541         State.Column = State.Stack.back().Indent;
542         // Ensure that we fall back to indenting 4 spaces instead of just
543         // flushing continuations left.
544         if (State.Column == FirstIndent)
545           State.Column += 4;
546       }
547 
548       if (Current.is(tok::question))
549         State.Stack.back().BreakBeforeParameter = true;
550       if ((Previous.isOneOf(tok::comma, tok::semi) &&
551            !State.Stack.back().AvoidBinPacking) ||
552           Previous.Type == TT_BinaryOperator)
553         State.Stack.back().BreakBeforeParameter = false;
554       if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
555         State.Stack.back().BreakBeforeParameter = false;
556 
557       if (!DryRun) {
558         unsigned NewLines = 1;
559         if (Current.is(tok::comment))
560           NewLines = std::max(
561               NewLines,
562               std::min(Current.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1));
563         Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
564                                       State.Column, Line.InPPDirective);
565       }
566 
567       State.Stack.back().LastSpace = State.Column;
568       if (Current.isOneOf(tok::arrow, tok::period) &&
569           Current.Type != TT_DesignatedInitializerPeriod)
570         State.Stack.back().LastSpace += Current.CodePointCount;
571       State.StartOfLineLevel = State.ParenLevel;
572       State.LowestCallLevel = State.ParenLevel;
573 
574       // Any break on this level means that the parent level has been broken
575       // and we need to avoid bin packing there.
576       for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
577         State.Stack[i].BreakBeforeParameter = true;
578       }
579       const FormatToken *TokenBefore = Current.getPreviousNoneComment();
580       if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
581           TokenBefore->Type != TT_TemplateCloser &&
582           TokenBefore->Type != TT_BinaryOperator && !TokenBefore->opensScope())
583         State.Stack.back().BreakBeforeParameter = true;
584 
585       // If we break after {, we should also break before the corresponding }.
586       if (Previous.is(tok::l_brace))
587         State.Stack.back().BreakBeforeClosingBrace = true;
588 
589       if (State.Stack.back().AvoidBinPacking) {
590         // If we are breaking after '(', '{', '<', this is not bin packing
591         // unless AllowAllParametersOfDeclarationOnNextLine is false.
592         if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
593               Previous.Type == TT_BinaryOperator) ||
594             (!Style.AllowAllParametersOfDeclarationOnNextLine &&
595              Line.MustBeDeclaration))
596           State.Stack.back().BreakBeforeParameter = true;
597       }
598     } else {
599       if (Current.is(tok::equal) &&
600           (RootToken->is(tok::kw_for) || State.ParenLevel == 0) &&
601           State.Stack.back().VariablePos == 0) {
602         State.Stack.back().VariablePos = State.Column;
603         // Move over * and & if they are bound to the variable name.
604         const FormatToken *Tok = &Previous;
605         while (Tok && State.Stack.back().VariablePos >= Tok->CodePointCount) {
606           State.Stack.back().VariablePos -= Tok->CodePointCount;
607           if (Tok->SpacesRequiredBefore != 0)
608             break;
609           Tok = Tok->Previous;
610         }
611         if (Previous.PartOfMultiVariableDeclStmt)
612           State.Stack.back().LastSpace = State.Stack.back().VariablePos;
613       }
614 
615       unsigned Spaces = State.NextToken->SpacesRequiredBefore;
616 
617       if (!DryRun)
618         Whitespaces.replaceWhitespace(Current, 0, Spaces,
619                                       State.Column + Spaces);
620 
621       if (Current.Type == TT_ObjCSelectorName &&
622           State.Stack.back().ColonPos == 0) {
623         if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
624             State.Column + Spaces + Current.CodePointCount)
625           State.Stack.back().ColonPos =
626               State.Stack.back().Indent + Current.LongestObjCSelectorName;
627         else
628           State.Stack.back().ColonPos =
629               State.Column + Spaces + Current.CodePointCount;
630       }
631 
632       if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
633           Current.Type != TT_LineComment)
634         State.Stack.back().Indent = State.Column + Spaces;
635       if (Previous.is(tok::comma) && !Current.isTrailingComment() &&
636           State.Stack.back().AvoidBinPacking)
637         State.Stack.back().NoLineBreak = true;
638 
639       State.Column += Spaces;
640       if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
641         // Treat the condition inside an if as if it was a second function
642         // parameter, i.e. let nested calls have an indent of 4.
643         State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
644       else if (Previous.is(tok::comma))
645         State.Stack.back().LastSpace = State.Column;
646       else if ((Previous.Type == TT_BinaryOperator ||
647                 Previous.Type == TT_ConditionalExpr ||
648                 Previous.Type == TT_CtorInitializerColon) &&
649                !(Previous.getPrecedence() == prec::Assignment &&
650                  Current.FakeLParens.empty()))
651         // Always indent relative to the RHS of the expression unless this is a
652         // simple assignment without binary expression on the RHS.
653         State.Stack.back().LastSpace = State.Column;
654       else if (Previous.Type == TT_InheritanceColon)
655         State.Stack.back().Indent = State.Column;
656       else if (Previous.opensScope() && !Current.FakeLParens.empty())
657         // If this function has multiple parameters or a binary expression
658         // parameter, indent nested calls from the start of the first parameter.
659         State.Stack.back().LastSpace = State.Column;
660     }
661 
662     return moveStateToNextToken(State, DryRun);
663   }
664 
665   /// \brief Mark the next token as consumed in \p State and modify its stacks
666   /// accordingly.
667   unsigned moveStateToNextToken(LineState &State, bool DryRun) {
668     const FormatToken &Current = *State.NextToken;
669     assert(State.Stack.size());
670 
671     if (Current.Type == TT_InheritanceColon)
672       State.Stack.back().AvoidBinPacking = true;
673     if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
674       State.Stack.back().FirstLessLess = State.Column;
675     if (Current.is(tok::question))
676       State.Stack.back().QuestionColumn = State.Column;
677     if (Current.isOneOf(tok::period, tok::arrow)) {
678       State.LowestCallLevel = std::min(State.LowestCallLevel, State.ParenLevel);
679       if (Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
680         State.Stack.back().StartOfFunctionCall =
681             Current.LastInChainOfCalls ? 0
682                                        : State.Column + Current.CodePointCount;
683     }
684     if (Current.Type == TT_CtorInitializerColon) {
685       // Indent 2 from the column, so:
686       // SomeClass::SomeClass()
687       //     : First(...), ...
688       //       Next(...)
689       //       ^ line up here.
690       State.Stack.back().Indent = State.Column + 2;
691       if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
692         State.Stack.back().AvoidBinPacking = true;
693       State.Stack.back().BreakBeforeParameter = false;
694     }
695 
696     // If return returns a binary expression, align after it.
697     if (Current.is(tok::kw_return) && !Current.FakeLParens.empty())
698       State.Stack.back().LastSpace = State.Column + 7;
699 
700     // In ObjC method declaration we align on the ":" of parameters, but we need
701     // to ensure that we indent parameters on subsequent lines by at least 4.
702     if (Current.Type == TT_ObjCMethodSpecifier)
703       State.Stack.back().Indent += 4;
704 
705     // Insert scopes created by fake parenthesis.
706     const FormatToken *Previous = Current.getPreviousNoneComment();
707     // Don't add extra indentation for the first fake parenthesis after
708     // 'return', assignements or opening <({[. The indentation for these cases
709     // is special cased.
710     bool SkipFirstExtraIndent =
711         Current.is(tok::kw_return) ||
712         (Previous && (Previous->opensScope() ||
713                       Previous->getPrecedence() == prec::Assignment));
714     for (SmallVector<prec::Level, 4>::const_reverse_iterator
715              I = Current.FakeLParens.rbegin(),
716              E = Current.FakeLParens.rend();
717          I != E; ++I) {
718       ParenState NewParenState = State.Stack.back();
719       NewParenState.ForFakeParenthesis = true;
720       NewParenState.Indent =
721           std::max(std::max(State.Column, NewParenState.Indent),
722                    State.Stack.back().LastSpace);
723 
724       // Always indent conditional expressions. Never indent expression where
725       // the 'operator' is ',', ';' or an assignment (i.e. *I <=
726       // prec::Assignment) as those have different indentation rules. Indent
727       // other expression, unless the indentation needs to be skipped.
728       if (*I == prec::Conditional ||
729           (!SkipFirstExtraIndent && *I > prec::Assignment))
730         NewParenState.Indent += 4;
731       if (Previous && !Previous->opensScope())
732         NewParenState.BreakBeforeParameter = false;
733       State.Stack.push_back(NewParenState);
734       SkipFirstExtraIndent = false;
735     }
736 
737     // If we encounter an opening (, [, { or <, we add a level to our stacks to
738     // prepare for the following tokens.
739     if (Current.opensScope()) {
740       unsigned NewIndent;
741       unsigned LastSpace = State.Stack.back().LastSpace;
742       bool AvoidBinPacking;
743       if (Current.is(tok::l_brace)) {
744         NewIndent = Style.IndentWidth + LastSpace;
745         const FormatToken *NextNoComment = Current.getNextNoneComment();
746         AvoidBinPacking = NextNoComment &&
747                           NextNoComment->Type == TT_DesignatedInitializerPeriod;
748       } else {
749         NewIndent =
750             4 + std::max(LastSpace, State.Stack.back().StartOfFunctionCall);
751         AvoidBinPacking = !Style.BinPackParameters;
752       }
753 
754       State.Stack.push_back(ParenState(NewIndent, LastSpace, AvoidBinPacking,
755                                        State.Stack.back().NoLineBreak));
756       ++State.ParenLevel;
757     }
758 
759     // If this '[' opens an ObjC call, determine whether all parameters fit into
760     // one line and put one per line if they don't.
761     if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
762         Current.MatchingParen != NULL) {
763       if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
764         State.Stack.back().BreakBeforeParameter = true;
765     }
766 
767     // If we encounter a closing ), ], } or >, we can remove a level from our
768     // stacks.
769     if (Current.isOneOf(tok::r_paren, tok::r_square) ||
770         (Current.is(tok::r_brace) && State.NextToken != RootToken) ||
771         State.NextToken->Type == TT_TemplateCloser) {
772       State.Stack.pop_back();
773       --State.ParenLevel;
774     }
775 
776     // Remove scopes created by fake parenthesis.
777     for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
778       unsigned VariablePos = State.Stack.back().VariablePos;
779       State.Stack.pop_back();
780       State.Stack.back().VariablePos = VariablePos;
781     }
782 
783     if (Current.is(tok::string_literal) && State.StartOfStringLiteral == 0) {
784       State.StartOfStringLiteral = State.Column;
785     } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash,
786                                 tok::string_literal)) {
787       State.StartOfStringLiteral = 0;
788     }
789 
790     State.Column += Current.CodePointCount;
791 
792     State.NextToken = State.NextToken->Next;
793 
794     return breakProtrudingToken(Current, State, DryRun);
795   }
796 
797   /// \brief If the current token sticks out over the end of the line, break
798   /// it if possible.
799   ///
800   /// \returns An extra penalty if a token was broken, otherwise 0.
801   ///
802   /// Note that the penalty of the token protruding the allowed line length is
803   /// already handled in \c addNextStateToQueue; the returned penalty will only
804   /// cover the cost of the additional line breaks.
805   unsigned breakProtrudingToken(const FormatToken &Current, LineState &State,
806                                 bool DryRun) {
807     llvm::OwningPtr<BreakableToken> Token;
808     unsigned StartColumn = State.Column - Current.CodePointCount;
809     unsigned OriginalStartColumn =
810         SourceMgr.getSpellingColumnNumber(Current.getStartOfNonWhitespace()) -
811         1;
812 
813     if (Current.is(tok::string_literal) &&
814         Current.Type != TT_ImplicitStringLiteral) {
815       // Only break up default narrow strings.
816       if (!Current.TokenText.startswith("\""))
817         return 0;
818 
819       Token.reset(new BreakableStringLiteral(Current, StartColumn,
820                                              Line.InPPDirective, Encoding));
821     } else if (Current.Type == TT_BlockComment) {
822       Token.reset(new BreakableBlockComment(
823           Style, Current, StartColumn, OriginalStartColumn, !Current.Previous,
824           Line.InPPDirective, Encoding));
825     } else if (Current.Type == TT_LineComment &&
826                (Current.Previous == NULL ||
827                 Current.Previous->Type != TT_ImplicitStringLiteral)) {
828       Token.reset(new BreakableLineComment(Current, StartColumn,
829                                            Line.InPPDirective, Encoding));
830     } else {
831       return 0;
832     }
833     if (Current.UnbreakableTailLength >= getColumnLimit())
834       return 0;
835     unsigned RemainingSpace = getColumnLimit() - Current.UnbreakableTailLength;
836 
837     bool BreakInserted = false;
838     unsigned Penalty = 0;
839     unsigned PositionAfterLastLineInToken = 0;
840     for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
841          LineIndex != EndIndex; ++LineIndex) {
842       if (!DryRun)
843         Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
844       unsigned TailOffset = 0;
845       unsigned RemainingTokenColumns = Token->getLineLengthAfterSplit(
846           LineIndex, TailOffset, StringRef::npos);
847       while (RemainingTokenColumns > RemainingSpace) {
848         BreakableToken::Split Split =
849             Token->getSplit(LineIndex, TailOffset, getColumnLimit());
850         if (Split.first == StringRef::npos)
851           break;
852         assert(Split.first != 0);
853         unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
854             LineIndex, TailOffset + Split.first + Split.second,
855             StringRef::npos);
856         assert(NewRemainingTokenColumns < RemainingTokenColumns);
857         if (!DryRun)
858           Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
859         Penalty += Current.is(tok::string_literal) ? Style.PenaltyBreakString
860                                                    : Style.PenaltyBreakComment;
861         unsigned ColumnsUsed =
862             Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
863         if (ColumnsUsed > getColumnLimit()) {
864           Penalty +=
865               Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit());
866         }
867         TailOffset += Split.first + Split.second;
868         RemainingTokenColumns = NewRemainingTokenColumns;
869         BreakInserted = true;
870       }
871       PositionAfterLastLineInToken = RemainingTokenColumns;
872     }
873 
874     if (BreakInserted) {
875       State.Column = PositionAfterLastLineInToken;
876       for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
877         State.Stack[i].BreakBeforeParameter = true;
878       State.Stack.back().LastSpace = StartColumn;
879     }
880     return Penalty;
881   }
882 
883   unsigned getColumnLimit() {
884     // In preprocessor directives reserve two chars for trailing " \"
885     return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
886   }
887 
888   /// \brief An edge in the solution space from \c Previous->State to \c State,
889   /// inserting a newline dependent on the \c NewLine.
890   struct StateNode {
891     StateNode(const LineState &State, bool NewLine, StateNode *Previous)
892         : State(State), NewLine(NewLine), Previous(Previous) {}
893     LineState State;
894     bool NewLine;
895     StateNode *Previous;
896   };
897 
898   /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
899   ///
900   /// In case of equal penalties, we want to prefer states that were inserted
901   /// first. During state generation we make sure that we insert states first
902   /// that break the line as late as possible.
903   typedef std::pair<unsigned, unsigned> OrderedPenalty;
904 
905   /// \brief An item in the prioritized BFS search queue. The \c StateNode's
906   /// \c State has the given \c OrderedPenalty.
907   typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
908 
909   /// \brief The BFS queue type.
910   typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
911                               std::greater<QueueItem> > QueueType;
912 
913   /// \brief Analyze the entire solution space starting from \p InitialState.
914   ///
915   /// This implements a variant of Dijkstra's algorithm on the graph that spans
916   /// the solution space (\c LineStates are the nodes). The algorithm tries to
917   /// find the shortest path (the one with lowest penalty) from \p InitialState
918   /// to a state where all tokens are placed.
919   void analyzeSolutionSpace(LineState &InitialState) {
920     std::set<LineState> Seen;
921 
922     // Insert start element into queue.
923     StateNode *Node =
924         new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
925     Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
926     ++Count;
927 
928     // While not empty, take first element and follow edges.
929     while (!Queue.empty()) {
930       unsigned Penalty = Queue.top().first.first;
931       StateNode *Node = Queue.top().second;
932       if (Node->State.NextToken == NULL) {
933         DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
934         break;
935       }
936       Queue.pop();
937 
938       // Cut off the analysis of certain solutions if the analysis gets too
939       // complex. See description of IgnoreStackForComparison.
940       if (Count > 10000)
941         Node->State.IgnoreStackForComparison = true;
942 
943       if (!Seen.insert(Node->State).second)
944         // State already examined with lower penalty.
945         continue;
946 
947       addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
948       addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
949     }
950 
951     if (Queue.empty())
952       // We were unable to find a solution, do nothing.
953       // FIXME: Add diagnostic?
954       return;
955 
956     // Reconstruct the solution.
957     reconstructPath(InitialState, Queue.top().second);
958     DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
959     DEBUG(llvm::dbgs() << "---\n");
960   }
961 
962   void reconstructPath(LineState &State, StateNode *Current) {
963     std::deque<StateNode *> Path;
964     // We do not need a break before the initial token.
965     while (Current->Previous) {
966       Path.push_front(Current);
967       Current = Current->Previous;
968     }
969     for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
970          I != E; ++I) {
971       DEBUG({
972         if ((*I)->NewLine) {
973           llvm::dbgs() << "Penalty for splitting before "
974                        << (*I)->Previous->State.NextToken->Tok.getName() << ": "
975                        << (*I)->Previous->State.NextToken->SplitPenalty << "\n";
976         }
977       });
978       addTokenToState((*I)->NewLine, false, State);
979     }
980   }
981 
982   /// \brief Add the following state to the analysis queue \c Queue.
983   ///
984   /// Assume the current state is \p PreviousNode and has been reached with a
985   /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
986   void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
987                            bool NewLine) {
988     if (NewLine && !canBreak(PreviousNode->State))
989       return;
990     if (!NewLine && mustBreak(PreviousNode->State))
991       return;
992     if (NewLine)
993       Penalty += PreviousNode->State.NextToken->SplitPenalty;
994 
995     StateNode *Node = new (Allocator.Allocate())
996         StateNode(PreviousNode->State, NewLine, PreviousNode);
997     Penalty += addTokenToState(NewLine, true, Node->State);
998     if (Node->State.Column > getColumnLimit()) {
999       unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
1000       Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
1001     }
1002 
1003     Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
1004     ++Count;
1005   }
1006 
1007   /// \brief Returns \c true, if a line break after \p State is allowed.
1008   bool canBreak(const LineState &State) {
1009     const FormatToken &Current = *State.NextToken;
1010     const FormatToken &Previous = *Current.Previous;
1011     assert(&Previous == Current.Previous);
1012     if (!Current.CanBreakBefore &&
1013         !(Current.is(tok::r_brace) &&
1014           State.Stack.back().BreakBeforeClosingBrace))
1015       return false;
1016     // The opening "{" of a braced list has to be on the same line as the first
1017     // element if it is nested in another braced init list or function call.
1018     if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
1019         Previous.Previous &&
1020         Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
1021       return false;
1022     // This prevents breaks like:
1023     //   ...
1024     //   SomeParameter, OtherParameter).DoSomething(
1025     //   ...
1026     // As they hide "DoSomething" and are generally bad for readability.
1027     if (Previous.opensScope() && State.LowestCallLevel < State.StartOfLineLevel)
1028       return false;
1029     return !State.Stack.back().NoLineBreak;
1030   }
1031 
1032   /// \brief Returns \c true, if a line break after \p State is mandatory.
1033   bool mustBreak(const LineState &State) {
1034     const FormatToken &Current = *State.NextToken;
1035     const FormatToken &Previous = *Current.Previous;
1036     if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
1037       return true;
1038     if (Current.is(tok::r_brace) && State.Stack.back().BreakBeforeClosingBrace)
1039       return true;
1040     if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
1041       return true;
1042     if ((Previous.isOneOf(tok::comma, tok::semi) || Current.is(tok::question) ||
1043          Current.Type == TT_ConditionalExpr) &&
1044         State.Stack.back().BreakBeforeParameter &&
1045         !Current.isTrailingComment() &&
1046         !Current.isOneOf(tok::r_paren, tok::r_brace))
1047       return true;
1048 
1049     // If we need to break somewhere inside the LHS of a binary expression, we
1050     // should also break after the operator.
1051     if (Previous.Type == TT_BinaryOperator &&
1052         Current.Type != TT_BinaryOperator && // Special case for ">>".
1053         !Current.isTrailingComment() &&
1054         !Previous.isOneOf(tok::lessless, tok::question) &&
1055         Previous.getPrecedence() != prec::Assignment &&
1056         State.Stack.back().BreakBeforeParameter)
1057       return true;
1058 
1059     // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
1060     // out whether it is the first parameter. Clean this up.
1061     if (Current.Type == TT_ObjCSelectorName &&
1062         Current.LongestObjCSelectorName == 0 &&
1063         State.Stack.back().BreakBeforeParameter)
1064       return true;
1065     if ((Current.Type == TT_CtorInitializerColon ||
1066          (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0)))
1067       return true;
1068 
1069     if (Current.Type == TT_StartOfName && Line.MightBeFunctionDecl &&
1070         State.Stack.back().BreakBeforeParameter && State.ParenLevel == 0)
1071       return true;
1072     return false;
1073   }
1074 
1075   // Returns the total number of columns required for the remaining tokens.
1076   unsigned getRemainingLength(const LineState &State) {
1077     if (State.NextToken && State.NextToken->Previous)
1078       return Line.Last->TotalLength - State.NextToken->Previous->TotalLength;
1079     return 0;
1080   }
1081 
1082   FormatStyle Style;
1083   SourceManager &SourceMgr;
1084   const AnnotatedLine &Line;
1085   const unsigned FirstIndent;
1086   const FormatToken *RootToken;
1087   WhitespaceManager &Whitespaces;
1088 
1089   llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1090   QueueType Queue;
1091   // Increasing count of \c StateNode items we have created. This is used
1092   // to create a deterministic order independent of the container.
1093   unsigned Count;
1094   encoding::Encoding Encoding;
1095 };
1096 
1097 class FormatTokenLexer {
1098 public:
1099   FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr,
1100                    encoding::Encoding Encoding)
1101       : FormatTok(NULL), GreaterStashed(false), TrailingWhitespace(0), Lex(Lex),
1102         SourceMgr(SourceMgr), IdentTable(Lex.getLangOpts()),
1103         Encoding(Encoding) {
1104     Lex.SetKeepWhitespaceMode(true);
1105   }
1106 
1107   ArrayRef<FormatToken *> lex() {
1108     assert(Tokens.empty());
1109     do {
1110       Tokens.push_back(getNextToken());
1111     } while (Tokens.back()->Tok.isNot(tok::eof));
1112     return Tokens;
1113   }
1114 
1115   IdentifierTable &getIdentTable() { return IdentTable; }
1116 
1117 private:
1118   FormatToken *getNextToken() {
1119     if (GreaterStashed) {
1120       // Create a synthesized second '>' token.
1121       Token Greater = FormatTok->Tok;
1122       FormatTok = new (Allocator.Allocate()) FormatToken;
1123       FormatTok->Tok = Greater;
1124       SourceLocation GreaterLocation =
1125           FormatTok->Tok.getLocation().getLocWithOffset(1);
1126       FormatTok->WhitespaceRange =
1127           SourceRange(GreaterLocation, GreaterLocation);
1128       FormatTok->TokenText = ">";
1129       FormatTok->CodePointCount = 1;
1130       GreaterStashed = false;
1131       return FormatTok;
1132     }
1133 
1134     FormatTok = new (Allocator.Allocate()) FormatToken;
1135     Lex.LexFromRawLexer(FormatTok->Tok);
1136     StringRef Text = rawTokenText(FormatTok->Tok);
1137     SourceLocation WhitespaceStart =
1138         FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
1139     if (SourceMgr.getFileOffset(WhitespaceStart) == 0)
1140       FormatTok->IsFirst = true;
1141 
1142     // Consume and record whitespace until we find a significant token.
1143     unsigned WhitespaceLength = TrailingWhitespace;
1144     while (FormatTok->Tok.is(tok::unknown)) {
1145       unsigned Newlines = Text.count('\n');
1146       if (Newlines > 0)
1147         FormatTok->LastNewlineOffset = WhitespaceLength + Text.rfind('\n') + 1;
1148       FormatTok->NewlinesBefore += Newlines;
1149       unsigned EscapedNewlines = Text.count("\\\n");
1150       FormatTok->HasUnescapedNewline |= EscapedNewlines != Newlines;
1151       WhitespaceLength += FormatTok->Tok.getLength();
1152 
1153       Lex.LexFromRawLexer(FormatTok->Tok);
1154       Text = rawTokenText(FormatTok->Tok);
1155     }
1156 
1157     // In case the token starts with escaped newlines, we want to
1158     // take them into account as whitespace - this pattern is quite frequent
1159     // in macro definitions.
1160     // FIXME: What do we want to do with other escaped spaces, and escaped
1161     // spaces or newlines in the middle of tokens?
1162     // FIXME: Add a more explicit test.
1163     while (Text.size() > 1 && Text[0] == '\\' && Text[1] == '\n') {
1164       // FIXME: ++FormatTok->NewlinesBefore is missing...
1165       WhitespaceLength += 2;
1166       Text = Text.substr(2);
1167     }
1168 
1169     TrailingWhitespace = 0;
1170     if (FormatTok->Tok.is(tok::comment)) {
1171       StringRef UntrimmedText = Text;
1172       Text = Text.rtrim();
1173       TrailingWhitespace = UntrimmedText.size() - Text.size();
1174     } else if (FormatTok->Tok.is(tok::raw_identifier)) {
1175       IdentifierInfo &Info = IdentTable.get(Text);
1176       FormatTok->Tok.setIdentifierInfo(&Info);
1177       FormatTok->Tok.setKind(Info.getTokenID());
1178     } else if (FormatTok->Tok.is(tok::greatergreater)) {
1179       FormatTok->Tok.setKind(tok::greater);
1180       Text = Text.substr(0, 1);
1181       GreaterStashed = true;
1182     }
1183 
1184     // Now FormatTok is the next non-whitespace token.
1185     FormatTok->TokenText = Text;
1186     FormatTok->CodePointCount = encoding::getCodePointCount(Text, Encoding);
1187 
1188     FormatTok->WhitespaceRange = SourceRange(
1189         WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1190     return FormatTok;
1191   }
1192 
1193   FormatToken *FormatTok;
1194   bool GreaterStashed;
1195   unsigned TrailingWhitespace;
1196   Lexer &Lex;
1197   SourceManager &SourceMgr;
1198   IdentifierTable IdentTable;
1199   encoding::Encoding Encoding;
1200   llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
1201   SmallVector<FormatToken *, 16> Tokens;
1202 
1203   /// Returns the text of \c FormatTok.
1204   StringRef rawTokenText(Token &Tok) {
1205     return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1206                      Tok.getLength());
1207   }
1208 };
1209 
1210 class Formatter : public UnwrappedLineConsumer {
1211 public:
1212   Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1213             const std::vector<CharSourceRange> &Ranges)
1214       : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
1215         Whitespaces(SourceMgr, Style), Ranges(Ranges),
1216         Encoding(encoding::detectEncoding(Lex.getBuffer())) {
1217     DEBUG(llvm::dbgs()
1218           << "File encoding: "
1219           << (Encoding == encoding::Encoding_UTF8 ? "UTF8" : "unknown")
1220           << "\n");
1221   }
1222 
1223   virtual ~Formatter() {}
1224 
1225   tooling::Replacements format() {
1226     FormatTokenLexer Tokens(Lex, SourceMgr, Encoding);
1227 
1228     UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
1229     bool StructuralError = Parser.parse();
1230     TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
1231     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1232       Annotator.annotate(AnnotatedLines[i]);
1233     }
1234     deriveLocalStyle();
1235     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1236       Annotator.calculateFormattingInformation(AnnotatedLines[i]);
1237     }
1238 
1239     // Adapt level to the next line if this is a comment.
1240     // FIXME: Can/should this be done in the UnwrappedLineParser?
1241     const AnnotatedLine *NextNoneCommentLine = NULL;
1242     for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
1243       if (NextNoneCommentLine && AnnotatedLines[i].First->is(tok::comment) &&
1244           !AnnotatedLines[i].First->Next)
1245         AnnotatedLines[i].Level = NextNoneCommentLine->Level;
1246       else
1247         NextNoneCommentLine =
1248             AnnotatedLines[i].First->isNot(tok::r_brace) ? &AnnotatedLines[i]
1249                                                          : NULL;
1250     }
1251 
1252     std::vector<int> IndentForLevel;
1253     bool PreviousLineWasTouched = false;
1254     const FormatToken *PreviousLineLastToken = 0;
1255     bool FormatPPDirective = false;
1256     for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1257                                               E = AnnotatedLines.end();
1258          I != E; ++I) {
1259       const AnnotatedLine &TheLine = *I;
1260       const FormatToken *FirstTok = TheLine.First;
1261       int Offset = getIndentOffset(*TheLine.First);
1262 
1263       // Check whether this line is part of a formatted preprocessor directive.
1264       if (FirstTok->HasUnescapedNewline)
1265         FormatPPDirective = false;
1266       if (!FormatPPDirective && TheLine.InPPDirective &&
1267           (touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
1268         FormatPPDirective = true;
1269 
1270       // Determine indent and try to merge multiple unwrapped lines.
1271       while (IndentForLevel.size() <= TheLine.Level)
1272         IndentForLevel.push_back(-1);
1273       IndentForLevel.resize(TheLine.Level + 1);
1274       unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
1275       if (static_cast<int>(Indent) + Offset >= 0)
1276         Indent += Offset;
1277       tryFitMultipleLinesInOne(Indent, I, E);
1278 
1279       bool WasMoved = PreviousLineWasTouched && FirstTok->NewlinesBefore == 0;
1280       if (TheLine.First->is(tok::eof)) {
1281         if (PreviousLineWasTouched) {
1282           unsigned NewLines = std::min(FirstTok->NewlinesBefore, 1u);
1283           Whitespaces.replaceWhitespace(*TheLine.First, NewLines, /*Indent*/ 0,
1284                                         /*TargetColumn*/ 0);
1285         }
1286       } else if (TheLine.Type != LT_Invalid &&
1287                  (WasMoved || FormatPPDirective || touchesLine(TheLine))) {
1288         unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
1289         if (FirstTok->WhitespaceRange.isValid() &&
1290             // Insert a break even if there is a structural error in case where
1291             // we break apart a line consisting of multiple unwrapped lines.
1292             (FirstTok->NewlinesBefore == 0 || !StructuralError)) {
1293           formatFirstToken(*TheLine.First, PreviousLineLastToken, Indent,
1294                            TheLine.InPPDirective);
1295         } else {
1296           Indent = LevelIndent =
1297               SourceMgr.getSpellingColumnNumber(FirstTok->Tok.getLocation()) -
1298               1;
1299         }
1300         UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
1301                                          TheLine.First, Whitespaces, Encoding);
1302         Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
1303         IndentForLevel[TheLine.Level] = LevelIndent;
1304         PreviousLineWasTouched = true;
1305       } else {
1306         // Format the first token if necessary, and notify the WhitespaceManager
1307         // about the unchanged whitespace.
1308         for (const FormatToken *Tok = TheLine.First; Tok != NULL;
1309              Tok = Tok->Next) {
1310           if (Tok == TheLine.First &&
1311               (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
1312             unsigned LevelIndent =
1313                 SourceMgr.getSpellingColumnNumber(Tok->Tok.getLocation()) - 1;
1314             // Remove trailing whitespace of the previous line if it was
1315             // touched.
1316             if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine)) {
1317               formatFirstToken(*Tok, PreviousLineLastToken, LevelIndent,
1318                                TheLine.InPPDirective);
1319             } else {
1320               Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
1321             }
1322 
1323             if (static_cast<int>(LevelIndent) - Offset >= 0)
1324               LevelIndent -= Offset;
1325             if (Tok->isNot(tok::comment))
1326               IndentForLevel[TheLine.Level] = LevelIndent;
1327           } else {
1328             Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
1329           }
1330         }
1331         // If we did not reformat this unwrapped line, the column at the end of
1332         // the last token is unchanged - thus, we can calculate the end of the
1333         // last token.
1334         PreviousLineWasTouched = false;
1335       }
1336       PreviousLineLastToken = I->Last;
1337     }
1338     return Whitespaces.generateReplacements();
1339   }
1340 
1341 private:
1342   void deriveLocalStyle() {
1343     unsigned CountBoundToVariable = 0;
1344     unsigned CountBoundToType = 0;
1345     bool HasCpp03IncompatibleFormat = false;
1346     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1347       if (!AnnotatedLines[i].First->Next)
1348         continue;
1349       FormatToken *Tok = AnnotatedLines[i].First->Next;
1350       while (Tok->Next) {
1351         if (Tok->Type == TT_PointerOrReference) {
1352           bool SpacesBefore =
1353               Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1354           bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1355                              Tok->Next->WhitespaceRange.getEnd();
1356           if (SpacesBefore && !SpacesAfter)
1357             ++CountBoundToVariable;
1358           else if (!SpacesBefore && SpacesAfter)
1359             ++CountBoundToType;
1360         }
1361 
1362         if (Tok->Type == TT_TemplateCloser &&
1363             Tok->Previous->Type == TT_TemplateCloser &&
1364             Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd())
1365           HasCpp03IncompatibleFormat = true;
1366         Tok = Tok->Next;
1367       }
1368     }
1369     if (Style.DerivePointerBinding) {
1370       if (CountBoundToType > CountBoundToVariable)
1371         Style.PointerBindsToType = true;
1372       else if (CountBoundToType < CountBoundToVariable)
1373         Style.PointerBindsToType = false;
1374     }
1375     if (Style.Standard == FormatStyle::LS_Auto) {
1376       Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1377                                                   : FormatStyle::LS_Cpp03;
1378     }
1379   }
1380 
1381   /// \brief Get the indent of \p Level from \p IndentForLevel.
1382   ///
1383   /// \p IndentForLevel must contain the indent for the level \c l
1384   /// at \p IndentForLevel[l], or a value < 0 if the indent for
1385   /// that level is unknown.
1386   unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
1387     if (IndentForLevel[Level] != -1)
1388       return IndentForLevel[Level];
1389     if (Level == 0)
1390       return 0;
1391     return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
1392   }
1393 
1394   /// \brief Get the offset of the line relatively to the level.
1395   ///
1396   /// For example, 'public:' labels in classes are offset by 1 or 2
1397   /// characters to the left from their level.
1398   int getIndentOffset(const FormatToken &RootToken) {
1399     if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
1400       return Style.AccessModifierOffset;
1401     return 0;
1402   }
1403 
1404   /// \brief Tries to merge lines into one.
1405   ///
1406   /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1407   /// if possible; note that \c I will be incremented when lines are merged.
1408   void tryFitMultipleLinesInOne(unsigned Indent,
1409                                 std::vector<AnnotatedLine>::iterator &I,
1410                                 std::vector<AnnotatedLine>::iterator E) {
1411     // We can never merge stuff if there are trailing line comments.
1412     if (I->Last->Type == TT_LineComment)
1413       return;
1414 
1415     unsigned Limit = Style.ColumnLimit - Indent;
1416     // If we already exceed the column limit, we set 'Limit' to 0. The different
1417     // tryMerge..() functions can then decide whether to still do merging.
1418     Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
1419 
1420     if (I + 1 == E || (I + 1)->Type == LT_Invalid)
1421       return;
1422 
1423     if (I->Last->is(tok::l_brace)) {
1424       tryMergeSimpleBlock(I, E, Limit);
1425     } else if (Style.AllowShortIfStatementsOnASingleLine &&
1426                I->First->is(tok::kw_if)) {
1427       tryMergeSimpleControlStatement(I, E, Limit);
1428     } else if (Style.AllowShortLoopsOnASingleLine &&
1429                I->First->isOneOf(tok::kw_for, tok::kw_while)) {
1430       tryMergeSimpleControlStatement(I, E, Limit);
1431     } else if (I->InPPDirective &&
1432                (I->First->HasUnescapedNewline || I->First->IsFirst)) {
1433       tryMergeSimplePPDirective(I, E, Limit);
1434     }
1435   }
1436 
1437   void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1438                                  std::vector<AnnotatedLine>::iterator E,
1439                                  unsigned Limit) {
1440     if (Limit == 0)
1441       return;
1442     AnnotatedLine &Line = *I;
1443     if (!(I + 1)->InPPDirective || (I + 1)->First->HasUnescapedNewline)
1444       return;
1445     if (I + 2 != E && (I + 2)->InPPDirective &&
1446         !(I + 2)->First->HasUnescapedNewline)
1447       return;
1448     if (1 + (I + 1)->Last->TotalLength > Limit)
1449       return;
1450     join(Line, *(++I));
1451   }
1452 
1453   void tryMergeSimpleControlStatement(std::vector<AnnotatedLine>::iterator &I,
1454                                       std::vector<AnnotatedLine>::iterator E,
1455                                       unsigned Limit) {
1456     if (Limit == 0)
1457       return;
1458     if ((I + 1)->InPPDirective != I->InPPDirective ||
1459         ((I + 1)->InPPDirective && (I + 1)->First->HasUnescapedNewline))
1460       return;
1461     AnnotatedLine &Line = *I;
1462     if (Line.Last->isNot(tok::r_paren))
1463       return;
1464     if (1 + (I + 1)->Last->TotalLength > Limit)
1465       return;
1466     if ((I + 1)->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
1467                                 tok::kw_while) ||
1468         (I + 1)->First->Type == TT_LineComment)
1469       return;
1470     // Only inline simple if's (no nested if or else).
1471     if (I + 2 != E && Line.First->is(tok::kw_if) &&
1472         (I + 2)->First->is(tok::kw_else))
1473       return;
1474     join(Line, *(++I));
1475   }
1476 
1477   void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
1478                            std::vector<AnnotatedLine>::iterator E,
1479                            unsigned Limit) {
1480     // No merging if the brace already is on the next line.
1481     if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
1482       return;
1483 
1484     // First, check that the current line allows merging. This is the case if
1485     // we're not in a control flow statement and the last token is an opening
1486     // brace.
1487     AnnotatedLine &Line = *I;
1488     if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1489                             tok::kw_else, tok::kw_try, tok::kw_catch,
1490                             tok::kw_for,
1491                             // This gets rid of all ObjC @ keywords and methods.
1492                             tok::at, tok::minus, tok::plus))
1493       return;
1494 
1495     FormatToken *Tok = (I + 1)->First;
1496     if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
1497         (Tok->getNextNoneComment() == NULL ||
1498          Tok->getNextNoneComment()->is(tok::semi))) {
1499       // We merge empty blocks even if the line exceeds the column limit.
1500       Tok->SpacesRequiredBefore = 0;
1501       Tok->CanBreakBefore = true;
1502       join(Line, *(I + 1));
1503       I += 1;
1504     } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
1505       // Check that we still have three lines and they fit into the limit.
1506       if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1507           !nextTwoLinesFitInto(I, Limit))
1508         return;
1509 
1510       // Second, check that the next line does not contain any braces - if it
1511       // does, readability declines when putting it into a single line.
1512       if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1513         return;
1514       do {
1515         if (Tok->isOneOf(tok::l_brace, tok::r_brace))
1516           return;
1517         Tok = Tok->Next;
1518       } while (Tok != NULL);
1519 
1520       // Last, check that the third line contains a single closing brace.
1521       Tok = (I + 2)->First;
1522       if (Tok->getNextNoneComment() != NULL || Tok->isNot(tok::r_brace) ||
1523           Tok->MustBreakBefore)
1524         return;
1525 
1526       join(Line, *(I + 1));
1527       join(Line, *(I + 2));
1528       I += 2;
1529     }
1530   }
1531 
1532   bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1533                            unsigned Limit) {
1534     return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1535            Limit;
1536   }
1537 
1538   void join(AnnotatedLine &A, const AnnotatedLine &B) {
1539     assert(!A.Last->Next);
1540     assert(!B.First->Previous);
1541     A.Last->Next = B.First;
1542     B.First->Previous = A.Last;
1543     unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1544     for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1545       Tok->TotalLength += LengthA;
1546       A.Last = Tok;
1547     }
1548   }
1549 
1550   bool touchesRanges(const CharSourceRange &Range) {
1551     for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1552       if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1553                                                Ranges[i].getBegin()) &&
1554           !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1555                                                Range.getBegin()))
1556         return true;
1557     }
1558     return false;
1559   }
1560 
1561   bool touchesLine(const AnnotatedLine &TheLine) {
1562     const FormatToken *First = TheLine.First;
1563     const FormatToken *Last = TheLine.Last;
1564     CharSourceRange LineRange = CharSourceRange::getCharRange(
1565         First->WhitespaceRange.getBegin().getLocWithOffset(
1566             First->LastNewlineOffset),
1567         Last->Tok.getLocation().getLocWithOffset(Last->TokenText.size() - 1));
1568     return touchesRanges(LineRange);
1569   }
1570 
1571   bool touchesPPDirective(std::vector<AnnotatedLine>::iterator I,
1572                           std::vector<AnnotatedLine>::iterator E) {
1573     for (; I != E; ++I) {
1574       if (I->First->HasUnescapedNewline)
1575         return false;
1576       if (touchesLine(*I))
1577         return true;
1578     }
1579     return false;
1580   }
1581 
1582   bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
1583     const FormatToken *First = TheLine.First;
1584     CharSourceRange LineRange = CharSourceRange::getCharRange(
1585         First->WhitespaceRange.getBegin(),
1586         First->WhitespaceRange.getBegin().getLocWithOffset(
1587             First->LastNewlineOffset));
1588     return touchesRanges(LineRange);
1589   }
1590 
1591   virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
1592     AnnotatedLines.push_back(AnnotatedLine(TheLine));
1593   }
1594 
1595   /// \brief Add a new line and the required indent before the first Token
1596   /// of the \c UnwrappedLine if there was no structural parsing error.
1597   /// Returns the indent level of the \c UnwrappedLine.
1598   void formatFirstToken(const FormatToken &RootToken,
1599                         const FormatToken *PreviousToken, unsigned Indent,
1600                         bool InPPDirective) {
1601     unsigned Newlines =
1602         std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1603     // Remove empty lines before "}" where applicable.
1604     if (RootToken.is(tok::r_brace) &&
1605         (!RootToken.Next ||
1606          (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1607       Newlines = std::min(Newlines, 1u);
1608     if (Newlines == 0 && !RootToken.IsFirst)
1609       Newlines = 1;
1610 
1611     // Insert extra new line before access specifiers.
1612     if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
1613         RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
1614       ++Newlines;
1615 
1616     Whitespaces.replaceWhitespace(
1617         RootToken, Newlines, Indent, Indent,
1618         InPPDirective && !RootToken.HasUnescapedNewline);
1619   }
1620 
1621   FormatStyle Style;
1622   Lexer &Lex;
1623   SourceManager &SourceMgr;
1624   WhitespaceManager Whitespaces;
1625   std::vector<CharSourceRange> Ranges;
1626   std::vector<AnnotatedLine> AnnotatedLines;
1627 
1628   encoding::Encoding Encoding;
1629 };
1630 
1631 tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1632                                SourceManager &SourceMgr,
1633                                std::vector<CharSourceRange> Ranges) {
1634   Formatter formatter(Style, Lex, SourceMgr, Ranges);
1635   return formatter.format();
1636 }
1637 
1638 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1639                                std::vector<tooling::Range> Ranges,
1640                                StringRef FileName) {
1641   FileManager Files((FileSystemOptions()));
1642   DiagnosticsEngine Diagnostics(
1643       IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1644       new DiagnosticOptions);
1645   SourceManager SourceMgr(Diagnostics, Files);
1646   llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1647   const clang::FileEntry *Entry =
1648       Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1649   SourceMgr.overrideFileContents(Entry, Buf);
1650   FileID ID =
1651       SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
1652   Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr, getFormattingLangOpts());
1653   SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1654   std::vector<CharSourceRange> CharRanges;
1655   for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1656     SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1657     SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1658     CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1659   }
1660   return reformat(Style, Lex, SourceMgr, CharRanges);
1661 }
1662 
1663 LangOptions getFormattingLangOpts() {
1664   LangOptions LangOpts;
1665   LangOpts.CPlusPlus = 1;
1666   LangOpts.CPlusPlus11 = 1;
1667   LangOpts.LineComment = 1;
1668   LangOpts.Bool = 1;
1669   LangOpts.ObjC1 = 1;
1670   LangOpts.ObjC2 = 1;
1671   return LangOpts;
1672 }
1673 
1674 } // namespace format
1675 } // namespace clang
1676