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