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       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.is(tok::l_paren) && State.Column > getNewLineColumn(State) &&
357       (!Previous.Previous ||
358        !Previous.Previous->isOneOf(tok::kw_for, tok::kw_while, tok::kw_switch)))
359     State.Stack.back().NoLineBreak = true;
360 
361   if (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign &&
362       Previous.opensScope() && Previous.isNot(TT_ObjCMethodExpr) &&
363       (Current.isNot(TT_LineComment) || Previous.BlockKind == BK_BracedInit))
364     State.Stack.back().Indent = State.Column + Spaces;
365   if (State.Stack.back().AvoidBinPacking && startsNextParameter(Current, Style))
366     State.Stack.back().NoLineBreak = true;
367   if (startsSegmentOfBuilderTypeCall(Current) &&
368       State.Column > getNewLineColumn(State))
369     State.Stack.back().ContainsUnwrappedBuilder = true;
370 
371   if (Current.is(TT_LambdaArrow) && Style.Language == FormatStyle::LK_Java)
372     State.Stack.back().NoLineBreak = true;
373   if (Current.isMemberAccess() && Previous.is(tok::r_paren) &&
374       (Previous.MatchingParen &&
375        (Previous.TotalLength - Previous.MatchingParen->TotalLength > 10))) {
376     // If there is a function call with long parameters, break before trailing
377     // calls. This prevents things like:
378     //   EXPECT_CALL(SomeLongParameter).Times(
379     //       2);
380     // We don't want to do this for short parameters as they can just be
381     // indexes.
382     State.Stack.back().NoLineBreak = true;
383   }
384 
385   State.Column += Spaces;
386   if (Current.isNot(tok::comment) && Previous.is(tok::l_paren) &&
387       Previous.Previous &&
388       Previous.Previous->isOneOf(tok::kw_if, tok::kw_for)) {
389     // Treat the condition inside an if as if it was a second function
390     // parameter, i.e. let nested calls have a continuation indent.
391     State.Stack.back().LastSpace = State.Column;
392     State.Stack.back().NestedBlockIndent = State.Column;
393   } else if (!Current.isOneOf(tok::comment, tok::caret) &&
394              ((Previous.is(tok::comma) &&
395                !Previous.is(TT_OverloadedOperator)) ||
396               (Previous.is(tok::colon) && Previous.is(TT_ObjCMethodExpr)))) {
397     State.Stack.back().LastSpace = State.Column;
398   } else if ((Previous.isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
399                                TT_CtorInitializerColon)) &&
400              ((Previous.getPrecedence() != prec::Assignment &&
401                (Previous.isNot(tok::lessless) || Previous.OperatorIndex != 0 ||
402                 Previous.NextOperator)) ||
403               Current.StartsBinaryExpression)) {
404     // Always indent relative to the RHS of the expression unless this is a
405     // simple assignment without binary expression on the RHS. Also indent
406     // relative to unary operators and the colons of constructor initializers.
407     State.Stack.back().LastSpace = State.Column;
408   } else if (Previous.is(TT_InheritanceColon)) {
409     State.Stack.back().Indent = State.Column;
410     State.Stack.back().LastSpace = State.Column;
411   } else if (Previous.opensScope()) {
412     // If a function has a trailing call, indent all parameters from the
413     // opening parenthesis. This avoids confusing indents like:
414     //   OuterFunction(InnerFunctionCall( // break
415     //       ParameterToInnerFunction))   // break
416     //       .SecondInnerFunctionCall();
417     bool HasTrailingCall = false;
418     if (Previous.MatchingParen) {
419       const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
420       HasTrailingCall = Next && Next->isMemberAccess();
421     }
422     if (HasTrailingCall && State.Stack.size() > 1 &&
423         State.Stack[State.Stack.size() - 2].CallContinuation == 0)
424       State.Stack.back().LastSpace = State.Column;
425   }
426 }
427 
428 unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
429                                                  bool DryRun) {
430   FormatToken &Current = *State.NextToken;
431   const FormatToken &Previous = *State.NextToken->Previous;
432 
433   // Extra penalty that needs to be added because of the way certain line
434   // breaks are chosen.
435   unsigned Penalty = 0;
436 
437   const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
438   const FormatToken *NextNonComment = Previous.getNextNonComment();
439   if (!NextNonComment)
440     NextNonComment = &Current;
441   // The first line break on any NestingLevel causes an extra penalty in order
442   // prefer similar line breaks.
443   if (!State.Stack.back().ContainsLineBreak)
444     Penalty += 15;
445   State.Stack.back().ContainsLineBreak = true;
446 
447   Penalty += State.NextToken->SplitPenalty;
448 
449   // Breaking before the first "<<" is generally not desirable if the LHS is
450   // short. Also always add the penalty if the LHS is split over mutliple lines
451   // to avoid unnecessary line breaks that just work around this penalty.
452   if (NextNonComment->is(tok::lessless) &&
453       State.Stack.back().FirstLessLess == 0 &&
454       (State.Column <= Style.ColumnLimit / 3 ||
455        State.Stack.back().BreakBeforeParameter))
456     Penalty += Style.PenaltyBreakFirstLessLess;
457 
458   State.Column = getNewLineColumn(State);
459 
460   // Indent nested blocks relative to this column, unless in a very specific
461   // JavaScript special case where:
462   //
463   //   var loooooong_name =
464   //       function() {
465   //     // code
466   //   }
467   //
468   // is common and should be formatted like a free-standing function.
469   if (Style.Language != FormatStyle::LK_JavaScript ||
470       Current.NestingLevel != 0 || !PreviousNonComment->is(tok::equal) ||
471       !Current.is(Keywords.kw_function))
472     State.Stack.back().NestedBlockIndent = State.Column;
473 
474   if (NextNonComment->isMemberAccess()) {
475     if (State.Stack.back().CallContinuation == 0)
476       State.Stack.back().CallContinuation = State.Column;
477   } else if (NextNonComment->is(TT_SelectorName)) {
478     if (!State.Stack.back().ObjCSelectorNameFound) {
479       if (NextNonComment->LongestObjCSelectorName == 0) {
480         State.Stack.back().AlignColons = false;
481       } else {
482         State.Stack.back().ColonPos =
483             (Style.IndentWrappedFunctionNames
484                  ? std::max(State.Stack.back().Indent,
485                             State.FirstIndent + Style.ContinuationIndentWidth)
486                  : State.Stack.back().Indent) +
487             NextNonComment->LongestObjCSelectorName;
488       }
489     } else if (State.Stack.back().AlignColons &&
490                State.Stack.back().ColonPos <= NextNonComment->ColumnWidth) {
491       State.Stack.back().ColonPos = State.Column + NextNonComment->ColumnWidth;
492     }
493   } else if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
494              PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) {
495     // FIXME: This is hacky, find a better way. The problem is that in an ObjC
496     // method expression, the block should be aligned to the line starting it,
497     // e.g.:
498     //   [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason
499     //                        ^(int *i) {
500     //                            // ...
501     //                        }];
502     // Thus, we set LastSpace of the next higher NestingLevel, to which we move
503     // when we consume all of the "}"'s FakeRParens at the "{".
504     if (State.Stack.size() > 1)
505       State.Stack[State.Stack.size() - 2].LastSpace =
506           std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
507           Style.ContinuationIndentWidth;
508   }
509 
510   if ((Previous.isOneOf(tok::comma, tok::semi) &&
511        !State.Stack.back().AvoidBinPacking) ||
512       Previous.is(TT_BinaryOperator))
513     State.Stack.back().BreakBeforeParameter = false;
514   if (Previous.isOneOf(TT_TemplateCloser, TT_JavaAnnotation) &&
515       Current.NestingLevel == 0)
516     State.Stack.back().BreakBeforeParameter = false;
517   if (NextNonComment->is(tok::question) ||
518       (PreviousNonComment && PreviousNonComment->is(tok::question)))
519     State.Stack.back().BreakBeforeParameter = true;
520   if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore)
521     State.Stack.back().BreakBeforeParameter = false;
522 
523   if (!DryRun) {
524     unsigned Newlines = std::max(
525         1u, std::min(Current.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1));
526     Whitespaces.replaceWhitespace(Current, Newlines,
527                                   State.Stack.back().IndentLevel, State.Column,
528                                   State.Column, State.Line->InPPDirective);
529   }
530 
531   if (!Current.isTrailingComment())
532     State.Stack.back().LastSpace = State.Column;
533   State.StartOfLineLevel = Current.NestingLevel;
534   State.LowestLevelOnLine = Current.NestingLevel;
535 
536   // Any break on this level means that the parent level has been broken
537   // and we need to avoid bin packing there.
538   bool NestedBlockSpecialCase =
539       Style.Language != FormatStyle::LK_Cpp &&
540       Current.is(tok::r_brace) && State.Stack.size() > 1 &&
541       State.Stack[State.Stack.size() - 2].NestedBlockInlined;
542   if (!NestedBlockSpecialCase)
543     for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i)
544       State.Stack[i].BreakBeforeParameter = true;
545 
546   if (PreviousNonComment &&
547       !PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
548       (PreviousNonComment->isNot(TT_TemplateCloser) ||
549        Current.NestingLevel != 0) &&
550       !PreviousNonComment->isOneOf(
551           TT_BinaryOperator, TT_FunctionAnnotationRParen, TT_JavaAnnotation,
552           TT_LeadingJavaAnnotation) &&
553       Current.isNot(TT_BinaryOperator) && !PreviousNonComment->opensScope())
554     State.Stack.back().BreakBeforeParameter = true;
555 
556   // If we break after { or the [ of an array initializer, we should also break
557   // before the corresponding } or ].
558   if (PreviousNonComment &&
559       (PreviousNonComment->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare)))
560     State.Stack.back().BreakBeforeClosingBrace = true;
561 
562   if (State.Stack.back().AvoidBinPacking) {
563     // If we are breaking after '(', '{', '<', this is not bin packing
564     // unless AllowAllParametersOfDeclarationOnNextLine is false or this is a
565     // dict/object literal.
566     if (!Previous.isOneOf(tok::l_paren, tok::l_brace, TT_BinaryOperator) ||
567         (!Style.AllowAllParametersOfDeclarationOnNextLine &&
568          State.Line->MustBeDeclaration) ||
569         Previous.is(TT_DictLiteral))
570       State.Stack.back().BreakBeforeParameter = true;
571   }
572 
573   return Penalty;
574 }
575 
576 unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) {
577   if (!State.NextToken || !State.NextToken->Previous)
578     return 0;
579   FormatToken &Current = *State.NextToken;
580   const FormatToken &Previous = *Current.Previous;
581   // If we are continuing an expression, we want to use the continuation indent.
582   unsigned ContinuationIndent =
583       std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
584       Style.ContinuationIndentWidth;
585   const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
586   const FormatToken *NextNonComment = Previous.getNextNonComment();
587   if (!NextNonComment)
588     NextNonComment = &Current;
589 
590   // Java specific bits.
591   if (Style.Language == FormatStyle::LK_Java &&
592       Current.isOneOf(Keywords.kw_implements, Keywords.kw_extends))
593     return std::max(State.Stack.back().LastSpace,
594                     State.Stack.back().Indent + Style.ContinuationIndentWidth);
595 
596   if (NextNonComment->is(tok::l_brace) && NextNonComment->BlockKind == BK_Block)
597     return Current.NestingLevel == 0 ? State.FirstIndent
598                                      : State.Stack.back().Indent;
599   if (Current.isOneOf(tok::r_brace, tok::r_square) && State.Stack.size() > 1) {
600     if (Current.closesBlockOrBlockTypeList(Style))
601       return State.Stack[State.Stack.size() - 2].NestedBlockIndent;
602     if (Current.MatchingParen &&
603         Current.MatchingParen->BlockKind == BK_BracedInit)
604       return State.Stack[State.Stack.size() - 2].LastSpace;
605     return State.FirstIndent;
606   }
607   if (Current.is(tok::identifier) && Current.Next &&
608       Current.Next->is(TT_DictLiteral))
609     return State.Stack.back().Indent;
610   if (NextNonComment->isStringLiteral() && State.StartOfStringLiteral != 0)
611     return State.StartOfStringLiteral;
612   if (NextNonComment->is(TT_ObjCStringLiteral) &&
613       State.StartOfStringLiteral != 0)
614     return State.StartOfStringLiteral - 1;
615   if (NextNonComment->is(tok::lessless) &&
616       State.Stack.back().FirstLessLess != 0)
617     return State.Stack.back().FirstLessLess;
618   if (NextNonComment->isMemberAccess()) {
619     if (State.Stack.back().CallContinuation == 0)
620       return ContinuationIndent;
621     return State.Stack.back().CallContinuation;
622   }
623   if (State.Stack.back().QuestionColumn != 0 &&
624       ((NextNonComment->is(tok::colon) &&
625         NextNonComment->is(TT_ConditionalExpr)) ||
626        Previous.is(TT_ConditionalExpr)))
627     return State.Stack.back().QuestionColumn;
628   if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0)
629     return State.Stack.back().VariablePos;
630   if ((PreviousNonComment &&
631        (PreviousNonComment->ClosesTemplateDeclaration ||
632         PreviousNonComment->isOneOf(
633             TT_AttributeParen, TT_FunctionAnnotationRParen, TT_JavaAnnotation,
634             TT_LeadingJavaAnnotation))) ||
635       (!Style.IndentWrappedFunctionNames &&
636        NextNonComment->isOneOf(tok::kw_operator, TT_FunctionDeclarationName)))
637     return std::max(State.Stack.back().LastSpace, State.Stack.back().Indent);
638   if (NextNonComment->is(TT_SelectorName)) {
639     if (!State.Stack.back().ObjCSelectorNameFound) {
640       if (NextNonComment->LongestObjCSelectorName == 0)
641         return State.Stack.back().Indent;
642       return (Style.IndentWrappedFunctionNames
643                   ? std::max(State.Stack.back().Indent,
644                              State.FirstIndent + Style.ContinuationIndentWidth)
645                   : State.Stack.back().Indent) +
646              NextNonComment->LongestObjCSelectorName -
647              NextNonComment->ColumnWidth;
648     }
649     if (!State.Stack.back().AlignColons)
650       return State.Stack.back().Indent;
651     if (State.Stack.back().ColonPos > NextNonComment->ColumnWidth)
652       return State.Stack.back().ColonPos - NextNonComment->ColumnWidth;
653     return State.Stack.back().Indent;
654   }
655   if (NextNonComment->is(TT_ArraySubscriptLSquare)) {
656     if (State.Stack.back().StartOfArraySubscripts != 0)
657       return State.Stack.back().StartOfArraySubscripts;
658     return ContinuationIndent;
659   }
660 
661   // This ensure that we correctly format ObjC methods calls without inputs,
662   // i.e. where the last element isn't selector like: [callee method];
663   if (NextNonComment->is(tok::identifier) && NextNonComment->FakeRParens == 0 &&
664       NextNonComment->Next && NextNonComment->Next->is(TT_ObjCMethodExpr))
665     return State.Stack.back().Indent;
666 
667   if (NextNonComment->isOneOf(TT_StartOfName, TT_PointerOrReference) ||
668       Previous.isOneOf(tok::coloncolon, tok::equal, TT_JsTypeColon))
669     return ContinuationIndent;
670   if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
671       PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))
672     return ContinuationIndent;
673   if (NextNonComment->is(TT_CtorInitializerColon))
674     return State.FirstIndent + Style.ConstructorInitializerIndentWidth;
675   if (NextNonComment->is(TT_CtorInitializerComma))
676     return State.Stack.back().Indent;
677   if (Previous.is(tok::r_paren) && !Current.isBinaryOperator() &&
678       !Current.isOneOf(tok::colon, tok::comment))
679     return ContinuationIndent;
680   if (State.Stack.back().Indent == State.FirstIndent && PreviousNonComment &&
681       PreviousNonComment->isNot(tok::r_brace))
682     // Ensure that we fall back to the continuation indent width instead of
683     // just flushing continuations left.
684     return State.Stack.back().Indent + Style.ContinuationIndentWidth;
685   return State.Stack.back().Indent;
686 }
687 
688 unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
689                                                     bool DryRun, bool Newline) {
690   assert(State.Stack.size());
691   const FormatToken &Current = *State.NextToken;
692 
693   if (Current.is(TT_InheritanceColon))
694     State.Stack.back().AvoidBinPacking = true;
695   if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator)) {
696     if (State.Stack.back().FirstLessLess == 0)
697       State.Stack.back().FirstLessLess = State.Column;
698     else
699       State.Stack.back().LastOperatorWrapped = Newline;
700   }
701   if ((Current.is(TT_BinaryOperator) && Current.isNot(tok::lessless)) ||
702       Current.is(TT_ConditionalExpr))
703     State.Stack.back().LastOperatorWrapped = Newline;
704   if (Current.is(TT_ArraySubscriptLSquare) &&
705       State.Stack.back().StartOfArraySubscripts == 0)
706     State.Stack.back().StartOfArraySubscripts = State.Column;
707   if ((Current.is(tok::question) && Style.BreakBeforeTernaryOperators) ||
708       (Current.getPreviousNonComment() && Current.isNot(tok::colon) &&
709        Current.getPreviousNonComment()->is(tok::question) &&
710        !Style.BreakBeforeTernaryOperators))
711     State.Stack.back().QuestionColumn = State.Column;
712   if (!Current.opensScope() && !Current.closesScope())
713     State.LowestLevelOnLine =
714         std::min(State.LowestLevelOnLine, Current.NestingLevel);
715   if (Current.isMemberAccess())
716     State.Stack.back().StartOfFunctionCall =
717         !Current.NextOperator ? 0 : State.Column;
718   if (Current.is(TT_SelectorName)) {
719     State.Stack.back().ObjCSelectorNameFound = true;
720     if (Style.IndentWrappedFunctionNames) {
721       State.Stack.back().Indent =
722           State.FirstIndent + Style.ContinuationIndentWidth;
723     }
724   }
725   if (Current.is(TT_CtorInitializerColon)) {
726     // Indent 2 from the column, so:
727     // SomeClass::SomeClass()
728     //     : First(...), ...
729     //       Next(...)
730     //       ^ line up here.
731     State.Stack.back().Indent =
732         State.Column + (Style.BreakConstructorInitializersBeforeComma ? 0 : 2);
733     State.Stack.back().NestedBlockIndent = State.Stack.back().Indent;
734     if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
735       State.Stack.back().AvoidBinPacking = true;
736     State.Stack.back().BreakBeforeParameter = false;
737   }
738   if (Current.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) && Newline)
739     State.Stack.back().NestedBlockIndent =
740         State.Column + Current.ColumnWidth + 1;
741 
742   // Insert scopes created by fake parenthesis.
743   const FormatToken *Previous = Current.getPreviousNonComment();
744 
745   // Add special behavior to support a format commonly used for JavaScript
746   // closures:
747   //   SomeFunction(function() {
748   //     foo();
749   //     bar();
750   //   }, a, b, c);
751   if (Current.isNot(tok::comment) && Previous &&
752       Previous->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
753       !Previous->is(TT_DictLiteral) && State.Stack.size() > 1) {
754     if (State.Stack[State.Stack.size() - 2].NestedBlockInlined && Newline)
755       for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i)
756         State.Stack[i].NoLineBreak = true;
757     State.Stack[State.Stack.size() - 2].NestedBlockInlined = false;
758   }
759   if (Previous && (Previous->isOneOf(tok::l_paren, tok::comma, tok::colon) ||
760                    Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr)) &&
761       !Previous->isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
762     State.Stack.back().NestedBlockInlined =
763         !Newline &&
764         (Previous->isNot(tok::l_paren) || Previous->ParameterCount > 1);
765   }
766 
767   moveStatePastFakeLParens(State, Newline);
768   moveStatePastScopeOpener(State, Newline);
769   moveStatePastScopeCloser(State);
770   moveStatePastFakeRParens(State);
771 
772   if (Current.isStringLiteral() && State.StartOfStringLiteral == 0)
773     State.StartOfStringLiteral = State.Column;
774   if (Current.is(TT_ObjCStringLiteral) && State.StartOfStringLiteral == 0)
775     State.StartOfStringLiteral = State.Column + 1;
776   else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
777            !Current.isStringLiteral())
778     State.StartOfStringLiteral = 0;
779 
780   State.Column += Current.ColumnWidth;
781   State.NextToken = State.NextToken->Next;
782   unsigned Penalty = breakProtrudingToken(Current, State, DryRun);
783   if (State.Column > getColumnLimit(State)) {
784     unsigned ExcessCharacters = State.Column - getColumnLimit(State);
785     Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
786   }
787 
788   if (Current.Role)
789     Current.Role->formatFromToken(State, this, DryRun);
790   // If the previous has a special role, let it consume tokens as appropriate.
791   // It is necessary to start at the previous token for the only implemented
792   // role (comma separated list). That way, the decision whether or not to break
793   // after the "{" is already done and both options are tried and evaluated.
794   // FIXME: This is ugly, find a better way.
795   if (Previous && Previous->Role)
796     Penalty += Previous->Role->formatAfterToken(State, this, DryRun);
797 
798   return Penalty;
799 }
800 
801 void ContinuationIndenter::moveStatePastFakeLParens(LineState &State,
802                                                     bool Newline) {
803   const FormatToken &Current = *State.NextToken;
804   const FormatToken *Previous = Current.getPreviousNonComment();
805 
806   // Don't add extra indentation for the first fake parenthesis after
807   // 'return', assignments or opening <({[. The indentation for these cases
808   // is special cased.
809   bool SkipFirstExtraIndent =
810       (Previous && (Previous->opensScope() ||
811                     Previous->isOneOf(tok::semi, tok::kw_return) ||
812                     (Previous->getPrecedence() == prec::Assignment &&
813                      Style.AlignOperands) ||
814                     Previous->is(TT_ObjCMethodExpr)));
815   for (SmallVectorImpl<prec::Level>::const_reverse_iterator
816            I = Current.FakeLParens.rbegin(),
817            E = Current.FakeLParens.rend();
818        I != E; ++I) {
819     ParenState NewParenState = State.Stack.back();
820     NewParenState.ContainsLineBreak = false;
821 
822     // Indent from 'LastSpace' unless these are fake parentheses encapsulating
823     // a builder type call after 'return' or, if the alignment after opening
824     // brackets is disabled.
825     if (!Current.isTrailingComment() &&
826         (Style.AlignOperands || *I < prec::Assignment) &&
827         (!Previous || Previous->isNot(tok::kw_return) ||
828          (Style.Language != FormatStyle::LK_Java && *I > 0)) &&
829         (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign ||
830          *I != prec::Comma || Current.NestingLevel == 0))
831       NewParenState.Indent =
832           std::max(std::max(State.Column, NewParenState.Indent),
833                    State.Stack.back().LastSpace);
834 
835     // Don't allow the RHS of an operator to be split over multiple lines unless
836     // there is a line-break right after the operator.
837     // Exclude relational operators, as there, it is always more desirable to
838     // have the LHS 'left' of the RHS.
839     if (Previous && Previous->getPrecedence() > prec::Assignment &&
840         Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
841         Previous->getPrecedence() != prec::Relational) {
842       bool BreakBeforeOperator =
843           Previous->is(tok::lessless) ||
844           (Previous->is(TT_BinaryOperator) &&
845            Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None) ||
846           (Previous->is(TT_ConditionalExpr) &&
847            Style.BreakBeforeTernaryOperators);
848       if ((!Newline && !BreakBeforeOperator) ||
849           (!State.Stack.back().LastOperatorWrapped && BreakBeforeOperator))
850         NewParenState.NoLineBreak = true;
851     }
852 
853     // Do not indent relative to the fake parentheses inserted for "." or "->".
854     // This is a special case to make the following to statements consistent:
855     //   OuterFunction(InnerFunctionCall( // break
856     //       ParameterToInnerFunction));
857     //   OuterFunction(SomeObject.InnerFunctionCall( // break
858     //       ParameterToInnerFunction));
859     if (*I > prec::Unknown)
860       NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
861     if (*I != prec::Conditional && !Current.is(TT_UnaryOperator))
862       NewParenState.StartOfFunctionCall = State.Column;
863 
864     // Always indent conditional expressions. Never indent expression where
865     // the 'operator' is ',', ';' or an assignment (i.e. *I <=
866     // prec::Assignment) as those have different indentation rules. Indent
867     // other expression, unless the indentation needs to be skipped.
868     if (*I == prec::Conditional ||
869         (!SkipFirstExtraIndent && *I > prec::Assignment &&
870          !Current.isTrailingComment()))
871       NewParenState.Indent += Style.ContinuationIndentWidth;
872     if ((Previous && !Previous->opensScope()) || *I != prec::Comma)
873       NewParenState.BreakBeforeParameter = false;
874     State.Stack.push_back(NewParenState);
875     SkipFirstExtraIndent = false;
876   }
877 }
878 
879 void ContinuationIndenter::moveStatePastFakeRParens(LineState &State) {
880   for (unsigned i = 0, e = State.NextToken->FakeRParens; i != e; ++i) {
881     unsigned VariablePos = State.Stack.back().VariablePos;
882     if (State.Stack.size() == 1) {
883       // Do not pop the last element.
884       break;
885     }
886     State.Stack.pop_back();
887     State.Stack.back().VariablePos = VariablePos;
888   }
889 }
890 
891 void ContinuationIndenter::moveStatePastScopeOpener(LineState &State,
892                                                     bool Newline) {
893   const FormatToken &Current = *State.NextToken;
894   if (!Current.opensScope())
895     return;
896 
897   if (Current.MatchingParen && Current.BlockKind == BK_Block) {
898     moveStateToNewBlock(State);
899     return;
900   }
901 
902   unsigned NewIndent;
903   unsigned NewIndentLevel = State.Stack.back().IndentLevel;
904   unsigned LastSpace = State.Stack.back().LastSpace;
905   bool AvoidBinPacking;
906   bool BreakBeforeParameter = false;
907   unsigned NestedBlockIndent = std::max(State.Stack.back().StartOfFunctionCall,
908                                         State.Stack.back().NestedBlockIndent);
909   if (Current.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare)) {
910     if (Current.opensBlockOrBlockTypeList(Style)) {
911       NewIndent = State.Stack.back().NestedBlockIndent + Style.IndentWidth;
912       NewIndent = std::min(State.Column + 2, NewIndent);
913       ++NewIndentLevel;
914     } else {
915       NewIndent = State.Stack.back().LastSpace + Style.ContinuationIndentWidth;
916     }
917     const FormatToken *NextNoComment = Current.getNextNonComment();
918     bool EndsInComma = Current.MatchingParen &&
919                        Current.MatchingParen->Previous &&
920                        Current.MatchingParen->Previous->is(tok::comma);
921     AvoidBinPacking =
922         (Current.is(TT_ArrayInitializerLSquare) && EndsInComma) ||
923         Current.is(TT_DictLiteral) ||
924         Style.Language == FormatStyle::LK_Proto || !Style.BinPackArguments ||
925         (NextNoComment && NextNoComment->is(TT_DesignatedInitializerPeriod));
926     if (Current.ParameterCount > 1)
927       NestedBlockIndent = std::max(NestedBlockIndent, State.Column + 1);
928   } else {
929     NewIndent = Style.ContinuationIndentWidth +
930                 std::max(State.Stack.back().LastSpace,
931                          State.Stack.back().StartOfFunctionCall);
932 
933     // Ensure that different different brackets force relative alignment, e.g.:
934     // void SomeFunction(vector<  // break
935     //                       int> v);
936     // FIXME: We likely want to do this for more combinations of brackets.
937     // Verify that it is wanted for ObjC, too.
938     if (Current.Tok.getKind() == tok::less &&
939         Current.ParentBracket == tok::l_paren) {
940       NewIndent = std::max(NewIndent, State.Stack.back().Indent);
941       LastSpace = std::max(LastSpace, State.Stack.back().Indent);
942     }
943 
944     AvoidBinPacking =
945         (State.Line->MustBeDeclaration && !Style.BinPackParameters) ||
946         (!State.Line->MustBeDeclaration && !Style.BinPackArguments) ||
947         (Style.ExperimentalAutoDetectBinPacking &&
948          (Current.PackingKind == PPK_OnePerLine ||
949           (!BinPackInconclusiveFunctions &&
950            Current.PackingKind == PPK_Inconclusive)));
951     if (Current.is(TT_ObjCMethodExpr) && Current.MatchingParen) {
952       if (Style.ColumnLimit) {
953         // If this '[' opens an ObjC call, determine whether all parameters fit
954         // into one line and put one per line if they don't.
955         if (getLengthToMatchingParen(Current) + State.Column >
956             getColumnLimit(State))
957           BreakBeforeParameter = true;
958       } else {
959         // For ColumnLimit = 0, we have to figure out whether there is or has to
960         // be a line break within this call.
961         for (const FormatToken *Tok = &Current;
962              Tok && Tok != Current.MatchingParen; Tok = Tok->Next) {
963           if (Tok->MustBreakBefore ||
964               (Tok->CanBreakBefore && Tok->NewlinesBefore > 0)) {
965             BreakBeforeParameter = true;
966             break;
967           }
968         }
969       }
970     }
971   }
972   // Generally inherit NoLineBreak from the current scope to nested scope.
973   // However, don't do this for non-empty nested blocks, dict literals and
974   // array literals as these follow different indentation rules.
975   bool NoLineBreak =
976       Current.Children.empty() &&
977       !Current.isOneOf(TT_DictLiteral, TT_ArrayInitializerLSquare) &&
978       (State.Stack.back().NoLineBreak ||
979        (Current.is(TT_TemplateOpener) &&
980         State.Stack.back().ContainsUnwrappedBuilder));
981   State.Stack.push_back(ParenState(NewIndent, NewIndentLevel, LastSpace,
982                                    AvoidBinPacking, NoLineBreak));
983   State.Stack.back().NestedBlockIndent = NestedBlockIndent;
984   State.Stack.back().BreakBeforeParameter = BreakBeforeParameter;
985   State.Stack.back().HasMultipleNestedBlocks = Current.BlockParameterCount > 1;
986 }
987 
988 void ContinuationIndenter::moveStatePastScopeCloser(LineState &State) {
989   const FormatToken &Current = *State.NextToken;
990   if (!Current.closesScope())
991     return;
992 
993   // If we encounter a closing ), ], } or >, we can remove a level from our
994   // stacks.
995   if (State.Stack.size() > 1 &&
996       (Current.isOneOf(tok::r_paren, tok::r_square) ||
997        (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
998        State.NextToken->is(TT_TemplateCloser)))
999     State.Stack.pop_back();
1000 
1001   if (Current.is(tok::r_square)) {
1002     // If this ends the array subscript expr, reset the corresponding value.
1003     const FormatToken *NextNonComment = Current.getNextNonComment();
1004     if (NextNonComment && NextNonComment->isNot(tok::l_square))
1005       State.Stack.back().StartOfArraySubscripts = 0;
1006   }
1007 }
1008 
1009 void ContinuationIndenter::moveStateToNewBlock(LineState &State) {
1010   unsigned NestedBlockIndent = State.Stack.back().NestedBlockIndent;
1011   // ObjC block sometimes follow special indentation rules.
1012   unsigned NewIndent =
1013       NestedBlockIndent + (State.NextToken->is(TT_ObjCBlockLBrace)
1014                                ? Style.ObjCBlockIndentWidth
1015                                : Style.IndentWidth);
1016   State.Stack.push_back(ParenState(
1017       NewIndent, /*NewIndentLevel=*/State.Stack.back().IndentLevel + 1,
1018       State.Stack.back().LastSpace, /*AvoidBinPacking=*/true,
1019       /*NoLineBreak=*/false));
1020   State.Stack.back().NestedBlockIndent = NestedBlockIndent;
1021   State.Stack.back().BreakBeforeParameter = true;
1022 }
1023 
1024 unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
1025                                                  LineState &State) {
1026   // Break before further function parameters on all levels.
1027   for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
1028     State.Stack[i].BreakBeforeParameter = true;
1029 
1030   unsigned ColumnsUsed = State.Column;
1031   // We can only affect layout of the first and the last line, so the penalty
1032   // for all other lines is constant, and we ignore it.
1033   State.Column = Current.LastLineColumnWidth;
1034 
1035   if (ColumnsUsed > getColumnLimit(State))
1036     return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
1037   return 0;
1038 }
1039 
1040 unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
1041                                                     LineState &State,
1042                                                     bool DryRun) {
1043   // Don't break multi-line tokens other than block comments. Instead, just
1044   // update the state.
1045   if (Current.isNot(TT_BlockComment) && Current.IsMultiline)
1046     return addMultilineToken(Current, State);
1047 
1048   // Don't break implicit string literals or import statements.
1049   if (Current.is(TT_ImplicitStringLiteral) ||
1050       State.Line->Type == LT_ImportStatement)
1051     return 0;
1052 
1053   if (!Current.isStringLiteral() && !Current.is(tok::comment))
1054     return 0;
1055 
1056   std::unique_ptr<BreakableToken> Token;
1057   unsigned StartColumn = State.Column - Current.ColumnWidth;
1058   unsigned ColumnLimit = getColumnLimit(State);
1059 
1060   if (Current.isStringLiteral()) {
1061     // FIXME: String literal breaking is currently disabled for Java and JS, as
1062     // it requires strings to be merged using "+" which we don't support.
1063     if (Style.Language == FormatStyle::LK_Java ||
1064         Style.Language == FormatStyle::LK_JavaScript)
1065       return 0;
1066 
1067     // Don't break string literals inside preprocessor directives (except for
1068     // #define directives, as their contents are stored in separate lines and
1069     // are not affected by this check).
1070     // This way we avoid breaking code with line directives and unknown
1071     // preprocessor directives that contain long string literals.
1072     if (State.Line->Type == LT_PreprocessorDirective)
1073       return 0;
1074     // Exempts unterminated string literals from line breaking. The user will
1075     // likely want to terminate the string before any line breaking is done.
1076     if (Current.IsUnterminatedLiteral)
1077       return 0;
1078 
1079     StringRef Text = Current.TokenText;
1080     StringRef Prefix;
1081     StringRef Postfix;
1082     bool IsNSStringLiteral = false;
1083     // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
1084     // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
1085     // reduce the overhead) for each FormatToken, which is a string, so that we
1086     // don't run multiple checks here on the hot path.
1087     if (Text.startswith("\"") && Current.Previous &&
1088         Current.Previous->is(tok::at)) {
1089       IsNSStringLiteral = true;
1090       Prefix = "@\"";
1091     }
1092     if ((Text.endswith(Postfix = "\"") &&
1093          (IsNSStringLiteral || Text.startswith(Prefix = "\"") ||
1094           Text.startswith(Prefix = "u\"") || Text.startswith(Prefix = "U\"") ||
1095           Text.startswith(Prefix = "u8\"") ||
1096           Text.startswith(Prefix = "L\""))) ||
1097         (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")"))) {
1098       Token.reset(new BreakableStringLiteral(
1099           Current, State.Line->Level, StartColumn, Prefix, Postfix,
1100           State.Line->InPPDirective, Encoding, Style));
1101     } else {
1102       return 0;
1103     }
1104   } else if (Current.is(TT_BlockComment) && Current.isTrailingComment()) {
1105     if (!Style.ReflowComments ||
1106         CommentPragmasRegex.match(Current.TokenText.substr(2)))
1107       return 0;
1108     Token.reset(new BreakableBlockComment(
1109         Current, State.Line->Level, StartColumn, Current.OriginalColumn,
1110         !Current.Previous, State.Line->InPPDirective, Encoding, Style));
1111   } else if (Current.is(TT_LineComment) &&
1112              (Current.Previous == nullptr ||
1113               Current.Previous->isNot(TT_ImplicitStringLiteral))) {
1114     if (!Style.ReflowComments ||
1115         CommentPragmasRegex.match(Current.TokenText.substr(2)))
1116       return 0;
1117     Token.reset(new BreakableLineComment(Current, State.Line->Level,
1118                                          StartColumn, /*InPPDirective=*/false,
1119                                          Encoding, Style));
1120     // We don't insert backslashes when breaking line comments.
1121     ColumnLimit = Style.ColumnLimit;
1122   } else {
1123     return 0;
1124   }
1125   if (Current.UnbreakableTailLength >= ColumnLimit)
1126     return 0;
1127 
1128   unsigned RemainingSpace = ColumnLimit - Current.UnbreakableTailLength;
1129   bool BreakInserted = false;
1130   unsigned Penalty = 0;
1131   unsigned RemainingTokenColumns = 0;
1132   for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
1133        LineIndex != EndIndex; ++LineIndex) {
1134     if (!DryRun)
1135       Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
1136     unsigned TailOffset = 0;
1137     RemainingTokenColumns =
1138         Token->getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
1139     while (RemainingTokenColumns > RemainingSpace) {
1140       BreakableToken::Split Split =
1141           Token->getSplit(LineIndex, TailOffset, ColumnLimit);
1142       if (Split.first == StringRef::npos) {
1143         // The last line's penalty is handled in addNextStateToQueue().
1144         if (LineIndex < EndIndex - 1)
1145           Penalty += Style.PenaltyExcessCharacter *
1146                      (RemainingTokenColumns - RemainingSpace);
1147         break;
1148       }
1149       assert(Split.first != 0);
1150       unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
1151           LineIndex, TailOffset + Split.first + Split.second, StringRef::npos);
1152 
1153       // We can remove extra whitespace instead of breaking the line.
1154       if (RemainingTokenColumns + 1 - Split.second <= RemainingSpace) {
1155         RemainingTokenColumns = 0;
1156         if (!DryRun)
1157           Token->replaceWhitespace(LineIndex, TailOffset, Split, Whitespaces);
1158         break;
1159       }
1160 
1161       // When breaking before a tab character, it may be moved by a few columns,
1162       // but will still be expanded to the next tab stop, so we don't save any
1163       // columns.
1164       if (NewRemainingTokenColumns == RemainingTokenColumns)
1165         break;
1166 
1167       assert(NewRemainingTokenColumns < RemainingTokenColumns);
1168       if (!DryRun)
1169         Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
1170       Penalty += Current.SplitPenalty;
1171       unsigned ColumnsUsed =
1172           Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
1173       if (ColumnsUsed > ColumnLimit) {
1174         Penalty += Style.PenaltyExcessCharacter * (ColumnsUsed - ColumnLimit);
1175       }
1176       TailOffset += Split.first + Split.second;
1177       RemainingTokenColumns = NewRemainingTokenColumns;
1178       BreakInserted = true;
1179     }
1180   }
1181 
1182   State.Column = RemainingTokenColumns;
1183 
1184   if (BreakInserted) {
1185     // If we break the token inside a parameter list, we need to break before
1186     // the next parameter on all levels, so that the next parameter is clearly
1187     // visible. Line comments already introduce a break.
1188     if (Current.isNot(TT_LineComment)) {
1189       for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
1190         State.Stack[i].BreakBeforeParameter = true;
1191     }
1192 
1193     Penalty += Current.isStringLiteral() ? Style.PenaltyBreakString
1194                                          : Style.PenaltyBreakComment;
1195 
1196     State.Stack.back().LastSpace = StartColumn;
1197   }
1198   return Penalty;
1199 }
1200 
1201 unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
1202   // In preprocessor directives reserve two chars for trailing " \"
1203   return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
1204 }
1205 
1206 bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
1207   const FormatToken &Current = *State.NextToken;
1208   if (!Current.isStringLiteral() || Current.is(TT_ImplicitStringLiteral))
1209     return false;
1210   // We never consider raw string literals "multiline" for the purpose of
1211   // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
1212   // (see TokenAnnotator::mustBreakBefore().
1213   if (Current.TokenText.startswith("R\""))
1214     return false;
1215   if (Current.IsMultiline)
1216     return true;
1217   if (Current.getNextNonComment() &&
1218       Current.getNextNonComment()->isStringLiteral())
1219     return true; // Implicit concatenation.
1220   if (Style.ColumnLimit != 0 &&
1221       State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
1222           Style.ColumnLimit)
1223     return true; // String will be split.
1224   return false;
1225 }
1226 
1227 } // namespace format
1228 } // namespace clang
1229