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