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