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