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