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