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