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   }
489 
490   if (PreviousNonComment &&
491       !PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
492       (PreviousNonComment->isNot(TT_TemplateCloser) ||
493        Current.NestingLevel != 0) &&
494       !PreviousNonComment->isOneOf(
495           TT_BinaryOperator, TT_FunctionAnnotationRParen, TT_JavaAnnotation,
496           TT_LeadingJavaAnnotation) &&
497       Current.isNot(TT_BinaryOperator) && !PreviousNonComment->opensScope())
498     State.Stack.back().BreakBeforeParameter = true;
499 
500   // If we break after { or the [ of an array initializer, we should also break
501   // before the corresponding } or ].
502   if (PreviousNonComment &&
503       (PreviousNonComment->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare)))
504     State.Stack.back().BreakBeforeClosingBrace = true;
505 
506   if (State.Stack.back().AvoidBinPacking) {
507     // If we are breaking after '(', '{', '<', this is not bin packing
508     // unless AllowAllParametersOfDeclarationOnNextLine is false or this is a
509     // dict/object literal.
510     if (!Previous.isOneOf(tok::l_paren, tok::l_brace, TT_BinaryOperator) ||
511         (!Style.AllowAllParametersOfDeclarationOnNextLine &&
512          State.Line->MustBeDeclaration) ||
513         Previous.is(TT_DictLiteral))
514       State.Stack.back().BreakBeforeParameter = true;
515   }
516 
517   return Penalty;
518 }
519 
520 unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) {
521   if (!State.NextToken || !State.NextToken->Previous)
522     return 0;
523   FormatToken &Current = *State.NextToken;
524   const FormatToken &Previous = *Current.Previous;
525   // If we are continuing an expression, we want to use the continuation indent.
526   unsigned ContinuationIndent =
527       std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
528       Style.ContinuationIndentWidth;
529   const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
530   const FormatToken *NextNonComment = Previous.getNextNonComment();
531   if (!NextNonComment)
532     NextNonComment = &Current;
533 
534   // Java specific bits.
535   if (Style.Language == FormatStyle::LK_Java &&
536       Current.isOneOf(Keywords.kw_implements, Keywords.kw_extends))
537     return std::max(State.Stack.back().LastSpace,
538                     State.Stack.back().Indent + Style.ContinuationIndentWidth);
539 
540   if (NextNonComment->is(tok::l_brace) && NextNonComment->BlockKind == BK_Block)
541     return Current.NestingLevel == 0 ? State.FirstIndent
542                                      : State.Stack.back().Indent;
543   if (Current.isOneOf(tok::r_brace, tok::r_square) && State.Stack.size() > 1) {
544     if (Current.closesBlockTypeList(Style))
545       return State.Stack[State.Stack.size() - 2].NestedBlockIndent;
546     if (Current.MatchingParen &&
547         Current.MatchingParen->BlockKind == BK_BracedInit)
548       return State.Stack[State.Stack.size() - 2].LastSpace;
549     return State.FirstIndent;
550   }
551   if (Current.is(tok::identifier) && Current.Next &&
552       Current.Next->is(TT_DictLiteral))
553     return State.Stack.back().Indent;
554   if (NextNonComment->isStringLiteral() && State.StartOfStringLiteral != 0)
555     return State.StartOfStringLiteral;
556   if (NextNonComment->is(TT_ObjCStringLiteral) &&
557       State.StartOfStringLiteral != 0)
558     return State.StartOfStringLiteral - 1;
559   if (NextNonComment->is(tok::lessless) &&
560       State.Stack.back().FirstLessLess != 0)
561     return State.Stack.back().FirstLessLess;
562   if (NextNonComment->isMemberAccess()) {
563     if (State.Stack.back().CallContinuation == 0)
564       return ContinuationIndent;
565     return State.Stack.back().CallContinuation;
566   }
567   if (State.Stack.back().QuestionColumn != 0 &&
568       ((NextNonComment->is(tok::colon) &&
569         NextNonComment->is(TT_ConditionalExpr)) ||
570        Previous.is(TT_ConditionalExpr)))
571     return State.Stack.back().QuestionColumn;
572   if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0)
573     return State.Stack.back().VariablePos;
574   if ((PreviousNonComment &&
575        (PreviousNonComment->ClosesTemplateDeclaration ||
576         PreviousNonComment->isOneOf(
577             TT_AttributeParen, TT_FunctionAnnotationRParen, TT_JavaAnnotation,
578             TT_LeadingJavaAnnotation))) ||
579       (!Style.IndentWrappedFunctionNames &&
580        NextNonComment->isOneOf(tok::kw_operator, TT_FunctionDeclarationName)))
581     return std::max(State.Stack.back().LastSpace, State.Stack.back().Indent);
582   if (NextNonComment->is(TT_SelectorName)) {
583     if (!State.Stack.back().ObjCSelectorNameFound) {
584       if (NextNonComment->LongestObjCSelectorName == 0)
585         return State.Stack.back().Indent;
586       return (Style.IndentWrappedFunctionNames
587                   ? std::max(State.Stack.back().Indent,
588                              State.FirstIndent + Style.ContinuationIndentWidth)
589                   : State.Stack.back().Indent) +
590              NextNonComment->LongestObjCSelectorName -
591              NextNonComment->ColumnWidth;
592     }
593     if (!State.Stack.back().AlignColons)
594       return State.Stack.back().Indent;
595     if (State.Stack.back().ColonPos > NextNonComment->ColumnWidth)
596       return State.Stack.back().ColonPos - NextNonComment->ColumnWidth;
597     return State.Stack.back().Indent;
598   }
599   if (NextNonComment->is(TT_ArraySubscriptLSquare)) {
600     if (State.Stack.back().StartOfArraySubscripts != 0)
601       return State.Stack.back().StartOfArraySubscripts;
602     return ContinuationIndent;
603   }
604 
605   // This ensure that we correctly format ObjC methods calls without inputs,
606   // i.e. where the last element isn't selector like: [callee method];
607   if (NextNonComment->is(tok::identifier) && NextNonComment->FakeRParens == 0 &&
608       NextNonComment->Next && NextNonComment->Next->is(TT_ObjCMethodExpr))
609     return State.Stack.back().Indent;
610 
611   if (NextNonComment->isOneOf(TT_StartOfName, TT_PointerOrReference) ||
612       Previous.isOneOf(tok::coloncolon, tok::equal))
613     return ContinuationIndent;
614   if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
615       PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))
616     return ContinuationIndent;
617   if (NextNonComment->is(TT_CtorInitializerColon))
618     return State.FirstIndent + Style.ConstructorInitializerIndentWidth;
619   if (NextNonComment->is(TT_CtorInitializerComma))
620     return State.Stack.back().Indent;
621   if (Previous.is(tok::r_paren) && !Current.isBinaryOperator() &&
622       !Current.isOneOf(tok::colon, tok::comment))
623     return ContinuationIndent;
624   if (State.Stack.back().Indent == State.FirstIndent && PreviousNonComment &&
625       PreviousNonComment->isNot(tok::r_brace))
626     // Ensure that we fall back to the continuation indent width instead of
627     // just flushing continuations left.
628     return State.Stack.back().Indent + Style.ContinuationIndentWidth;
629   return State.Stack.back().Indent;
630 }
631 
632 unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
633                                                     bool DryRun, bool Newline) {
634   assert(State.Stack.size());
635   const FormatToken &Current = *State.NextToken;
636 
637   if (Current.is(TT_InheritanceColon))
638     State.Stack.back().AvoidBinPacking = true;
639   if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator)) {
640     if (State.Stack.back().FirstLessLess == 0)
641       State.Stack.back().FirstLessLess = State.Column;
642     else
643       State.Stack.back().LastOperatorWrapped = Newline;
644   }
645   if ((Current.is(TT_BinaryOperator) && Current.isNot(tok::lessless)) ||
646       Current.is(TT_ConditionalExpr))
647     State.Stack.back().LastOperatorWrapped = Newline;
648   if (Current.is(TT_ArraySubscriptLSquare) &&
649       State.Stack.back().StartOfArraySubscripts == 0)
650     State.Stack.back().StartOfArraySubscripts = State.Column;
651   if ((Current.is(tok::question) && Style.BreakBeforeTernaryOperators) ||
652       (Current.getPreviousNonComment() && Current.isNot(tok::colon) &&
653        Current.getPreviousNonComment()->is(tok::question) &&
654        !Style.BreakBeforeTernaryOperators))
655     State.Stack.back().QuestionColumn = State.Column;
656   if (!Current.opensScope() && !Current.closesScope())
657     State.LowestLevelOnLine =
658         std::min(State.LowestLevelOnLine, Current.NestingLevel);
659   if (Current.isMemberAccess())
660     State.Stack.back().StartOfFunctionCall =
661         Current.LastOperator ? 0 : State.Column;
662   if (Current.is(TT_SelectorName))
663     State.Stack.back().ObjCSelectorNameFound = true;
664   if (Current.is(TT_CtorInitializerColon)) {
665     // Indent 2 from the column, so:
666     // SomeClass::SomeClass()
667     //     : First(...), ...
668     //       Next(...)
669     //       ^ line up here.
670     State.Stack.back().Indent =
671         State.Column + (Style.BreakConstructorInitializersBeforeComma ? 0 : 2);
672     State.Stack.back().NestedBlockIndent = State.Stack.back().Indent;
673     if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
674       State.Stack.back().AvoidBinPacking = true;
675     State.Stack.back().BreakBeforeParameter = false;
676   }
677   if (Current.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) && Newline)
678     State.Stack.back().NestedBlockIndent =
679         State.Column + Current.ColumnWidth + 1;
680 
681   // Insert scopes created by fake parenthesis.
682   const FormatToken *Previous = Current.getPreviousNonComment();
683 
684   // Add special behavior to support a format commonly used for JavaScript
685   // closures:
686   //   SomeFunction(function() {
687   //     foo();
688   //     bar();
689   //   }, a, b, c);
690   if (Current.isNot(tok::comment) && Previous && Previous->is(tok::l_brace) &&
691       State.Stack.size() > 1) {
692     if (State.Stack[State.Stack.size() - 2].NestedBlockInlined && Newline) {
693       for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
694         State.Stack[i].NoLineBreak = true;
695       }
696     }
697     State.Stack[State.Stack.size() - 2].NestedBlockInlined = false;
698   }
699   if (Previous && (Previous->isOneOf(tok::l_paren, tok::comma, tok::colon) ||
700                    Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr)) &&
701       !Previous->isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
702     State.Stack.back().NestedBlockInlined =
703         !Newline &&
704         (Previous->isNot(tok::l_paren) || Previous->ParameterCount > 1);
705   }
706 
707   moveStatePastFakeLParens(State, Newline);
708   moveStatePastScopeOpener(State, Newline);
709   moveStatePastScopeCloser(State);
710   moveStatePastFakeRParens(State);
711 
712   if (Current.isStringLiteral() && State.StartOfStringLiteral == 0)
713     State.StartOfStringLiteral = State.Column;
714   if (Current.is(TT_ObjCStringLiteral) && State.StartOfStringLiteral == 0)
715     State.StartOfStringLiteral = State.Column + 1;
716   else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
717              !Current.isStringLiteral())
718     State.StartOfStringLiteral = 0;
719 
720   State.Column += Current.ColumnWidth;
721   State.NextToken = State.NextToken->Next;
722   unsigned Penalty = breakProtrudingToken(Current, State, DryRun);
723   if (State.Column > getColumnLimit(State)) {
724     unsigned ExcessCharacters = State.Column - getColumnLimit(State);
725     Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
726   }
727 
728   if (Current.Role)
729     Current.Role->formatFromToken(State, this, DryRun);
730   // If the previous has a special role, let it consume tokens as appropriate.
731   // It is necessary to start at the previous token for the only implemented
732   // role (comma separated list). That way, the decision whether or not to break
733   // after the "{" is already done and both options are tried and evaluated.
734   // FIXME: This is ugly, find a better way.
735   if (Previous && Previous->Role)
736     Penalty += Previous->Role->formatAfterToken(State, this, DryRun);
737 
738   return Penalty;
739 }
740 
741 void ContinuationIndenter::moveStatePastFakeLParens(LineState &State,
742                                                     bool Newline) {
743   const FormatToken &Current = *State.NextToken;
744   const FormatToken *Previous = Current.getPreviousNonComment();
745 
746   // Don't add extra indentation for the first fake parenthesis after
747   // 'return', assignments or opening <({[. The indentation for these cases
748   // is special cased.
749   bool SkipFirstExtraIndent =
750       (Previous && (Previous->opensScope() ||
751                     Previous->isOneOf(tok::semi, tok::kw_return) ||
752                     (Previous->getPrecedence() == prec::Assignment &&
753                      Style.AlignOperands) ||
754                     Previous->is(TT_ObjCMethodExpr)));
755   for (SmallVectorImpl<prec::Level>::const_reverse_iterator
756            I = Current.FakeLParens.rbegin(),
757            E = Current.FakeLParens.rend();
758        I != E; ++I) {
759     ParenState NewParenState = State.Stack.back();
760     NewParenState.ContainsLineBreak = false;
761 
762     // Indent from 'LastSpace' unless these are fake parentheses encapsulating
763     // a builder type call after 'return' or, if the alignment after opening
764     // brackets is disabled.
765     if (!Current.isTrailingComment() &&
766         (Style.AlignOperands || *I < prec::Assignment) &&
767         (!Previous || Previous->isNot(tok::kw_return) ||
768          (Style.Language != FormatStyle::LK_Java && *I > 0)) &&
769         (Style.AlignAfterOpenBracket || *I != prec::Comma ||
770          Current.NestingLevel == 0))
771       NewParenState.Indent =
772           std::max(std::max(State.Column, NewParenState.Indent),
773                    State.Stack.back().LastSpace);
774 
775     // Don't allow the RHS of an operator to be split over multiple lines unless
776     // there is a line-break right after the operator.
777     // Exclude relational operators, as there, it is always more desirable to
778     // have the LHS 'left' of the RHS.
779     if (Previous && Previous->getPrecedence() > prec::Assignment &&
780         Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
781         Previous->getPrecedence() != prec::Relational) {
782       bool BreakBeforeOperator =
783           Previous->is(tok::lessless) ||
784           (Previous->is(TT_BinaryOperator) &&
785            Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None) ||
786           (Previous->is(TT_ConditionalExpr) &&
787            Style.BreakBeforeTernaryOperators);
788       if ((!Newline && !BreakBeforeOperator) ||
789           (!State.Stack.back().LastOperatorWrapped && BreakBeforeOperator))
790         NewParenState.NoLineBreak = true;
791     }
792 
793     // Do not indent relative to the fake parentheses inserted for "." or "->".
794     // This is a special case to make the following to statements consistent:
795     //   OuterFunction(InnerFunctionCall( // break
796     //       ParameterToInnerFunction));
797     //   OuterFunction(SomeObject.InnerFunctionCall( // break
798     //       ParameterToInnerFunction));
799     if (*I > prec::Unknown)
800       NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
801     if (*I != prec::Conditional)
802       NewParenState.StartOfFunctionCall = State.Column;
803 
804     // Always indent conditional expressions. Never indent expression where
805     // the 'operator' is ',', ';' or an assignment (i.e. *I <=
806     // prec::Assignment) as those have different indentation rules. Indent
807     // other expression, unless the indentation needs to be skipped.
808     if (*I == prec::Conditional ||
809         (!SkipFirstExtraIndent && *I > prec::Assignment &&
810          !Current.isTrailingComment()))
811       NewParenState.Indent += Style.ContinuationIndentWidth;
812     if ((Previous && !Previous->opensScope()) || *I > prec::Comma)
813       NewParenState.BreakBeforeParameter = false;
814     State.Stack.push_back(NewParenState);
815     SkipFirstExtraIndent = false;
816   }
817 }
818 
819 void ContinuationIndenter::moveStatePastFakeRParens(LineState &State) {
820   for (unsigned i = 0, e = State.NextToken->FakeRParens; i != e; ++i) {
821     unsigned VariablePos = State.Stack.back().VariablePos;
822     if (State.Stack.size() == 1) {
823       // Do not pop the last element.
824       break;
825     }
826     State.Stack.pop_back();
827     State.Stack.back().VariablePos = VariablePos;
828   }
829 }
830 
831 void ContinuationIndenter::moveStatePastScopeOpener(LineState &State,
832                                                     bool Newline) {
833   const FormatToken &Current = *State.NextToken;
834   if (!Current.opensScope())
835     return;
836 
837   if (Current.MatchingParen && Current.BlockKind == BK_Block) {
838     moveStateToNewBlock(State);
839     return;
840   }
841 
842   unsigned NewIndent;
843   unsigned NewIndentLevel = State.Stack.back().IndentLevel;
844   unsigned LastSpace = State.Stack.back().LastSpace;
845   bool AvoidBinPacking;
846   bool BreakBeforeParameter = false;
847   if (Current.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare)) {
848     if (Current.opensBlockTypeList(Style)) {
849       NewIndent = State.Stack.back().NestedBlockIndent + Style.IndentWidth;
850       NewIndent = std::min(State.Column + 2, NewIndent);
851       ++NewIndentLevel;
852     } else {
853       NewIndent = State.Stack.back().LastSpace + Style.ContinuationIndentWidth;
854     }
855     const FormatToken *NextNoComment = Current.getNextNonComment();
856     AvoidBinPacking =
857         Current.isOneOf(TT_ArrayInitializerLSquare, TT_DictLiteral) ||
858         Style.Language == FormatStyle::LK_Proto || !Style.BinPackArguments ||
859         (NextNoComment && NextNoComment->is(TT_DesignatedInitializerPeriod));
860   } else {
861     NewIndent = Style.ContinuationIndentWidth +
862                 std::max(State.Stack.back().LastSpace,
863                          State.Stack.back().StartOfFunctionCall);
864 
865     // Ensure that different different brackets force relative alignment, e.g.:
866     // void SomeFunction(vector<  // break
867     //                       int> v);
868     // FIXME: We likely want to do this for more combinations of brackets.
869     // Verify that it is wanted for ObjC, too.
870     if (Current.Tok.getKind() == tok::less &&
871         Current.ParentBracket == tok::l_paren) {
872       NewIndent = std::max(NewIndent, State.Stack.back().Indent);
873       LastSpace = std::max(LastSpace, State.Stack.back().Indent);
874     }
875 
876     AvoidBinPacking =
877         (State.Line->MustBeDeclaration && !Style.BinPackParameters) ||
878         (!State.Line->MustBeDeclaration && !Style.BinPackArguments) ||
879         (Style.ExperimentalAutoDetectBinPacking &&
880          (Current.PackingKind == PPK_OnePerLine ||
881           (!BinPackInconclusiveFunctions &&
882            Current.PackingKind == PPK_Inconclusive)));
883     if (Current.is(TT_ObjCMethodExpr) && Current.MatchingParen) {
884       if (Style.ColumnLimit) {
885         // If this '[' opens an ObjC call, determine whether all parameters fit
886         // into one line and put one per line if they don't.
887         if (getLengthToMatchingParen(Current) + State.Column >
888             getColumnLimit(State))
889           BreakBeforeParameter = true;
890       } else {
891         // For ColumnLimit = 0, we have to figure out whether there is or has to
892         // be a line break within this call.
893         for (const FormatToken *Tok = &Current;
894              Tok && Tok != Current.MatchingParen; Tok = Tok->Next) {
895           if (Tok->MustBreakBefore ||
896               (Tok->CanBreakBefore && Tok->NewlinesBefore > 0)) {
897             BreakBeforeParameter = true;
898             break;
899           }
900         }
901       }
902     }
903   }
904   bool NoLineBreak = State.Stack.back().NoLineBreak ||
905                      (Current.is(TT_TemplateOpener) &&
906                       State.Stack.back().ContainsUnwrappedBuilder);
907   unsigned NestedBlockIndent = std::max(State.Stack.back().StartOfFunctionCall,
908                                         State.Stack.back().NestedBlockIndent);
909   State.Stack.push_back(ParenState(NewIndent, NewIndentLevel, LastSpace,
910                                    AvoidBinPacking, NoLineBreak));
911   State.Stack.back().NestedBlockIndent = NestedBlockIndent;
912   State.Stack.back().BreakBeforeParameter = BreakBeforeParameter;
913   State.Stack.back().HasMultipleNestedBlocks = Current.BlockParameterCount > 1;
914 }
915 
916 void ContinuationIndenter::moveStatePastScopeCloser(LineState &State) {
917   const FormatToken &Current = *State.NextToken;
918   if (!Current.closesScope())
919     return;
920 
921   // If we encounter a closing ), ], } or >, we can remove a level from our
922   // stacks.
923   if (State.Stack.size() > 1 &&
924       (Current.isOneOf(tok::r_paren, tok::r_square) ||
925        (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
926        State.NextToken->is(TT_TemplateCloser)))
927     State.Stack.pop_back();
928 
929   if (Current.is(tok::r_square)) {
930     // If this ends the array subscript expr, reset the corresponding value.
931     const FormatToken *NextNonComment = Current.getNextNonComment();
932     if (NextNonComment && NextNonComment->isNot(tok::l_square))
933       State.Stack.back().StartOfArraySubscripts = 0;
934   }
935 }
936 
937 void ContinuationIndenter::moveStateToNewBlock(LineState &State) {
938   unsigned NestedBlockIndent = State.Stack.back().NestedBlockIndent;
939   // ObjC block sometimes follow special indentation rules.
940   unsigned NewIndent =
941       NestedBlockIndent + (State.NextToken->is(TT_ObjCBlockLBrace)
942                                ? Style.ObjCBlockIndentWidth
943                                : Style.IndentWidth);
944   State.Stack.push_back(ParenState(
945       NewIndent, /*NewIndentLevel=*/State.Stack.back().IndentLevel + 1,
946       State.Stack.back().LastSpace, /*AvoidBinPacking=*/true,
947       State.Stack.back().NoLineBreak));
948   State.Stack.back().NestedBlockIndent = NestedBlockIndent;
949   State.Stack.back().BreakBeforeParameter = true;
950 }
951 
952 unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
953                                                  LineState &State) {
954   // Break before further function parameters on all levels.
955   for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
956     State.Stack[i].BreakBeforeParameter = true;
957 
958   unsigned ColumnsUsed = State.Column;
959   // We can only affect layout of the first and the last line, so the penalty
960   // for all other lines is constant, and we ignore it.
961   State.Column = Current.LastLineColumnWidth;
962 
963   if (ColumnsUsed > getColumnLimit(State))
964     return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
965   return 0;
966 }
967 
968 unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
969                                                     LineState &State,
970                                                     bool DryRun) {
971   // Don't break multi-line tokens other than block comments. Instead, just
972   // update the state.
973   if (Current.isNot(TT_BlockComment) && Current.IsMultiline)
974     return addMultilineToken(Current, State);
975 
976   // Don't break implicit string literals or import statements.
977   if (Current.is(TT_ImplicitStringLiteral) ||
978       State.Line->Type == LT_ImportStatement)
979     return 0;
980 
981   if (!Current.isStringLiteral() && !Current.is(tok::comment))
982     return 0;
983 
984   std::unique_ptr<BreakableToken> Token;
985   unsigned StartColumn = State.Column - Current.ColumnWidth;
986   unsigned ColumnLimit = getColumnLimit(State);
987 
988   if (Current.isStringLiteral()) {
989     // FIXME: String literal breaking is currently disabled for Java and JS, as
990     // it requires strings to be merged using "+" which we don't support.
991     if (Style.Language == FormatStyle::LK_Java ||
992         Style.Language == FormatStyle::LK_JavaScript)
993       return 0;
994 
995     // Don't break string literals inside preprocessor directives (except for
996     // #define directives, as their contents are stored in separate lines and
997     // are not affected by this check).
998     // This way we avoid breaking code with line directives and unknown
999     // preprocessor directives that contain long string literals.
1000     if (State.Line->Type == LT_PreprocessorDirective)
1001       return 0;
1002     // Exempts unterminated string literals from line breaking. The user will
1003     // likely want to terminate the string before any line breaking is done.
1004     if (Current.IsUnterminatedLiteral)
1005       return 0;
1006 
1007     StringRef Text = Current.TokenText;
1008     StringRef Prefix;
1009     StringRef Postfix;
1010     bool IsNSStringLiteral = false;
1011     // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
1012     // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
1013     // reduce the overhead) for each FormatToken, which is a string, so that we
1014     // don't run multiple checks here on the hot path.
1015     if (Text.startswith("\"") && Current.Previous &&
1016         Current.Previous->is(tok::at)) {
1017       IsNSStringLiteral = true;
1018       Prefix = "@\"";
1019     }
1020     if ((Text.endswith(Postfix = "\"") &&
1021          (IsNSStringLiteral || Text.startswith(Prefix = "\"") ||
1022           Text.startswith(Prefix = "u\"") || Text.startswith(Prefix = "U\"") ||
1023           Text.startswith(Prefix = "u8\"") ||
1024           Text.startswith(Prefix = "L\""))) ||
1025         (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")"))) {
1026       Token.reset(new BreakableStringLiteral(
1027           Current, State.Line->Level, StartColumn, Prefix, Postfix,
1028           State.Line->InPPDirective, Encoding, Style));
1029     } else {
1030       return 0;
1031     }
1032   } else if (Current.is(TT_BlockComment) && Current.isTrailingComment()) {
1033     if (CommentPragmasRegex.match(Current.TokenText.substr(2)))
1034       return 0;
1035     Token.reset(new BreakableBlockComment(
1036         Current, State.Line->Level, StartColumn, Current.OriginalColumn,
1037         !Current.Previous, State.Line->InPPDirective, Encoding, Style));
1038   } else if (Current.is(TT_LineComment) &&
1039              (Current.Previous == nullptr ||
1040               Current.Previous->isNot(TT_ImplicitStringLiteral))) {
1041     if (CommentPragmasRegex.match(Current.TokenText.substr(2)))
1042       return 0;
1043     Token.reset(new BreakableLineComment(Current, State.Line->Level,
1044                                          StartColumn, /*InPPDirective=*/false,
1045                                          Encoding, Style));
1046     // We don't insert backslashes when breaking line comments.
1047     ColumnLimit = Style.ColumnLimit;
1048   } else {
1049     return 0;
1050   }
1051   if (Current.UnbreakableTailLength >= ColumnLimit)
1052     return 0;
1053 
1054   unsigned RemainingSpace = ColumnLimit - Current.UnbreakableTailLength;
1055   bool BreakInserted = false;
1056   unsigned Penalty = 0;
1057   unsigned RemainingTokenColumns = 0;
1058   for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
1059        LineIndex != EndIndex; ++LineIndex) {
1060     if (!DryRun)
1061       Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
1062     unsigned TailOffset = 0;
1063     RemainingTokenColumns =
1064         Token->getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
1065     while (RemainingTokenColumns > RemainingSpace) {
1066       BreakableToken::Split Split =
1067           Token->getSplit(LineIndex, TailOffset, ColumnLimit);
1068       if (Split.first == StringRef::npos) {
1069         // The last line's penalty is handled in addNextStateToQueue().
1070         if (LineIndex < EndIndex - 1)
1071           Penalty += Style.PenaltyExcessCharacter *
1072                      (RemainingTokenColumns - RemainingSpace);
1073         break;
1074       }
1075       assert(Split.first != 0);
1076       unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
1077           LineIndex, TailOffset + Split.first + Split.second, StringRef::npos);
1078 
1079       // We can remove extra whitespace instead of breaking the line.
1080       if (RemainingTokenColumns + 1 - Split.second <= RemainingSpace) {
1081         RemainingTokenColumns = 0;
1082         if (!DryRun)
1083           Token->replaceWhitespace(LineIndex, TailOffset, Split, Whitespaces);
1084         break;
1085       }
1086 
1087       // When breaking before a tab character, it may be moved by a few columns,
1088       // but will still be expanded to the next tab stop, so we don't save any
1089       // columns.
1090       if (NewRemainingTokenColumns == RemainingTokenColumns)
1091         break;
1092 
1093       assert(NewRemainingTokenColumns < RemainingTokenColumns);
1094       if (!DryRun)
1095         Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
1096       Penalty += Current.SplitPenalty;
1097       unsigned ColumnsUsed =
1098           Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
1099       if (ColumnsUsed > ColumnLimit) {
1100         Penalty += Style.PenaltyExcessCharacter * (ColumnsUsed - ColumnLimit);
1101       }
1102       TailOffset += Split.first + Split.second;
1103       RemainingTokenColumns = NewRemainingTokenColumns;
1104       BreakInserted = true;
1105     }
1106   }
1107 
1108   State.Column = RemainingTokenColumns;
1109 
1110   if (BreakInserted) {
1111     // If we break the token inside a parameter list, we need to break before
1112     // the next parameter on all levels, so that the next parameter is clearly
1113     // visible. Line comments already introduce a break.
1114     if (Current.isNot(TT_LineComment)) {
1115       for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
1116         State.Stack[i].BreakBeforeParameter = true;
1117     }
1118 
1119     Penalty += Current.isStringLiteral() ? Style.PenaltyBreakString
1120                                          : Style.PenaltyBreakComment;
1121 
1122     State.Stack.back().LastSpace = StartColumn;
1123   }
1124   return Penalty;
1125 }
1126 
1127 unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
1128   // In preprocessor directives reserve two chars for trailing " \"
1129   return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
1130 }
1131 
1132 bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
1133   const FormatToken &Current = *State.NextToken;
1134   if (!Current.isStringLiteral() || Current.is(TT_ImplicitStringLiteral))
1135     return false;
1136   // We never consider raw string literals "multiline" for the purpose of
1137   // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
1138   // (see TokenAnnotator::mustBreakBefore().
1139   if (Current.TokenText.startswith("R\""))
1140     return false;
1141   if (Current.IsMultiline)
1142     return true;
1143   if (Current.getNextNonComment() &&
1144       Current.getNextNonComment()->isStringLiteral())
1145     return true; // Implicit concatenation.
1146   if (Style.ColumnLimit != 0 &&
1147       State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
1148           Style.ColumnLimit)
1149     return true; // String will be split.
1150   return false;
1151 }
1152 
1153 } // namespace format
1154 } // namespace clang
1155