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