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/Frontend/TextDiagnosticPrinter.h"
27 #include "clang/Lex/Lexer.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/Support/Allocator.h"
30 #include "llvm/Support/Debug.h"
31 #include <queue>
32 #include <string>
33 
34 namespace clang {
35 namespace format {
36 
37 FormatStyle getLLVMStyle() {
38   FormatStyle LLVMStyle;
39   LLVMStyle.ColumnLimit = 80;
40   LLVMStyle.MaxEmptyLinesToKeep = 1;
41   LLVMStyle.PointerBindsToType = false;
42   LLVMStyle.DerivePointerBinding = false;
43   LLVMStyle.AccessModifierOffset = -2;
44   LLVMStyle.Standard = FormatStyle::LS_Cpp03;
45   LLVMStyle.IndentCaseLabels = false;
46   LLVMStyle.SpacesBeforeTrailingComments = 1;
47   LLVMStyle.BinPackParameters = true;
48   LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
49   LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
50   LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
51   LLVMStyle.ObjCSpaceBeforeProtocolList = true;
52   LLVMStyle.PenaltyExcessCharacter = 1000000;
53   LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 75;
54   return LLVMStyle;
55 }
56 
57 FormatStyle getGoogleStyle() {
58   FormatStyle GoogleStyle;
59   GoogleStyle.ColumnLimit = 80;
60   GoogleStyle.MaxEmptyLinesToKeep = 1;
61   GoogleStyle.PointerBindsToType = true;
62   GoogleStyle.DerivePointerBinding = true;
63   GoogleStyle.AccessModifierOffset = -1;
64   GoogleStyle.Standard = FormatStyle::LS_Auto;
65   GoogleStyle.IndentCaseLabels = true;
66   GoogleStyle.SpacesBeforeTrailingComments = 2;
67   GoogleStyle.BinPackParameters = true;
68   GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
69   GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
70   GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
71   GoogleStyle.ObjCSpaceBeforeProtocolList = false;
72   GoogleStyle.PenaltyExcessCharacter = 1000000;
73   GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
74   return GoogleStyle;
75 }
76 
77 FormatStyle getChromiumStyle() {
78   FormatStyle ChromiumStyle = getGoogleStyle();
79   ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
80   ChromiumStyle.BinPackParameters = false;
81   ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
82   ChromiumStyle.DerivePointerBinding = false;
83   return ChromiumStyle;
84 }
85 
86 // Returns the length of everything up to the first possible line break after
87 // the ), ], } or > matching \c Tok.
88 static unsigned getLengthToMatchingParen(const AnnotatedToken &Tok) {
89   if (Tok.MatchingParen == NULL)
90     return 0;
91   AnnotatedToken *End = Tok.MatchingParen;
92   while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
93     End = &End->Children[0];
94   }
95   return End->TotalLength - Tok.TotalLength + 1;
96 }
97 
98 class UnwrappedLineFormatter {
99 public:
100   UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
101                          const AnnotatedLine &Line, unsigned FirstIndent,
102                          const AnnotatedToken &RootToken,
103                          WhitespaceManager &Whitespaces)
104       : Style(Style), SourceMgr(SourceMgr), Line(Line),
105         FirstIndent(FirstIndent), RootToken(RootToken),
106         Whitespaces(Whitespaces), Count(0) {}
107 
108   /// \brief Formats an \c UnwrappedLine.
109   ///
110   /// \returns The column after the last token in the last line of the
111   /// \c UnwrappedLine.
112   unsigned format(const AnnotatedLine *NextLine) {
113     // Initialize state dependent on indent.
114     LineState State;
115     State.Column = FirstIndent;
116     State.NextToken = &RootToken;
117     State.Stack.push_back(
118         ParenState(FirstIndent, FirstIndent, !Style.BinPackParameters,
119                    /*HasMultiParameterLine=*/ false));
120     State.LineContainsContinuedForLoopSection = false;
121     State.ParenLevel = 0;
122     State.StartOfStringLiteral = 0;
123     State.StartOfLineLevel = State.ParenLevel;
124 
125     // The first token has already been indented and thus consumed.
126     moveStateToNextToken(State, /*DryRun=*/ false);
127 
128     // If everything fits on a single line, just put it there.
129     unsigned ColumnLimit = Style.ColumnLimit;
130     if (NextLine && NextLine->InPPDirective &&
131         !NextLine->First.FormatTok.HasUnescapedNewline)
132       ColumnLimit = getColumnLimit();
133     if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
134       while (State.NextToken != NULL) {
135         addTokenToState(false, false, State);
136       }
137       return State.Column;
138     }
139 
140     // If the ObjC method declaration does not fit on a line, we should format
141     // it with one arg per line.
142     if (Line.Type == LT_ObjCMethodDecl)
143       State.Stack.back().BreakBeforeParameter = true;
144 
145     // Find best solution in solution space.
146     return analyzeSolutionSpace(State);
147   }
148 
149 private:
150   void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
151     const Token &Tok = AnnotatedTok.FormatTok.Tok;
152     llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
153                               Tok.getLength());
154     llvm::errs();
155   }
156 
157   struct ParenState {
158     ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
159                bool HasMultiParameterLine)
160         : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
161           BreakBeforeClosingBrace(false), QuestionColumn(0),
162           AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
163           HasMultiParameterLine(HasMultiParameterLine), ColonPos(0),
164           StartOfFunctionCall(0), NestedNameSpecifierContinuation(0),
165           CallContinuation(0), VariablePos(0) {}
166 
167     /// \brief The position to which a specific parenthesis level needs to be
168     /// indented.
169     unsigned Indent;
170 
171     /// \brief The position of the last space on each level.
172     ///
173     /// Used e.g. to break like:
174     /// functionCall(Parameter, otherCall(
175     ///                             OtherParameter));
176     unsigned LastSpace;
177 
178     /// \brief The position the first "<<" operator encountered on each level.
179     ///
180     /// Used to align "<<" operators. 0 if no such operator has been encountered
181     /// on a level.
182     unsigned FirstLessLess;
183 
184     /// \brief Whether a newline needs to be inserted before the block's closing
185     /// brace.
186     ///
187     /// We only want to insert a newline before the closing brace if there also
188     /// was a newline after the beginning left brace.
189     bool BreakBeforeClosingBrace;
190 
191     /// \brief The column of a \c ? in a conditional expression;
192     unsigned QuestionColumn;
193 
194     /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
195     /// lines, in this context.
196     bool AvoidBinPacking;
197 
198     /// \brief Break after the next comma (or all the commas in this context if
199     /// \c AvoidBinPacking is \c true).
200     bool BreakBeforeParameter;
201 
202     /// \brief This context already has a line with more than one parameter.
203     bool HasMultiParameterLine;
204 
205     /// \brief The position of the colon in an ObjC method declaration/call.
206     unsigned ColonPos;
207 
208     /// \brief The start of the most recent function in a builder-type call.
209     unsigned StartOfFunctionCall;
210 
211     /// \brief If a nested name specifier was broken over multiple lines, this
212     /// contains the start column of the second line. Otherwise 0.
213     unsigned NestedNameSpecifierContinuation;
214 
215     /// \brief If a call expression was broken over multiple lines, this
216     /// contains the start column of the second line. Otherwise 0.
217     unsigned CallContinuation;
218 
219     /// \brief The column of the first variable name in a variable declaration.
220     ///
221     /// Used to align further variables if necessary.
222     unsigned VariablePos;
223 
224     bool operator<(const ParenState &Other) const {
225       if (Indent != Other.Indent)
226         return Indent < Other.Indent;
227       if (LastSpace != Other.LastSpace)
228         return LastSpace < Other.LastSpace;
229       if (FirstLessLess != Other.FirstLessLess)
230         return FirstLessLess < Other.FirstLessLess;
231       if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
232         return BreakBeforeClosingBrace;
233       if (QuestionColumn != Other.QuestionColumn)
234         return QuestionColumn < Other.QuestionColumn;
235       if (AvoidBinPacking != Other.AvoidBinPacking)
236         return AvoidBinPacking;
237       if (BreakBeforeParameter != Other.BreakBeforeParameter)
238         return BreakBeforeParameter;
239       if (HasMultiParameterLine != Other.HasMultiParameterLine)
240         return HasMultiParameterLine;
241       if (ColonPos != Other.ColonPos)
242         return ColonPos < Other.ColonPos;
243       if (StartOfFunctionCall != Other.StartOfFunctionCall)
244         return StartOfFunctionCall < Other.StartOfFunctionCall;
245       if (NestedNameSpecifierContinuation !=
246           Other.NestedNameSpecifierContinuation)
247         return NestedNameSpecifierContinuation <
248                Other.NestedNameSpecifierContinuation;
249       if (CallContinuation != Other.CallContinuation)
250         return CallContinuation < Other.CallContinuation;
251       if (VariablePos != Other.VariablePos)
252         return VariablePos < Other.VariablePos;
253       return false;
254     }
255   };
256 
257   /// \brief The current state when indenting a unwrapped line.
258   ///
259   /// As the indenting tries different combinations this is copied by value.
260   struct LineState {
261     /// \brief The number of used columns in the current line.
262     unsigned Column;
263 
264     /// \brief The token that needs to be next formatted.
265     const AnnotatedToken *NextToken;
266 
267     /// \brief \c true if this line contains a continued for-loop section.
268     bool LineContainsContinuedForLoopSection;
269 
270     /// \brief The level of nesting inside (), [], <> and {}.
271     unsigned ParenLevel;
272 
273     /// \brief The \c ParenLevel at the start of this line.
274     unsigned StartOfLineLevel;
275 
276     /// \brief The start column of the string literal, if we're in a string
277     /// literal sequence, 0 otherwise.
278     unsigned StartOfStringLiteral;
279 
280     /// \brief A stack keeping track of properties applying to parenthesis
281     /// levels.
282     std::vector<ParenState> Stack;
283 
284     /// \brief Comparison operator to be able to used \c LineState in \c map.
285     bool operator<(const LineState &Other) const {
286       if (NextToken != Other.NextToken)
287         return NextToken < Other.NextToken;
288       if (Column != Other.Column)
289         return Column < Other.Column;
290       if (LineContainsContinuedForLoopSection !=
291           Other.LineContainsContinuedForLoopSection)
292         return LineContainsContinuedForLoopSection;
293       if (ParenLevel != Other.ParenLevel)
294         return ParenLevel < Other.ParenLevel;
295       if (StartOfLineLevel != Other.StartOfLineLevel)
296         return StartOfLineLevel < Other.StartOfLineLevel;
297       if (StartOfStringLiteral != Other.StartOfStringLiteral)
298         return StartOfStringLiteral < Other.StartOfStringLiteral;
299       return Stack < Other.Stack;
300     }
301   };
302 
303   /// \brief Appends the next token to \p State and updates information
304   /// necessary for indentation.
305   ///
306   /// Puts the token on the current line if \p Newline is \c true and adds a
307   /// line break and necessary indentation otherwise.
308   ///
309   /// If \p DryRun is \c false, also creates and stores the required
310   /// \c Replacement.
311   unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
312     const AnnotatedToken &Current = *State.NextToken;
313     const AnnotatedToken &Previous = *State.NextToken->Parent;
314 
315     if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
316       State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
317                       State.NextToken->FormatTok.TokenLength;
318       if (State.NextToken->Children.empty())
319         State.NextToken = NULL;
320       else
321         State.NextToken = &State.NextToken->Children[0];
322       return 0;
323     }
324 
325     // If we are continuing an expression, we want to indent an extra 4 spaces.
326     unsigned ContinuationIndent =
327         std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
328     if (Newline) {
329       unsigned WhitespaceStartColumn = State.Column;
330       if (Current.is(tok::r_brace)) {
331         State.Column = Line.Level * 2;
332       } else if (Current.is(tok::string_literal) &&
333                  State.StartOfStringLiteral != 0) {
334         State.Column = State.StartOfStringLiteral;
335         State.Stack.back().BreakBeforeParameter = true;
336       } else if (Current.is(tok::lessless) &&
337                  State.Stack.back().FirstLessLess != 0) {
338         State.Column = State.Stack.back().FirstLessLess;
339       } else if (Previous.is(tok::coloncolon)) {
340         if (State.Stack.back().NestedNameSpecifierContinuation == 0) {
341           State.Column = ContinuationIndent;
342           State.Stack.back().NestedNameSpecifierContinuation = State.Column;
343         } else {
344           State.Column = State.Stack.back().NestedNameSpecifierContinuation;
345         }
346       } else if (Current.isOneOf(tok::period, tok::arrow)) {
347         if (State.Stack.back().CallContinuation == 0) {
348           State.Column = ContinuationIndent;
349           State.Stack.back().CallContinuation = State.Column;
350         } else {
351           State.Column = State.Stack.back().CallContinuation;
352         }
353       } else if (Current.Type == TT_ConditionalExpr) {
354         State.Column = State.Stack.back().QuestionColumn;
355       } else if (Previous.is(tok::comma) &&
356                  State.Stack.back().VariablePos != 0) {
357         State.Column = State.Stack.back().VariablePos;
358       } else if (Previous.ClosesTemplateDeclaration ||
359                  (Current.Type == TT_StartOfName && State.ParenLevel == 0)) {
360         State.Column = State.Stack.back().Indent;
361       } else if (Current.Type == TT_ObjCSelectorName) {
362         if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
363           State.Column =
364               State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
365         } else {
366           State.Column = State.Stack.back().Indent;
367           State.Stack.back().ColonPos =
368               State.Column + Current.FormatTok.TokenLength;
369         }
370       } else if (Current.Type == TT_StartOfName || Previous.is(tok::equal) ||
371                  Previous.Type == TT_ObjCMethodExpr) {
372         State.Column = ContinuationIndent;
373       } else {
374         State.Column = State.Stack.back().Indent;
375         // Ensure that we fall back to indenting 4 spaces instead of just
376         // flushing continuations left.
377         if (State.Column == FirstIndent)
378           State.Column += 4;
379       }
380 
381       if (Current.is(tok::question))
382         State.Stack.back().BreakBeforeParameter = true;
383       if (Previous.isOneOf(tok::comma, tok::semi) &&
384           !State.Stack.back().AvoidBinPacking)
385         State.Stack.back().BreakBeforeParameter = false;
386 
387       if (!DryRun) {
388         unsigned NewLines = 1;
389         if (Current.Type == TT_LineComment)
390           NewLines =
391               std::max(NewLines, std::min(Current.FormatTok.NewlinesBefore,
392                                           Style.MaxEmptyLinesToKeep + 1));
393         if (!Line.InPPDirective)
394           Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
395                                         WhitespaceStartColumn);
396         else
397           Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
398                                           WhitespaceStartColumn);
399       }
400 
401       State.Stack.back().LastSpace = State.Column;
402       State.StartOfLineLevel = State.ParenLevel;
403 
404       // Any break on this level means that the parent level has been broken
405       // and we need to avoid bin packing there.
406       for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
407         State.Stack[i].BreakBeforeParameter = true;
408       }
409       const AnnotatedToken *TokenBefore = Current.getPreviousNoneComment();
410       if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
411           !TokenBefore->opensScope())
412         State.Stack.back().BreakBeforeParameter = true;
413 
414       // If we break after {, we should also break before the corresponding }.
415       if (Previous.is(tok::l_brace))
416         State.Stack.back().BreakBeforeClosingBrace = true;
417 
418       if (State.Stack.back().AvoidBinPacking) {
419         // If we are breaking after '(', '{', '<', this is not bin packing
420         // unless AllowAllParametersOfDeclarationOnNextLine is false.
421         if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace)) ||
422             (!Style.AllowAllParametersOfDeclarationOnNextLine &&
423              Line.MustBeDeclaration))
424           State.Stack.back().BreakBeforeParameter = true;
425       }
426     } else {
427       if (Current.is(tok::equal) &&
428           (RootToken.is(tok::kw_for) || State.ParenLevel == 0) &&
429           State.Stack.back().VariablePos == 0) {
430         State.Stack.back().VariablePos = State.Column;
431         // Move over * and & if they are bound to the variable name.
432         const AnnotatedToken *Tok = &Previous;
433         while (Tok &&
434                State.Stack.back().VariablePos >= Tok->FormatTok.TokenLength) {
435           State.Stack.back().VariablePos -= Tok->FormatTok.TokenLength;
436           if (Tok->SpacesRequiredBefore != 0)
437             break;
438           Tok = Tok->Parent;
439         }
440         if (Previous.PartOfMultiVariableDeclStmt)
441           State.Stack.back().LastSpace = State.Stack.back().VariablePos;
442       }
443 
444       unsigned Spaces = State.NextToken->SpacesRequiredBefore;
445 
446       if (!DryRun)
447         Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column);
448 
449       if (Current.Type == TT_ObjCSelectorName &&
450           State.Stack.back().ColonPos == 0) {
451         if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
452             State.Column + Spaces + Current.FormatTok.TokenLength)
453           State.Stack.back().ColonPos =
454               State.Stack.back().Indent + Current.LongestObjCSelectorName;
455         else
456           State.Stack.back().ColonPos =
457               State.Column + Spaces + Current.FormatTok.TokenLength;
458       }
459 
460       if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
461           Current.Type != TT_LineComment)
462         State.Stack.back().Indent = State.Column + Spaces;
463       if (Previous.is(tok::comma) && !Current.isTrailingComment())
464         State.Stack.back().HasMultiParameterLine = true;
465 
466       State.Column += Spaces;
467       if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
468         // Treat the condition inside an if as if it was a second function
469         // parameter, i.e. let nested calls have an indent of 4.
470         State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
471       else if (Previous.is(tok::comma))
472         State.Stack.back().LastSpace = State.Column;
473       else if ((Previous.Type == TT_BinaryOperator ||
474                 Previous.Type == TT_ConditionalExpr ||
475                 Previous.Type == TT_CtorInitializerColon) &&
476                getPrecedence(Previous) != prec::Assignment)
477         State.Stack.back().LastSpace = State.Column;
478       else if (Previous.Type == TT_InheritanceColon)
479         State.Stack.back().Indent = State.Column;
480       else if (Previous.opensScope() && Previous.ParameterCount > 1)
481         // If this function has multiple parameters, indent nested calls from
482         // the start of the first parameter.
483         State.Stack.back().LastSpace = State.Column;
484     }
485 
486     return moveStateToNextToken(State, DryRun);
487   }
488 
489   /// \brief Mark the next token as consumed in \p State and modify its stacks
490   /// accordingly.
491   unsigned moveStateToNextToken(LineState &State, bool DryRun) {
492     const AnnotatedToken &Current = *State.NextToken;
493     assert(State.Stack.size());
494 
495     if (Current.Type == TT_InheritanceColon)
496       State.Stack.back().AvoidBinPacking = true;
497     if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
498       State.Stack.back().FirstLessLess = State.Column;
499     if (Current.is(tok::question))
500       State.Stack.back().QuestionColumn = State.Column;
501     if (Current.isOneOf(tok::period, tok::arrow) &&
502         Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
503       State.Stack.back().StartOfFunctionCall =
504           Current.LastInChainOfCalls ? 0 : State.Column;
505     if (Current.Type == TT_CtorInitializerColon) {
506       State.Stack.back().Indent = State.Column + 2;
507       if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
508         State.Stack.back().AvoidBinPacking = true;
509       State.Stack.back().BreakBeforeParameter = false;
510     }
511 
512     // If return returns a binary expression, align after it.
513     if (Current.is(tok::kw_return) && !Current.FakeLParens.empty())
514       State.Stack.back().LastSpace = State.Column + 7;
515 
516     // In ObjC method declaration we align on the ":" of parameters, but we need
517     // to ensure that we indent parameters on subsequent lines by at least 4.
518     if (Current.Type == TT_ObjCMethodSpecifier)
519       State.Stack.back().Indent += 4;
520 
521     // Insert scopes created by fake parenthesis.
522     const AnnotatedToken *Previous = Current.getPreviousNoneComment();
523     // Don't add extra indentation for the first fake parenthesis after
524     // 'return', assignements or opening <({[. The indentation for these cases
525     // is special cased.
526     bool SkipFirstExtraIndent =
527         Current.is(tok::kw_return) ||
528         (Previous && (Previous->opensScope() ||
529                       getPrecedence(*Previous) == prec::Assignment));
530     for (SmallVector<prec::Level, 4>::const_reverse_iterator
531              I = Current.FakeLParens.rbegin(),
532              E = Current.FakeLParens.rend();
533          I != E; ++I) {
534       ParenState NewParenState = State.Stack.back();
535       NewParenState.Indent =
536           std::max(std::max(State.Column, NewParenState.Indent),
537                    State.Stack.back().LastSpace);
538 
539       // Always indent conditional expressions. Never indent expression where
540       // the 'operator' is ',', ';' or an assignment (i.e. *I <=
541       // prec::Assignment) as those have different indentation rules. Indent
542       // other expression, unless the indentation needs to be skipped.
543       if (*I == prec::Conditional ||
544           (!SkipFirstExtraIndent && *I > prec::Assignment))
545         NewParenState.Indent += 4;
546       if (Previous && !Previous->opensScope())
547         NewParenState.BreakBeforeParameter = false;
548       State.Stack.push_back(NewParenState);
549       SkipFirstExtraIndent = false;
550     }
551 
552     // If we encounter an opening (, [, { or <, we add a level to our stacks to
553     // prepare for the following tokens.
554     if (Current.opensScope()) {
555       unsigned NewIndent;
556       bool AvoidBinPacking;
557       if (Current.is(tok::l_brace)) {
558         NewIndent = 2 + State.Stack.back().LastSpace;
559         AvoidBinPacking = false;
560       } else {
561         NewIndent = 4 + std::max(State.Stack.back().LastSpace,
562                                  State.Stack.back().StartOfFunctionCall);
563         AvoidBinPacking =
564             !Style.BinPackParameters || State.Stack.back().AvoidBinPacking;
565       }
566       State.Stack.push_back(
567           ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
568                      State.Stack.back().HasMultiParameterLine));
569       ++State.ParenLevel;
570     }
571 
572     // If this '[' opens an ObjC call, determine whether all parameters fit into
573     // one line and put one per line if they don't.
574     if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
575         Current.MatchingParen != NULL) {
576       if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
577         State.Stack.back().BreakBeforeParameter = true;
578     }
579 
580     // If we encounter a closing ), ], } or >, we can remove a level from our
581     // stacks.
582     if (Current.isOneOf(tok::r_paren, tok::r_square) ||
583         (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
584         State.NextToken->Type == TT_TemplateCloser) {
585       State.Stack.pop_back();
586       --State.ParenLevel;
587     }
588 
589     // Remove scopes created by fake parenthesis.
590     for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
591       unsigned VariablePos = State.Stack.back().VariablePos;
592       State.Stack.pop_back();
593       State.Stack.back().VariablePos = VariablePos;
594     }
595 
596     if (Current.is(tok::string_literal)) {
597       State.StartOfStringLiteral = State.Column;
598     } else if (Current.isNot(tok::comment)) {
599       State.StartOfStringLiteral = 0;
600     }
601 
602     State.Column += Current.FormatTok.TokenLength;
603 
604     if (State.NextToken->Children.empty())
605       State.NextToken = NULL;
606     else
607       State.NextToken = &State.NextToken->Children[0];
608 
609     return breakProtrudingToken(Current, State, DryRun);
610   }
611 
612   /// \brief If the current token sticks out over the end of the line, break
613   /// it if possible.
614   unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
615                                 bool DryRun) {
616     llvm::OwningPtr<BreakableToken> Token;
617     unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
618     if (Current.is(tok::string_literal)) {
619       // Only break up default narrow strings.
620       const char *LiteralData = SourceMgr.getCharacterData(
621           Current.FormatTok.getStartOfNonWhitespace());
622       if (!LiteralData || *LiteralData != '"')
623         return 0;
624 
625       Token.reset(new BreakableStringLiteral(SourceMgr, Current.FormatTok,
626                                              StartColumn));
627     } else if (Current.Type == TT_BlockComment) {
628       BreakableBlockComment *BBC =
629           new BreakableBlockComment(SourceMgr, Current, StartColumn);
630       if (!DryRun)
631         BBC->alignLines(Whitespaces);
632       Token.reset(BBC);
633     } else if (Current.Type == TT_LineComment) {
634       Token.reset(new BreakableLineComment(SourceMgr, Current, StartColumn));
635     } else {
636       return 0;
637     }
638 
639     bool BreakInserted = false;
640     unsigned Penalty = 0;
641     for (unsigned LineIndex = 0; LineIndex < Token->getLineCount();
642          ++LineIndex) {
643       unsigned TailOffset = 0;
644       unsigned RemainingLength =
645           Token->getLineLengthAfterSplit(LineIndex, TailOffset);
646       while (RemainingLength > getColumnLimit()) {
647         BreakableToken::Split Split =
648             Token->getSplit(LineIndex, TailOffset, getColumnLimit());
649         if (Split.first == StringRef::npos)
650           break;
651         assert(Split.first != 0);
652         unsigned NewRemainingLength = Token->getLineLengthAfterSplit(
653             LineIndex, TailOffset + Split.first + Split.second);
654         if (NewRemainingLength >= RemainingLength)
655           break;
656         if (!DryRun) {
657           Token->insertBreak(LineIndex, TailOffset, Split, Line.InPPDirective,
658                              Whitespaces);
659         }
660         TailOffset += Split.first + Split.second;
661         RemainingLength = NewRemainingLength;
662         Penalty += Style.PenaltyExcessCharacter;
663         BreakInserted = true;
664       }
665       State.Column = RemainingLength;
666       if (!DryRun) {
667         Token->trimLine(LineIndex, TailOffset, Line.InPPDirective, Whitespaces);
668       }
669     }
670 
671     if (BreakInserted) {
672       for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
673         State.Stack[i].BreakBeforeParameter = true;
674       State.Stack.back().LastSpace = StartColumn;
675     }
676     return Penalty;
677   }
678 
679   unsigned getColumnLimit() {
680     // In preprocessor directives reserve two chars for trailing " \"
681     return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
682   }
683 
684   /// \brief An edge in the solution space from \c Previous->State to \c State,
685   /// inserting a newline dependent on the \c NewLine.
686   struct StateNode {
687     StateNode(const LineState &State, bool NewLine, StateNode *Previous)
688         : State(State), NewLine(NewLine), Previous(Previous) {}
689     LineState State;
690     bool NewLine;
691     StateNode *Previous;
692   };
693 
694   /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
695   ///
696   /// In case of equal penalties, we want to prefer states that were inserted
697   /// first. During state generation we make sure that we insert states first
698   /// that break the line as late as possible.
699   typedef std::pair<unsigned, unsigned> OrderedPenalty;
700 
701   /// \brief An item in the prioritized BFS search queue. The \c StateNode's
702   /// \c State has the given \c OrderedPenalty.
703   typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
704 
705   /// \brief The BFS queue type.
706   typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
707                               std::greater<QueueItem> > QueueType;
708 
709   /// \brief Analyze the entire solution space starting from \p InitialState.
710   ///
711   /// This implements a variant of Dijkstra's algorithm on the graph that spans
712   /// the solution space (\c LineStates are the nodes). The algorithm tries to
713   /// find the shortest path (the one with lowest penalty) from \p InitialState
714   /// to a state where all tokens are placed.
715   unsigned analyzeSolutionSpace(LineState &InitialState) {
716     std::set<LineState> Seen;
717 
718     // Insert start element into queue.
719     StateNode *Node =
720         new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
721     Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
722     ++Count;
723 
724     // While not empty, take first element and follow edges.
725     while (!Queue.empty()) {
726       unsigned Penalty = Queue.top().first.first;
727       StateNode *Node = Queue.top().second;
728       if (Node->State.NextToken == NULL) {
729         DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
730         break;
731       }
732       Queue.pop();
733 
734       if (!Seen.insert(Node->State).second)
735         // State already examined with lower penalty.
736         continue;
737 
738       addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
739       addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
740     }
741 
742     if (Queue.empty())
743       // We were unable to find a solution, do nothing.
744       // FIXME: Add diagnostic?
745       return 0;
746 
747     // Reconstruct the solution.
748     reconstructPath(InitialState, Queue.top().second);
749     DEBUG(llvm::errs() << "---\n");
750 
751     // Return the column after the last token of the solution.
752     return Queue.top().second->State.Column;
753   }
754 
755   void reconstructPath(LineState &State, StateNode *Current) {
756     // FIXME: This recursive implementation limits the possible number
757     // of tokens per line if compiled into a binary with small stack space.
758     // To become more independent of stack frame limitations we would need
759     // to also change the TokenAnnotator.
760     if (Current->Previous == NULL)
761       return;
762     reconstructPath(State, Current->Previous);
763     DEBUG({
764       if (Current->NewLine) {
765         llvm::errs()
766             << "Penalty for splitting before "
767             << Current->Previous->State.NextToken->FormatTok.Tok.getName()
768             << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
769       }
770     });
771     addTokenToState(Current->NewLine, false, State);
772   }
773 
774   /// \brief Add the following state to the analysis queue \c Queue.
775   ///
776   /// Assume the current state is \p PreviousNode and has been reached with a
777   /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
778   void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
779                            bool NewLine) {
780     if (NewLine && !canBreak(PreviousNode->State))
781       return;
782     if (!NewLine && mustBreak(PreviousNode->State))
783       return;
784     if (NewLine)
785       Penalty += PreviousNode->State.NextToken->SplitPenalty;
786 
787     StateNode *Node = new (Allocator.Allocate())
788         StateNode(PreviousNode->State, NewLine, PreviousNode);
789     Penalty += addTokenToState(NewLine, true, Node->State);
790     if (Node->State.Column > getColumnLimit()) {
791       unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
792       Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
793     }
794 
795     Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
796     ++Count;
797   }
798 
799   /// \brief Returns \c true, if a line break after \p State is allowed.
800   bool canBreak(const LineState &State) {
801     if (!State.NextToken->CanBreakBefore &&
802         !(State.NextToken->is(tok::r_brace) &&
803           State.Stack.back().BreakBeforeClosingBrace))
804       return false;
805     // Trying to insert a parameter on a new line if there are already more than
806     // one parameter on the current line is bin packing.
807     if (State.Stack.back().HasMultiParameterLine &&
808         State.Stack.back().AvoidBinPacking)
809       return false;
810     return true;
811   }
812 
813   /// \brief Returns \c true, if a line break after \p State is mandatory.
814   bool mustBreak(const LineState &State) {
815     if (State.NextToken->MustBreakBefore)
816       return true;
817     if (State.NextToken->is(tok::r_brace) &&
818         State.Stack.back().BreakBeforeClosingBrace)
819       return true;
820     if (State.NextToken->Parent->is(tok::semi) &&
821         State.LineContainsContinuedForLoopSection)
822       return true;
823     if ((State.NextToken->Parent->isOneOf(tok::comma, tok::semi) ||
824          State.NextToken->is(tok::question) ||
825          State.NextToken->Type == TT_ConditionalExpr) &&
826         State.Stack.back().BreakBeforeParameter &&
827         !State.NextToken->isTrailingComment() &&
828         State.NextToken->isNot(tok::r_paren) &&
829         State.NextToken->isNot(tok::r_brace))
830       return true;
831     // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
832     // out whether it is the first parameter. Clean this up.
833     if (State.NextToken->Type == TT_ObjCSelectorName &&
834         State.NextToken->LongestObjCSelectorName == 0 &&
835         State.Stack.back().BreakBeforeParameter)
836       return true;
837     if ((State.NextToken->Type == TT_CtorInitializerColon ||
838          (State.NextToken->Parent->ClosesTemplateDeclaration &&
839           State.ParenLevel == 0)))
840       return true;
841     if (State.NextToken->Type == TT_InlineASMColon)
842       return true;
843     // This prevents breaks like:
844     //   ...
845     //   SomeParameter, OtherParameter).DoSomething(
846     //   ...
847     // As they hide "DoSomething" and generally bad for readability.
848     if (State.NextToken->isOneOf(tok::period, tok::arrow) &&
849         getRemainingLength(State) + State.Column > getColumnLimit() &&
850         State.ParenLevel < State.StartOfLineLevel)
851       return true;
852     return false;
853   }
854 
855   // Returns the total number of columns required for the remaining tokens.
856   unsigned getRemainingLength(const LineState &State) {
857     if (State.NextToken && State.NextToken->Parent)
858       return Line.Last->TotalLength - State.NextToken->Parent->TotalLength;
859     return 0;
860   }
861 
862   FormatStyle Style;
863   SourceManager &SourceMgr;
864   const AnnotatedLine &Line;
865   const unsigned FirstIndent;
866   const AnnotatedToken &RootToken;
867   WhitespaceManager &Whitespaces;
868 
869   llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
870   QueueType Queue;
871   // Increasing count of \c StateNode items we have created. This is used
872   // to create a deterministic order independent of the container.
873   unsigned Count;
874 };
875 
876 class LexerBasedFormatTokenSource : public FormatTokenSource {
877 public:
878   LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
879       : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
880         IdentTable(Lex.getLangOpts()) {
881     Lex.SetKeepWhitespaceMode(true);
882   }
883 
884   virtual FormatToken getNextToken() {
885     if (GreaterStashed) {
886       FormatTok.NewlinesBefore = 0;
887       FormatTok.WhiteSpaceStart =
888           FormatTok.Tok.getLocation().getLocWithOffset(1);
889       FormatTok.WhiteSpaceLength = 0;
890       GreaterStashed = false;
891       return FormatTok;
892     }
893 
894     FormatTok = FormatToken();
895     Lex.LexFromRawLexer(FormatTok.Tok);
896     StringRef Text = rawTokenText(FormatTok.Tok);
897     FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
898     if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
899       FormatTok.IsFirst = true;
900 
901     // Consume and record whitespace until we find a significant token.
902     while (FormatTok.Tok.is(tok::unknown)) {
903       unsigned Newlines = Text.count('\n');
904       if (Newlines > 0)
905         FormatTok.LastNewlineOffset =
906             FormatTok.WhiteSpaceLength + Text.rfind('\n') + 1;
907       unsigned EscapedNewlines = Text.count("\\\n");
908       FormatTok.NewlinesBefore += Newlines;
909       FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
910       FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
911 
912       if (FormatTok.Tok.is(tok::eof))
913         return FormatTok;
914       Lex.LexFromRawLexer(FormatTok.Tok);
915       Text = rawTokenText(FormatTok.Tok);
916     }
917 
918     // Now FormatTok is the next non-whitespace token.
919     FormatTok.TokenLength = Text.size();
920 
921     if (FormatTok.Tok.is(tok::comment)) {
922       FormatTok.TrailingWhiteSpaceLength = Text.size() - Text.rtrim().size();
923       FormatTok.TokenLength -= FormatTok.TrailingWhiteSpaceLength;
924     }
925 
926     // In case the token starts with escaped newlines, we want to
927     // take them into account as whitespace - this pattern is quite frequent
928     // in macro definitions.
929     // FIXME: What do we want to do with other escaped spaces, and escaped
930     // spaces or newlines in the middle of tokens?
931     // FIXME: Add a more explicit test.
932     unsigned i = 0;
933     while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
934       // FIXME: ++FormatTok.NewlinesBefore is missing...
935       FormatTok.WhiteSpaceLength += 2;
936       FormatTok.TokenLength -= 2;
937       i += 2;
938     }
939 
940     if (FormatTok.Tok.is(tok::raw_identifier)) {
941       IdentifierInfo &Info = IdentTable.get(Text);
942       FormatTok.Tok.setIdentifierInfo(&Info);
943       FormatTok.Tok.setKind(Info.getTokenID());
944     }
945 
946     if (FormatTok.Tok.is(tok::greatergreater)) {
947       FormatTok.Tok.setKind(tok::greater);
948       FormatTok.TokenLength = 1;
949       GreaterStashed = true;
950     }
951 
952     return FormatTok;
953   }
954 
955   IdentifierTable &getIdentTable() { return IdentTable; }
956 
957 private:
958   FormatToken FormatTok;
959   bool GreaterStashed;
960   Lexer &Lex;
961   SourceManager &SourceMgr;
962   IdentifierTable IdentTable;
963 
964   /// Returns the text of \c FormatTok.
965   StringRef rawTokenText(Token &Tok) {
966     return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
967                      Tok.getLength());
968   }
969 };
970 
971 class Formatter : public UnwrappedLineConsumer {
972 public:
973   Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
974             SourceManager &SourceMgr,
975             const std::vector<CharSourceRange> &Ranges)
976       : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
977         Whitespaces(SourceMgr, Style), Ranges(Ranges) {}
978 
979   virtual ~Formatter() {}
980 
981   tooling::Replacements format() {
982     LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
983     UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
984     bool StructuralError = Parser.parse();
985     unsigned PreviousEndOfLineColumn = 0;
986     TokenAnnotator Annotator(Style, SourceMgr, Lex,
987                              Tokens.getIdentTable().get("in"));
988     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
989       Annotator.annotate(AnnotatedLines[i]);
990     }
991     deriveLocalStyle();
992     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
993       Annotator.calculateFormattingInformation(AnnotatedLines[i]);
994     }
995 
996     // Adapt level to the next line if this is a comment.
997     // FIXME: Can/should this be done in the UnwrappedLineParser?
998     const AnnotatedLine *NextNoneCommentLine = NULL;
999     for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
1000       if (NextNoneCommentLine && AnnotatedLines[i].First.is(tok::comment) &&
1001           AnnotatedLines[i].First.Children.empty())
1002         AnnotatedLines[i].Level = NextNoneCommentLine->Level;
1003       else
1004         NextNoneCommentLine =
1005             AnnotatedLines[i].First.isNot(tok::r_brace) ? &AnnotatedLines[i]
1006                                                         : NULL;
1007     }
1008 
1009     std::vector<int> IndentForLevel;
1010     bool PreviousLineWasTouched = false;
1011     const AnnotatedToken *PreviousLineLastToken = 0;
1012     for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1013                                               E = AnnotatedLines.end();
1014          I != E; ++I) {
1015       const AnnotatedLine &TheLine = *I;
1016       const FormatToken &FirstTok = TheLine.First.FormatTok;
1017       int Offset = getIndentOffset(TheLine.First);
1018       while (IndentForLevel.size() <= TheLine.Level)
1019         IndentForLevel.push_back(-1);
1020       IndentForLevel.resize(TheLine.Level + 1);
1021       bool WasMoved = PreviousLineWasTouched && FirstTok.NewlinesBefore == 0;
1022       if (TheLine.First.is(tok::eof)) {
1023         if (PreviousLineWasTouched) {
1024           unsigned NewLines = std::min(FirstTok.NewlinesBefore, 1u);
1025           Whitespaces.replaceWhitespace(TheLine.First, NewLines, /*Indent*/ 0,
1026                                         /*WhitespaceStartColumn*/ 0);
1027         }
1028       } else if (TheLine.Type != LT_Invalid &&
1029                  (WasMoved || touchesLine(TheLine))) {
1030         unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
1031         unsigned Indent = LevelIndent;
1032         if (static_cast<int>(Indent) + Offset >= 0)
1033           Indent += Offset;
1034         if (FirstTok.WhiteSpaceStart.isValid() &&
1035             // Insert a break even if there is a structural error in case where
1036             // we break apart a line consisting of multiple unwrapped lines.
1037             (FirstTok.NewlinesBefore == 0 || !StructuralError)) {
1038           formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1039                            TheLine.InPPDirective, PreviousEndOfLineColumn);
1040         } else {
1041           Indent = LevelIndent =
1042               SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
1043         }
1044         tryFitMultipleLinesInOne(Indent, I, E);
1045         UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
1046                                          TheLine.First, Whitespaces);
1047         PreviousEndOfLineColumn =
1048             Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
1049         IndentForLevel[TheLine.Level] = LevelIndent;
1050         PreviousLineWasTouched = true;
1051       } else {
1052         if (FirstTok.NewlinesBefore > 0 || FirstTok.IsFirst) {
1053           unsigned Indent =
1054               SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
1055           unsigned LevelIndent = Indent;
1056           if (static_cast<int>(LevelIndent) - Offset >= 0)
1057             LevelIndent -= Offset;
1058           if (TheLine.First.isNot(tok::comment))
1059             IndentForLevel[TheLine.Level] = LevelIndent;
1060 
1061           // Remove trailing whitespace of the previous line if it was touched.
1062           if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine))
1063             formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1064                              TheLine.InPPDirective, PreviousEndOfLineColumn);
1065         }
1066         // If we did not reformat this unwrapped line, the column at the end of
1067         // the last token is unchanged - thus, we can calculate the end of the
1068         // last token.
1069         SourceLocation LastLoc = TheLine.Last->FormatTok.Tok.getLocation();
1070         PreviousEndOfLineColumn =
1071             SourceMgr.getSpellingColumnNumber(LastLoc) +
1072             Lex.MeasureTokenLength(LastLoc, SourceMgr, Lex.getLangOpts()) - 1;
1073         PreviousLineWasTouched = false;
1074         if (TheLine.Last->is(tok::comment))
1075           Whitespaces.addUntouchableComment(SourceMgr.getSpellingColumnNumber(
1076               TheLine.Last->FormatTok.Tok.getLocation()) - 1);
1077       }
1078       PreviousLineLastToken = I->Last;
1079     }
1080     return Whitespaces.generateReplacements();
1081   }
1082 
1083 private:
1084   void deriveLocalStyle() {
1085     unsigned CountBoundToVariable = 0;
1086     unsigned CountBoundToType = 0;
1087     bool HasCpp03IncompatibleFormat = false;
1088     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1089       if (AnnotatedLines[i].First.Children.empty())
1090         continue;
1091       AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1092       while (!Tok->Children.empty()) {
1093         if (Tok->Type == TT_PointerOrReference) {
1094           bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1095           bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1096           if (SpacesBefore && !SpacesAfter)
1097             ++CountBoundToVariable;
1098           else if (!SpacesBefore && SpacesAfter)
1099             ++CountBoundToType;
1100         }
1101 
1102         if (Tok->Type == TT_TemplateCloser &&
1103             Tok->Parent->Type == TT_TemplateCloser &&
1104             Tok->FormatTok.WhiteSpaceLength == 0)
1105           HasCpp03IncompatibleFormat = true;
1106         Tok = &Tok->Children[0];
1107       }
1108     }
1109     if (Style.DerivePointerBinding) {
1110       if (CountBoundToType > CountBoundToVariable)
1111         Style.PointerBindsToType = true;
1112       else if (CountBoundToType < CountBoundToVariable)
1113         Style.PointerBindsToType = false;
1114     }
1115     if (Style.Standard == FormatStyle::LS_Auto) {
1116       Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1117                                                   : FormatStyle::LS_Cpp03;
1118     }
1119   }
1120 
1121   /// \brief Get the indent of \p Level from \p IndentForLevel.
1122   ///
1123   /// \p IndentForLevel must contain the indent for the level \c l
1124   /// at \p IndentForLevel[l], or a value < 0 if the indent for
1125   /// that level is unknown.
1126   unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
1127     if (IndentForLevel[Level] != -1)
1128       return IndentForLevel[Level];
1129     if (Level == 0)
1130       return 0;
1131     return getIndent(IndentForLevel, Level - 1) + 2;
1132   }
1133 
1134   /// \brief Get the offset of the line relatively to the level.
1135   ///
1136   /// For example, 'public:' labels in classes are offset by 1 or 2
1137   /// characters to the left from their level.
1138   int getIndentOffset(const AnnotatedToken &RootToken) {
1139     if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
1140       return Style.AccessModifierOffset;
1141     return 0;
1142   }
1143 
1144   /// \brief Tries to merge lines into one.
1145   ///
1146   /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1147   /// if possible; note that \c I will be incremented when lines are merged.
1148   ///
1149   /// Returns whether the resulting \c Line can fit in a single line.
1150   void tryFitMultipleLinesInOne(unsigned Indent,
1151                                 std::vector<AnnotatedLine>::iterator &I,
1152                                 std::vector<AnnotatedLine>::iterator E) {
1153     // We can never merge stuff if there are trailing line comments.
1154     if (I->Last->Type == TT_LineComment)
1155       return;
1156 
1157     unsigned Limit = Style.ColumnLimit - Indent;
1158     // If we already exceed the column limit, we set 'Limit' to 0. The different
1159     // tryMerge..() functions can then decide whether to still do merging.
1160     Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
1161 
1162     if (I + 1 == E || (I + 1)->Type == LT_Invalid)
1163       return;
1164 
1165     if (I->Last->is(tok::l_brace)) {
1166       tryMergeSimpleBlock(I, E, Limit);
1167     } else if (I->First.is(tok::kw_if)) {
1168       tryMergeSimpleIf(I, E, Limit);
1169     } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1170                                     I->First.FormatTok.IsFirst)) {
1171       tryMergeSimplePPDirective(I, E, Limit);
1172     }
1173     return;
1174   }
1175 
1176   void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1177                                  std::vector<AnnotatedLine>::iterator E,
1178                                  unsigned Limit) {
1179     if (Limit == 0)
1180       return;
1181     AnnotatedLine &Line = *I;
1182     if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1183       return;
1184     if (I + 2 != E && (I + 2)->InPPDirective &&
1185         !(I + 2)->First.FormatTok.HasUnescapedNewline)
1186       return;
1187     if (1 + (I + 1)->Last->TotalLength > Limit)
1188       return;
1189     join(Line, *(++I));
1190   }
1191 
1192   void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1193                         std::vector<AnnotatedLine>::iterator E,
1194                         unsigned Limit) {
1195     if (Limit == 0)
1196       return;
1197     if (!Style.AllowShortIfStatementsOnASingleLine)
1198       return;
1199     if ((I + 1)->InPPDirective != I->InPPDirective ||
1200         ((I + 1)->InPPDirective &&
1201          (I + 1)->First.FormatTok.HasUnescapedNewline))
1202       return;
1203     AnnotatedLine &Line = *I;
1204     if (Line.Last->isNot(tok::r_paren))
1205       return;
1206     if (1 + (I + 1)->Last->TotalLength > Limit)
1207       return;
1208     if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1209       return;
1210     // Only inline simple if's (no nested if or else).
1211     if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1212       return;
1213     join(Line, *(++I));
1214   }
1215 
1216   void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
1217                            std::vector<AnnotatedLine>::iterator E,
1218                            unsigned Limit) {
1219     // First, check that the current line allows merging. This is the case if
1220     // we're not in a control flow statement and the last token is an opening
1221     // brace.
1222     AnnotatedLine &Line = *I;
1223     if (Line.First.isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1224                            tok::kw_else, tok::kw_try, tok::kw_catch,
1225                            tok::kw_for,
1226                            // This gets rid of all ObjC @ keywords and methods.
1227                            tok::at, tok::minus, tok::plus))
1228       return;
1229 
1230     AnnotatedToken *Tok = &(I + 1)->First;
1231     if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
1232         !Tok->MustBreakBefore) {
1233       // We merge empty blocks even if the line exceeds the column limit.
1234       Tok->SpacesRequiredBefore = 0;
1235       Tok->CanBreakBefore = true;
1236       join(Line, *(I + 1));
1237       I += 1;
1238     } else if (Limit != 0) {
1239       // Check that we still have three lines and they fit into the limit.
1240       if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1241           !nextTwoLinesFitInto(I, Limit))
1242         return;
1243 
1244       // Second, check that the next line does not contain any braces - if it
1245       // does, readability declines when putting it into a single line.
1246       if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1247         return;
1248       do {
1249         if (Tok->isOneOf(tok::l_brace, tok::r_brace))
1250           return;
1251         Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1252       } while (Tok != NULL);
1253 
1254       // Last, check that the third line contains a single closing brace.
1255       Tok = &(I + 2)->First;
1256       if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1257           Tok->MustBreakBefore)
1258         return;
1259 
1260       join(Line, *(I + 1));
1261       join(Line, *(I + 2));
1262       I += 2;
1263     }
1264   }
1265 
1266   bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1267                            unsigned Limit) {
1268     return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1269            Limit;
1270   }
1271 
1272   void join(AnnotatedLine &A, const AnnotatedLine &B) {
1273     unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
1274     A.Last->Children.push_back(B.First);
1275     while (!A.Last->Children.empty()) {
1276       A.Last->Children[0].Parent = A.Last;
1277       A.Last->Children[0].TotalLength += LengthA;
1278       A.Last = &A.Last->Children[0];
1279     }
1280   }
1281 
1282   bool touchesRanges(const CharSourceRange &Range) {
1283     for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1284       if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1285                                                Ranges[i].getBegin()) &&
1286           !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1287                                                Range.getBegin()))
1288         return true;
1289     }
1290     return false;
1291   }
1292 
1293   bool touchesLine(const AnnotatedLine &TheLine) {
1294     const FormatToken *First = &TheLine.First.FormatTok;
1295     const FormatToken *Last = &TheLine.Last->FormatTok;
1296     CharSourceRange LineRange = CharSourceRange::getTokenRange(
1297         First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset),
1298         Last->Tok.getLocation());
1299     return touchesRanges(LineRange);
1300   }
1301 
1302   bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
1303     const FormatToken *First = &TheLine.First.FormatTok;
1304     CharSourceRange LineRange = CharSourceRange::getCharRange(
1305         First->WhiteSpaceStart,
1306         First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset));
1307     return touchesRanges(LineRange);
1308   }
1309 
1310   virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
1311     AnnotatedLines.push_back(AnnotatedLine(TheLine));
1312   }
1313 
1314   /// \brief Add a new line and the required indent before the first Token
1315   /// of the \c UnwrappedLine if there was no structural parsing error.
1316   /// Returns the indent level of the \c UnwrappedLine.
1317   void formatFirstToken(const AnnotatedToken &RootToken,
1318                         const AnnotatedToken *PreviousToken, unsigned Indent,
1319                         bool InPPDirective, unsigned PreviousEndOfLineColumn) {
1320     const FormatToken &Tok = RootToken.FormatTok;
1321 
1322     unsigned Newlines =
1323         std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1324     if (Newlines == 0 && !Tok.IsFirst)
1325       Newlines = 1;
1326 
1327     if (!InPPDirective || Tok.HasUnescapedNewline) {
1328       // Insert extra new line before access specifiers.
1329       if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
1330           RootToken.isAccessSpecifier() && Tok.NewlinesBefore == 1)
1331         ++Newlines;
1332 
1333       Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0);
1334     } else {
1335       Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1336                                       PreviousEndOfLineColumn);
1337     }
1338   }
1339 
1340   DiagnosticsEngine &Diag;
1341   FormatStyle Style;
1342   Lexer &Lex;
1343   SourceManager &SourceMgr;
1344   WhitespaceManager Whitespaces;
1345   std::vector<CharSourceRange> Ranges;
1346   std::vector<AnnotatedLine> AnnotatedLines;
1347 };
1348 
1349 tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1350                                SourceManager &SourceMgr,
1351                                std::vector<CharSourceRange> Ranges,
1352                                DiagnosticConsumer *DiagClient) {
1353   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
1354   OwningPtr<DiagnosticConsumer> DiagPrinter;
1355   if (DiagClient == 0) {
1356     DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1357     DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1358     DiagClient = DiagPrinter.get();
1359   }
1360   DiagnosticsEngine Diagnostics(
1361       IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
1362       DiagClient, false);
1363   Diagnostics.setSourceManager(&SourceMgr);
1364   Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
1365   return formatter.format();
1366 }
1367 
1368 LangOptions getFormattingLangOpts() {
1369   LangOptions LangOpts;
1370   LangOpts.CPlusPlus = 1;
1371   LangOpts.CPlusPlus11 = 1;
1372   LangOpts.LineComment = 1;
1373   LangOpts.Bool = 1;
1374   LangOpts.ObjC1 = 1;
1375   LangOpts.ObjC2 = 1;
1376   return LangOpts;
1377 }
1378 
1379 } // namespace format
1380 } // namespace clang
1381