1 //===--- ContinuationIndenter.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 the continuation indenter.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #define DEBUG_TYPE "format-formatter"
16 
17 #include "BreakableToken.h"
18 #include "ContinuationIndenter.h"
19 #include "WhitespaceManager.h"
20 #include "clang/Basic/OperatorPrecedence.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "clang/Format/Format.h"
23 #include "llvm/Support/Debug.h"
24 #include <string>
25 
26 namespace clang {
27 namespace format {
28 
29 // Returns the length of everything up to the first possible line break after
30 // the ), ], } or > matching \c Tok.
31 static unsigned getLengthToMatchingParen(const FormatToken &Tok) {
32   if (Tok.MatchingParen == NULL)
33     return 0;
34   FormatToken *End = Tok.MatchingParen;
35   while (End->Next && !End->Next->CanBreakBefore) {
36     End = End->Next;
37   }
38   return End->TotalLength - Tok.TotalLength + 1;
39 }
40 
41 // Returns \c true if \c Tok is the "." or "->" of a call and starts the next
42 // segment of a builder type call.
43 static bool startsSegmentOfBuilderTypeCall(const FormatToken &Tok) {
44   return Tok.isMemberAccess() && Tok.Previous && Tok.Previous->closesScope();
45 }
46 
47 // Returns \c true if \c Current starts a new parameter.
48 static bool startsNextParameter(const FormatToken &Current,
49                                 const FormatStyle &Style) {
50   const FormatToken &Previous = *Current.Previous;
51   if (Current.Type == TT_CtorInitializerComma &&
52       Style.BreakConstructorInitializersBeforeComma)
53     return true;
54   return Previous.is(tok::comma) && !Current.isTrailingComment() &&
55          (Previous.Type != TT_CtorInitializerComma ||
56           !Style.BreakConstructorInitializersBeforeComma);
57 }
58 
59 ContinuationIndenter::ContinuationIndenter(const FormatStyle &Style,
60                                            SourceManager &SourceMgr,
61                                            WhitespaceManager &Whitespaces,
62                                            encoding::Encoding Encoding,
63                                            bool BinPackInconclusiveFunctions)
64     : Style(Style), SourceMgr(SourceMgr), Whitespaces(Whitespaces),
65       Encoding(Encoding),
66       BinPackInconclusiveFunctions(BinPackInconclusiveFunctions) {}
67 
68 LineState ContinuationIndenter::getInitialState(unsigned FirstIndent,
69                                                 const AnnotatedLine *Line,
70                                                 bool DryRun) {
71   LineState State;
72   State.FirstIndent = FirstIndent;
73   State.Column = FirstIndent;
74   State.Line = Line;
75   State.NextToken = Line->First;
76   State.Stack.push_back(ParenState(FirstIndent, Line->Level, FirstIndent,
77                                    /*AvoidBinPacking=*/false,
78                                    /*NoLineBreak=*/false));
79   State.LineContainsContinuedForLoopSection = false;
80   State.ParenLevel = 0;
81   State.StartOfStringLiteral = 0;
82   State.StartOfLineLevel = State.ParenLevel;
83   State.LowestLevelOnLine = State.ParenLevel;
84   State.IgnoreStackForComparison = false;
85 
86   // The first token has already been indented and thus consumed.
87   moveStateToNextToken(State, DryRun, /*Newline=*/false);
88   return State;
89 }
90 
91 bool ContinuationIndenter::canBreak(const LineState &State) {
92   const FormatToken &Current = *State.NextToken;
93   const FormatToken &Previous = *Current.Previous;
94   assert(&Previous == Current.Previous);
95   if (!Current.CanBreakBefore && !(State.Stack.back().BreakBeforeClosingBrace &&
96                                    Current.closesBlockTypeList(Style)))
97     return false;
98   // The opening "{" of a braced list has to be on the same line as the first
99   // element if it is nested in another braced init list or function call.
100   if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
101       Previous.Type != TT_DictLiteral &&
102       Previous.BlockKind == BK_BracedInit && Previous.Previous &&
103       Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
104     return false;
105   // This prevents breaks like:
106   //   ...
107   //   SomeParameter, OtherParameter).DoSomething(
108   //   ...
109   // As they hide "DoSomething" and are generally bad for readability.
110   if (Previous.opensScope() && State.LowestLevelOnLine < State.StartOfLineLevel)
111     return false;
112   if (Current.isMemberAccess() && State.Stack.back().ContainsUnwrappedBuilder)
113     return false;
114   return !State.Stack.back().NoLineBreak;
115 }
116 
117 bool ContinuationIndenter::mustBreak(const LineState &State) {
118   const FormatToken &Current = *State.NextToken;
119   const FormatToken &Previous = *Current.Previous;
120   if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
121     return true;
122   if (State.Stack.back().BreakBeforeClosingBrace &&
123       Current.closesBlockTypeList(Style))
124     return true;
125   if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
126     return true;
127   if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
128        (Style.BreakBeforeTernaryOperators &&
129         (Current.is(tok::question) || (Current.Type == TT_ConditionalExpr &&
130                                        Previous.isNot(tok::question)))) ||
131        (!Style.BreakBeforeTernaryOperators &&
132         (Previous.is(tok::question) || Previous.Type == TT_ConditionalExpr))) &&
133       State.Stack.back().BreakBeforeParameter && !Current.isTrailingComment() &&
134       !Current.isOneOf(tok::r_paren, tok::r_brace))
135     return true;
136   if (Style.AlwaysBreakBeforeMultilineStrings &&
137       State.Column > State.Stack.back().Indent && // Breaking saves columns.
138       !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at) &&
139       Previous.Type != TT_InlineASMColon && NextIsMultilineString(State))
140     return true;
141   if (((Previous.Type == TT_DictLiteral && Previous.is(tok::l_brace)) ||
142        Previous.Type == TT_ArrayInitializerLSquare) &&
143       getLengthToMatchingParen(Previous) + State.Column > getColumnLimit(State))
144     return true;
145 
146   if (!Style.BreakBeforeBinaryOperators) {
147     // If we need to break somewhere inside the LHS of a binary expression, we
148     // should also break after the operator. Otherwise, the formatting would
149     // hide the operator precedence, e.g. in:
150     //   if (aaaaaaaaaaaaaa ==
151     //           bbbbbbbbbbbbbb && c) {..
152     // For comparisons, we only apply this rule, if the LHS is a binary
153     // expression itself as otherwise, the line breaks seem superfluous.
154     // We need special cases for ">>" which we have split into two ">" while
155     // lexing in order to make template parsing easier.
156     //
157     // FIXME: We'll need something similar for styles that break before binary
158     // operators.
159     bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
160                          Previous.getPrecedence() == prec::Equality) &&
161                         Previous.Previous &&
162                         Previous.Previous->Type != TT_BinaryOperator; // For >>.
163     bool LHSIsBinaryExpr =
164         Previous.Previous && Previous.Previous->EndsBinaryExpression;
165     if (Previous.Type == TT_BinaryOperator &&
166         (!IsComparison || LHSIsBinaryExpr) &&
167         Current.Type != TT_BinaryOperator && // For >>.
168         !Current.isTrailingComment() &&
169         !Previous.isOneOf(tok::lessless, tok::question) &&
170         Previous.getPrecedence() != prec::Assignment &&
171         State.Stack.back().BreakBeforeParameter)
172       return true;
173   }
174 
175   // Same as above, but for the first "<<" operator.
176   if (Current.is(tok::lessless) && State.Stack.back().BreakBeforeParameter &&
177       State.Stack.back().FirstLessLess == 0)
178     return true;
179 
180   // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
181   // out whether it is the first parameter. Clean this up.
182   if (Current.Type == TT_ObjCSelectorName &&
183       Current.LongestObjCSelectorName == 0 &&
184       State.Stack.back().BreakBeforeParameter)
185     return true;
186   if ((Current.Type == TT_CtorInitializerColon ||
187        (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0 &&
188         !Current.isTrailingComment())))
189     return true;
190 
191   if ((Current.Type == TT_StartOfName || Current.is(tok::kw_operator)) &&
192       State.Line->MightBeFunctionDecl &&
193       State.Stack.back().BreakBeforeParameter && State.ParenLevel == 0)
194     return true;
195   if (startsSegmentOfBuilderTypeCall(Current) &&
196       (State.Stack.back().CallContinuation != 0 ||
197        (State.Stack.back().BreakBeforeParameter &&
198         State.Stack.back().ContainsUnwrappedBuilder)))
199     return true;
200   return false;
201 }
202 
203 unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
204                                                bool DryRun,
205                                                unsigned ExtraSpaces) {
206   const FormatToken &Current = *State.NextToken;
207 
208   if (State.Stack.size() == 0 ||
209       (Current.Type == TT_ImplicitStringLiteral &&
210        (Current.Previous->Tok.getIdentifierInfo() == NULL ||
211         Current.Previous->Tok.getIdentifierInfo()->getPPKeywordID() ==
212             tok::pp_not_keyword))) {
213     // FIXME: Is this correct?
214     int WhitespaceLength = SourceMgr.getSpellingColumnNumber(
215                                State.NextToken->WhitespaceRange.getEnd()) -
216                            SourceMgr.getSpellingColumnNumber(
217                                State.NextToken->WhitespaceRange.getBegin());
218     State.Column += WhitespaceLength + State.NextToken->ColumnWidth;
219     State.NextToken = State.NextToken->Next;
220     return 0;
221   }
222 
223   unsigned Penalty = 0;
224   if (Newline)
225     Penalty = addTokenOnNewLine(State, DryRun);
226   else
227     addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
228 
229   return moveStateToNextToken(State, DryRun, Newline) + Penalty;
230 }
231 
232 void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
233                                                  unsigned ExtraSpaces) {
234   FormatToken &Current = *State.NextToken;
235   const FormatToken &Previous = *State.NextToken->Previous;
236   if (Current.is(tok::equal) &&
237       (State.Line->First->is(tok::kw_for) || State.ParenLevel == 0) &&
238       State.Stack.back().VariablePos == 0) {
239     State.Stack.back().VariablePos = State.Column;
240     // Move over * and & if they are bound to the variable name.
241     const FormatToken *Tok = &Previous;
242     while (Tok && State.Stack.back().VariablePos >= Tok->ColumnWidth) {
243       State.Stack.back().VariablePos -= Tok->ColumnWidth;
244       if (Tok->SpacesRequiredBefore != 0)
245         break;
246       Tok = Tok->Previous;
247     }
248     if (Previous.PartOfMultiVariableDeclStmt)
249       State.Stack.back().LastSpace = State.Stack.back().VariablePos;
250   }
251 
252   unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
253 
254   if (!DryRun)
255     Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, /*IndentLevel=*/0,
256                                   Spaces, State.Column + Spaces);
257 
258   if (Current.Type == TT_ObjCSelectorName && State.Stack.back().ColonPos == 0) {
259     if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
260         State.Column + Spaces + Current.ColumnWidth)
261       State.Stack.back().ColonPos =
262           State.Stack.back().Indent + Current.LongestObjCSelectorName;
263     else
264       State.Stack.back().ColonPos = State.Column + Spaces + Current.ColumnWidth;
265   }
266 
267   if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
268       Current.Type != TT_LineComment)
269     State.Stack.back().Indent = State.Column + Spaces;
270   if (State.Stack.back().AvoidBinPacking && startsNextParameter(Current, Style))
271     State.Stack.back().NoLineBreak = true;
272   if (startsSegmentOfBuilderTypeCall(Current))
273     State.Stack.back().ContainsUnwrappedBuilder = true;
274 
275   State.Column += Spaces;
276   if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
277     // Treat the condition inside an if as if it was a second function
278     // parameter, i.e. let nested calls have a continuation indent.
279     State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
280   else if (Previous.is(tok::comma) || Previous.Type == TT_ObjCMethodExpr)
281     State.Stack.back().LastSpace = State.Column;
282   else if ((Previous.Type == TT_BinaryOperator ||
283             Previous.Type == TT_ConditionalExpr ||
284             Previous.Type == TT_UnaryOperator ||
285             Previous.Type == TT_CtorInitializerColon) &&
286            (Previous.getPrecedence() != prec::Assignment ||
287             Current.StartsBinaryExpression))
288     // Always indent relative to the RHS of the expression unless this is a
289     // simple assignment without binary expression on the RHS. Also indent
290     // relative to unary operators and the colons of constructor initializers.
291     State.Stack.back().LastSpace = State.Column;
292   else if (Previous.Type == TT_InheritanceColon) {
293     State.Stack.back().Indent = State.Column;
294     State.Stack.back().LastSpace = State.Column;
295   } else if (Previous.opensScope()) {
296     // If a function has a trailing call, indent all parameters from the
297     // opening parenthesis. This avoids confusing indents like:
298     //   OuterFunction(InnerFunctionCall( // break
299     //       ParameterToInnerFunction))   // break
300     //       .SecondInnerFunctionCall();
301     bool HasTrailingCall = false;
302     if (Previous.MatchingParen) {
303       const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
304       HasTrailingCall = Next && Next->isMemberAccess();
305     }
306     if (HasTrailingCall &&
307         State.Stack[State.Stack.size() - 2].CallContinuation == 0)
308       State.Stack.back().LastSpace = State.Column;
309   }
310 }
311 
312 unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
313                                                  bool DryRun) {
314   FormatToken &Current = *State.NextToken;
315   const FormatToken &Previous = *State.NextToken->Previous;
316   // If we are continuing an expression, we want to use the continuation indent.
317   unsigned ContinuationIndent =
318       std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
319       Style.ContinuationIndentWidth;
320   // Extra penalty that needs to be added because of the way certain line
321   // breaks are chosen.
322   unsigned Penalty = 0;
323 
324   const FormatToken *PreviousNonComment =
325       State.NextToken->getPreviousNonComment();
326   // The first line break on any ParenLevel causes an extra penalty in order
327   // prefer similar line breaks.
328   if (!State.Stack.back().ContainsLineBreak)
329     Penalty += 15;
330   State.Stack.back().ContainsLineBreak = true;
331 
332   Penalty += State.NextToken->SplitPenalty;
333 
334   // Breaking before the first "<<" is generally not desirable if the LHS is
335   // short. Also always add the penalty if the LHS is split over mutliple lines
336   // to avoid unncessary line breaks that just work around this penalty.
337   if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0 &&
338       (State.Column <= Style.ColumnLimit / 2 ||
339        State.Stack.back().BreakBeforeParameter))
340     Penalty += Style.PenaltyBreakFirstLessLess;
341 
342   if (Current.is(tok::l_brace) && Current.BlockKind == BK_Block) {
343     State.Column = State.FirstIndent;
344   } else if (Current.isOneOf(tok::r_brace, tok::r_square)) {
345     if (Current.closesBlockTypeList(Style) ||
346         (Current.MatchingParen &&
347          Current.MatchingParen->BlockKind == BK_BracedInit))
348       State.Column = State.Stack[State.Stack.size() - 2].LastSpace;
349     else
350       State.Column = State.FirstIndent;
351   } else if (Current.is(tok::string_literal) &&
352              State.StartOfStringLiteral != 0) {
353     State.Column = State.StartOfStringLiteral;
354     State.Stack.back().BreakBeforeParameter = true;
355   } else if (Current.is(tok::lessless) &&
356              State.Stack.back().FirstLessLess != 0) {
357     State.Column = State.Stack.back().FirstLessLess;
358   } else if (Current.isMemberAccess()) {
359     if (State.Stack.back().CallContinuation == 0) {
360       State.Column = ContinuationIndent;
361       State.Stack.back().CallContinuation = State.Column;
362     } else {
363       State.Column = State.Stack.back().CallContinuation;
364     }
365   } else if (State.Stack.back().QuestionColumn != 0 &&
366              (Current.Type == TT_ConditionalExpr ||
367               Previous.Type == TT_ConditionalExpr)) {
368     State.Column = State.Stack.back().QuestionColumn;
369   } else if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0) {
370     State.Column = State.Stack.back().VariablePos;
371   } else if ((PreviousNonComment &&
372               PreviousNonComment->ClosesTemplateDeclaration) ||
373              ((Current.Type == TT_StartOfName ||
374                Current.is(tok::kw_operator)) &&
375               State.ParenLevel == 0 &&
376               (!Style.IndentFunctionDeclarationAfterType ||
377                State.Line->StartsDefinition))) {
378     State.Column = State.Stack.back().Indent;
379   } else if (Current.Type == TT_ObjCSelectorName) {
380     if (State.Stack.back().ColonPos == 0) {
381       State.Stack.back().ColonPos =
382           State.Stack.back().Indent + Current.LongestObjCSelectorName;
383       State.Column = State.Stack.back().ColonPos - Current.ColumnWidth;
384     } else if (State.Stack.back().ColonPos > Current.ColumnWidth) {
385       State.Column = State.Stack.back().ColonPos - Current.ColumnWidth;
386     } else {
387       State.Column = State.Stack.back().Indent;
388       State.Stack.back().ColonPos = State.Column + Current.ColumnWidth;
389     }
390   } else if (Current.Type == TT_ArraySubscriptLSquare) {
391     if (State.Stack.back().StartOfArraySubscripts != 0)
392       State.Column = State.Stack.back().StartOfArraySubscripts;
393     else
394       State.Column = ContinuationIndent;
395   } else if (Current.Type == TT_StartOfName ||
396              Previous.isOneOf(tok::coloncolon, tok::equal) ||
397              Previous.Type == TT_ObjCMethodExpr) {
398     State.Column = ContinuationIndent;
399   } else if (Current.Type == TT_CtorInitializerColon) {
400     State.Column = State.FirstIndent + Style.ConstructorInitializerIndentWidth;
401   } else if (Current.Type == TT_CtorInitializerComma) {
402     State.Column = State.Stack.back().Indent;
403   } else {
404     State.Column = State.Stack.back().Indent;
405     // Ensure that we fall back to the continuation indent width instead of just
406     // flushing continuations left.
407     if (State.Column == State.FirstIndent &&
408         PreviousNonComment->isNot(tok::r_brace))
409       State.Column += Style.ContinuationIndentWidth;
410   }
411 
412   if ((Previous.isOneOf(tok::comma, tok::semi) &&
413        !State.Stack.back().AvoidBinPacking) ||
414       Previous.Type == TT_BinaryOperator)
415     State.Stack.back().BreakBeforeParameter = false;
416   if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
417     State.Stack.back().BreakBeforeParameter = false;
418   if (Current.is(tok::question) ||
419       (PreviousNonComment && PreviousNonComment->is(tok::question)))
420     State.Stack.back().BreakBeforeParameter = true;
421 
422   if (!DryRun) {
423     unsigned Newlines = 1;
424     if (Current.is(tok::comment))
425       Newlines = std::max(Newlines, std::min(Current.NewlinesBefore,
426                                              Style.MaxEmptyLinesToKeep + 1));
427     Whitespaces.replaceWhitespace(Current, Newlines,
428                                   State.Stack.back().IndentLevel, State.Column,
429                                   State.Column, State.Line->InPPDirective);
430   }
431 
432   if (!Current.isTrailingComment())
433     State.Stack.back().LastSpace = State.Column;
434   if (Current.isMemberAccess())
435     State.Stack.back().LastSpace += Current.ColumnWidth;
436   State.StartOfLineLevel = State.ParenLevel;
437   State.LowestLevelOnLine = State.ParenLevel;
438 
439   // Any break on this level means that the parent level has been broken
440   // and we need to avoid bin packing there.
441   for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
442     State.Stack[i].BreakBeforeParameter = true;
443   }
444   if (PreviousNonComment &&
445       !PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
446       PreviousNonComment->Type != TT_TemplateCloser &&
447       PreviousNonComment->Type != TT_BinaryOperator &&
448       Current.Type != TT_BinaryOperator &&
449       !PreviousNonComment->opensScope())
450     State.Stack.back().BreakBeforeParameter = true;
451 
452   // If we break after { or the [ of an array initializer, we should also break
453   // before the corresponding } or ].
454   if (Previous.is(tok::l_brace) || Previous.Type == TT_ArrayInitializerLSquare)
455     State.Stack.back().BreakBeforeClosingBrace = true;
456 
457   if (State.Stack.back().AvoidBinPacking) {
458     // If we are breaking after '(', '{', '<', this is not bin packing
459     // unless AllowAllParametersOfDeclarationOnNextLine is false.
460     if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
461           Previous.Type == TT_BinaryOperator) ||
462         (!Style.AllowAllParametersOfDeclarationOnNextLine &&
463          State.Line->MustBeDeclaration))
464       State.Stack.back().BreakBeforeParameter = true;
465   }
466 
467   return Penalty;
468 }
469 
470 unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
471                                                     bool DryRun, bool Newline) {
472   const FormatToken &Current = *State.NextToken;
473   assert(State.Stack.size());
474 
475   if (Current.Type == TT_InheritanceColon)
476     State.Stack.back().AvoidBinPacking = true;
477   if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
478     State.Stack.back().FirstLessLess = State.Column;
479   if (Current.Type == TT_ArraySubscriptLSquare &&
480       State.Stack.back().StartOfArraySubscripts == 0)
481     State.Stack.back().StartOfArraySubscripts = State.Column;
482   if ((Current.is(tok::question) && Style.BreakBeforeTernaryOperators) ||
483       (Current.getPreviousNonComment() && Current.isNot(tok::colon) &&
484        Current.getPreviousNonComment()->is(tok::question) &&
485        !Style.BreakBeforeTernaryOperators))
486     State.Stack.back().QuestionColumn = State.Column;
487   if (!Current.opensScope() && !Current.closesScope())
488     State.LowestLevelOnLine =
489         std::min(State.LowestLevelOnLine, State.ParenLevel);
490   if (Current.isMemberAccess())
491     State.Stack.back().StartOfFunctionCall =
492         Current.LastInChainOfCalls ? 0 : State.Column + Current.ColumnWidth;
493   if (Current.Type == TT_CtorInitializerColon) {
494     // Indent 2 from the column, so:
495     // SomeClass::SomeClass()
496     //     : First(...), ...
497     //       Next(...)
498     //       ^ line up here.
499     State.Stack.back().Indent =
500         State.Column + (Style.BreakConstructorInitializersBeforeComma ? 0 : 2);
501     if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
502       State.Stack.back().AvoidBinPacking = true;
503     State.Stack.back().BreakBeforeParameter = false;
504   }
505 
506   // In ObjC method declaration we align on the ":" of parameters, but we need
507   // to ensure that we indent parameters on subsequent lines by at least our
508   // continuation indent width.
509   if (Current.Type == TT_ObjCMethodSpecifier)
510     State.Stack.back().Indent += Style.ContinuationIndentWidth;
511 
512   // Insert scopes created by fake parenthesis.
513   const FormatToken *Previous = Current.getPreviousNonComment();
514   // Don't add extra indentation for the first fake parenthesis after
515   // 'return', assignements or opening <({[. The indentation for these cases
516   // is special cased.
517   bool SkipFirstExtraIndent =
518       (Previous && (Previous->opensScope() || Previous->is(tok::kw_return) ||
519                     Previous->getPrecedence() == prec::Assignment ||
520                     Previous->Type == TT_ObjCMethodExpr));
521   for (SmallVectorImpl<prec::Level>::const_reverse_iterator
522            I = Current.FakeLParens.rbegin(),
523            E = Current.FakeLParens.rend();
524        I != E; ++I) {
525     ParenState NewParenState = State.Stack.back();
526     NewParenState.ContainsLineBreak = false;
527 
528     // Indent from 'LastSpace' unless this the fake parentheses encapsulating a
529     // builder type call after 'return'. If such a call is line-wrapped, we
530     // commonly just want to indent from the start of the line.
531     if (!Previous || Previous->isNot(tok::kw_return) || *I > 0)
532       NewParenState.Indent =
533           std::max(std::max(State.Column, NewParenState.Indent),
534                    State.Stack.back().LastSpace);
535 
536     // Do not indent relative to the fake parentheses inserted for "." or "->".
537     // This is a special case to make the following to statements consistent:
538     //   OuterFunction(InnerFunctionCall( // break
539     //       ParameterToInnerFunction));
540     //   OuterFunction(SomeObject.InnerFunctionCall( // break
541     //       ParameterToInnerFunction));
542     if (*I > prec::Unknown)
543       NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
544 
545     // Always indent conditional expressions. Never indent expression where
546     // the 'operator' is ',', ';' or an assignment (i.e. *I <=
547     // prec::Assignment) as those have different indentation rules. Indent
548     // other expression, unless the indentation needs to be skipped.
549     if (*I == prec::Conditional ||
550         (!SkipFirstExtraIndent && *I > prec::Assignment &&
551          !Style.BreakBeforeBinaryOperators))
552       NewParenState.Indent += Style.ContinuationIndentWidth;
553     if ((Previous && !Previous->opensScope()) || *I > prec::Comma)
554       NewParenState.BreakBeforeParameter = false;
555     State.Stack.push_back(NewParenState);
556     SkipFirstExtraIndent = false;
557   }
558 
559   // If we encounter an opening (, [, { or <, we add a level to our stacks to
560   // prepare for the following tokens.
561   if (Current.opensScope()) {
562     unsigned NewIndent;
563     unsigned NewIndentLevel = State.Stack.back().IndentLevel;
564     bool AvoidBinPacking;
565     bool BreakBeforeParameter = false;
566     if (Current.is(tok::l_brace) ||
567         Current.Type == TT_ArrayInitializerLSquare) {
568       if (Current.MatchingParen && Current.BlockKind == BK_Block) {
569         // If this is an l_brace starting a nested block, we pretend (wrt. to
570         // indentation) that we already consumed the corresponding r_brace.
571         // Thus, we remove all ParenStates caused bake fake parentheses that end
572         // at the r_brace. The net effect of this is that we don't indent
573         // relative to the l_brace, if the nested block is the last parameter of
574         // a function. For example, this formats:
575         //
576         //   SomeFunction(a, [] {
577         //     f();  // break
578         //   });
579         //
580         // instead of:
581         //   SomeFunction(a, [] {
582         //                        f();  // break
583         //                      });
584         for (unsigned i = 0; i != Current.MatchingParen->FakeRParens; ++i)
585           State.Stack.pop_back();
586         NewIndent = State.Stack.back().LastSpace + Style.IndentWidth;
587         ++NewIndentLevel;
588         BreakBeforeParameter = true;
589       } else {
590         NewIndent = State.Stack.back().LastSpace;
591         if (Current.opensBlockTypeList(Style)) {
592           NewIndent += Style.IndentWidth;
593           ++NewIndentLevel;
594         } else {
595           NewIndent += Style.ContinuationIndentWidth;
596         }
597       }
598       const FormatToken *NextNoComment = Current.getNextNonComment();
599       AvoidBinPacking = Current.BlockKind == BK_Block ||
600                         Current.Type == TT_ArrayInitializerLSquare ||
601                         Current.Type == TT_DictLiteral ||
602                         (NextNoComment &&
603                          NextNoComment->Type == TT_DesignatedInitializerPeriod);
604     } else {
605       NewIndent = Style.ContinuationIndentWidth +
606                   std::max(State.Stack.back().LastSpace,
607                            State.Stack.back().StartOfFunctionCall);
608       AvoidBinPacking = !Style.BinPackParameters ||
609                         (Style.ExperimentalAutoDetectBinPacking &&
610                          (Current.PackingKind == PPK_OnePerLine ||
611                           (!BinPackInconclusiveFunctions &&
612                            Current.PackingKind == PPK_Inconclusive)));
613       // If this '[' opens an ObjC call, determine whether all parameters fit
614       // into one line and put one per line if they don't.
615       if (Current.Type == TT_ObjCMethodExpr &&
616           getLengthToMatchingParen(Current) + State.Column >
617               getColumnLimit(State))
618         BreakBeforeParameter = true;
619     }
620 
621     bool NoLineBreak = State.Stack.back().NoLineBreak ||
622                        (Current.Type == TT_TemplateOpener &&
623                         State.Stack.back().ContainsUnwrappedBuilder);
624     State.Stack.push_back(ParenState(NewIndent, NewIndentLevel,
625                                      State.Stack.back().LastSpace,
626                                      AvoidBinPacking, NoLineBreak));
627     State.Stack.back().BreakBeforeParameter = BreakBeforeParameter;
628     ++State.ParenLevel;
629   }
630 
631   // If we encounter a closing ), ], } or >, we can remove a level from our
632   // stacks.
633   if (State.Stack.size() > 1 &&
634       (Current.isOneOf(tok::r_paren, tok::r_square) ||
635        (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
636        State.NextToken->Type == TT_TemplateCloser)) {
637     State.Stack.pop_back();
638     --State.ParenLevel;
639   }
640   if (Current.is(tok::r_square)) {
641     // If this ends the array subscript expr, reset the corresponding value.
642     const FormatToken *NextNonComment = Current.getNextNonComment();
643     if (NextNonComment && NextNonComment->isNot(tok::l_square))
644       State.Stack.back().StartOfArraySubscripts = 0;
645   }
646 
647   // Remove scopes created by fake parenthesis.
648   if (Current.isNot(tok::r_brace) ||
649       (Current.MatchingParen && Current.MatchingParen->BlockKind != BK_Block)) {
650     // Don't remove FakeRParens attached to r_braces that surround nested blocks
651     // as they will have been removed early (see above).
652     for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
653       unsigned VariablePos = State.Stack.back().VariablePos;
654       State.Stack.pop_back();
655       State.Stack.back().VariablePos = VariablePos;
656     }
657   }
658 
659   if (Current.is(tok::string_literal) && State.StartOfStringLiteral == 0) {
660     State.StartOfStringLiteral = State.Column;
661   } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash,
662                               tok::string_literal)) {
663     State.StartOfStringLiteral = 0;
664   }
665 
666   State.Column += Current.ColumnWidth;
667   State.NextToken = State.NextToken->Next;
668   unsigned Penalty = breakProtrudingToken(Current, State, DryRun);
669   if (State.Column > getColumnLimit(State)) {
670     unsigned ExcessCharacters = State.Column - getColumnLimit(State);
671     Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
672   }
673 
674   // If the previous has a special role, let it consume tokens as appropriate.
675   // It is necessary to start at the previous token for the only implemented
676   // role (comma separated list). That way, the decision whether or not to break
677   // after the "{" is already done and both options are tried and evaluated.
678   // FIXME: This is ugly, find a better way.
679   if (Previous && Previous->Role)
680     Penalty += Previous->Role->format(State, this, DryRun);
681 
682   return Penalty;
683 }
684 
685 unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
686                                                  LineState &State) {
687   // Break before further function parameters on all levels.
688   for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
689     State.Stack[i].BreakBeforeParameter = true;
690 
691   unsigned ColumnsUsed = State.Column;
692   // We can only affect layout of the first and the last line, so the penalty
693   // for all other lines is constant, and we ignore it.
694   State.Column = Current.LastLineColumnWidth;
695 
696   if (ColumnsUsed > getColumnLimit(State))
697     return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
698   return 0;
699 }
700 
701 static bool getRawStringLiteralPrefixPostfix(StringRef Text,
702                                              StringRef &Prefix,
703                                              StringRef &Postfix) {
704   if (Text.startswith(Prefix = "R\"") || Text.startswith(Prefix = "uR\"") ||
705       Text.startswith(Prefix = "UR\"") || Text.startswith(Prefix = "u8R\"") ||
706       Text.startswith(Prefix = "LR\"")) {
707     size_t ParenPos = Text.find('(');
708     if (ParenPos != StringRef::npos) {
709       StringRef Delimiter =
710           Text.substr(Prefix.size(), ParenPos - Prefix.size());
711       Prefix = Text.substr(0, ParenPos + 1);
712       Postfix = Text.substr(Text.size() - 2 - Delimiter.size());
713       return Postfix.front() == ')' && Postfix.back() == '"' &&
714              Postfix.substr(1).startswith(Delimiter);
715     }
716   }
717   return false;
718 }
719 
720 unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
721                                                     LineState &State,
722                                                     bool DryRun) {
723   // Don't break multi-line tokens other than block comments. Instead, just
724   // update the state.
725   if (Current.Type != TT_BlockComment && Current.IsMultiline)
726     return addMultilineToken(Current, State);
727 
728   // Don't break implicit string literals.
729   if (Current.Type == TT_ImplicitStringLiteral)
730     return 0;
731 
732   if (!Current.isOneOf(tok::string_literal, tok::wide_string_literal,
733                        tok::utf8_string_literal, tok::utf16_string_literal,
734                        tok::utf32_string_literal, tok::comment))
735     return 0;
736 
737   llvm::OwningPtr<BreakableToken> Token;
738   unsigned StartColumn = State.Column - Current.ColumnWidth;
739   unsigned ColumnLimit = getColumnLimit(State);
740 
741   if (Current.isOneOf(tok::string_literal, tok::wide_string_literal,
742                       tok::utf8_string_literal, tok::utf16_string_literal,
743                       tok::utf32_string_literal) &&
744       Current.Type != TT_ImplicitStringLiteral) {
745     // Don't break string literals inside preprocessor directives (except for
746     // #define directives, as their contents are stored in separate lines and
747     // are not affected by this check).
748     // This way we avoid breaking code with line directives and unknown
749     // preprocessor directives that contain long string literals.
750     if (State.Line->Type == LT_PreprocessorDirective)
751       return 0;
752     // Exempts unterminated string literals from line breaking. The user will
753     // likely want to terminate the string before any line breaking is done.
754     if (Current.IsUnterminatedLiteral)
755       return 0;
756 
757     StringRef Text = Current.TokenText;
758     StringRef Prefix;
759     StringRef Postfix;
760     // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
761     // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
762     // reduce the overhead) for each FormatToken, which is a string, so that we
763     // don't run multiple checks here on the hot path.
764     if ((Text.endswith(Postfix = "\"") &&
765          (Text.startswith(Prefix = "\"") || Text.startswith(Prefix = "u\"") ||
766           Text.startswith(Prefix = "U\"") || Text.startswith(Prefix = "u8\"") ||
767           Text.startswith(Prefix = "L\""))) ||
768         (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")")) ||
769         getRawStringLiteralPrefixPostfix(Text, Prefix, Postfix)) {
770       Token.reset(new BreakableStringLiteral(
771           Current, State.Line->Level, StartColumn, Prefix, Postfix,
772           State.Line->InPPDirective, Encoding, Style));
773     } else {
774       return 0;
775     }
776   } else if (Current.Type == TT_BlockComment && Current.isTrailingComment()) {
777     Token.reset(new BreakableBlockComment(
778         Current, State.Line->Level, StartColumn, Current.OriginalColumn,
779         !Current.Previous, State.Line->InPPDirective, Encoding, Style));
780   } else if (Current.Type == TT_LineComment &&
781              (Current.Previous == NULL ||
782               Current.Previous->Type != TT_ImplicitStringLiteral)) {
783     Token.reset(new BreakableLineComment(Current, State.Line->Level,
784                                          StartColumn, /*InPPDirective=*/false,
785                                          Encoding, Style));
786     // We don't insert backslashes when breaking line comments.
787     ColumnLimit = Style.ColumnLimit;
788   } else {
789     return 0;
790   }
791   if (Current.UnbreakableTailLength >= ColumnLimit)
792     return 0;
793 
794   unsigned RemainingSpace = ColumnLimit - Current.UnbreakableTailLength;
795   bool BreakInserted = false;
796   unsigned Penalty = 0;
797   unsigned RemainingTokenColumns = 0;
798   for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
799        LineIndex != EndIndex; ++LineIndex) {
800     if (!DryRun)
801       Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
802     unsigned TailOffset = 0;
803     RemainingTokenColumns =
804         Token->getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
805     while (RemainingTokenColumns > RemainingSpace) {
806       BreakableToken::Split Split =
807           Token->getSplit(LineIndex, TailOffset, ColumnLimit);
808       if (Split.first == StringRef::npos) {
809         // The last line's penalty is handled in addNextStateToQueue().
810         if (LineIndex < EndIndex - 1)
811           Penalty += Style.PenaltyExcessCharacter *
812                      (RemainingTokenColumns - RemainingSpace);
813         break;
814       }
815       assert(Split.first != 0);
816       unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
817           LineIndex, TailOffset + Split.first + Split.second, StringRef::npos);
818 
819       // We can remove extra whitespace instead of breaking the line.
820       if (RemainingTokenColumns + 1 - Split.second <= RemainingSpace) {
821         RemainingTokenColumns = 0;
822         if (!DryRun)
823           Token->replaceWhitespace(LineIndex, TailOffset, Split, Whitespaces);
824         break;
825       }
826 
827       assert(NewRemainingTokenColumns < RemainingTokenColumns);
828       if (!DryRun)
829         Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
830       Penalty += Current.SplitPenalty;
831       unsigned ColumnsUsed =
832           Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
833       if (ColumnsUsed > ColumnLimit) {
834         Penalty += Style.PenaltyExcessCharacter * (ColumnsUsed - ColumnLimit);
835       }
836       TailOffset += Split.first + Split.second;
837       RemainingTokenColumns = NewRemainingTokenColumns;
838       BreakInserted = true;
839     }
840   }
841 
842   State.Column = RemainingTokenColumns;
843 
844   if (BreakInserted) {
845     // If we break the token inside a parameter list, we need to break before
846     // the next parameter on all levels, so that the next parameter is clearly
847     // visible. Line comments already introduce a break.
848     if (Current.Type != TT_LineComment) {
849       for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
850         State.Stack[i].BreakBeforeParameter = true;
851     }
852 
853     Penalty += Current.is(tok::string_literal) ? Style.PenaltyBreakString
854                                                : Style.PenaltyBreakComment;
855 
856     State.Stack.back().LastSpace = StartColumn;
857   }
858   return Penalty;
859 }
860 
861 unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
862   // In preprocessor directives reserve two chars for trailing " \"
863   return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
864 }
865 
866 bool ContinuationIndenter::NextIsMultilineString(const LineState &State) {
867   const FormatToken &Current = *State.NextToken;
868   if (!Current.is(tok::string_literal))
869     return false;
870   // We never consider raw string literals "multiline" for the purpose of
871   // AlwaysBreakBeforeMultilineStrings implementation.
872   if (Current.TokenText.startswith("R\""))
873     return false;
874   if (Current.IsMultiline)
875     return true;
876   if (Current.getNextNonComment() &&
877       Current.getNextNonComment()->is(tok::string_literal))
878     return true; // Implicit concatenation.
879   if (State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
880       Style.ColumnLimit)
881     return true; // String will be split.
882   return false;
883 }
884 
885 } // namespace format
886 } // namespace clang
887