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