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