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