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