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