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