1 //===--- ContinuationIndenter.cpp - Format C++ code -----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file implements the continuation indenter.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "ContinuationIndenter.h"
15 #include "BreakableToken.h"
16 #include "FormatInternal.h"
17 #include "FormatToken.h"
18 #include "WhitespaceManager.h"
19 #include "clang/Basic/OperatorPrecedence.h"
20 #include "clang/Basic/SourceManager.h"
21 #include "clang/Format/Format.h"
22 #include "llvm/Support/Debug.h"
23 
24 #define DEBUG_TYPE "format-indenter"
25 
26 namespace clang {
27 namespace format {
28 
29 // Returns true if a TT_SelectorName should be indented when wrapped,
30 // false otherwise.
31 static bool shouldIndentWrappedSelectorName(const FormatStyle &Style,
32                                             LineType LineType) {
33   return Style.IndentWrappedFunctionNames || LineType == LT_ObjCMethodDecl;
34 }
35 
36 // Returns the length of everything up to the first possible line break after
37 // the ), ], } or > matching \c Tok.
38 static unsigned getLengthToMatchingParen(const FormatToken &Tok,
39                                          const std::vector<ParenState> &Stack) {
40   // Normally whether or not a break before T is possible is calculated and
41   // stored in T.CanBreakBefore. Braces, array initializers and text proto
42   // messages like `key: < ... >` are an exception: a break is possible
43   // before a closing brace R if a break was inserted after the corresponding
44   // opening brace. The information about whether or not a break is needed
45   // before a closing brace R is stored in the ParenState field
46   // S.BreakBeforeClosingBrace where S is the state that R closes.
47   //
48   // In order to decide whether there can be a break before encountered right
49   // braces, this implementation iterates over the sequence of tokens and over
50   // the paren stack in lockstep, keeping track of the stack level which visited
51   // right braces correspond to in MatchingStackIndex.
52   //
53   // For example, consider:
54   // L. <- line number
55   // 1. {
56   // 2. {1},
57   // 3. {2},
58   // 4. {{3}}}
59   //     ^ where we call this method with this token.
60   // The paren stack at this point contains 3 brace levels:
61   //  0. { at line 1, BreakBeforeClosingBrace: true
62   //  1. first { at line 4, BreakBeforeClosingBrace: false
63   //  2. second { at line 4, BreakBeforeClosingBrace: false,
64   //  where there might be fake parens levels in-between these levels.
65   // The algorithm will start at the first } on line 4, which is the matching
66   // brace of the initial left brace and at level 2 of the stack. Then,
67   // examining BreakBeforeClosingBrace: false at level 2, it will continue to
68   // the second } on line 4, and will traverse the stack downwards until it
69   // finds the matching { on level 1. Then, examining BreakBeforeClosingBrace:
70   // false at level 1, it will continue to the third } on line 4 and will
71   // traverse the stack downwards until it finds the matching { on level 0.
72   // Then, examining BreakBeforeClosingBrace: true at level 0, the algorithm
73   // will stop and will use the second } on line 4 to determine the length to
74   // return, as in this example the range will include the tokens: {3}}
75   //
76   // The algorithm will only traverse the stack if it encounters braces, array
77   // initializer squares or text proto angle brackets.
78   if (!Tok.MatchingParen)
79     return 0;
80   FormatToken *End = Tok.MatchingParen;
81   // Maintains a stack level corresponding to the current End token.
82   int MatchingStackIndex = Stack.size() - 1;
83   // Traverses the stack downwards, looking for the level to which LBrace
84   // corresponds. Returns either a pointer to the matching level or nullptr if
85   // LParen is not found in the initial portion of the stack up to
86   // MatchingStackIndex.
87   auto FindParenState = [&](const FormatToken *LBrace) -> const ParenState * {
88     while (MatchingStackIndex >= 0 && Stack[MatchingStackIndex].Tok != LBrace)
89       --MatchingStackIndex;
90     return MatchingStackIndex >= 0 ? &Stack[MatchingStackIndex] : nullptr;
91   };
92   for (; End->Next; End = End->Next) {
93     if (End->Next->CanBreakBefore)
94       break;
95     if (!End->Next->closesScope())
96       continue;
97     if (End->Next->MatchingParen &&
98         End->Next->MatchingParen->isOneOf(
99             tok::l_brace, TT_ArrayInitializerLSquare, tok::less)) {
100       const ParenState *State = FindParenState(End->Next->MatchingParen);
101       if (State && State->BreakBeforeClosingBrace)
102         break;
103     }
104   }
105   return End->TotalLength - Tok.TotalLength + 1;
106 }
107 
108 static unsigned getLengthToNextOperator(const FormatToken &Tok) {
109   if (!Tok.NextOperator)
110     return 0;
111   return Tok.NextOperator->TotalLength - Tok.TotalLength;
112 }
113 
114 // Returns \c true if \c Tok is the "." or "->" of a call and starts the next
115 // segment of a builder type call.
116 static bool startsSegmentOfBuilderTypeCall(const FormatToken &Tok) {
117   return Tok.isMemberAccess() && Tok.Previous && Tok.Previous->closesScope();
118 }
119 
120 // Returns \c true if \c Current starts a new parameter.
121 static bool startsNextParameter(const FormatToken &Current,
122                                 const FormatStyle &Style) {
123   const FormatToken &Previous = *Current.Previous;
124   if (Current.is(TT_CtorInitializerComma) &&
125       Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma)
126     return true;
127   if (Style.Language == FormatStyle::LK_Proto && Current.is(TT_SelectorName))
128     return true;
129   return Previous.is(tok::comma) && !Current.isTrailingComment() &&
130          ((Previous.isNot(TT_CtorInitializerComma) ||
131            Style.BreakConstructorInitializers !=
132                FormatStyle::BCIS_BeforeComma) &&
133           (Previous.isNot(TT_InheritanceComma) ||
134            Style.BreakInheritanceList != FormatStyle::BILS_BeforeComma));
135 }
136 
137 static bool opensProtoMessageField(const FormatToken &LessTok,
138                                    const FormatStyle &Style) {
139   if (LessTok.isNot(tok::less))
140     return false;
141   return Style.Language == FormatStyle::LK_TextProto ||
142          (Style.Language == FormatStyle::LK_Proto &&
143           (LessTok.NestingLevel > 0 ||
144            (LessTok.Previous && LessTok.Previous->is(tok::equal))));
145 }
146 
147 // Returns the delimiter of a raw string literal, or None if TokenText is not
148 // the text of a raw string literal. The delimiter could be the empty string.
149 // For example, the delimiter of R"deli(cont)deli" is deli.
150 static llvm::Optional<StringRef> getRawStringDelimiter(StringRef TokenText) {
151   if (TokenText.size() < 5 // The smallest raw string possible is 'R"()"'.
152       || !TokenText.startswith("R\"") || !TokenText.endswith("\""))
153     return None;
154 
155   // A raw string starts with 'R"<delimiter>(' and delimiter is ascii and has
156   // size at most 16 by the standard, so the first '(' must be among the first
157   // 19 bytes.
158   size_t LParenPos = TokenText.substr(0, 19).find_first_of('(');
159   if (LParenPos == StringRef::npos)
160     return None;
161   StringRef Delimiter = TokenText.substr(2, LParenPos - 2);
162 
163   // Check that the string ends in ')Delimiter"'.
164   size_t RParenPos = TokenText.size() - Delimiter.size() - 2;
165   if (TokenText[RParenPos] != ')')
166     return None;
167   if (!TokenText.substr(RParenPos + 1).startswith(Delimiter))
168     return None;
169   return Delimiter;
170 }
171 
172 // Returns the canonical delimiter for \p Language, or the empty string if no
173 // canonical delimiter is specified.
174 static StringRef
175 getCanonicalRawStringDelimiter(const FormatStyle &Style,
176                                FormatStyle::LanguageKind Language) {
177   for (const auto &Format : Style.RawStringFormats) {
178     if (Format.Language == Language)
179       return StringRef(Format.CanonicalDelimiter);
180   }
181   return "";
182 }
183 
184 RawStringFormatStyleManager::RawStringFormatStyleManager(
185     const FormatStyle &CodeStyle) {
186   for (const auto &RawStringFormat : CodeStyle.RawStringFormats) {
187     llvm::Optional<FormatStyle> LanguageStyle =
188         CodeStyle.GetLanguageStyle(RawStringFormat.Language);
189     if (!LanguageStyle) {
190       FormatStyle PredefinedStyle;
191       if (!getPredefinedStyle(RawStringFormat.BasedOnStyle,
192                               RawStringFormat.Language, &PredefinedStyle)) {
193         PredefinedStyle = getLLVMStyle();
194         PredefinedStyle.Language = RawStringFormat.Language;
195       }
196       LanguageStyle = PredefinedStyle;
197     }
198     LanguageStyle->ColumnLimit = CodeStyle.ColumnLimit;
199     for (StringRef Delimiter : RawStringFormat.Delimiters) {
200       DelimiterStyle.insert({Delimiter, *LanguageStyle});
201     }
202     for (StringRef EnclosingFunction : RawStringFormat.EnclosingFunctions) {
203       EnclosingFunctionStyle.insert({EnclosingFunction, *LanguageStyle});
204     }
205   }
206 }
207 
208 llvm::Optional<FormatStyle>
209 RawStringFormatStyleManager::getDelimiterStyle(StringRef Delimiter) const {
210   auto It = DelimiterStyle.find(Delimiter);
211   if (It == DelimiterStyle.end())
212     return None;
213   return It->second;
214 }
215 
216 llvm::Optional<FormatStyle>
217 RawStringFormatStyleManager::getEnclosingFunctionStyle(
218     StringRef EnclosingFunction) const {
219   auto It = EnclosingFunctionStyle.find(EnclosingFunction);
220   if (It == EnclosingFunctionStyle.end())
221     return None;
222   return It->second;
223 }
224 
225 ContinuationIndenter::ContinuationIndenter(const FormatStyle &Style,
226                                            const AdditionalKeywords &Keywords,
227                                            const SourceManager &SourceMgr,
228                                            WhitespaceManager &Whitespaces,
229                                            encoding::Encoding Encoding,
230                                            bool BinPackInconclusiveFunctions)
231     : Style(Style), Keywords(Keywords), SourceMgr(SourceMgr),
232       Whitespaces(Whitespaces), Encoding(Encoding),
233       BinPackInconclusiveFunctions(BinPackInconclusiveFunctions),
234       CommentPragmasRegex(Style.CommentPragmas), RawStringFormats(Style) {}
235 
236 LineState ContinuationIndenter::getInitialState(unsigned FirstIndent,
237                                                 unsigned FirstStartColumn,
238                                                 const AnnotatedLine *Line,
239                                                 bool DryRun) {
240   LineState State;
241   State.FirstIndent = FirstIndent;
242   if (FirstStartColumn && Line->First->NewlinesBefore == 0)
243     State.Column = FirstStartColumn;
244   else
245     State.Column = FirstIndent;
246   // With preprocessor directive indentation, the line starts on column 0
247   // since it's indented after the hash, but FirstIndent is set to the
248   // preprocessor indent.
249   if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash &&
250       (Line->Type == LT_PreprocessorDirective ||
251        Line->Type == LT_ImportStatement))
252     State.Column = 0;
253   State.Line = Line;
254   State.NextToken = Line->First;
255   State.Stack.push_back(ParenState(/*Tok=*/nullptr, FirstIndent, FirstIndent,
256                                    /*AvoidBinPacking=*/false,
257                                    /*NoLineBreak=*/false));
258   State.LineContainsContinuedForLoopSection = false;
259   State.NoContinuation = false;
260   State.StartOfStringLiteral = 0;
261   State.StartOfLineLevel = 0;
262   State.LowestLevelOnLine = 0;
263   State.IgnoreStackForComparison = false;
264 
265   if (Style.Language == FormatStyle::LK_TextProto) {
266     // We need this in order to deal with the bin packing of text fields at
267     // global scope.
268     State.Stack.back().AvoidBinPacking = true;
269     State.Stack.back().BreakBeforeParameter = true;
270     State.Stack.back().AlignColons = false;
271   }
272 
273   // The first token has already been indented and thus consumed.
274   moveStateToNextToken(State, DryRun, /*Newline=*/false);
275   return State;
276 }
277 
278 bool ContinuationIndenter::canBreak(const LineState &State) {
279   const FormatToken &Current = *State.NextToken;
280   const FormatToken &Previous = *Current.Previous;
281   assert(&Previous == Current.Previous);
282   if (!Current.CanBreakBefore && !(State.Stack.back().BreakBeforeClosingBrace &&
283                                    Current.closesBlockOrBlockTypeList(Style)))
284     return false;
285   // The opening "{" of a braced list has to be on the same line as the first
286   // element if it is nested in another braced init list or function call.
287   if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
288       Previous.isNot(TT_DictLiteral) && Previous.is(BK_BracedInit) &&
289       Previous.Previous &&
290       Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
291     return false;
292   // This prevents breaks like:
293   //   ...
294   //   SomeParameter, OtherParameter).DoSomething(
295   //   ...
296   // As they hide "DoSomething" and are generally bad for readability.
297   if (Previous.opensScope() && Previous.isNot(tok::l_brace) &&
298       State.LowestLevelOnLine < State.StartOfLineLevel &&
299       State.LowestLevelOnLine < Current.NestingLevel)
300     return false;
301   if (Current.isMemberAccess() && State.Stack.back().ContainsUnwrappedBuilder)
302     return false;
303 
304   // Don't create a 'hanging' indent if there are multiple blocks in a single
305   // statement.
306   if (Previous.is(tok::l_brace) && State.Stack.size() > 1 &&
307       State.Stack[State.Stack.size() - 2].NestedBlockInlined &&
308       State.Stack[State.Stack.size() - 2].HasMultipleNestedBlocks)
309     return false;
310 
311   // Don't break after very short return types (e.g. "void") as that is often
312   // unexpected.
313   if (Current.is(TT_FunctionDeclarationName) && State.Column < 6) {
314     if (Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None)
315       return false;
316   }
317 
318   // If binary operators are moved to the next line (including commas for some
319   // styles of constructor initializers), that's always ok.
320   if (!Current.isOneOf(TT_BinaryOperator, tok::comma) &&
321       State.Stack.back().NoLineBreakInOperand)
322     return false;
323 
324   if (Previous.is(tok::l_square) && Previous.is(TT_ObjCMethodExpr))
325     return false;
326 
327   return !State.Stack.back().NoLineBreak;
328 }
329 
330 bool ContinuationIndenter::mustBreak(const LineState &State) {
331   const FormatToken &Current = *State.NextToken;
332   const FormatToken &Previous = *Current.Previous;
333   if (Style.BraceWrapping.BeforeLambdaBody && Current.CanBreakBefore &&
334       Current.is(TT_LambdaLBrace) && Previous.isNot(TT_LineComment)) {
335     auto LambdaBodyLength = getLengthToMatchingParen(Current, State.Stack);
336     return (LambdaBodyLength > getColumnLimit(State));
337   }
338   if (Current.MustBreakBefore || Current.is(TT_InlineASMColon))
339     return true;
340   if (State.Stack.back().BreakBeforeClosingBrace &&
341       Current.closesBlockOrBlockTypeList(Style))
342     return true;
343   if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
344     return true;
345   if (Style.Language == FormatStyle::LK_ObjC &&
346       Style.ObjCBreakBeforeNestedBlockParam &&
347       Current.ObjCSelectorNameParts > 1 &&
348       Current.startsSequence(TT_SelectorName, tok::colon, tok::caret)) {
349     return true;
350   }
351   // Avoid producing inconsistent states by requiring breaks where they are not
352   // permitted for C# generic type constraints.
353   if (State.Stack.back().IsCSharpGenericTypeConstraint &&
354       Previous.isNot(TT_CSharpGenericTypeConstraintComma))
355     return false;
356   if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
357        (Previous.is(TT_TemplateCloser) && Current.is(TT_StartOfName) &&
358         Style.isCpp() &&
359         // FIXME: This is a temporary workaround for the case where clang-format
360         // sets BreakBeforeParameter to avoid bin packing and this creates a
361         // completely unnecessary line break after a template type that isn't
362         // line-wrapped.
363         (Previous.NestingLevel == 1 || Style.BinPackParameters)) ||
364        (Style.BreakBeforeTernaryOperators && Current.is(TT_ConditionalExpr) &&
365         Previous.isNot(tok::question)) ||
366        (!Style.BreakBeforeTernaryOperators &&
367         Previous.is(TT_ConditionalExpr))) &&
368       State.Stack.back().BreakBeforeParameter && !Current.isTrailingComment() &&
369       !Current.isOneOf(tok::r_paren, tok::r_brace))
370     return true;
371   if (State.Stack.back().IsChainedConditional &&
372       ((Style.BreakBeforeTernaryOperators && Current.is(TT_ConditionalExpr) &&
373         Current.is(tok::colon)) ||
374        (!Style.BreakBeforeTernaryOperators && Previous.is(TT_ConditionalExpr) &&
375         Previous.is(tok::colon))))
376     return true;
377   if (((Previous.is(TT_DictLiteral) && Previous.is(tok::l_brace)) ||
378        (Previous.is(TT_ArrayInitializerLSquare) &&
379         Previous.ParameterCount > 1) ||
380        opensProtoMessageField(Previous, Style)) &&
381       Style.ColumnLimit > 0 &&
382       getLengthToMatchingParen(Previous, State.Stack) + State.Column - 1 >
383           getColumnLimit(State))
384     return true;
385 
386   const FormatToken &BreakConstructorInitializersToken =
387       Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon
388           ? Previous
389           : Current;
390   if (BreakConstructorInitializersToken.is(TT_CtorInitializerColon) &&
391       (State.Column + State.Line->Last->TotalLength - Previous.TotalLength >
392            getColumnLimit(State) ||
393        State.Stack.back().BreakBeforeParameter) &&
394       (Style.AllowShortFunctionsOnASingleLine != FormatStyle::SFS_All ||
395        Style.BreakConstructorInitializers != FormatStyle::BCIS_BeforeColon ||
396        Style.ColumnLimit != 0))
397     return true;
398 
399   if (Current.is(TT_ObjCMethodExpr) && !Previous.is(TT_SelectorName) &&
400       State.Line->startsWith(TT_ObjCMethodSpecifier))
401     return true;
402   if (Current.is(TT_SelectorName) && !Previous.is(tok::at) &&
403       State.Stack.back().ObjCSelectorNameFound &&
404       State.Stack.back().BreakBeforeParameter &&
405       (Style.ObjCBreakBeforeNestedBlockParam ||
406        !Current.startsSequence(TT_SelectorName, tok::colon, tok::caret)))
407     return true;
408 
409   unsigned NewLineColumn = getNewLineColumn(State);
410   if (Current.isMemberAccess() && Style.ColumnLimit != 0 &&
411       State.Column + getLengthToNextOperator(Current) > Style.ColumnLimit &&
412       (State.Column > NewLineColumn ||
413        Current.NestingLevel < State.StartOfLineLevel))
414     return true;
415 
416   if (startsSegmentOfBuilderTypeCall(Current) &&
417       (State.Stack.back().CallContinuation != 0 ||
418        State.Stack.back().BreakBeforeParameter) &&
419       // JavaScript is treated different here as there is a frequent pattern:
420       //   SomeFunction(function() {
421       //     ...
422       //   }.bind(...));
423       // FIXME: We should find a more generic solution to this problem.
424       !(State.Column <= NewLineColumn &&
425         Style.Language == FormatStyle::LK_JavaScript) &&
426       !(Previous.closesScopeAfterBlock() && State.Column <= NewLineColumn))
427     return true;
428 
429   // If the template declaration spans multiple lines, force wrap before the
430   // function/class declaration
431   if (Previous.ClosesTemplateDeclaration &&
432       State.Stack.back().BreakBeforeParameter && Current.CanBreakBefore)
433     return true;
434 
435   if (!State.Line->First->is(tok::kw_enum) && State.Column <= NewLineColumn)
436     return false;
437 
438   if (Style.AlwaysBreakBeforeMultilineStrings &&
439       (NewLineColumn == State.FirstIndent + Style.ContinuationIndentWidth ||
440        Previous.is(tok::comma) || Current.NestingLevel < 2) &&
441       !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at,
442                         Keywords.kw_dollar) &&
443       !Previous.isOneOf(TT_InlineASMColon, TT_ConditionalExpr) &&
444       nextIsMultilineString(State))
445     return true;
446 
447   // Using CanBreakBefore here and below takes care of the decision whether the
448   // current style uses wrapping before or after operators for the given
449   // operator.
450   if (Previous.is(TT_BinaryOperator) && Current.CanBreakBefore) {
451     // If we need to break somewhere inside the LHS of a binary expression, we
452     // should also break after the operator. Otherwise, the formatting would
453     // hide the operator precedence, e.g. in:
454     //   if (aaaaaaaaaaaaaa ==
455     //           bbbbbbbbbbbbbb && c) {..
456     // For comparisons, we only apply this rule, if the LHS is a binary
457     // expression itself as otherwise, the line breaks seem superfluous.
458     // We need special cases for ">>" which we have split into two ">" while
459     // lexing in order to make template parsing easier.
460     bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
461                          Previous.getPrecedence() == prec::Equality ||
462                          Previous.getPrecedence() == prec::Spaceship) &&
463                         Previous.Previous &&
464                         Previous.Previous->isNot(TT_BinaryOperator); // For >>.
465     bool LHSIsBinaryExpr =
466         Previous.Previous && Previous.Previous->EndsBinaryExpression;
467     if ((!IsComparison || LHSIsBinaryExpr) && !Current.isTrailingComment() &&
468         Previous.getPrecedence() != prec::Assignment &&
469         State.Stack.back().BreakBeforeParameter)
470       return true;
471   } else if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore &&
472              State.Stack.back().BreakBeforeParameter) {
473     return true;
474   }
475 
476   // Same as above, but for the first "<<" operator.
477   if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator) &&
478       State.Stack.back().BreakBeforeParameter &&
479       State.Stack.back().FirstLessLess == 0)
480     return true;
481 
482   if (Current.NestingLevel == 0 && !Current.isTrailingComment()) {
483     // Always break after "template <...>" and leading annotations. This is only
484     // for cases where the entire line does not fit on a single line as a
485     // different LineFormatter would be used otherwise.
486     if (Previous.ClosesTemplateDeclaration)
487       return Style.AlwaysBreakTemplateDeclarations != FormatStyle::BTDS_No;
488     if (Previous.is(TT_FunctionAnnotationRParen))
489       return true;
490     if (Previous.is(TT_LeadingJavaAnnotation) && Current.isNot(tok::l_paren) &&
491         Current.isNot(TT_LeadingJavaAnnotation))
492       return true;
493   }
494 
495   // Break after the closing parenthesis of TypeScript decorators.
496   if (Style.Language == FormatStyle::LK_JavaScript &&
497       Previous.is(tok::r_paren) && Previous.is(TT_JavaAnnotation)) {
498     return true;
499   }
500 
501   // If the return type spans multiple lines, wrap before the function name.
502   if (((Current.is(TT_FunctionDeclarationName) &&
503         // Don't break before a C# function when no break after return type
504         (!Style.isCSharp() ||
505          Style.AlwaysBreakAfterReturnType != FormatStyle::RTBS_None) &&
506         // Don't always break between a JavaScript `function` and the function
507         // name.
508         Style.Language != FormatStyle::LK_JavaScript) ||
509        (Current.is(tok::kw_operator) && !Previous.is(tok::coloncolon))) &&
510       !Previous.is(tok::kw_template) && State.Stack.back().BreakBeforeParameter)
511     return true;
512 
513   // The following could be precomputed as they do not depend on the state.
514   // However, as they should take effect only if the UnwrappedLine does not fit
515   // into the ColumnLimit, they are checked here in the ContinuationIndenter.
516   if (Style.ColumnLimit != 0 && Previous.is(BK_Block) &&
517       Previous.is(tok::l_brace) && !Current.isOneOf(tok::r_brace, tok::comment))
518     return true;
519 
520   if (Current.is(tok::lessless) &&
521       ((Previous.is(tok::identifier) && Previous.TokenText == "endl") ||
522        (Previous.Tok.isLiteral() && (Previous.TokenText.endswith("\\n\"") ||
523                                      Previous.TokenText == "\'\\n\'"))))
524     return true;
525 
526   if (Previous.is(TT_BlockComment) && Previous.IsMultiline)
527     return true;
528 
529   if (State.NoContinuation)
530     return true;
531 
532   return false;
533 }
534 
535 unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
536                                                bool DryRun,
537                                                unsigned ExtraSpaces) {
538   const FormatToken &Current = *State.NextToken;
539 
540   assert(!State.Stack.empty());
541   State.NoContinuation = false;
542 
543   if ((Current.is(TT_ImplicitStringLiteral) &&
544        (Current.Previous->Tok.getIdentifierInfo() == nullptr ||
545         Current.Previous->Tok.getIdentifierInfo()->getPPKeywordID() ==
546             tok::pp_not_keyword))) {
547     unsigned EndColumn =
548         SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getEnd());
549     if (Current.LastNewlineOffset != 0) {
550       // If there is a newline within this token, the final column will solely
551       // determined by the current end column.
552       State.Column = EndColumn;
553     } else {
554       unsigned StartColumn =
555           SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getBegin());
556       assert(EndColumn >= StartColumn);
557       State.Column += EndColumn - StartColumn;
558     }
559     moveStateToNextToken(State, DryRun, /*Newline=*/false);
560     return 0;
561   }
562 
563   unsigned Penalty = 0;
564   if (Newline)
565     Penalty = addTokenOnNewLine(State, DryRun);
566   else
567     addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
568 
569   return moveStateToNextToken(State, DryRun, Newline) + Penalty;
570 }
571 
572 void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
573                                                  unsigned ExtraSpaces) {
574   FormatToken &Current = *State.NextToken;
575   const FormatToken &Previous = *State.NextToken->Previous;
576   if (Current.is(tok::equal) &&
577       (State.Line->First->is(tok::kw_for) || Current.NestingLevel == 0) &&
578       State.Stack.back().VariablePos == 0) {
579     State.Stack.back().VariablePos = State.Column;
580     // Move over * and & if they are bound to the variable name.
581     const FormatToken *Tok = &Previous;
582     while (Tok && State.Stack.back().VariablePos >= Tok->ColumnWidth) {
583       State.Stack.back().VariablePos -= Tok->ColumnWidth;
584       if (Tok->SpacesRequiredBefore != 0)
585         break;
586       Tok = Tok->Previous;
587     }
588     if (Previous.PartOfMultiVariableDeclStmt)
589       State.Stack.back().LastSpace = State.Stack.back().VariablePos;
590   }
591 
592   unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
593 
594   // Indent preprocessor directives after the hash if required.
595   int PPColumnCorrection = 0;
596   if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash &&
597       Previous.is(tok::hash) && State.FirstIndent > 0 &&
598       (State.Line->Type == LT_PreprocessorDirective ||
599        State.Line->Type == LT_ImportStatement)) {
600     Spaces += State.FirstIndent;
601 
602     // For preprocessor indent with tabs, State.Column will be 1 because of the
603     // hash. This causes second-level indents onward to have an extra space
604     // after the tabs. We avoid this misalignment by subtracting 1 from the
605     // column value passed to replaceWhitespace().
606     if (Style.UseTab != FormatStyle::UT_Never)
607       PPColumnCorrection = -1;
608   }
609 
610   if (!DryRun)
611     Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, Spaces,
612                                   State.Column + Spaces + PPColumnCorrection);
613 
614   // If "BreakBeforeInheritanceComma" mode, don't break within the inheritance
615   // declaration unless there is multiple inheritance.
616   if (Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma &&
617       Current.is(TT_InheritanceColon))
618     State.Stack.back().NoLineBreak = true;
619   if (Style.BreakInheritanceList == FormatStyle::BILS_AfterColon &&
620       Previous.is(TT_InheritanceColon))
621     State.Stack.back().NoLineBreak = true;
622 
623   if (Current.is(TT_SelectorName) &&
624       !State.Stack.back().ObjCSelectorNameFound) {
625     unsigned MinIndent =
626         std::max(State.FirstIndent + Style.ContinuationIndentWidth,
627                  State.Stack.back().Indent);
628     unsigned FirstColonPos = State.Column + Spaces + Current.ColumnWidth;
629     if (Current.LongestObjCSelectorName == 0)
630       State.Stack.back().AlignColons = false;
631     else if (MinIndent + Current.LongestObjCSelectorName > FirstColonPos)
632       State.Stack.back().ColonPos = MinIndent + Current.LongestObjCSelectorName;
633     else
634       State.Stack.back().ColonPos = FirstColonPos;
635   }
636 
637   // In "AlwaysBreak" mode, enforce wrapping directly after the parenthesis by
638   // disallowing any further line breaks if there is no line break after the
639   // opening parenthesis. Don't break if it doesn't conserve columns.
640   if (Style.AlignAfterOpenBracket == FormatStyle::BAS_AlwaysBreak &&
641       (Previous.isOneOf(tok::l_paren, TT_TemplateOpener, tok::l_square) ||
642        (Previous.is(tok::l_brace) && Previous.isNot(BK_Block) &&
643         Style.Cpp11BracedListStyle)) &&
644       State.Column > getNewLineColumn(State) &&
645       (!Previous.Previous || !Previous.Previous->isOneOf(
646                                  tok::kw_for, tok::kw_while, tok::kw_switch)) &&
647       // Don't do this for simple (no expressions) one-argument function calls
648       // as that feels like needlessly wasting whitespace, e.g.:
649       //
650       //   caaaaaaaaaaaall(
651       //       caaaaaaaaaaaall(
652       //           caaaaaaaaaaaall(
653       //               caaaaaaaaaaaaaaaaaaaaaaall(aaaaaaaaaaaaaa, aaaaaaaaa))));
654       Current.FakeLParens.size() > 0 &&
655       Current.FakeLParens.back() > prec::Unknown)
656     State.Stack.back().NoLineBreak = true;
657   if (Previous.is(TT_TemplateString) && Previous.opensScope())
658     State.Stack.back().NoLineBreak = true;
659 
660   if (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign &&
661       !State.Stack.back().IsCSharpGenericTypeConstraint &&
662       Previous.opensScope() && Previous.isNot(TT_ObjCMethodExpr) &&
663       (Current.isNot(TT_LineComment) || Previous.is(BK_BracedInit))) {
664     State.Stack.back().Indent = State.Column + Spaces;
665     State.Stack.back().IsAligned = true;
666   }
667   if (State.Stack.back().AvoidBinPacking && startsNextParameter(Current, Style))
668     State.Stack.back().NoLineBreak = true;
669   if (startsSegmentOfBuilderTypeCall(Current) &&
670       State.Column > getNewLineColumn(State))
671     State.Stack.back().ContainsUnwrappedBuilder = true;
672 
673   if (Current.is(TT_LambdaArrow) && Style.Language == FormatStyle::LK_Java)
674     State.Stack.back().NoLineBreak = true;
675   if (Current.isMemberAccess() && Previous.is(tok::r_paren) &&
676       (Previous.MatchingParen &&
677        (Previous.TotalLength - Previous.MatchingParen->TotalLength > 10)))
678     // If there is a function call with long parameters, break before trailing
679     // calls. This prevents things like:
680     //   EXPECT_CALL(SomeLongParameter).Times(
681     //       2);
682     // We don't want to do this for short parameters as they can just be
683     // indexes.
684     State.Stack.back().NoLineBreak = true;
685 
686   // Don't allow the RHS of an operator to be split over multiple lines unless
687   // there is a line-break right after the operator.
688   // Exclude relational operators, as there, it is always more desirable to
689   // have the LHS 'left' of the RHS.
690   const FormatToken *P = Current.getPreviousNonComment();
691   if (!Current.is(tok::comment) && P &&
692       (P->isOneOf(TT_BinaryOperator, tok::comma) ||
693        (P->is(TT_ConditionalExpr) && P->is(tok::colon))) &&
694       !P->isOneOf(TT_OverloadedOperator, TT_CtorInitializerComma) &&
695       P->getPrecedence() != prec::Assignment &&
696       P->getPrecedence() != prec::Relational &&
697       P->getPrecedence() != prec::Spaceship) {
698     bool BreakBeforeOperator =
699         P->MustBreakBefore || P->is(tok::lessless) ||
700         (P->is(TT_BinaryOperator) &&
701          Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None) ||
702         (P->is(TT_ConditionalExpr) && Style.BreakBeforeTernaryOperators);
703     // Don't do this if there are only two operands. In these cases, there is
704     // always a nice vertical separation between them and the extra line break
705     // does not help.
706     bool HasTwoOperands =
707         P->OperatorIndex == 0 && !P->NextOperator && !P->is(TT_ConditionalExpr);
708     if ((!BreakBeforeOperator &&
709          !(HasTwoOperands &&
710            Style.AlignOperands != FormatStyle::OAS_DontAlign)) ||
711         (!State.Stack.back().LastOperatorWrapped && BreakBeforeOperator))
712       State.Stack.back().NoLineBreakInOperand = true;
713   }
714 
715   State.Column += Spaces;
716   if (Current.isNot(tok::comment) && Previous.is(tok::l_paren) &&
717       Previous.Previous &&
718       (Previous.Previous->is(tok::kw_for) || Previous.Previous->isIf())) {
719     // Treat the condition inside an if as if it was a second function
720     // parameter, i.e. let nested calls have a continuation indent.
721     State.Stack.back().LastSpace = State.Column;
722     State.Stack.back().NestedBlockIndent = State.Column;
723   } else if (!Current.isOneOf(tok::comment, tok::caret) &&
724              ((Previous.is(tok::comma) &&
725                !Previous.is(TT_OverloadedOperator)) ||
726               (Previous.is(tok::colon) && Previous.is(TT_ObjCMethodExpr)))) {
727     State.Stack.back().LastSpace = State.Column;
728   } else if (Previous.is(TT_CtorInitializerColon) &&
729              Style.BreakConstructorInitializers ==
730                  FormatStyle::BCIS_AfterColon) {
731     State.Stack.back().Indent = State.Column;
732     State.Stack.back().LastSpace = State.Column;
733   } else if ((Previous.isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
734                                TT_CtorInitializerColon)) &&
735              ((Previous.getPrecedence() != prec::Assignment &&
736                (Previous.isNot(tok::lessless) || Previous.OperatorIndex != 0 ||
737                 Previous.NextOperator)) ||
738               Current.StartsBinaryExpression)) {
739     // Indent relative to the RHS of the expression unless this is a simple
740     // assignment without binary expression on the RHS. Also indent relative to
741     // unary operators and the colons of constructor initializers.
742     if (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None)
743       State.Stack.back().LastSpace = State.Column;
744   } else if (Previous.is(TT_InheritanceColon)) {
745     State.Stack.back().Indent = State.Column;
746     State.Stack.back().LastSpace = State.Column;
747   } else if (Current.is(TT_CSharpGenericTypeConstraintColon)) {
748     State.Stack.back().ColonPos = State.Column;
749   } else if (Previous.opensScope()) {
750     // If a function has a trailing call, indent all parameters from the
751     // opening parenthesis. This avoids confusing indents like:
752     //   OuterFunction(InnerFunctionCall( // break
753     //       ParameterToInnerFunction))   // break
754     //       .SecondInnerFunctionCall();
755     bool HasTrailingCall = false;
756     if (Previous.MatchingParen) {
757       const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
758       HasTrailingCall = Next && Next->isMemberAccess();
759     }
760     if (HasTrailingCall && State.Stack.size() > 1 &&
761         State.Stack[State.Stack.size() - 2].CallContinuation == 0)
762       State.Stack.back().LastSpace = State.Column;
763   }
764 }
765 
766 unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
767                                                  bool DryRun) {
768   FormatToken &Current = *State.NextToken;
769   const FormatToken &Previous = *State.NextToken->Previous;
770 
771   // Extra penalty that needs to be added because of the way certain line
772   // breaks are chosen.
773   unsigned Penalty = 0;
774 
775   const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
776   const FormatToken *NextNonComment = Previous.getNextNonComment();
777   if (!NextNonComment)
778     NextNonComment = &Current;
779   // The first line break on any NestingLevel causes an extra penalty in order
780   // prefer similar line breaks.
781   if (!State.Stack.back().ContainsLineBreak)
782     Penalty += 15;
783   State.Stack.back().ContainsLineBreak = true;
784 
785   Penalty += State.NextToken->SplitPenalty;
786 
787   // Breaking before the first "<<" is generally not desirable if the LHS is
788   // short. Also always add the penalty if the LHS is split over multiple lines
789   // to avoid unnecessary line breaks that just work around this penalty.
790   if (NextNonComment->is(tok::lessless) &&
791       State.Stack.back().FirstLessLess == 0 &&
792       (State.Column <= Style.ColumnLimit / 3 ||
793        State.Stack.back().BreakBeforeParameter))
794     Penalty += Style.PenaltyBreakFirstLessLess;
795 
796   State.Column = getNewLineColumn(State);
797 
798   // Add Penalty proportional to amount of whitespace away from FirstColumn
799   // This tends to penalize several lines that are far-right indented,
800   // and prefers a line-break prior to such a block, e.g:
801   //
802   // Constructor() :
803   //   member(value), looooooooooooooooong_member(
804   //                      looooooooooong_call(param_1, param_2, param_3))
805   // would then become
806   // Constructor() :
807   //   member(value),
808   //   looooooooooooooooong_member(
809   //       looooooooooong_call(param_1, param_2, param_3))
810   if (State.Column > State.FirstIndent)
811     Penalty +=
812         Style.PenaltyIndentedWhitespace * (State.Column - State.FirstIndent);
813 
814   // Indent nested blocks relative to this column, unless in a very specific
815   // JavaScript special case where:
816   //
817   //   var loooooong_name =
818   //       function() {
819   //     // code
820   //   }
821   //
822   // is common and should be formatted like a free-standing function. The same
823   // goes for wrapping before the lambda return type arrow.
824   if (!Current.is(TT_LambdaArrow) &&
825       (Style.Language != FormatStyle::LK_JavaScript ||
826        Current.NestingLevel != 0 || !PreviousNonComment ||
827        !PreviousNonComment->is(tok::equal) ||
828        !Current.isOneOf(Keywords.kw_async, Keywords.kw_function)))
829     State.Stack.back().NestedBlockIndent = State.Column;
830 
831   if (NextNonComment->isMemberAccess()) {
832     if (State.Stack.back().CallContinuation == 0)
833       State.Stack.back().CallContinuation = State.Column;
834   } else if (NextNonComment->is(TT_SelectorName)) {
835     if (!State.Stack.back().ObjCSelectorNameFound) {
836       if (NextNonComment->LongestObjCSelectorName == 0) {
837         State.Stack.back().AlignColons = false;
838       } else {
839         State.Stack.back().ColonPos =
840             (shouldIndentWrappedSelectorName(Style, State.Line->Type)
841                  ? std::max(State.Stack.back().Indent,
842                             State.FirstIndent + Style.ContinuationIndentWidth)
843                  : State.Stack.back().Indent) +
844             std::max(NextNonComment->LongestObjCSelectorName,
845                      NextNonComment->ColumnWidth);
846       }
847     } else if (State.Stack.back().AlignColons &&
848                State.Stack.back().ColonPos <= NextNonComment->ColumnWidth) {
849       State.Stack.back().ColonPos = State.Column + NextNonComment->ColumnWidth;
850     }
851   } else if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
852              PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) {
853     // FIXME: This is hacky, find a better way. The problem is that in an ObjC
854     // method expression, the block should be aligned to the line starting it,
855     // e.g.:
856     //   [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason
857     //                        ^(int *i) {
858     //                            // ...
859     //                        }];
860     // Thus, we set LastSpace of the next higher NestingLevel, to which we move
861     // when we consume all of the "}"'s FakeRParens at the "{".
862     if (State.Stack.size() > 1)
863       State.Stack[State.Stack.size() - 2].LastSpace =
864           std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
865           Style.ContinuationIndentWidth;
866   }
867 
868   if ((PreviousNonComment &&
869        PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
870        !State.Stack.back().AvoidBinPacking) ||
871       Previous.is(TT_BinaryOperator))
872     State.Stack.back().BreakBeforeParameter = false;
873   if (PreviousNonComment &&
874       PreviousNonComment->isOneOf(TT_TemplateCloser, TT_JavaAnnotation) &&
875       Current.NestingLevel == 0)
876     State.Stack.back().BreakBeforeParameter = false;
877   if (NextNonComment->is(tok::question) ||
878       (PreviousNonComment && PreviousNonComment->is(tok::question)))
879     State.Stack.back().BreakBeforeParameter = true;
880   if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore)
881     State.Stack.back().BreakBeforeParameter = false;
882 
883   if (!DryRun) {
884     unsigned MaxEmptyLinesToKeep = Style.MaxEmptyLinesToKeep + 1;
885     if (Current.is(tok::r_brace) && Current.MatchingParen &&
886         // Only strip trailing empty lines for l_braces that have children, i.e.
887         // for function expressions (lambdas, arrows, etc).
888         !Current.MatchingParen->Children.empty()) {
889       // lambdas and arrow functions are expressions, thus their r_brace is not
890       // on its own line, and thus not covered by UnwrappedLineFormatter's logic
891       // about removing empty lines on closing blocks. Special case them here.
892       MaxEmptyLinesToKeep = 1;
893     }
894     unsigned Newlines =
895         std::max(1u, std::min(Current.NewlinesBefore, MaxEmptyLinesToKeep));
896     bool ContinuePPDirective =
897         State.Line->InPPDirective && State.Line->Type != LT_ImportStatement;
898     Whitespaces.replaceWhitespace(Current, Newlines, State.Column, State.Column,
899                                   State.Stack.back().IsAligned,
900                                   ContinuePPDirective);
901   }
902 
903   if (!Current.isTrailingComment())
904     State.Stack.back().LastSpace = State.Column;
905   if (Current.is(tok::lessless))
906     // If we are breaking before a "<<", we always want to indent relative to
907     // RHS. This is necessary only for "<<", as we special-case it and don't
908     // always indent relative to the RHS.
909     State.Stack.back().LastSpace += 3; // 3 -> width of "<< ".
910 
911   State.StartOfLineLevel = Current.NestingLevel;
912   State.LowestLevelOnLine = Current.NestingLevel;
913 
914   // Any break on this level means that the parent level has been broken
915   // and we need to avoid bin packing there.
916   bool NestedBlockSpecialCase =
917       (!Style.isCpp() && Current.is(tok::r_brace) && State.Stack.size() > 1 &&
918        State.Stack[State.Stack.size() - 2].NestedBlockInlined) ||
919       (Style.Language == FormatStyle::LK_ObjC && Current.is(tok::r_brace) &&
920        State.Stack.size() > 1 && !Style.ObjCBreakBeforeNestedBlockParam);
921   if (!NestedBlockSpecialCase)
922     for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i)
923       State.Stack[i].BreakBeforeParameter = true;
924 
925   if (PreviousNonComment &&
926       !PreviousNonComment->isOneOf(tok::comma, tok::colon, tok::semi) &&
927       (PreviousNonComment->isNot(TT_TemplateCloser) ||
928        Current.NestingLevel != 0) &&
929       !PreviousNonComment->isOneOf(
930           TT_BinaryOperator, TT_FunctionAnnotationRParen, TT_JavaAnnotation,
931           TT_LeadingJavaAnnotation) &&
932       Current.isNot(TT_BinaryOperator) && !PreviousNonComment->opensScope())
933     State.Stack.back().BreakBeforeParameter = true;
934 
935   // If we break after { or the [ of an array initializer, we should also break
936   // before the corresponding } or ].
937   if (PreviousNonComment &&
938       (PreviousNonComment->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
939        opensProtoMessageField(*PreviousNonComment, Style)))
940     State.Stack.back().BreakBeforeClosingBrace = true;
941 
942   if (State.Stack.back().AvoidBinPacking) {
943     // If we are breaking after '(', '{', '<', or this is the break after a ':'
944     // to start a member initializater list in a constructor, this should not
945     // be considered bin packing unless the relevant AllowAll option is false or
946     // this is a dict/object literal.
947     bool PreviousIsBreakingCtorInitializerColon =
948         Previous.is(TT_CtorInitializerColon) &&
949         Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon;
950     if (!(Previous.isOneOf(tok::l_paren, tok::l_brace, TT_BinaryOperator) ||
951           PreviousIsBreakingCtorInitializerColon) ||
952         (!Style.AllowAllParametersOfDeclarationOnNextLine &&
953          State.Line->MustBeDeclaration) ||
954         (!Style.AllowAllArgumentsOnNextLine &&
955          !State.Line->MustBeDeclaration) ||
956         (!Style.AllowAllConstructorInitializersOnNextLine &&
957          PreviousIsBreakingCtorInitializerColon) ||
958         Previous.is(TT_DictLiteral))
959       State.Stack.back().BreakBeforeParameter = true;
960 
961     // If we are breaking after a ':' to start a member initializer list,
962     // and we allow all arguments on the next line, we should not break
963     // before the next parameter.
964     if (PreviousIsBreakingCtorInitializerColon &&
965         Style.AllowAllConstructorInitializersOnNextLine)
966       State.Stack.back().BreakBeforeParameter = false;
967   }
968 
969   return Penalty;
970 }
971 
972 unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) {
973   if (!State.NextToken || !State.NextToken->Previous)
974     return 0;
975 
976   FormatToken &Current = *State.NextToken;
977 
978   if (State.Stack.back().IsCSharpGenericTypeConstraint &&
979       Current.isNot(TT_CSharpGenericTypeConstraint))
980     return State.Stack.back().ColonPos + 2;
981 
982   const FormatToken &Previous = *Current.Previous;
983   // If we are continuing an expression, we want to use the continuation indent.
984   unsigned ContinuationIndent =
985       std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
986       Style.ContinuationIndentWidth;
987   const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
988   const FormatToken *NextNonComment = Previous.getNextNonComment();
989   if (!NextNonComment)
990     NextNonComment = &Current;
991 
992   // Java specific bits.
993   if (Style.Language == FormatStyle::LK_Java &&
994       Current.isOneOf(Keywords.kw_implements, Keywords.kw_extends))
995     return std::max(State.Stack.back().LastSpace,
996                     State.Stack.back().Indent + Style.ContinuationIndentWidth);
997 
998   if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths &&
999       State.Line->First->is(tok::kw_enum))
1000     return (Style.IndentWidth * State.Line->First->IndentLevel) +
1001            Style.IndentWidth;
1002 
1003   if (NextNonComment->is(tok::l_brace) && NextNonComment->is(BK_Block))
1004     return Current.NestingLevel == 0 ? State.FirstIndent
1005                                      : State.Stack.back().Indent;
1006   if ((Current.isOneOf(tok::r_brace, tok::r_square) ||
1007        (Current.is(tok::greater) &&
1008         (Style.Language == FormatStyle::LK_Proto ||
1009          Style.Language == FormatStyle::LK_TextProto))) &&
1010       State.Stack.size() > 1) {
1011     if (Current.closesBlockOrBlockTypeList(Style))
1012       return State.Stack[State.Stack.size() - 2].NestedBlockIndent;
1013     if (Current.MatchingParen && Current.MatchingParen->is(BK_BracedInit))
1014       return State.Stack[State.Stack.size() - 2].LastSpace;
1015     return State.FirstIndent;
1016   }
1017   // Indent a closing parenthesis at the previous level if followed by a semi,
1018   // const, or opening brace. This allows indentations such as:
1019   //     foo(
1020   //       a,
1021   //     );
1022   //     int Foo::getter(
1023   //         //
1024   //     ) const {
1025   //       return foo;
1026   //     }
1027   //     function foo(
1028   //       a,
1029   //     ) {
1030   //       code(); //
1031   //     }
1032   if (Current.is(tok::r_paren) && State.Stack.size() > 1 &&
1033       (!Current.Next ||
1034        Current.Next->isOneOf(tok::semi, tok::kw_const, tok::l_brace)))
1035     return State.Stack[State.Stack.size() - 2].LastSpace;
1036   if (NextNonComment->is(TT_TemplateString) && NextNonComment->closesScope())
1037     return State.Stack[State.Stack.size() - 2].LastSpace;
1038   if (Current.is(tok::identifier) && Current.Next &&
1039       (Current.Next->is(TT_DictLiteral) ||
1040        ((Style.Language == FormatStyle::LK_Proto ||
1041          Style.Language == FormatStyle::LK_TextProto) &&
1042         Current.Next->isOneOf(tok::less, tok::l_brace))))
1043     return State.Stack.back().Indent;
1044   if (NextNonComment->is(TT_ObjCStringLiteral) &&
1045       State.StartOfStringLiteral != 0)
1046     return State.StartOfStringLiteral - 1;
1047   if (NextNonComment->isStringLiteral() && State.StartOfStringLiteral != 0)
1048     return State.StartOfStringLiteral;
1049   if (NextNonComment->is(tok::lessless) &&
1050       State.Stack.back().FirstLessLess != 0)
1051     return State.Stack.back().FirstLessLess;
1052   if (NextNonComment->isMemberAccess()) {
1053     if (State.Stack.back().CallContinuation == 0)
1054       return ContinuationIndent;
1055     return State.Stack.back().CallContinuation;
1056   }
1057   if (State.Stack.back().QuestionColumn != 0 &&
1058       ((NextNonComment->is(tok::colon) &&
1059         NextNonComment->is(TT_ConditionalExpr)) ||
1060        Previous.is(TT_ConditionalExpr))) {
1061     if (((NextNonComment->is(tok::colon) && NextNonComment->Next &&
1062           !NextNonComment->Next->FakeLParens.empty() &&
1063           NextNonComment->Next->FakeLParens.back() == prec::Conditional) ||
1064          (Previous.is(tok::colon) && !Current.FakeLParens.empty() &&
1065           Current.FakeLParens.back() == prec::Conditional)) &&
1066         !State.Stack.back().IsWrappedConditional) {
1067       // NOTE: we may tweak this slightly:
1068       //    * not remove the 'lead' ContinuationIndentWidth
1069       //    * always un-indent by the operator when
1070       //    BreakBeforeTernaryOperators=true
1071       unsigned Indent = State.Stack.back().Indent;
1072       if (Style.AlignOperands != FormatStyle::OAS_DontAlign) {
1073         Indent -= Style.ContinuationIndentWidth;
1074       }
1075       if (Style.BreakBeforeTernaryOperators &&
1076           State.Stack.back().UnindentOperator)
1077         Indent -= 2;
1078       return Indent;
1079     }
1080     return State.Stack.back().QuestionColumn;
1081   }
1082   if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0)
1083     return State.Stack.back().VariablePos;
1084   if ((PreviousNonComment &&
1085        (PreviousNonComment->ClosesTemplateDeclaration ||
1086         PreviousNonComment->isOneOf(
1087             TT_AttributeParen, TT_AttributeSquare, TT_FunctionAnnotationRParen,
1088             TT_JavaAnnotation, TT_LeadingJavaAnnotation))) ||
1089       (!Style.IndentWrappedFunctionNames &&
1090        NextNonComment->isOneOf(tok::kw_operator, TT_FunctionDeclarationName)))
1091     return std::max(State.Stack.back().LastSpace, State.Stack.back().Indent);
1092   if (NextNonComment->is(TT_SelectorName)) {
1093     if (!State.Stack.back().ObjCSelectorNameFound) {
1094       unsigned MinIndent = State.Stack.back().Indent;
1095       if (shouldIndentWrappedSelectorName(Style, State.Line->Type))
1096         MinIndent = std::max(MinIndent,
1097                              State.FirstIndent + Style.ContinuationIndentWidth);
1098       // If LongestObjCSelectorName is 0, we are indenting the first
1099       // part of an ObjC selector (or a selector component which is
1100       // not colon-aligned due to block formatting).
1101       //
1102       // Otherwise, we are indenting a subsequent part of an ObjC
1103       // selector which should be colon-aligned to the longest
1104       // component of the ObjC selector.
1105       //
1106       // In either case, we want to respect Style.IndentWrappedFunctionNames.
1107       return MinIndent +
1108              std::max(NextNonComment->LongestObjCSelectorName,
1109                       NextNonComment->ColumnWidth) -
1110              NextNonComment->ColumnWidth;
1111     }
1112     if (!State.Stack.back().AlignColons)
1113       return State.Stack.back().Indent;
1114     if (State.Stack.back().ColonPos > NextNonComment->ColumnWidth)
1115       return State.Stack.back().ColonPos - NextNonComment->ColumnWidth;
1116     return State.Stack.back().Indent;
1117   }
1118   if (NextNonComment->is(tok::colon) && NextNonComment->is(TT_ObjCMethodExpr))
1119     return State.Stack.back().ColonPos;
1120   if (NextNonComment->is(TT_ArraySubscriptLSquare)) {
1121     if (State.Stack.back().StartOfArraySubscripts != 0)
1122       return State.Stack.back().StartOfArraySubscripts;
1123     else if (Style.isCSharp()) // C# allows `["key"] = value` inside object
1124                                // initializers.
1125       return State.Stack.back().Indent;
1126     return ContinuationIndent;
1127   }
1128 
1129   // This ensure that we correctly format ObjC methods calls without inputs,
1130   // i.e. where the last element isn't selector like: [callee method];
1131   if (NextNonComment->is(tok::identifier) && NextNonComment->FakeRParens == 0 &&
1132       NextNonComment->Next && NextNonComment->Next->is(TT_ObjCMethodExpr))
1133     return State.Stack.back().Indent;
1134 
1135   if (NextNonComment->isOneOf(TT_StartOfName, TT_PointerOrReference) ||
1136       Previous.isOneOf(tok::coloncolon, tok::equal, TT_JsTypeColon))
1137     return ContinuationIndent;
1138   if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
1139       PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))
1140     return ContinuationIndent;
1141   if (NextNonComment->is(TT_CtorInitializerComma))
1142     return State.Stack.back().Indent;
1143   if (PreviousNonComment && PreviousNonComment->is(TT_CtorInitializerColon) &&
1144       Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon)
1145     return State.Stack.back().Indent;
1146   if (PreviousNonComment && PreviousNonComment->is(TT_InheritanceColon) &&
1147       Style.BreakInheritanceList == FormatStyle::BILS_AfterColon)
1148     return State.Stack.back().Indent;
1149   if (NextNonComment->isOneOf(TT_CtorInitializerColon, TT_InheritanceColon,
1150                               TT_InheritanceComma))
1151     return State.FirstIndent + Style.ConstructorInitializerIndentWidth;
1152   if (Previous.is(tok::r_paren) && !Current.isBinaryOperator() &&
1153       !Current.isOneOf(tok::colon, tok::comment))
1154     return ContinuationIndent;
1155   if (Current.is(TT_ProtoExtensionLSquare))
1156     return State.Stack.back().Indent;
1157   if (Current.isBinaryOperator() && State.Stack.back().UnindentOperator)
1158     return State.Stack.back().Indent - Current.Tok.getLength() -
1159            Current.SpacesRequiredBefore;
1160   if (Current.isOneOf(tok::comment, TT_BlockComment, TT_LineComment) &&
1161       NextNonComment->isBinaryOperator() && State.Stack.back().UnindentOperator)
1162     return State.Stack.back().Indent - NextNonComment->Tok.getLength() -
1163            NextNonComment->SpacesRequiredBefore;
1164   if (State.Stack.back().Indent == State.FirstIndent && PreviousNonComment &&
1165       !PreviousNonComment->isOneOf(tok::r_brace, TT_CtorInitializerComma))
1166     // Ensure that we fall back to the continuation indent width instead of
1167     // just flushing continuations left.
1168     return State.Stack.back().Indent + Style.ContinuationIndentWidth;
1169   return State.Stack.back().Indent;
1170 }
1171 
1172 static bool hasNestedBlockInlined(const FormatToken *Previous,
1173                                   const FormatToken &Current,
1174                                   const FormatStyle &Style) {
1175   if (Previous->isNot(tok::l_paren))
1176     return true;
1177   if (Previous->ParameterCount > 1)
1178     return true;
1179 
1180   // Also a nested block if contains a lambda inside function with 1 parameter
1181   return (Style.BraceWrapping.BeforeLambdaBody && Current.is(TT_LambdaLSquare));
1182 }
1183 
1184 unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
1185                                                     bool DryRun, bool Newline) {
1186   assert(State.Stack.size());
1187   const FormatToken &Current = *State.NextToken;
1188 
1189   if (Current.is(TT_CSharpGenericTypeConstraint))
1190     State.Stack.back().IsCSharpGenericTypeConstraint = true;
1191   if (Current.isOneOf(tok::comma, TT_BinaryOperator))
1192     State.Stack.back().NoLineBreakInOperand = false;
1193   if (Current.isOneOf(TT_InheritanceColon, TT_CSharpGenericTypeConstraintColon))
1194     State.Stack.back().AvoidBinPacking = true;
1195   if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator)) {
1196     if (State.Stack.back().FirstLessLess == 0)
1197       State.Stack.back().FirstLessLess = State.Column;
1198     else
1199       State.Stack.back().LastOperatorWrapped = Newline;
1200   }
1201   if (Current.is(TT_BinaryOperator) && Current.isNot(tok::lessless))
1202     State.Stack.back().LastOperatorWrapped = Newline;
1203   if (Current.is(TT_ConditionalExpr) && Current.Previous &&
1204       !Current.Previous->is(TT_ConditionalExpr))
1205     State.Stack.back().LastOperatorWrapped = Newline;
1206   if (Current.is(TT_ArraySubscriptLSquare) &&
1207       State.Stack.back().StartOfArraySubscripts == 0)
1208     State.Stack.back().StartOfArraySubscripts = State.Column;
1209   if (Current.is(TT_ConditionalExpr) && Current.is(tok::question) &&
1210       ((Current.MustBreakBefore) ||
1211        (Current.getNextNonComment() &&
1212         Current.getNextNonComment()->MustBreakBefore)))
1213     State.Stack.back().IsWrappedConditional = true;
1214   if (Style.BreakBeforeTernaryOperators && Current.is(tok::question))
1215     State.Stack.back().QuestionColumn = State.Column;
1216   if (!Style.BreakBeforeTernaryOperators && Current.isNot(tok::colon)) {
1217     const FormatToken *Previous = Current.Previous;
1218     while (Previous && Previous->isTrailingComment())
1219       Previous = Previous->Previous;
1220     if (Previous && Previous->is(tok::question))
1221       State.Stack.back().QuestionColumn = State.Column;
1222   }
1223   if (!Current.opensScope() && !Current.closesScope() &&
1224       !Current.is(TT_PointerOrReference))
1225     State.LowestLevelOnLine =
1226         std::min(State.LowestLevelOnLine, Current.NestingLevel);
1227   if (Current.isMemberAccess())
1228     State.Stack.back().StartOfFunctionCall =
1229         !Current.NextOperator ? 0 : State.Column;
1230   if (Current.is(TT_SelectorName))
1231     State.Stack.back().ObjCSelectorNameFound = true;
1232   if (Current.is(TT_CtorInitializerColon) &&
1233       Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon) {
1234     // Indent 2 from the column, so:
1235     // SomeClass::SomeClass()
1236     //     : First(...), ...
1237     //       Next(...)
1238     //       ^ line up here.
1239     State.Stack.back().Indent =
1240         State.Column +
1241         (Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma
1242              ? 0
1243              : 2);
1244     State.Stack.back().NestedBlockIndent = State.Stack.back().Indent;
1245     if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine) {
1246       State.Stack.back().AvoidBinPacking = true;
1247       State.Stack.back().BreakBeforeParameter =
1248           !Style.AllowAllConstructorInitializersOnNextLine;
1249     } else {
1250       State.Stack.back().BreakBeforeParameter = false;
1251     }
1252   }
1253   if (Current.is(TT_CtorInitializerColon) &&
1254       Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon) {
1255     State.Stack.back().Indent =
1256         State.FirstIndent + Style.ConstructorInitializerIndentWidth;
1257     State.Stack.back().NestedBlockIndent = State.Stack.back().Indent;
1258     if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
1259       State.Stack.back().AvoidBinPacking = true;
1260   }
1261   if (Current.is(TT_InheritanceColon))
1262     State.Stack.back().Indent =
1263         State.FirstIndent + Style.ConstructorInitializerIndentWidth;
1264   if (Current.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) && Newline)
1265     State.Stack.back().NestedBlockIndent =
1266         State.Column + Current.ColumnWidth + 1;
1267   if (Current.isOneOf(TT_LambdaLSquare, TT_LambdaArrow))
1268     State.Stack.back().LastSpace = State.Column;
1269 
1270   // Insert scopes created by fake parenthesis.
1271   const FormatToken *Previous = Current.getPreviousNonComment();
1272 
1273   // Add special behavior to support a format commonly used for JavaScript
1274   // closures:
1275   //   SomeFunction(function() {
1276   //     foo();
1277   //     bar();
1278   //   }, a, b, c);
1279   if (Current.isNot(tok::comment) && Previous &&
1280       Previous->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
1281       !Previous->is(TT_DictLiteral) && State.Stack.size() > 1 &&
1282       !State.Stack.back().HasMultipleNestedBlocks) {
1283     if (State.Stack[State.Stack.size() - 2].NestedBlockInlined && Newline)
1284       for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i)
1285         State.Stack[i].NoLineBreak = true;
1286     State.Stack[State.Stack.size() - 2].NestedBlockInlined = false;
1287   }
1288   if (Previous &&
1289       (Previous->isOneOf(tok::l_paren, tok::comma, tok::colon) ||
1290        Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr)) &&
1291       !Previous->isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
1292     State.Stack.back().NestedBlockInlined =
1293         !Newline && hasNestedBlockInlined(Previous, Current, Style);
1294   }
1295 
1296   moveStatePastFakeLParens(State, Newline);
1297   moveStatePastScopeCloser(State);
1298   bool AllowBreak = !State.Stack.back().NoLineBreak &&
1299                     !State.Stack.back().NoLineBreakInOperand;
1300   moveStatePastScopeOpener(State, Newline);
1301   moveStatePastFakeRParens(State);
1302 
1303   if (Current.is(TT_ObjCStringLiteral) && State.StartOfStringLiteral == 0)
1304     State.StartOfStringLiteral = State.Column + 1;
1305   if (Current.is(TT_CSharpStringLiteral) && State.StartOfStringLiteral == 0)
1306     State.StartOfStringLiteral = State.Column + 1;
1307   else if (Current.isStringLiteral() && State.StartOfStringLiteral == 0)
1308     State.StartOfStringLiteral = State.Column;
1309   else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
1310            !Current.isStringLiteral())
1311     State.StartOfStringLiteral = 0;
1312 
1313   State.Column += Current.ColumnWidth;
1314   State.NextToken = State.NextToken->Next;
1315 
1316   unsigned Penalty =
1317       handleEndOfLine(Current, State, DryRun, AllowBreak, Newline);
1318 
1319   if (Current.Role)
1320     Current.Role->formatFromToken(State, this, DryRun);
1321   // If the previous has a special role, let it consume tokens as appropriate.
1322   // It is necessary to start at the previous token for the only implemented
1323   // role (comma separated list). That way, the decision whether or not to break
1324   // after the "{" is already done and both options are tried and evaluated.
1325   // FIXME: This is ugly, find a better way.
1326   if (Previous && Previous->Role)
1327     Penalty += Previous->Role->formatAfterToken(State, this, DryRun);
1328 
1329   return Penalty;
1330 }
1331 
1332 void ContinuationIndenter::moveStatePastFakeLParens(LineState &State,
1333                                                     bool Newline) {
1334   const FormatToken &Current = *State.NextToken;
1335   const FormatToken *Previous = Current.getPreviousNonComment();
1336 
1337   // Don't add extra indentation for the first fake parenthesis after
1338   // 'return', assignments or opening <({[. The indentation for these cases
1339   // is special cased.
1340   bool SkipFirstExtraIndent =
1341       (Previous && (Previous->opensScope() ||
1342                     Previous->isOneOf(tok::semi, tok::kw_return) ||
1343                     (Previous->getPrecedence() == prec::Assignment &&
1344                      Style.AlignOperands != FormatStyle::OAS_DontAlign) ||
1345                     Previous->is(TT_ObjCMethodExpr)));
1346   for (SmallVectorImpl<prec::Level>::const_reverse_iterator
1347            I = Current.FakeLParens.rbegin(),
1348            E = Current.FakeLParens.rend();
1349        I != E; ++I) {
1350     ParenState NewParenState = State.Stack.back();
1351     NewParenState.Tok = nullptr;
1352     NewParenState.ContainsLineBreak = false;
1353     NewParenState.LastOperatorWrapped = true;
1354     NewParenState.IsChainedConditional = false;
1355     NewParenState.IsWrappedConditional = false;
1356     NewParenState.UnindentOperator = false;
1357     NewParenState.NoLineBreak =
1358         NewParenState.NoLineBreak || State.Stack.back().NoLineBreakInOperand;
1359 
1360     // Don't propagate AvoidBinPacking into subexpressions of arg/param lists.
1361     if (*I > prec::Comma)
1362       NewParenState.AvoidBinPacking = false;
1363 
1364     // Indent from 'LastSpace' unless these are fake parentheses encapsulating
1365     // a builder type call after 'return' or, if the alignment after opening
1366     // brackets is disabled.
1367     if (!Current.isTrailingComment() &&
1368         (Style.AlignOperands != FormatStyle::OAS_DontAlign ||
1369          *I < prec::Assignment) &&
1370         (!Previous || Previous->isNot(tok::kw_return) ||
1371          (Style.Language != FormatStyle::LK_Java && *I > 0)) &&
1372         (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign ||
1373          *I != prec::Comma || Current.NestingLevel == 0)) {
1374       NewParenState.Indent =
1375           std::max(std::max(State.Column, NewParenState.Indent),
1376                    State.Stack.back().LastSpace);
1377     }
1378 
1379     if (Previous &&
1380         (Previous->getPrecedence() == prec::Assignment ||
1381          Previous->is(tok::kw_return) ||
1382          (*I == prec::Conditional && Previous->is(tok::question) &&
1383           Previous->is(TT_ConditionalExpr))) &&
1384         !Newline) {
1385       // If BreakBeforeBinaryOperators is set, un-indent a bit to account for
1386       // the operator and keep the operands aligned
1387       if (Style.AlignOperands == FormatStyle::OAS_AlignAfterOperator)
1388         NewParenState.UnindentOperator = true;
1389       // Mark indentation as alignment if the expression is aligned.
1390       if (Style.AlignOperands != FormatStyle::OAS_DontAlign)
1391         NewParenState.IsAligned = true;
1392     }
1393 
1394     // Do not indent relative to the fake parentheses inserted for "." or "->".
1395     // This is a special case to make the following to statements consistent:
1396     //   OuterFunction(InnerFunctionCall( // break
1397     //       ParameterToInnerFunction));
1398     //   OuterFunction(SomeObject.InnerFunctionCall( // break
1399     //       ParameterToInnerFunction));
1400     if (*I > prec::Unknown)
1401       NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
1402     if (*I != prec::Conditional && !Current.is(TT_UnaryOperator) &&
1403         Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
1404       NewParenState.StartOfFunctionCall = State.Column;
1405 
1406     // Indent conditional expressions, unless they are chained "else-if"
1407     // conditionals. Never indent expression where the 'operator' is ',', ';' or
1408     // an assignment (i.e. *I <= prec::Assignment) as those have different
1409     // indentation rules. Indent other expression, unless the indentation needs
1410     // to be skipped.
1411     if (*I == prec::Conditional && Previous && Previous->is(tok::colon) &&
1412         Previous->is(TT_ConditionalExpr) && I == Current.FakeLParens.rbegin() &&
1413         !State.Stack.back().IsWrappedConditional) {
1414       NewParenState.IsChainedConditional = true;
1415       NewParenState.UnindentOperator = State.Stack.back().UnindentOperator;
1416     } else if (*I == prec::Conditional ||
1417                (!SkipFirstExtraIndent && *I > prec::Assignment &&
1418                 !Current.isTrailingComment())) {
1419       NewParenState.Indent += Style.ContinuationIndentWidth;
1420     }
1421     if ((Previous && !Previous->opensScope()) || *I != prec::Comma)
1422       NewParenState.BreakBeforeParameter = false;
1423     State.Stack.push_back(NewParenState);
1424     SkipFirstExtraIndent = false;
1425   }
1426 }
1427 
1428 void ContinuationIndenter::moveStatePastFakeRParens(LineState &State) {
1429   for (unsigned i = 0, e = State.NextToken->FakeRParens; i != e; ++i) {
1430     unsigned VariablePos = State.Stack.back().VariablePos;
1431     if (State.Stack.size() == 1) {
1432       // Do not pop the last element.
1433       break;
1434     }
1435     State.Stack.pop_back();
1436     State.Stack.back().VariablePos = VariablePos;
1437   }
1438 }
1439 
1440 void ContinuationIndenter::moveStatePastScopeOpener(LineState &State,
1441                                                     bool Newline) {
1442   const FormatToken &Current = *State.NextToken;
1443   if (!Current.opensScope())
1444     return;
1445 
1446   // Don't allow '<' or '(' in C# generic type constraints to start new scopes.
1447   if (Current.isOneOf(tok::less, tok::l_paren) &&
1448       State.Stack.back().IsCSharpGenericTypeConstraint)
1449     return;
1450 
1451   if (Current.MatchingParen && Current.is(BK_Block)) {
1452     moveStateToNewBlock(State);
1453     return;
1454   }
1455 
1456   unsigned NewIndent;
1457   unsigned LastSpace = State.Stack.back().LastSpace;
1458   bool AvoidBinPacking;
1459   bool BreakBeforeParameter = false;
1460   unsigned NestedBlockIndent = std::max(State.Stack.back().StartOfFunctionCall,
1461                                         State.Stack.back().NestedBlockIndent);
1462   if (Current.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
1463       opensProtoMessageField(Current, Style)) {
1464     if (Current.opensBlockOrBlockTypeList(Style)) {
1465       NewIndent = Style.IndentWidth +
1466                   std::min(State.Column, State.Stack.back().NestedBlockIndent);
1467     } else {
1468       NewIndent = State.Stack.back().LastSpace + Style.ContinuationIndentWidth;
1469     }
1470     const FormatToken *NextNoComment = Current.getNextNonComment();
1471     bool EndsInComma = Current.MatchingParen &&
1472                        Current.MatchingParen->Previous &&
1473                        Current.MatchingParen->Previous->is(tok::comma);
1474     AvoidBinPacking = EndsInComma || Current.is(TT_DictLiteral) ||
1475                       Style.Language == FormatStyle::LK_Proto ||
1476                       Style.Language == FormatStyle::LK_TextProto ||
1477                       !Style.BinPackArguments ||
1478                       (NextNoComment &&
1479                        NextNoComment->isOneOf(TT_DesignatedInitializerPeriod,
1480                                               TT_DesignatedInitializerLSquare));
1481     BreakBeforeParameter = EndsInComma;
1482     if (Current.ParameterCount > 1)
1483       NestedBlockIndent = std::max(NestedBlockIndent, State.Column + 1);
1484   } else {
1485     NewIndent = Style.ContinuationIndentWidth +
1486                 std::max(State.Stack.back().LastSpace,
1487                          State.Stack.back().StartOfFunctionCall);
1488 
1489     // Ensure that different different brackets force relative alignment, e.g.:
1490     // void SomeFunction(vector<  // break
1491     //                       int> v);
1492     // FIXME: We likely want to do this for more combinations of brackets.
1493     if (Current.is(tok::less) && Current.ParentBracket == tok::l_paren) {
1494       NewIndent = std::max(NewIndent, State.Stack.back().Indent);
1495       LastSpace = std::max(LastSpace, State.Stack.back().Indent);
1496     }
1497 
1498     bool EndsInComma =
1499         Current.MatchingParen &&
1500         Current.MatchingParen->getPreviousNonComment() &&
1501         Current.MatchingParen->getPreviousNonComment()->is(tok::comma);
1502 
1503     // If ObjCBinPackProtocolList is unspecified, fall back to BinPackParameters
1504     // for backwards compatibility.
1505     bool ObjCBinPackProtocolList =
1506         (Style.ObjCBinPackProtocolList == FormatStyle::BPS_Auto &&
1507          Style.BinPackParameters) ||
1508         Style.ObjCBinPackProtocolList == FormatStyle::BPS_Always;
1509 
1510     bool BinPackDeclaration =
1511         (State.Line->Type != LT_ObjCDecl && Style.BinPackParameters) ||
1512         (State.Line->Type == LT_ObjCDecl && ObjCBinPackProtocolList);
1513 
1514     AvoidBinPacking =
1515         (State.Stack.back().IsCSharpGenericTypeConstraint) ||
1516         (Style.Language == FormatStyle::LK_JavaScript && EndsInComma) ||
1517         (State.Line->MustBeDeclaration && !BinPackDeclaration) ||
1518         (!State.Line->MustBeDeclaration && !Style.BinPackArguments) ||
1519         (Style.ExperimentalAutoDetectBinPacking &&
1520          (Current.is(PPK_OnePerLine) ||
1521           (!BinPackInconclusiveFunctions && Current.is(PPK_Inconclusive))));
1522 
1523     if (Current.is(TT_ObjCMethodExpr) && Current.MatchingParen &&
1524         Style.ObjCBreakBeforeNestedBlockParam) {
1525       if (Style.ColumnLimit) {
1526         // If this '[' opens an ObjC call, determine whether all parameters fit
1527         // into one line and put one per line if they don't.
1528         if (getLengthToMatchingParen(Current, State.Stack) + State.Column >
1529             getColumnLimit(State))
1530           BreakBeforeParameter = true;
1531       } else {
1532         // For ColumnLimit = 0, we have to figure out whether there is or has to
1533         // be a line break within this call.
1534         for (const FormatToken *Tok = &Current;
1535              Tok && Tok != Current.MatchingParen; Tok = Tok->Next) {
1536           if (Tok->MustBreakBefore ||
1537               (Tok->CanBreakBefore && Tok->NewlinesBefore > 0)) {
1538             BreakBeforeParameter = true;
1539             break;
1540           }
1541         }
1542       }
1543     }
1544 
1545     if (Style.Language == FormatStyle::LK_JavaScript && EndsInComma)
1546       BreakBeforeParameter = true;
1547   }
1548   // Generally inherit NoLineBreak from the current scope to nested scope.
1549   // However, don't do this for non-empty nested blocks, dict literals and
1550   // array literals as these follow different indentation rules.
1551   bool NoLineBreak =
1552       Current.Children.empty() &&
1553       !Current.isOneOf(TT_DictLiteral, TT_ArrayInitializerLSquare) &&
1554       (State.Stack.back().NoLineBreak ||
1555        State.Stack.back().NoLineBreakInOperand ||
1556        (Current.is(TT_TemplateOpener) &&
1557         State.Stack.back().ContainsUnwrappedBuilder));
1558   State.Stack.push_back(
1559       ParenState(&Current, NewIndent, LastSpace, AvoidBinPacking, NoLineBreak));
1560   State.Stack.back().NestedBlockIndent = NestedBlockIndent;
1561   State.Stack.back().BreakBeforeParameter = BreakBeforeParameter;
1562   State.Stack.back().HasMultipleNestedBlocks =
1563       (Current.BlockParameterCount > 1);
1564 
1565   if (Style.BraceWrapping.BeforeLambdaBody && Current.Next != nullptr &&
1566       Current.Tok.is(tok::l_paren)) {
1567     // Search for any parameter that is a lambda
1568     FormatToken const *next = Current.Next;
1569     while (next != nullptr) {
1570       if (next->is(TT_LambdaLSquare)) {
1571         State.Stack.back().HasMultipleNestedBlocks = true;
1572         break;
1573       }
1574       next = next->Next;
1575     }
1576   }
1577 
1578   State.Stack.back().IsInsideObjCArrayLiteral =
1579       Current.is(TT_ArrayInitializerLSquare) && Current.Previous &&
1580       Current.Previous->is(tok::at);
1581 }
1582 
1583 void ContinuationIndenter::moveStatePastScopeCloser(LineState &State) {
1584   const FormatToken &Current = *State.NextToken;
1585   if (!Current.closesScope())
1586     return;
1587 
1588   // If we encounter a closing ), ], } or >, we can remove a level from our
1589   // stacks.
1590   if (State.Stack.size() > 1 &&
1591       (Current.isOneOf(tok::r_paren, tok::r_square, TT_TemplateString) ||
1592        (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
1593        State.NextToken->is(TT_TemplateCloser) ||
1594        (Current.is(tok::greater) && Current.is(TT_DictLiteral))))
1595     State.Stack.pop_back();
1596 
1597   // Reevaluate whether ObjC message arguments fit into one line.
1598   // If a receiver spans multiple lines, e.g.:
1599   //   [[object block:^{
1600   //     return 42;
1601   //   }] a:42 b:42];
1602   // BreakBeforeParameter is calculated based on an incorrect assumption
1603   // (it is checked whether the whole expression fits into one line without
1604   // considering a line break inside a message receiver).
1605   // We check whether arguements fit after receiver scope closer (into the same
1606   // line).
1607   if (State.Stack.back().BreakBeforeParameter && Current.MatchingParen &&
1608       Current.MatchingParen->Previous) {
1609     const FormatToken &CurrentScopeOpener = *Current.MatchingParen->Previous;
1610     if (CurrentScopeOpener.is(TT_ObjCMethodExpr) &&
1611         CurrentScopeOpener.MatchingParen) {
1612       int NecessarySpaceInLine =
1613           getLengthToMatchingParen(CurrentScopeOpener, State.Stack) +
1614           CurrentScopeOpener.TotalLength - Current.TotalLength - 1;
1615       if (State.Column + Current.ColumnWidth + NecessarySpaceInLine <=
1616           Style.ColumnLimit)
1617         State.Stack.back().BreakBeforeParameter = false;
1618     }
1619   }
1620 
1621   if (Current.is(tok::r_square)) {
1622     // If this ends the array subscript expr, reset the corresponding value.
1623     const FormatToken *NextNonComment = Current.getNextNonComment();
1624     if (NextNonComment && NextNonComment->isNot(tok::l_square))
1625       State.Stack.back().StartOfArraySubscripts = 0;
1626   }
1627 }
1628 
1629 void ContinuationIndenter::moveStateToNewBlock(LineState &State) {
1630   unsigned NestedBlockIndent = State.Stack.back().NestedBlockIndent;
1631   // ObjC block sometimes follow special indentation rules.
1632   unsigned NewIndent =
1633       NestedBlockIndent + (State.NextToken->is(TT_ObjCBlockLBrace)
1634                                ? Style.ObjCBlockIndentWidth
1635                                : Style.IndentWidth);
1636   State.Stack.push_back(ParenState(State.NextToken, NewIndent,
1637                                    State.Stack.back().LastSpace,
1638                                    /*AvoidBinPacking=*/true,
1639                                    /*NoLineBreak=*/false));
1640   State.Stack.back().NestedBlockIndent = NestedBlockIndent;
1641   State.Stack.back().BreakBeforeParameter = true;
1642 }
1643 
1644 static unsigned getLastLineEndColumn(StringRef Text, unsigned StartColumn,
1645                                      unsigned TabWidth,
1646                                      encoding::Encoding Encoding) {
1647   size_t LastNewlinePos = Text.find_last_of("\n");
1648   if (LastNewlinePos == StringRef::npos) {
1649     return StartColumn +
1650            encoding::columnWidthWithTabs(Text, StartColumn, TabWidth, Encoding);
1651   } else {
1652     return encoding::columnWidthWithTabs(Text.substr(LastNewlinePos),
1653                                          /*StartColumn=*/0, TabWidth, Encoding);
1654   }
1655 }
1656 
1657 unsigned ContinuationIndenter::reformatRawStringLiteral(
1658     const FormatToken &Current, LineState &State,
1659     const FormatStyle &RawStringStyle, bool DryRun, bool Newline) {
1660   unsigned StartColumn = State.Column - Current.ColumnWidth;
1661   StringRef OldDelimiter = *getRawStringDelimiter(Current.TokenText);
1662   StringRef NewDelimiter =
1663       getCanonicalRawStringDelimiter(Style, RawStringStyle.Language);
1664   if (NewDelimiter.empty())
1665     NewDelimiter = OldDelimiter;
1666   // The text of a raw string is between the leading 'R"delimiter(' and the
1667   // trailing 'delimiter)"'.
1668   unsigned OldPrefixSize = 3 + OldDelimiter.size();
1669   unsigned OldSuffixSize = 2 + OldDelimiter.size();
1670   // We create a virtual text environment which expects a null-terminated
1671   // string, so we cannot use StringRef.
1672   std::string RawText = std::string(
1673       Current.TokenText.substr(OldPrefixSize).drop_back(OldSuffixSize));
1674   if (NewDelimiter != OldDelimiter) {
1675     // Don't update to the canonical delimiter 'deli' if ')deli"' occurs in the
1676     // raw string.
1677     std::string CanonicalDelimiterSuffix = (")" + NewDelimiter + "\"").str();
1678     if (StringRef(RawText).contains(CanonicalDelimiterSuffix))
1679       NewDelimiter = OldDelimiter;
1680   }
1681 
1682   unsigned NewPrefixSize = 3 + NewDelimiter.size();
1683   unsigned NewSuffixSize = 2 + NewDelimiter.size();
1684 
1685   // The first start column is the column the raw text starts after formatting.
1686   unsigned FirstStartColumn = StartColumn + NewPrefixSize;
1687 
1688   // The next start column is the intended indentation a line break inside
1689   // the raw string at level 0. It is determined by the following rules:
1690   //   - if the content starts on newline, it is one level more than the current
1691   //     indent, and
1692   //   - if the content does not start on a newline, it is the first start
1693   //     column.
1694   // These rules have the advantage that the formatted content both does not
1695   // violate the rectangle rule and visually flows within the surrounding
1696   // source.
1697   bool ContentStartsOnNewline = Current.TokenText[OldPrefixSize] == '\n';
1698   // If this token is the last parameter (checked by looking if it's followed by
1699   // `)` and is not on a newline, the base the indent off the line's nested
1700   // block indent. Otherwise, base the indent off the arguments indent, so we
1701   // can achieve:
1702   //
1703   // fffffffffff(1, 2, 3, R"pb(
1704   //     key1: 1  #
1705   //     key2: 2)pb");
1706   //
1707   // fffffffffff(1, 2, 3,
1708   //             R"pb(
1709   //               key1: 1  #
1710   //               key2: 2
1711   //             )pb");
1712   //
1713   // fffffffffff(1, 2, 3,
1714   //             R"pb(
1715   //               key1: 1  #
1716   //               key2: 2
1717   //             )pb",
1718   //             5);
1719   unsigned CurrentIndent =
1720       (!Newline && Current.Next && Current.Next->is(tok::r_paren))
1721           ? State.Stack.back().NestedBlockIndent
1722           : State.Stack.back().Indent;
1723   unsigned NextStartColumn = ContentStartsOnNewline
1724                                  ? CurrentIndent + Style.IndentWidth
1725                                  : FirstStartColumn;
1726 
1727   // The last start column is the column the raw string suffix starts if it is
1728   // put on a newline.
1729   // The last start column is the intended indentation of the raw string postfix
1730   // if it is put on a newline. It is determined by the following rules:
1731   //   - if the raw string prefix starts on a newline, it is the column where
1732   //     that raw string prefix starts, and
1733   //   - if the raw string prefix does not start on a newline, it is the current
1734   //     indent.
1735   unsigned LastStartColumn =
1736       Current.NewlinesBefore ? FirstStartColumn - NewPrefixSize : CurrentIndent;
1737 
1738   std::pair<tooling::Replacements, unsigned> Fixes = internal::reformat(
1739       RawStringStyle, RawText, {tooling::Range(0, RawText.size())},
1740       FirstStartColumn, NextStartColumn, LastStartColumn, "<stdin>",
1741       /*Status=*/nullptr);
1742 
1743   auto NewCode = applyAllReplacements(RawText, Fixes.first);
1744   tooling::Replacements NoFixes;
1745   if (!NewCode) {
1746     return addMultilineToken(Current, State);
1747   }
1748   if (!DryRun) {
1749     if (NewDelimiter != OldDelimiter) {
1750       // In 'R"delimiter(...', the delimiter starts 2 characters after the start
1751       // of the token.
1752       SourceLocation PrefixDelimiterStart =
1753           Current.Tok.getLocation().getLocWithOffset(2);
1754       auto PrefixErr = Whitespaces.addReplacement(tooling::Replacement(
1755           SourceMgr, PrefixDelimiterStart, OldDelimiter.size(), NewDelimiter));
1756       if (PrefixErr) {
1757         llvm::errs()
1758             << "Failed to update the prefix delimiter of a raw string: "
1759             << llvm::toString(std::move(PrefixErr)) << "\n";
1760       }
1761       // In 'R"delimiter(...)delimiter"', the suffix delimiter starts at
1762       // position length - 1 - |delimiter|.
1763       SourceLocation SuffixDelimiterStart =
1764           Current.Tok.getLocation().getLocWithOffset(Current.TokenText.size() -
1765                                                      1 - OldDelimiter.size());
1766       auto SuffixErr = Whitespaces.addReplacement(tooling::Replacement(
1767           SourceMgr, SuffixDelimiterStart, OldDelimiter.size(), NewDelimiter));
1768       if (SuffixErr) {
1769         llvm::errs()
1770             << "Failed to update the suffix delimiter of a raw string: "
1771             << llvm::toString(std::move(SuffixErr)) << "\n";
1772       }
1773     }
1774     SourceLocation OriginLoc =
1775         Current.Tok.getLocation().getLocWithOffset(OldPrefixSize);
1776     for (const tooling::Replacement &Fix : Fixes.first) {
1777       auto Err = Whitespaces.addReplacement(tooling::Replacement(
1778           SourceMgr, OriginLoc.getLocWithOffset(Fix.getOffset()),
1779           Fix.getLength(), Fix.getReplacementText()));
1780       if (Err) {
1781         llvm::errs() << "Failed to reformat raw string: "
1782                      << llvm::toString(std::move(Err)) << "\n";
1783       }
1784     }
1785   }
1786   unsigned RawLastLineEndColumn = getLastLineEndColumn(
1787       *NewCode, FirstStartColumn, Style.TabWidth, Encoding);
1788   State.Column = RawLastLineEndColumn + NewSuffixSize;
1789   // Since we're updating the column to after the raw string literal here, we
1790   // have to manually add the penalty for the prefix R"delim( over the column
1791   // limit.
1792   unsigned PrefixExcessCharacters =
1793       StartColumn + NewPrefixSize > Style.ColumnLimit
1794           ? StartColumn + NewPrefixSize - Style.ColumnLimit
1795           : 0;
1796   bool IsMultiline =
1797       ContentStartsOnNewline || (NewCode->find('\n') != std::string::npos);
1798   if (IsMultiline) {
1799     // Break before further function parameters on all levels.
1800     for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
1801       State.Stack[i].BreakBeforeParameter = true;
1802   }
1803   return Fixes.second + PrefixExcessCharacters * Style.PenaltyExcessCharacter;
1804 }
1805 
1806 unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
1807                                                  LineState &State) {
1808   // Break before further function parameters on all levels.
1809   for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
1810     State.Stack[i].BreakBeforeParameter = true;
1811 
1812   unsigned ColumnsUsed = State.Column;
1813   // We can only affect layout of the first and the last line, so the penalty
1814   // for all other lines is constant, and we ignore it.
1815   State.Column = Current.LastLineColumnWidth;
1816 
1817   if (ColumnsUsed > getColumnLimit(State))
1818     return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
1819   return 0;
1820 }
1821 
1822 unsigned ContinuationIndenter::handleEndOfLine(const FormatToken &Current,
1823                                                LineState &State, bool DryRun,
1824                                                bool AllowBreak, bool Newline) {
1825   unsigned Penalty = 0;
1826   // Compute the raw string style to use in case this is a raw string literal
1827   // that can be reformatted.
1828   auto RawStringStyle = getRawStringStyle(Current, State);
1829   if (RawStringStyle && !Current.Finalized) {
1830     Penalty = reformatRawStringLiteral(Current, State, *RawStringStyle, DryRun,
1831                                        Newline);
1832   } else if (Current.IsMultiline && Current.isNot(TT_BlockComment)) {
1833     // Don't break multi-line tokens other than block comments and raw string
1834     // literals. Instead, just update the state.
1835     Penalty = addMultilineToken(Current, State);
1836   } else if (State.Line->Type != LT_ImportStatement) {
1837     // We generally don't break import statements.
1838     LineState OriginalState = State;
1839 
1840     // Whether we force the reflowing algorithm to stay strictly within the
1841     // column limit.
1842     bool Strict = false;
1843     // Whether the first non-strict attempt at reflowing did intentionally
1844     // exceed the column limit.
1845     bool Exceeded = false;
1846     std::tie(Penalty, Exceeded) = breakProtrudingToken(
1847         Current, State, AllowBreak, /*DryRun=*/true, Strict);
1848     if (Exceeded) {
1849       // If non-strict reflowing exceeds the column limit, try whether strict
1850       // reflowing leads to an overall lower penalty.
1851       LineState StrictState = OriginalState;
1852       unsigned StrictPenalty =
1853           breakProtrudingToken(Current, StrictState, AllowBreak,
1854                                /*DryRun=*/true, /*Strict=*/true)
1855               .first;
1856       Strict = StrictPenalty <= Penalty;
1857       if (Strict) {
1858         Penalty = StrictPenalty;
1859         State = StrictState;
1860       }
1861     }
1862     if (!DryRun) {
1863       // If we're not in dry-run mode, apply the changes with the decision on
1864       // strictness made above.
1865       breakProtrudingToken(Current, OriginalState, AllowBreak, /*DryRun=*/false,
1866                            Strict);
1867     }
1868   }
1869   if (State.Column > getColumnLimit(State)) {
1870     unsigned ExcessCharacters = State.Column - getColumnLimit(State);
1871     Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
1872   }
1873   return Penalty;
1874 }
1875 
1876 // Returns the enclosing function name of a token, or the empty string if not
1877 // found.
1878 static StringRef getEnclosingFunctionName(const FormatToken &Current) {
1879   // Look for: 'function(' or 'function<templates>(' before Current.
1880   auto Tok = Current.getPreviousNonComment();
1881   if (!Tok || !Tok->is(tok::l_paren))
1882     return "";
1883   Tok = Tok->getPreviousNonComment();
1884   if (!Tok)
1885     return "";
1886   if (Tok->is(TT_TemplateCloser)) {
1887     Tok = Tok->MatchingParen;
1888     if (Tok)
1889       Tok = Tok->getPreviousNonComment();
1890   }
1891   if (!Tok || !Tok->is(tok::identifier))
1892     return "";
1893   return Tok->TokenText;
1894 }
1895 
1896 llvm::Optional<FormatStyle>
1897 ContinuationIndenter::getRawStringStyle(const FormatToken &Current,
1898                                         const LineState &State) {
1899   if (!Current.isStringLiteral())
1900     return None;
1901   auto Delimiter = getRawStringDelimiter(Current.TokenText);
1902   if (!Delimiter)
1903     return None;
1904   auto RawStringStyle = RawStringFormats.getDelimiterStyle(*Delimiter);
1905   if (!RawStringStyle && Delimiter->empty())
1906     RawStringStyle = RawStringFormats.getEnclosingFunctionStyle(
1907         getEnclosingFunctionName(Current));
1908   if (!RawStringStyle)
1909     return None;
1910   RawStringStyle->ColumnLimit = getColumnLimit(State);
1911   return RawStringStyle;
1912 }
1913 
1914 std::unique_ptr<BreakableToken>
1915 ContinuationIndenter::createBreakableToken(const FormatToken &Current,
1916                                            LineState &State, bool AllowBreak) {
1917   unsigned StartColumn = State.Column - Current.ColumnWidth;
1918   if (Current.isStringLiteral()) {
1919     // FIXME: String literal breaking is currently disabled for C#, Java, Json
1920     // and JavaScript, as it requires strings to be merged using "+" which we
1921     // don't support.
1922     if (Style.Language == FormatStyle::LK_Java ||
1923         Style.Language == FormatStyle::LK_JavaScript || Style.isCSharp() ||
1924         Style.isJson() || !Style.BreakStringLiterals || !AllowBreak)
1925       return nullptr;
1926 
1927     // Don't break string literals inside preprocessor directives (except for
1928     // #define directives, as their contents are stored in separate lines and
1929     // are not affected by this check).
1930     // This way we avoid breaking code with line directives and unknown
1931     // preprocessor directives that contain long string literals.
1932     if (State.Line->Type == LT_PreprocessorDirective)
1933       return nullptr;
1934     // Exempts unterminated string literals from line breaking. The user will
1935     // likely want to terminate the string before any line breaking is done.
1936     if (Current.IsUnterminatedLiteral)
1937       return nullptr;
1938     // Don't break string literals inside Objective-C array literals (doing so
1939     // raises the warning -Wobjc-string-concatenation).
1940     if (State.Stack.back().IsInsideObjCArrayLiteral) {
1941       return nullptr;
1942     }
1943 
1944     StringRef Text = Current.TokenText;
1945     StringRef Prefix;
1946     StringRef Postfix;
1947     // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
1948     // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
1949     // reduce the overhead) for each FormatToken, which is a string, so that we
1950     // don't run multiple checks here on the hot path.
1951     if ((Text.endswith(Postfix = "\"") &&
1952          (Text.startswith(Prefix = "@\"") || Text.startswith(Prefix = "\"") ||
1953           Text.startswith(Prefix = "u\"") || Text.startswith(Prefix = "U\"") ||
1954           Text.startswith(Prefix = "u8\"") ||
1955           Text.startswith(Prefix = "L\""))) ||
1956         (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")"))) {
1957       // We need this to address the case where there is an unbreakable tail
1958       // only if certain other formatting decisions have been taken. The
1959       // UnbreakableTailLength of Current is an overapproximation is that case
1960       // and we need to be correct here.
1961       unsigned UnbreakableTailLength = (State.NextToken && canBreak(State))
1962                                            ? 0
1963                                            : Current.UnbreakableTailLength;
1964       return std::make_unique<BreakableStringLiteral>(
1965           Current, StartColumn, Prefix, Postfix, UnbreakableTailLength,
1966           State.Line->InPPDirective, Encoding, Style);
1967     }
1968   } else if (Current.is(TT_BlockComment)) {
1969     if (!Style.ReflowComments ||
1970         // If a comment token switches formatting, like
1971         // /* clang-format on */, we don't want to break it further,
1972         // but we may still want to adjust its indentation.
1973         switchesFormatting(Current)) {
1974       return nullptr;
1975     }
1976     return std::make_unique<BreakableBlockComment>(
1977         Current, StartColumn, Current.OriginalColumn, !Current.Previous,
1978         State.Line->InPPDirective, Encoding, Style, Whitespaces.useCRLF());
1979   } else if (Current.is(TT_LineComment) &&
1980              (Current.Previous == nullptr ||
1981               Current.Previous->isNot(TT_ImplicitStringLiteral))) {
1982     if (!Style.ReflowComments ||
1983         CommentPragmasRegex.match(Current.TokenText.substr(2)) ||
1984         switchesFormatting(Current))
1985       return nullptr;
1986     return std::make_unique<BreakableLineCommentSection>(
1987         Current, StartColumn, /*InPPDirective=*/false, Encoding, Style);
1988   }
1989   return nullptr;
1990 }
1991 
1992 std::pair<unsigned, bool>
1993 ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
1994                                            LineState &State, bool AllowBreak,
1995                                            bool DryRun, bool Strict) {
1996   std::unique_ptr<const BreakableToken> Token =
1997       createBreakableToken(Current, State, AllowBreak);
1998   if (!Token)
1999     return {0, false};
2000   assert(Token->getLineCount() > 0);
2001   unsigned ColumnLimit = getColumnLimit(State);
2002   if (Current.is(TT_LineComment)) {
2003     // We don't insert backslashes when breaking line comments.
2004     ColumnLimit = Style.ColumnLimit;
2005   }
2006   if (ColumnLimit == 0) {
2007     // To make the rest of the function easier set the column limit to the
2008     // maximum, if there should be no limit.
2009     ColumnLimit = std::numeric_limits<decltype(ColumnLimit)>::max();
2010   }
2011   if (Current.UnbreakableTailLength >= ColumnLimit)
2012     return {0, false};
2013   // ColumnWidth was already accounted into State.Column before calling
2014   // breakProtrudingToken.
2015   unsigned StartColumn = State.Column - Current.ColumnWidth;
2016   unsigned NewBreakPenalty = Current.isStringLiteral()
2017                                  ? Style.PenaltyBreakString
2018                                  : Style.PenaltyBreakComment;
2019   // Stores whether we intentionally decide to let a line exceed the column
2020   // limit.
2021   bool Exceeded = false;
2022   // Stores whether we introduce a break anywhere in the token.
2023   bool BreakInserted = Token->introducesBreakBeforeToken();
2024   // Store whether we inserted a new line break at the end of the previous
2025   // logical line.
2026   bool NewBreakBefore = false;
2027   // We use a conservative reflowing strategy. Reflow starts after a line is
2028   // broken or the corresponding whitespace compressed. Reflow ends as soon as a
2029   // line that doesn't get reflown with the previous line is reached.
2030   bool Reflow = false;
2031   // Keep track of where we are in the token:
2032   // Where we are in the content of the current logical line.
2033   unsigned TailOffset = 0;
2034   // The column number we're currently at.
2035   unsigned ContentStartColumn =
2036       Token->getContentStartColumn(0, /*Break=*/false);
2037   // The number of columns left in the current logical line after TailOffset.
2038   unsigned RemainingTokenColumns =
2039       Token->getRemainingLength(0, TailOffset, ContentStartColumn);
2040   // Adapt the start of the token, for example indent.
2041   if (!DryRun)
2042     Token->adaptStartOfLine(0, Whitespaces);
2043 
2044   unsigned ContentIndent = 0;
2045   unsigned Penalty = 0;
2046   LLVM_DEBUG(llvm::dbgs() << "Breaking protruding token at column "
2047                           << StartColumn << ".\n");
2048   for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
2049        LineIndex != EndIndex; ++LineIndex) {
2050     LLVM_DEBUG(llvm::dbgs()
2051                << "  Line: " << LineIndex << " (Reflow: " << Reflow << ")\n");
2052     NewBreakBefore = false;
2053     // If we did reflow the previous line, we'll try reflowing again. Otherwise
2054     // we'll start reflowing if the current line is broken or whitespace is
2055     // compressed.
2056     bool TryReflow = Reflow;
2057     // Break the current token until we can fit the rest of the line.
2058     while (ContentStartColumn + RemainingTokenColumns > ColumnLimit) {
2059       LLVM_DEBUG(llvm::dbgs() << "    Over limit, need: "
2060                               << (ContentStartColumn + RemainingTokenColumns)
2061                               << ", space: " << ColumnLimit
2062                               << ", reflown prefix: " << ContentStartColumn
2063                               << ", offset in line: " << TailOffset << "\n");
2064       // If the current token doesn't fit, find the latest possible split in the
2065       // current line so that breaking at it will be under the column limit.
2066       // FIXME: Use the earliest possible split while reflowing to correctly
2067       // compress whitespace within a line.
2068       BreakableToken::Split Split =
2069           Token->getSplit(LineIndex, TailOffset, ColumnLimit,
2070                           ContentStartColumn, CommentPragmasRegex);
2071       if (Split.first == StringRef::npos) {
2072         // No break opportunity - update the penalty and continue with the next
2073         // logical line.
2074         if (LineIndex < EndIndex - 1)
2075           // The last line's penalty is handled in addNextStateToQueue() or when
2076           // calling replaceWhitespaceAfterLastLine below.
2077           Penalty += Style.PenaltyExcessCharacter *
2078                      (ContentStartColumn + RemainingTokenColumns - ColumnLimit);
2079         LLVM_DEBUG(llvm::dbgs() << "    No break opportunity.\n");
2080         break;
2081       }
2082       assert(Split.first != 0);
2083 
2084       if (Token->supportsReflow()) {
2085         // Check whether the next natural split point after the current one can
2086         // still fit the line, either because we can compress away whitespace,
2087         // or because the penalty the excess characters introduce is lower than
2088         // the break penalty.
2089         // We only do this for tokens that support reflowing, and thus allow us
2090         // to change the whitespace arbitrarily (e.g. comments).
2091         // Other tokens, like string literals, can be broken on arbitrary
2092         // positions.
2093 
2094         // First, compute the columns from TailOffset to the next possible split
2095         // position.
2096         // For example:
2097         // ColumnLimit:     |
2098         // // Some text   that    breaks
2099         //    ^ tail offset
2100         //             ^-- split
2101         //    ^-------- to split columns
2102         //                    ^--- next split
2103         //    ^--------------- to next split columns
2104         unsigned ToSplitColumns = Token->getRangeLength(
2105             LineIndex, TailOffset, Split.first, ContentStartColumn);
2106         LLVM_DEBUG(llvm::dbgs() << "    ToSplit: " << ToSplitColumns << "\n");
2107 
2108         BreakableToken::Split NextSplit = Token->getSplit(
2109             LineIndex, TailOffset + Split.first + Split.second, ColumnLimit,
2110             ContentStartColumn + ToSplitColumns + 1, CommentPragmasRegex);
2111         // Compute the columns necessary to fit the next non-breakable sequence
2112         // into the current line.
2113         unsigned ToNextSplitColumns = 0;
2114         if (NextSplit.first == StringRef::npos) {
2115           ToNextSplitColumns = Token->getRemainingLength(LineIndex, TailOffset,
2116                                                          ContentStartColumn);
2117         } else {
2118           ToNextSplitColumns = Token->getRangeLength(
2119               LineIndex, TailOffset,
2120               Split.first + Split.second + NextSplit.first, ContentStartColumn);
2121         }
2122         // Compress the whitespace between the break and the start of the next
2123         // unbreakable sequence.
2124         ToNextSplitColumns =
2125             Token->getLengthAfterCompression(ToNextSplitColumns, Split);
2126         LLVM_DEBUG(llvm::dbgs()
2127                    << "    ContentStartColumn: " << ContentStartColumn << "\n");
2128         LLVM_DEBUG(llvm::dbgs()
2129                    << "    ToNextSplit: " << ToNextSplitColumns << "\n");
2130         // If the whitespace compression makes us fit, continue on the current
2131         // line.
2132         bool ContinueOnLine =
2133             ContentStartColumn + ToNextSplitColumns <= ColumnLimit;
2134         unsigned ExcessCharactersPenalty = 0;
2135         if (!ContinueOnLine && !Strict) {
2136           // Similarly, if the excess characters' penalty is lower than the
2137           // penalty of introducing a new break, continue on the current line.
2138           ExcessCharactersPenalty =
2139               (ContentStartColumn + ToNextSplitColumns - ColumnLimit) *
2140               Style.PenaltyExcessCharacter;
2141           LLVM_DEBUG(llvm::dbgs()
2142                      << "    Penalty excess: " << ExcessCharactersPenalty
2143                      << "\n            break : " << NewBreakPenalty << "\n");
2144           if (ExcessCharactersPenalty < NewBreakPenalty) {
2145             Exceeded = true;
2146             ContinueOnLine = true;
2147           }
2148         }
2149         if (ContinueOnLine) {
2150           LLVM_DEBUG(llvm::dbgs() << "    Continuing on line...\n");
2151           // The current line fits after compressing the whitespace - reflow
2152           // the next line into it if possible.
2153           TryReflow = true;
2154           if (!DryRun)
2155             Token->compressWhitespace(LineIndex, TailOffset, Split,
2156                                       Whitespaces);
2157           // When we continue on the same line, leave one space between content.
2158           ContentStartColumn += ToSplitColumns + 1;
2159           Penalty += ExcessCharactersPenalty;
2160           TailOffset += Split.first + Split.second;
2161           RemainingTokenColumns = Token->getRemainingLength(
2162               LineIndex, TailOffset, ContentStartColumn);
2163           continue;
2164         }
2165       }
2166       LLVM_DEBUG(llvm::dbgs() << "    Breaking...\n");
2167       // Update the ContentIndent only if the current line was not reflown with
2168       // the previous line, since in that case the previous line should still
2169       // determine the ContentIndent. Also never intent the last line.
2170       if (!Reflow)
2171         ContentIndent = Token->getContentIndent(LineIndex);
2172       LLVM_DEBUG(llvm::dbgs()
2173                  << "    ContentIndent: " << ContentIndent << "\n");
2174       ContentStartColumn = ContentIndent + Token->getContentStartColumn(
2175                                                LineIndex, /*Break=*/true);
2176 
2177       unsigned NewRemainingTokenColumns = Token->getRemainingLength(
2178           LineIndex, TailOffset + Split.first + Split.second,
2179           ContentStartColumn);
2180       if (NewRemainingTokenColumns == 0) {
2181         // No content to indent.
2182         ContentIndent = 0;
2183         ContentStartColumn =
2184             Token->getContentStartColumn(LineIndex, /*Break=*/true);
2185         NewRemainingTokenColumns = Token->getRemainingLength(
2186             LineIndex, TailOffset + Split.first + Split.second,
2187             ContentStartColumn);
2188       }
2189 
2190       // When breaking before a tab character, it may be moved by a few columns,
2191       // but will still be expanded to the next tab stop, so we don't save any
2192       // columns.
2193       if (NewRemainingTokenColumns == RemainingTokenColumns) {
2194         // FIXME: Do we need to adjust the penalty?
2195         break;
2196       }
2197       assert(NewRemainingTokenColumns < RemainingTokenColumns);
2198 
2199       LLVM_DEBUG(llvm::dbgs() << "    Breaking at: " << TailOffset + Split.first
2200                               << ", " << Split.second << "\n");
2201       if (!DryRun)
2202         Token->insertBreak(LineIndex, TailOffset, Split, ContentIndent,
2203                            Whitespaces);
2204 
2205       Penalty += NewBreakPenalty;
2206       TailOffset += Split.first + Split.second;
2207       RemainingTokenColumns = NewRemainingTokenColumns;
2208       BreakInserted = true;
2209       NewBreakBefore = true;
2210     }
2211     // In case there's another line, prepare the state for the start of the next
2212     // line.
2213     if (LineIndex + 1 != EndIndex) {
2214       unsigned NextLineIndex = LineIndex + 1;
2215       if (NewBreakBefore)
2216         // After breaking a line, try to reflow the next line into the current
2217         // one once RemainingTokenColumns fits.
2218         TryReflow = true;
2219       if (TryReflow) {
2220         // We decided that we want to try reflowing the next line into the
2221         // current one.
2222         // We will now adjust the state as if the reflow is successful (in
2223         // preparation for the next line), and see whether that works. If we
2224         // decide that we cannot reflow, we will later reset the state to the
2225         // start of the next line.
2226         Reflow = false;
2227         // As we did not continue breaking the line, RemainingTokenColumns is
2228         // known to fit after ContentStartColumn. Adapt ContentStartColumn to
2229         // the position at which we want to format the next line if we do
2230         // actually reflow.
2231         // When we reflow, we need to add a space between the end of the current
2232         // line and the next line's start column.
2233         ContentStartColumn += RemainingTokenColumns + 1;
2234         // Get the split that we need to reflow next logical line into the end
2235         // of the current one; the split will include any leading whitespace of
2236         // the next logical line.
2237         BreakableToken::Split SplitBeforeNext =
2238             Token->getReflowSplit(NextLineIndex, CommentPragmasRegex);
2239         LLVM_DEBUG(llvm::dbgs()
2240                    << "    Size of reflown text: " << ContentStartColumn
2241                    << "\n    Potential reflow split: ");
2242         if (SplitBeforeNext.first != StringRef::npos) {
2243           LLVM_DEBUG(llvm::dbgs() << SplitBeforeNext.first << ", "
2244                                   << SplitBeforeNext.second << "\n");
2245           TailOffset = SplitBeforeNext.first + SplitBeforeNext.second;
2246           // If the rest of the next line fits into the current line below the
2247           // column limit, we can safely reflow.
2248           RemainingTokenColumns = Token->getRemainingLength(
2249               NextLineIndex, TailOffset, ContentStartColumn);
2250           Reflow = true;
2251           if (ContentStartColumn + RemainingTokenColumns > ColumnLimit) {
2252             LLVM_DEBUG(llvm::dbgs()
2253                        << "    Over limit after reflow, need: "
2254                        << (ContentStartColumn + RemainingTokenColumns)
2255                        << ", space: " << ColumnLimit
2256                        << ", reflown prefix: " << ContentStartColumn
2257                        << ", offset in line: " << TailOffset << "\n");
2258             // If the whole next line does not fit, try to find a point in
2259             // the next line at which we can break so that attaching the part
2260             // of the next line to that break point onto the current line is
2261             // below the column limit.
2262             BreakableToken::Split Split =
2263                 Token->getSplit(NextLineIndex, TailOffset, ColumnLimit,
2264                                 ContentStartColumn, CommentPragmasRegex);
2265             if (Split.first == StringRef::npos) {
2266               LLVM_DEBUG(llvm::dbgs() << "    Did not find later break\n");
2267               Reflow = false;
2268             } else {
2269               // Check whether the first split point gets us below the column
2270               // limit. Note that we will execute this split below as part of
2271               // the normal token breaking and reflow logic within the line.
2272               unsigned ToSplitColumns = Token->getRangeLength(
2273                   NextLineIndex, TailOffset, Split.first, ContentStartColumn);
2274               if (ContentStartColumn + ToSplitColumns > ColumnLimit) {
2275                 LLVM_DEBUG(llvm::dbgs() << "    Next split protrudes, need: "
2276                                         << (ContentStartColumn + ToSplitColumns)
2277                                         << ", space: " << ColumnLimit);
2278                 unsigned ExcessCharactersPenalty =
2279                     (ContentStartColumn + ToSplitColumns - ColumnLimit) *
2280                     Style.PenaltyExcessCharacter;
2281                 if (NewBreakPenalty < ExcessCharactersPenalty) {
2282                   Reflow = false;
2283                 }
2284               }
2285             }
2286           }
2287         } else {
2288           LLVM_DEBUG(llvm::dbgs() << "not found.\n");
2289         }
2290       }
2291       if (!Reflow) {
2292         // If we didn't reflow into the next line, the only space to consider is
2293         // the next logical line. Reset our state to match the start of the next
2294         // line.
2295         TailOffset = 0;
2296         ContentStartColumn =
2297             Token->getContentStartColumn(NextLineIndex, /*Break=*/false);
2298         RemainingTokenColumns = Token->getRemainingLength(
2299             NextLineIndex, TailOffset, ContentStartColumn);
2300         // Adapt the start of the token, for example indent.
2301         if (!DryRun)
2302           Token->adaptStartOfLine(NextLineIndex, Whitespaces);
2303       } else {
2304         // If we found a reflow split and have added a new break before the next
2305         // line, we are going to remove the line break at the start of the next
2306         // logical line. For example, here we'll add a new line break after
2307         // 'text', and subsequently delete the line break between 'that' and
2308         // 'reflows'.
2309         //   // some text that
2310         //   // reflows
2311         // ->
2312         //   // some text
2313         //   // that reflows
2314         // When adding the line break, we also added the penalty for it, so we
2315         // need to subtract that penalty again when we remove the line break due
2316         // to reflowing.
2317         if (NewBreakBefore) {
2318           assert(Penalty >= NewBreakPenalty);
2319           Penalty -= NewBreakPenalty;
2320         }
2321         if (!DryRun)
2322           Token->reflow(NextLineIndex, Whitespaces);
2323       }
2324     }
2325   }
2326 
2327   BreakableToken::Split SplitAfterLastLine =
2328       Token->getSplitAfterLastLine(TailOffset);
2329   if (SplitAfterLastLine.first != StringRef::npos) {
2330     LLVM_DEBUG(llvm::dbgs() << "Replacing whitespace after last line.\n");
2331 
2332     // We add the last line's penalty here, since that line is going to be split
2333     // now.
2334     Penalty += Style.PenaltyExcessCharacter *
2335                (ContentStartColumn + RemainingTokenColumns - ColumnLimit);
2336 
2337     if (!DryRun)
2338       Token->replaceWhitespaceAfterLastLine(TailOffset, SplitAfterLastLine,
2339                                             Whitespaces);
2340     ContentStartColumn =
2341         Token->getContentStartColumn(Token->getLineCount() - 1, /*Break=*/true);
2342     RemainingTokenColumns = Token->getRemainingLength(
2343         Token->getLineCount() - 1,
2344         TailOffset + SplitAfterLastLine.first + SplitAfterLastLine.second,
2345         ContentStartColumn);
2346   }
2347 
2348   State.Column = ContentStartColumn + RemainingTokenColumns -
2349                  Current.UnbreakableTailLength;
2350 
2351   if (BreakInserted) {
2352     // If we break the token inside a parameter list, we need to break before
2353     // the next parameter on all levels, so that the next parameter is clearly
2354     // visible. Line comments already introduce a break.
2355     if (Current.isNot(TT_LineComment)) {
2356       for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
2357         State.Stack[i].BreakBeforeParameter = true;
2358     }
2359 
2360     if (Current.is(TT_BlockComment))
2361       State.NoContinuation = true;
2362 
2363     State.Stack.back().LastSpace = StartColumn;
2364   }
2365 
2366   Token->updateNextToken(State);
2367 
2368   return {Penalty, Exceeded};
2369 }
2370 
2371 unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
2372   // In preprocessor directives reserve two chars for trailing " \"
2373   return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
2374 }
2375 
2376 bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
2377   const FormatToken &Current = *State.NextToken;
2378   if (!Current.isStringLiteral() || Current.is(TT_ImplicitStringLiteral))
2379     return false;
2380   // We never consider raw string literals "multiline" for the purpose of
2381   // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
2382   // (see TokenAnnotator::mustBreakBefore().
2383   if (Current.TokenText.startswith("R\""))
2384     return false;
2385   if (Current.IsMultiline)
2386     return true;
2387   if (Current.getNextNonComment() &&
2388       Current.getNextNonComment()->isStringLiteral())
2389     return true; // Implicit concatenation.
2390   if (Style.ColumnLimit != 0 && Style.BreakStringLiterals &&
2391       State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
2392           Style.ColumnLimit)
2393     return true; // String will be split.
2394   return false;
2395 }
2396 
2397 } // namespace format
2398 } // namespace clang
2399