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