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