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