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