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