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