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