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