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.is(Kind: tok::comma) &&
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.is(TT: TT_BinaryOperator) &&
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 !CurrentState.AvoidBinPacking) ||
1278 Previous.is(TT: TT_BinaryOperator)) {
1279 CurrentState.BreakBeforeParameter = false;
1280 }
1281 if (PreviousNonComment &&
1282 (PreviousNonComment->isOneOf(K1: TT_TemplateCloser, K2: TT_JavaAnnotation) ||
1283 PreviousNonComment->ClosesRequiresClause) &&
1284 Current.NestingLevel == 0) {
1285 CurrentState.BreakBeforeParameter = false;
1286 }
1287 if (NextNonComment->is(Kind: tok::question) ||
1288 (PreviousNonComment && PreviousNonComment->is(Kind: tok::question))) {
1289 CurrentState.BreakBeforeParameter = true;
1290 }
1291 if (Current.is(TT: TT_BinaryOperator) && Current.CanBreakBefore) {
1292 CurrentState.BreakBeforeParameter = false;
1293 CurrentState.AlignedTo = &Current;
1294 }
1295 if (Style.AlignOperands != FormatStyle::OAS_DontAlign &&
1296 Current.is(TT: TT_ConditionalExpr)) {
1297 switch (Style.AlignOperands) {
1298 case FormatStyle::OAS_Align:
1299 CurrentState.AlignedTo = Current.is(Kind: tok::question)
1300 ? Current.getPrevious(A1: tok::equal)
1301 : Current.getPrevious(A1: tok::question);
1302 break;
1303 case FormatStyle::OAS_AlignAfterOperator:
1304 if (Current.is(Kind: tok::colon))
1305 CurrentState.AlignedTo = Current.getPrevious(A1: tok::question);
1306 break;
1307 case FormatStyle::OAS_DontAlign:
1308 break;
1309 }
1310 }
1311
1312 if (!DryRun) {
1313 unsigned MaxEmptyLinesToKeep = Style.MaxEmptyLinesToKeep + 1;
1314 if (Current.is(Kind: tok::r_brace) && Current.MatchingParen &&
1315 // Only strip trailing empty lines for l_braces that have children, i.e.
1316 // for function expressions (lambdas, arrows, etc).
1317 !Current.MatchingParen->Children.empty()) {
1318 // lambdas and arrow functions are expressions, thus their r_brace is not
1319 // on its own line, and thus not covered by UnwrappedLineFormatter's logic
1320 // about removing empty lines on closing blocks. Special case them here
1321 // with an exception if the KeepEmptyLines.AtEndOfBlock is used.
1322 if (!Style.KeepEmptyLines.AtEndOfBlock)
1323 MaxEmptyLinesToKeep = 1;
1324 }
1325 const unsigned Newlines =
1326 std::max(a: 1u, b: std::min(a: Current.NewlinesBefore, b: MaxEmptyLinesToKeep));
1327 const bool ContinuePPDirective = State.Line->InPPDirective &&
1328 State.Line->Type != LT_ImportStatement &&
1329 Current.isNot(Kind: TT_LineComment);
1330 Whitespaces.replaceWhitespace(Tok&: Current, Newlines, Spaces: State.Column, StartOfTokenColumn: State.Column,
1331 AlignedTo: CurrentState.AlignedTo, InPPDirective: ContinuePPDirective,
1332 IndentedFromColumn);
1333 }
1334
1335 if (!Current.isTrailingComment())
1336 CurrentState.LastSpace = State.Column;
1337 if (Current.is(Kind: tok::lessless)) {
1338 // If we are breaking before a "<<", we always want to indent relative to
1339 // RHS. This is necessary only for "<<", as we special-case it and don't
1340 // always indent relative to the RHS.
1341 CurrentState.LastSpace += 3; // 3 -> width of "<< ".
1342 }
1343
1344 State.StartOfLineLevel = Current.NestingLevel;
1345 State.LowestLevelOnLine = Current.NestingLevel;
1346
1347 // Any break on this level means that the parent level has been broken
1348 // and we need to avoid bin packing there.
1349 bool NestedBlockSpecialCase =
1350 (!Style.isCpp() && Current.is(Kind: tok::r_brace) && State.Stack.size() > 1 &&
1351 State.Stack[State.Stack.size() - 2].NestedBlockInlined) ||
1352 (Style.Language == FormatStyle::LK_ObjC && Current.is(Kind: tok::r_brace) &&
1353 State.Stack.size() > 1 && !Style.ObjCBreakBeforeNestedBlockParam);
1354 // Do not force parameter break for statements with requires expressions.
1355 NestedBlockSpecialCase =
1356 NestedBlockSpecialCase ||
1357 (Current.MatchingParen &&
1358 Current.MatchingParen->is(TT: TT_RequiresExpressionLBrace));
1359 if (!NestedBlockSpecialCase) {
1360 auto ParentLevelIt = std::next(x: State.Stack.rbegin());
1361 if (Style.LambdaBodyIndentation == FormatStyle::LBI_OuterScope &&
1362 Current.MatchingParen && Current.MatchingParen->is(TT: TT_LambdaLBrace)) {
1363 // If the first character on the new line is a lambda's closing brace, the
1364 // stack still contains that lambda's parenthesis. As such, we need to
1365 // recurse further down the stack than usual to find the parenthesis level
1366 // containing the lambda, which is where we want to set
1367 // BreakBeforeParameter.
1368 //
1369 // We specifically special case "OuterScope"-formatted lambdas here
1370 // because, when using that setting, breaking before the parameter
1371 // directly following the lambda is particularly unsightly. However, when
1372 // "OuterScope" is not set, the logic to find the parent parenthesis level
1373 // still appears to be sometimes incorrect. It has not been fixed yet
1374 // because it would lead to significant changes in existing behaviour.
1375 //
1376 // TODO: fix the non-"OuterScope" case too.
1377 auto FindCurrentLevel = [&](const auto &It) {
1378 return std::find_if(It, State.Stack.rend(), [](const auto &PState) {
1379 return PState.Tok != nullptr; // Ignore fake parens.
1380 });
1381 };
1382 auto MaybeIncrement = [&](const auto &It) {
1383 return It != State.Stack.rend() ? std::next(It) : It;
1384 };
1385 auto LambdaLevelIt = FindCurrentLevel(State.Stack.rbegin());
1386 auto LevelContainingLambdaIt =
1387 FindCurrentLevel(MaybeIncrement(LambdaLevelIt));
1388 ParentLevelIt = MaybeIncrement(LevelContainingLambdaIt);
1389 }
1390 for (auto I = ParentLevelIt, E = State.Stack.rend(); I != E; ++I)
1391 I->BreakBeforeParameter = true;
1392 }
1393
1394 if (PreviousNonComment &&
1395 PreviousNonComment->isNoneOf(Ks: tok::comma, Ks: tok::colon, Ks: tok::semi) &&
1396 ((PreviousNonComment->isNot(Kind: TT_TemplateCloser) &&
1397 !PreviousNonComment->ClosesRequiresClause) ||
1398 Current.NestingLevel != 0) &&
1399 PreviousNonComment->isNoneOf(
1400 Ks: TT_BinaryOperator, Ks: TT_EnumEqual, Ks: TT_FunctionAnnotationRParen,
1401 Ks: TT_JavaAnnotation, Ks: TT_LeadingJavaAnnotation) &&
1402 Current.isNot(Kind: TT_BinaryOperator) && !PreviousNonComment->opensScope() &&
1403 // We don't want to enforce line breaks for subsequent arguments just
1404 // because we have been forced to break before a lambda body.
1405 (!Style.BraceWrapping.BeforeLambdaBody ||
1406 Current.isNot(Kind: TT_LambdaLBrace))) {
1407 CurrentState.BreakBeforeParameter = true;
1408 }
1409
1410 // If we break after { or the [ of an array initializer, we should also break
1411 // before the corresponding } or ].
1412 if (PreviousNonComment &&
1413 (PreviousNonComment->isOneOf(K1: tok::l_brace, K2: TT_ArrayInitializerLSquare) ||
1414 opensProtoMessageField(LessTok: *PreviousNonComment, Style))) {
1415 CurrentState.BreakBeforeClosingBrace = true;
1416 }
1417
1418 if (PreviousNonComment && PreviousNonComment->is(Kind: tok::l_paren)) {
1419 if (auto Previous = PreviousNonComment->Previous) {
1420 if (Previous->isIf()) {
1421 CurrentState.BreakBeforeClosingParen = Style.BreakBeforeCloseBracketIf;
1422 } else if (Previous->isLoop(Style)) {
1423 CurrentState.BreakBeforeClosingParen =
1424 Style.BreakBeforeCloseBracketLoop;
1425 } else if (Previous->is(Kind: tok::kw_switch)) {
1426 CurrentState.BreakBeforeClosingParen =
1427 Style.BreakBeforeCloseBracketSwitch;
1428 } else {
1429 CurrentState.BreakBeforeClosingParen =
1430 Style.BreakBeforeCloseBracketFunction;
1431 }
1432 }
1433 }
1434
1435 if (PreviousNonComment && PreviousNonComment->is(TT: TT_TemplateOpener))
1436 CurrentState.BreakBeforeClosingAngle = Style.BreakBeforeTemplateCloser;
1437
1438 if (CurrentState.AvoidBinPacking) {
1439 // If we are breaking after '(', '{', '<', or this is the break after a ':'
1440 // to start a member initializer list in a constructor, this should not
1441 // be considered bin packing unless the relevant AllowAll option is false or
1442 // this is a dict/object literal.
1443 bool PreviousIsBreakingCtorInitializerColon =
1444 PreviousNonComment && PreviousNonComment->is(TT: TT_CtorInitializerColon) &&
1445 Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon;
1446 bool AllowAllConstructorInitializersOnNextLine =
1447 Style.PackConstructorInitializers == FormatStyle::PCIS_NextLine ||
1448 Style.PackConstructorInitializers == FormatStyle::PCIS_NextLineOnly;
1449 if ((Previous.isNoneOf(Ks: tok::l_paren, Ks: tok::l_brace, Ks: TT_BinaryOperator) &&
1450 !PreviousIsBreakingCtorInitializerColon) ||
1451 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
1452 State.Line->MustBeDeclaration) ||
1453 (!Style.AllowAllArgumentsOnNextLine &&
1454 !State.Line->MustBeDeclaration) ||
1455 (!AllowAllConstructorInitializersOnNextLine &&
1456 PreviousIsBreakingCtorInitializerColon) ||
1457 Previous.is(TT: TT_DictLiteral)) {
1458 CurrentState.BreakBeforeParameter = true;
1459 }
1460
1461 // If we are breaking after a ':' to start a member initializer list,
1462 // and we allow all arguments on the next line, we should not break
1463 // before the next parameter.
1464 if (PreviousIsBreakingCtorInitializerColon &&
1465 AllowAllConstructorInitializersOnNextLine) {
1466 CurrentState.BreakBeforeParameter = false;
1467 }
1468 }
1469
1470 if (mustBreakBinaryOperation(Current, Style))
1471 CurrentState.BreakBeforeParameter = true;
1472
1473 return Penalty;
1474}
1475
1476IndentationAndAlignment
1477ContinuationIndenter::getNewLineColumn(const LineState &State) {
1478 if (!State.NextToken || !State.NextToken->Previous)
1479 return 0;
1480
1481 FormatToken &Current = *State.NextToken;
1482 const auto &CurrentState = State.Stack.back();
1483
1484 if (CurrentState.IsCSharpGenericTypeConstraint &&
1485 Current.isNot(Kind: TT_CSharpGenericTypeConstraint)) {
1486 return CurrentState.ColonPos + 2;
1487 }
1488
1489 const FormatToken &Previous = *Current.Previous;
1490 // If we are continuing an expression, we want to use the continuation indent.
1491 const auto ContinuationIndent =
1492 std::max(a: IndentationAndAlignment(CurrentState.LastSpace),
1493 b: CurrentState.Indent) +
1494 Style.ContinuationIndentWidth;
1495 const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
1496 const FormatToken *NextNonComment = Previous.getNextNonComment();
1497 if (!NextNonComment)
1498 NextNonComment = &Current;
1499
1500 // Java specific bits.
1501 if (Style.isJava() &&
1502 Current.isOneOf(K1: Keywords.kw_implements, K2: Keywords.kw_extends)) {
1503 return std::max(a: IndentationAndAlignment(CurrentState.LastSpace),
1504 b: CurrentState.Indent + Style.ContinuationIndentWidth);
1505 }
1506
1507 // Indentation of the statement following a Verilog case label is taken care
1508 // of in moveStateToNextToken.
1509 if (Style.isVerilog() && PreviousNonComment &&
1510 Keywords.isVerilogEndOfLabel(Tok: *PreviousNonComment)) {
1511 return State.FirstIndent;
1512 }
1513
1514 if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths &&
1515 State.Line->First->is(Kind: tok::kw_enum)) {
1516 return IndentationAndAlignment(Style.IndentWidth *
1517 State.Line->First->IndentLevel) +
1518 Style.IndentWidth;
1519 }
1520
1521 if (Style.BraceWrapping.BeforeLambdaBody &&
1522 Style.BraceWrapping.IndentBraces && Current.is(TT: TT_LambdaLBrace)) {
1523 const auto From = Style.LambdaBodyIndentation == FormatStyle::LBI_Signature
1524 ? CurrentState.Indent
1525 : State.FirstIndent;
1526 return From + Style.IndentWidth;
1527 }
1528
1529 // Align the wrapped opening brace of a requires expression with its
1530 // closing brace.
1531 if (Style.BraceWrapping.AfterRequiresExpression &&
1532 Current.is(TT: TT_RequiresExpressionLBrace)) {
1533 return CurrentState.NestedBlockIndent;
1534 }
1535
1536 if ((NextNonComment->is(Kind: tok::l_brace) && NextNonComment->is(BBK: BK_Block)) ||
1537 (Style.isVerilog() && Keywords.isVerilogBegin(Tok: *NextNonComment))) {
1538 if (Current.NestingLevel == 0 ||
1539 (Style.LambdaBodyIndentation == FormatStyle::LBI_OuterScope &&
1540 State.NextToken->is(TT: TT_LambdaLBrace))) {
1541 return State.FirstIndent;
1542 }
1543 return CurrentState.Indent;
1544 }
1545 if (Current.is(TT: TT_LambdaArrow) &&
1546 Previous.isOneOf(K1: tok::kw_noexcept, K2: tok::kw_mutable, Ks: tok::kw_constexpr,
1547 Ks: tok::kw_consteval, Ks: tok::kw_static,
1548 Ks: TT_AttributeRSquare)) {
1549 return ContinuationIndent;
1550 }
1551 if ((Current.isOneOf(K1: tok::r_brace, K2: tok::r_square) ||
1552 (Current.is(Kind: tok::greater) && (Style.isProto() || Style.isTableGen()))) &&
1553 State.Stack.size() > 1) {
1554 if (Current.closesBlockOrBlockTypeList(Style))
1555 return State.Stack[State.Stack.size() - 2].NestedBlockIndent;
1556 if (Current.MatchingParen && Current.MatchingParen->is(BBK: BK_BracedInit)) {
1557 // The brace should line up with the start of the line in this case. The
1558 // stack depth is checked to make sure that the brace is at the top
1559 // level. It should contain the levels for the top, the assignment if
1560 // there is an equal sign, and the braces.
1561 //
1562 // SomeStruct //
1563 // s = {
1564 // "xxxxxxxxxxxxx",
1565 // };
1566 if ((State.Stack.size() == 2 &&
1567 Current.MatchingParen->getPreviousNonComment() &&
1568 Current.MatchingParen->getPreviousNonComment()->is(
1569 TT: TT_StartOfName)) ||
1570 (State.Stack.size() == 3 &&
1571 State.Stack[1].Precedence == prec::Assignment)) {
1572 return State.FirstIndent;
1573 }
1574 return State.Stack[State.Stack.size() - 2].LastSpace;
1575 }
1576 return State.FirstIndent;
1577 }
1578 // Indent a closing parenthesis at the previous level if followed by a semi,
1579 // const, or opening brace. This allows indentations such as:
1580 // foo(
1581 // a,
1582 // );
1583 // int Foo::getter(
1584 // //
1585 // ) const {
1586 // return foo;
1587 // }
1588 // function foo(
1589 // a,
1590 // ) {
1591 // code(); //
1592 // }
1593 if (Current.is(Kind: tok::r_paren) && State.Stack.size() > 1 &&
1594 (!Current.Next ||
1595 Current.Next->isOneOf(K1: tok::semi, K2: tok::kw_const, Ks: tok::l_brace))) {
1596 return State.Stack[State.Stack.size() - 2].LastSpace;
1597 }
1598 // When DAGArg closer exists top of line, it should be aligned in the similar
1599 // way as function call above.
1600 if (Style.isTableGen() && Current.is(TT: TT_TableGenDAGArgCloser) &&
1601 State.Stack.size() > 1) {
1602 return State.Stack[State.Stack.size() - 2].LastSpace;
1603 }
1604 if (Style.BreakBeforeCloseBracketBracedList && Current.is(Kind: tok::r_brace) &&
1605 Current.MatchingParen && Current.MatchingParen->is(BBK: BK_BracedInit) &&
1606 State.Stack.size() > 1) {
1607 return State.Stack[State.Stack.size() - 2].LastSpace;
1608 }
1609 if ((Style.BreakBeforeCloseBracketFunction ||
1610 Style.BreakBeforeCloseBracketIf || Style.BreakBeforeCloseBracketLoop ||
1611 Style.BreakBeforeCloseBracketSwitch) &&
1612 Current.is(Kind: tok::r_paren) && State.Stack.size() > 1) {
1613 return State.Stack[State.Stack.size() - 2].LastSpace;
1614 }
1615 if (Style.BreakBeforeTemplateCloser && Current.is(TT: TT_TemplateCloser) &&
1616 State.Stack.size() > 1) {
1617 return State.Stack[State.Stack.size() - 2].LastSpace;
1618 }
1619 if (NextNonComment->is(TT: TT_TemplateString) && NextNonComment->closesScope())
1620 return State.Stack[State.Stack.size() - 2].LastSpace;
1621 // Field labels in a nested type should be aligned to the brace. For example
1622 // in ProtoBuf:
1623 // optional int32 b = 2 [(foo_options) = {aaaaaaaaaaaaaaaaaaa: 123,
1624 // bbbbbbbbbbbbbbbbbbbbbbbb:"baz"}];
1625 // For Verilog, a quote preceding a brace is treated as an identifier. And
1626 // Both braces and colons get annotated as TT_DictLiteral. So we have to
1627 // check.
1628 if (Current.is(Kind: tok::identifier) && Current.Next &&
1629 (!Style.isVerilog() || Current.Next->is(Kind: tok::colon)) &&
1630 (Current.Next->is(TT: TT_DictLiteral) ||
1631 (Style.isProto() && Current.Next->isOneOf(K1: tok::less, K2: tok::l_brace)))) {
1632 return CurrentState.Indent;
1633 }
1634 if (NextNonComment->is(TT: TT_ObjCStringLiteral) &&
1635 State.StartOfStringLiteral != 0) {
1636 return State.StartOfStringLiteral - 1;
1637 }
1638 if (NextNonComment->isStringLiteral() && State.StartOfStringLiteral != 0)
1639 return State.StartOfStringLiteral;
1640 if (NextNonComment->is(Kind: tok::lessless) && CurrentState.FirstLessLess != 0)
1641 return CurrentState.FirstLessLess;
1642 if (NextNonComment->isMemberAccess()) {
1643 if (CurrentState.CallContinuation == 0)
1644 return ContinuationIndent;
1645 return CurrentState.CallContinuation;
1646 }
1647 if (CurrentState.QuestionColumn != 0 &&
1648 ((NextNonComment->is(Kind: tok::colon) &&
1649 NextNonComment->is(TT: TT_ConditionalExpr)) ||
1650 Previous.is(TT: TT_ConditionalExpr))) {
1651 if (((NextNonComment->is(Kind: tok::colon) && NextNonComment->Next &&
1652 !NextNonComment->Next->FakeLParens.empty() &&
1653 NextNonComment->Next->FakeLParens.back() == prec::Conditional) ||
1654 (Previous.is(Kind: tok::colon) && !Current.FakeLParens.empty() &&
1655 Current.FakeLParens.back() == prec::Conditional)) &&
1656 !CurrentState.IsWrappedConditional) {
1657 // NOTE: we may tweak this slightly:
1658 // * not remove the 'lead' ContinuationIndentWidth
1659 // * always un-indent by the operator when
1660 // BreakBeforeTernaryOperators=true
1661 unsigned Indent = CurrentState.Indent.Total;
1662 if (Style.AlignOperands != FormatStyle::OAS_DontAlign)
1663 Indent -= Style.ContinuationIndentWidth;
1664 if (Style.BreakBeforeTernaryOperators && CurrentState.UnindentOperator)
1665 Indent -= 2;
1666 return Indent;
1667 }
1668 return CurrentState.QuestionColumn;
1669 }
1670 if (Previous.is(Kind: tok::comma) && CurrentState.VariablePos != 0)
1671 return CurrentState.VariablePos;
1672 if (Current.is(TT: TT_RequiresClause)) {
1673 if (Style.IndentRequiresClause)
1674 return CurrentState.Indent + Style.IndentWidth;
1675 switch (Style.RequiresClausePosition) {
1676 case FormatStyle::RCPS_OwnLine:
1677 case FormatStyle::RCPS_WithFollowing:
1678 case FormatStyle::RCPS_OwnLineWithBrace:
1679 return CurrentState.Indent;
1680 default:
1681 break;
1682 }
1683 }
1684 if (NextNonComment->isOneOf(K1: TT_CtorInitializerColon, K2: TT_InheritanceColon,
1685 Ks: TT_InheritanceComma)) {
1686 return State.FirstIndent + Style.ConstructorInitializerIndentWidth;
1687 }
1688 if ((PreviousNonComment &&
1689 (PreviousNonComment->ClosesTemplateDeclaration ||
1690 PreviousNonComment->ClosesRequiresClause ||
1691 (PreviousNonComment->is(TT: TT_AttributeMacro) &&
1692 Current.isNot(Kind: tok::l_paren) &&
1693 !Current.endsSequence(K1: TT_StartOfName, Tokens: TT_AttributeMacro,
1694 Tokens: TT_PointerOrReference)) ||
1695 (PreviousNonComment->isOneOf(K1: TT_AttributeRParen, K2: TT_AttributeRSquare,
1696 Ks: TT_FunctionAnnotationRParen,
1697 Ks: TT_JavaAnnotation,
1698 Ks: TT_LeadingJavaAnnotation) &&
1699 !Current.isBinaryOperator()))) ||
1700 (!Style.IndentWrappedFunctionNames &&
1701 NextNonComment->isOneOf(K1: tok::kw_operator, K2: TT_FunctionDeclarationName)) ||
1702 (State.Line->ReturnTypeWrapped && PreviousNonComment &&
1703 isReturnTypePrefixSpecifier(Tok: *PreviousNonComment))) {
1704 return std::max(a: IndentationAndAlignment(CurrentState.LastSpace),
1705 b: CurrentState.Indent);
1706 }
1707 if (NextNonComment->is(TT: TT_SelectorName)) {
1708 if (!CurrentState.ObjCSelectorNameFound) {
1709 auto MinIndent = CurrentState.Indent;
1710 if (shouldIndentWrappedSelectorName(Style, LineType: State.Line->Type)) {
1711 MinIndent =
1712 std::max(a: MinIndent, b: IndentationAndAlignment(State.FirstIndent) +
1713 Style.ContinuationIndentWidth);
1714 }
1715 // If LongestObjCSelectorName is 0, we are indenting the first
1716 // part of an ObjC selector (or a selector component which is
1717 // not colon-aligned due to block formatting).
1718 //
1719 // Otherwise, we are indenting a subsequent part of an ObjC
1720 // selector which should be colon-aligned to the longest
1721 // component of the ObjC selector.
1722 //
1723 // In either case, we want to respect Style.IndentWrappedFunctionNames.
1724 return MinIndent.addPadding(
1725 Spaces: std::max(a: NextNonComment->LongestObjCSelectorName,
1726 b: NextNonComment->ColumnWidth) -
1727 NextNonComment->ColumnWidth);
1728 }
1729 if (!CurrentState.AlignColons)
1730 return CurrentState.Indent;
1731 if (CurrentState.ColonPos > NextNonComment->ColumnWidth)
1732 return CurrentState.ColonPos - NextNonComment->ColumnWidth;
1733 return CurrentState.Indent;
1734 }
1735 if (NextNonComment->is(Kind: tok::colon) && NextNonComment->is(TT: TT_ObjCMethodExpr))
1736 return CurrentState.ColonPos;
1737 if (NextNonComment->is(TT: TT_ArraySubscriptLSquare)) {
1738 if (CurrentState.StartOfArraySubscripts != 0) {
1739 return CurrentState.StartOfArraySubscripts;
1740 } else if (Style.isCSharp()) { // C# allows `["key"] = value` inside object
1741 // initializers.
1742 return CurrentState.Indent;
1743 }
1744 return ContinuationIndent;
1745 }
1746
1747 // OpenMP clauses want to get additional indentation when they are pushed onto
1748 // the next line.
1749 if (State.Line->InPragmaDirective) {
1750 FormatToken *PragmaType = State.Line->First->Next->Next;
1751 if (PragmaType && PragmaType->TokenText == "omp")
1752 return CurrentState.Indent + Style.ContinuationIndentWidth;
1753 }
1754
1755 // This ensure that we correctly format ObjC methods calls without inputs,
1756 // i.e. where the last element isn't selector like: [callee method];
1757 if (NextNonComment->is(Kind: tok::identifier) && NextNonComment->FakeRParens == 0 &&
1758 NextNonComment->Next && NextNonComment->Next->is(TT: TT_ObjCMethodExpr)) {
1759 return CurrentState.Indent;
1760 }
1761
1762 if (NextNonComment->isOneOf(K1: TT_StartOfName, K2: TT_PointerOrReference) ||
1763 Previous.isOneOf(K1: tok::coloncolon, K2: tok::equal, Ks: TT_JsTypeColon)) {
1764 return ContinuationIndent;
1765 }
1766 if (PreviousNonComment && PreviousNonComment->is(Kind: tok::colon) &&
1767 PreviousNonComment->isOneOf(K1: TT_ObjCMethodExpr, K2: TT_DictLiteral)) {
1768 return ContinuationIndent;
1769 }
1770 if (NextNonComment->is(TT: TT_CtorInitializerComma))
1771 return CurrentState.Indent;
1772 if (PreviousNonComment && PreviousNonComment->is(TT: TT_CtorInitializerColon) &&
1773 Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon) {
1774 return CurrentState.Indent;
1775 }
1776 if (PreviousNonComment && PreviousNonComment->is(TT: TT_InheritanceColon) &&
1777 Style.BreakInheritanceList == FormatStyle::BILS_AfterColon) {
1778 return CurrentState.Indent;
1779 }
1780 if (Previous.is(Kind: tok::r_paren) &&
1781 Previous.isNot(Kind: TT_TableGenDAGArgOperatorToBreak) &&
1782 !Current.isBinaryOperator() &&
1783 Current.isNoneOf(Ks: tok::colon, Ks: tok::comment)) {
1784 return ContinuationIndent;
1785 }
1786 if (Current.is(TT: TT_ProtoExtensionLSquare))
1787 return CurrentState.Indent;
1788 if (Current.isBinaryOperator() && CurrentState.UnindentOperator) {
1789 return CurrentState.Indent - Current.Tok.getLength() -
1790 Current.SpacesRequiredBefore;
1791 }
1792 if (Current.is(Kind: tok::comment) && NextNonComment->isBinaryOperator() &&
1793 CurrentState.UnindentOperator) {
1794 return CurrentState.Indent - NextNonComment->Tok.getLength() -
1795 NextNonComment->SpacesRequiredBefore;
1796 }
1797 if (CurrentState.Indent.Total == State.FirstIndent && PreviousNonComment &&
1798 PreviousNonComment->isNoneOf(Ks: tok::r_brace, Ks: TT_CtorInitializerComma)) {
1799 // Ensure that we fall back to the continuation indent width instead of
1800 // just flushing continuations left.
1801 return CurrentState.Indent + Style.ContinuationIndentWidth;
1802 }
1803 return CurrentState.Indent;
1804}
1805
1806static bool hasNestedBlockInlined(const FormatToken *Previous,
1807 const FormatToken &Current,
1808 const FormatStyle &Style) {
1809 if (Previous->isNot(Kind: tok::l_paren))
1810 return true;
1811 if (Previous->ParameterCount > 1)
1812 return true;
1813
1814 // Also a nested block if contains a lambda inside function with 1 parameter.
1815 return Style.BraceWrapping.BeforeLambdaBody && Current.is(TT: TT_LambdaLSquare);
1816}
1817
1818unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
1819 bool DryRun, bool Newline) {
1820 assert(State.Stack.size());
1821 const FormatToken &Current = *State.NextToken;
1822 auto &CurrentState = State.Stack.back();
1823
1824 if (Current.is(TT: TT_CSharpGenericTypeConstraint))
1825 CurrentState.IsCSharpGenericTypeConstraint = true;
1826 if (Current.isOneOf(K1: tok::comma, K2: TT_BinaryOperator))
1827 CurrentState.NoLineBreakInOperand = false;
1828 if (Current.isOneOf(K1: TT_InheritanceColon, K2: TT_CSharpGenericTypeConstraintColon))
1829 CurrentState.AvoidBinPacking = true;
1830 if (Current.is(Kind: tok::lessless) && Current.isNot(Kind: TT_OverloadedOperator)) {
1831 if (CurrentState.FirstLessLess == 0)
1832 CurrentState.FirstLessLess = State.Column;
1833 else
1834 CurrentState.LastOperatorWrapped = Newline;
1835 }
1836 if (Current.is(TT: TT_BinaryOperator) && Current.isNot(Kind: tok::lessless))
1837 CurrentState.LastOperatorWrapped = Newline;
1838 if (Current.is(TT: TT_ConditionalExpr) && Current.Previous &&
1839 Current.Previous->isNot(Kind: TT_ConditionalExpr)) {
1840 CurrentState.LastOperatorWrapped = Newline;
1841 }
1842 if (Current.is(TT: TT_ArraySubscriptLSquare) &&
1843 CurrentState.StartOfArraySubscripts == 0) {
1844 CurrentState.StartOfArraySubscripts = State.Column;
1845 }
1846
1847 auto IsWrappedConditional = [](const FormatToken &Tok) {
1848 if (!(Tok.is(TT: TT_ConditionalExpr) && Tok.is(Kind: tok::question)))
1849 return false;
1850 if (Tok.MustBreakBefore)
1851 return true;
1852
1853 const FormatToken *Next = Tok.getNextNonComment();
1854 return Next && Next->MustBreakBefore;
1855 };
1856 if (IsWrappedConditional(Current))
1857 CurrentState.IsWrappedConditional = true;
1858 if (Style.BreakBeforeTernaryOperators && Current.is(Kind: tok::question))
1859 CurrentState.QuestionColumn = State.Column;
1860 if (!Style.BreakBeforeTernaryOperators && Current.isNot(Kind: tok::colon)) {
1861 const FormatToken *Previous = Current.Previous;
1862 while (Previous && Previous->isTrailingComment())
1863 Previous = Previous->Previous;
1864 if (Previous && Previous->is(Kind: tok::question))
1865 CurrentState.QuestionColumn = State.Column;
1866 }
1867 if (!Current.opensScope() && !Current.closesScope() &&
1868 Current.isNot(Kind: TT_PointerOrReference)) {
1869 State.LowestLevelOnLine =
1870 std::min(a: State.LowestLevelOnLine, b: Current.NestingLevel);
1871 }
1872 if (Current.isMemberAccess())
1873 CurrentState.StartOfFunctionCall = !Current.NextOperator ? 0 : State.Column;
1874 if (Current.is(TT: TT_SelectorName))
1875 CurrentState.ObjCSelectorNameFound = true;
1876 if (Current.is(TT: TT_CtorInitializerColon) &&
1877 Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon) {
1878 // Indent 2 from the column, so:
1879 // SomeClass::SomeClass()
1880 // : First(...), ...
1881 // Next(...)
1882 // ^ line up here.
1883 CurrentState.Indent = State.Column + (Style.BreakConstructorInitializers ==
1884 FormatStyle::BCIS_BeforeComma
1885 ? 0
1886 : 2);
1887 CurrentState.NestedBlockIndent = CurrentState.Indent.Total;
1888 if (Style.PackConstructorInitializers > FormatStyle::PCIS_BinPack) {
1889 CurrentState.AvoidBinPacking = true;
1890 CurrentState.BreakBeforeParameter =
1891 Style.ColumnLimit > 0 &&
1892 Style.PackConstructorInitializers != FormatStyle::PCIS_NextLine &&
1893 Style.PackConstructorInitializers != FormatStyle::PCIS_NextLineOnly;
1894 } else {
1895 CurrentState.BreakBeforeParameter = false;
1896 }
1897 }
1898 if (Current.is(TT: TT_CtorInitializerColon) &&
1899 Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon) {
1900 CurrentState.Indent =
1901 State.FirstIndent + Style.ConstructorInitializerIndentWidth;
1902 CurrentState.NestedBlockIndent = CurrentState.Indent.Total;
1903 if (Style.PackConstructorInitializers > FormatStyle::PCIS_BinPack)
1904 CurrentState.AvoidBinPacking = true;
1905 else
1906 CurrentState.BreakBeforeParameter = false;
1907 }
1908 if (Current.is(TT: TT_InheritanceColon)) {
1909 CurrentState.Indent =
1910 State.FirstIndent + Style.ConstructorInitializerIndentWidth;
1911 }
1912 if (Current.isOneOf(K1: TT_BinaryOperator, K2: TT_ConditionalExpr) && Newline)
1913 CurrentState.NestedBlockIndent = State.Column + Current.ColumnWidth + 1;
1914 if (Current.isOneOf(K1: TT_LambdaLSquare, K2: TT_LambdaArrow))
1915 CurrentState.LastSpace = State.Column;
1916 if (Current.is(TT: TT_RequiresExpression) &&
1917 Style.RequiresExpressionIndentation == FormatStyle::REI_Keyword) {
1918 CurrentState.NestedBlockIndent = State.Column;
1919 }
1920
1921 // Insert scopes created by fake parenthesis.
1922 const FormatToken *Previous = Current.getPreviousNonComment();
1923
1924 // Add special behavior to support a format commonly used for JavaScript
1925 // closures:
1926 // SomeFunction(function() {
1927 // foo();
1928 // bar();
1929 // }, a, b, c);
1930 if (Current.isNot(Kind: tok::comment) && !Current.ClosesRequiresClause &&
1931 Previous && Previous->isOneOf(K1: tok::l_brace, K2: TT_ArrayInitializerLSquare) &&
1932 Previous->isNot(Kind: TT_DictLiteral) && State.Stack.size() > 1 &&
1933 !CurrentState.HasMultipleNestedBlocks) {
1934 if (State.Stack[State.Stack.size() - 2].NestedBlockInlined && Newline)
1935 for (ParenState &PState : llvm::drop_end(RangeOrContainer&: State.Stack))
1936 PState.NoLineBreak = true;
1937 State.Stack[State.Stack.size() - 2].NestedBlockInlined = false;
1938 }
1939 if (Previous && (Previous->isOneOf(K1: TT_BinaryOperator, K2: TT_ConditionalExpr) ||
1940 (Previous->isOneOf(K1: tok::l_paren, K2: tok::comma, Ks: tok::colon) &&
1941 Previous->isNoneOf(Ks: TT_DictLiteral, Ks: TT_ObjCMethodExpr,
1942 Ks: TT_CtorInitializerColon)))) {
1943 CurrentState.NestedBlockInlined =
1944 !Newline && hasNestedBlockInlined(Previous, Current, Style);
1945 }
1946
1947 moveStatePastFakeLParens(State, Newline);
1948 moveStatePastScopeCloser(State);
1949 // Do not use CurrentState here, since the two functions before may change the
1950 // Stack.
1951 bool AllowBreak = !State.Stack.back().NoLineBreak &&
1952 !State.Stack.back().NoLineBreakInOperand;
1953 moveStatePastScopeOpener(State, Newline);
1954 moveStatePastFakeRParens(State);
1955
1956 if (Current.is(TT: TT_ObjCStringLiteral) && State.StartOfStringLiteral == 0)
1957 State.StartOfStringLiteral = State.Column + 1;
1958 if (Current.is(TT: TT_CSharpStringLiteral) && State.StartOfStringLiteral == 0) {
1959 State.StartOfStringLiteral = State.Column + 1;
1960 } else if (Current.is(TT: TT_TableGenMultiLineString) &&
1961 State.StartOfStringLiteral == 0) {
1962 State.StartOfStringLiteral = State.Column + 1;
1963 } else if (Current.isStringLiteral() && State.StartOfStringLiteral == 0) {
1964 State.StartOfStringLiteral = State.Column;
1965 } else if (Current.isNoneOf(Ks: tok::comment, Ks: tok::identifier, Ks: tok::hash) &&
1966 !Current.isStringLiteral()) {
1967 State.StartOfStringLiteral = 0;
1968 }
1969
1970 State.Column += Current.ColumnWidth;
1971 State.NextToken = State.NextToken->Next;
1972 // Verilog case labels are on the same unwrapped lines as the statements that
1973 // follow. TokenAnnotator identifies them and sets MustBreakBefore.
1974 // Indentation is taken care of here. A case label can only have 1 statement
1975 // in Verilog, so we don't have to worry about lines that follow.
1976 if (Style.isVerilog() && State.NextToken &&
1977 State.NextToken->MustBreakBefore &&
1978 Keywords.isVerilogEndOfLabel(Tok: Current)) {
1979 State.FirstIndent += Style.IndentWidth;
1980 CurrentState.Indent = State.FirstIndent;
1981 }
1982
1983 unsigned Penalty =
1984 handleEndOfLine(Current, State, DryRun, AllowBreak, Newline);
1985
1986 if (Current.Role)
1987 Current.Role->formatFromToken(State, Indenter: this, DryRun);
1988 // If the previous has a special role, let it consume tokens as appropriate.
1989 // It is necessary to start at the previous token for the only implemented
1990 // role (comma separated list). That way, the decision whether or not to break
1991 // after the "{" is already done and both options are tried and evaluated.
1992 // FIXME: This is ugly, find a better way.
1993 if (Previous && Previous->Role)
1994 Penalty += Previous->Role->formatAfterToken(State, Indenter: this, DryRun);
1995
1996 return Penalty;
1997}
1998
1999void ContinuationIndenter::moveStatePastFakeLParens(LineState &State,
2000 bool Newline) {
2001 const FormatToken &Current = *State.NextToken;
2002 if (Current.FakeLParens.empty())
2003 return;
2004
2005 const FormatToken *Previous = Current.getPreviousNonComment();
2006
2007 // Don't add extra indentation for the first fake parenthesis after
2008 // 'return', assignments, opening <({[, or requires clauses. The indentation
2009 // for these cases is special cased.
2010 bool SkipFirstExtraIndent =
2011 Previous &&
2012 (Previous->opensScope() ||
2013 Previous->isOneOf(K1: tok::semi, K2: tok::kw_return, Ks: TT_RequiresClause) ||
2014 (Previous->getPrecedence() == prec::Assignment &&
2015 Style.AlignOperands != FormatStyle::OAS_DontAlign) ||
2016 Previous->is(TT: TT_ObjCMethodExpr));
2017 for (const auto &PrecedenceLevel : llvm::reverse(C: Current.FakeLParens)) {
2018 const auto &CurrentState = State.Stack.back();
2019 ParenState NewParenState = CurrentState;
2020 NewParenState.Tok = nullptr;
2021 NewParenState.ContainsLineBreak = false;
2022 NewParenState.LastOperatorWrapped = true;
2023 NewParenState.IsChainedConditional = false;
2024 NewParenState.IsWrappedConditional = false;
2025 NewParenState.UnindentOperator = false;
2026 NewParenState.NoLineBreak =
2027 NewParenState.NoLineBreak || CurrentState.NoLineBreakInOperand;
2028 NewParenState.Precedence = PrecedenceLevel;
2029
2030 // Don't propagate AvoidBinPacking into subexpressions of arg/param lists.
2031 if (PrecedenceLevel > prec::Comma)
2032 NewParenState.AvoidBinPacking = false;
2033
2034 // Indent from 'LastSpace' unless these are fake parentheses encapsulating
2035 // a builder type call after 'return' or, if the alignment after opening
2036 // brackets is disabled.
2037 if (!Current.isTrailingComment() &&
2038 (Style.AlignOperands != FormatStyle::OAS_DontAlign ||
2039 PrecedenceLevel < prec::Assignment) &&
2040 (!Previous || Previous->isNot(Kind: tok::kw_return) ||
2041 (!Style.isJava() && PrecedenceLevel > 0)) &&
2042 (Style.AlignAfterOpenBracket || PrecedenceLevel > prec::Comma ||
2043 Current.NestingLevel == 0) &&
2044 (!Style.isTableGen() ||
2045 (Previous && Previous->isOneOf(K1: TT_TableGenDAGArgListComma,
2046 K2: TT_TableGenDAGArgListCommaToBreak)))) {
2047 NewParenState.Indent =
2048 std::max(l: {IndentationAndAlignment(State.Column), NewParenState.Indent,
2049 IndentationAndAlignment(CurrentState.LastSpace)});
2050 }
2051
2052 // Special case for generic selection expressions, its comma-separated
2053 // expressions are not aligned to the opening paren like regular calls, but
2054 // rather continuation-indented relative to the _Generic keyword.
2055 if (Previous && Previous->endsSequence(K1: tok::l_paren, Tokens: tok::kw__Generic) &&
2056 State.Stack.size() > 1) {
2057 NewParenState.Indent = State.Stack[State.Stack.size() - 2].Indent +
2058 Style.ContinuationIndentWidth;
2059 }
2060
2061 if ((shouldUnindentNextOperator(Tok: Current) ||
2062 (Previous &&
2063 (PrecedenceLevel == prec::Conditional &&
2064 Previous->is(Kind: tok::question) && Previous->is(TT: TT_ConditionalExpr)))) &&
2065 !Newline) {
2066 // If BreakBeforeBinaryOperators is set, un-indent a bit to account for
2067 // the operator and keep the operands aligned.
2068 if (Style.AlignOperands == FormatStyle::OAS_AlignAfterOperator)
2069 NewParenState.UnindentOperator = true;
2070 // Mark indentation as alignment if the expression is aligned.
2071 if (Style.AlignOperands != FormatStyle::OAS_DontAlign)
2072 NewParenState.AlignedTo = Previous;
2073 }
2074
2075 // Do not indent relative to the fake parentheses inserted for "." or "->".
2076 // This is a special case to make the following to statements consistent:
2077 // OuterFunction(InnerFunctionCall( // break
2078 // ParameterToInnerFunction));
2079 // OuterFunction(SomeObject.InnerFunctionCall( // break
2080 // ParameterToInnerFunction));
2081 if (PrecedenceLevel > prec::Unknown)
2082 NewParenState.LastSpace = std::max(a: NewParenState.LastSpace, b: State.Column);
2083 if (PrecedenceLevel != prec::Conditional &&
2084 Current.isNot(Kind: TT_UnaryOperator) && Style.AlignAfterOpenBracket) {
2085 NewParenState.StartOfFunctionCall = State.Column;
2086 }
2087
2088 // Indent conditional expressions, unless they are chained "else-if"
2089 // conditionals. Never indent expression where the 'operator' is ',', ';' or
2090 // an assignment (i.e. *I <= prec::Assignment) as those have different
2091 // indentation rules. Indent other expression, unless the indentation needs
2092 // to be skipped.
2093 if (PrecedenceLevel == prec::Conditional && Previous &&
2094 Previous->is(Kind: tok::colon) && Previous->is(TT: TT_ConditionalExpr) &&
2095 &PrecedenceLevel == &Current.FakeLParens.back() &&
2096 !CurrentState.IsWrappedConditional) {
2097 NewParenState.IsChainedConditional = true;
2098 NewParenState.UnindentOperator = State.Stack.back().UnindentOperator;
2099 } else if (PrecedenceLevel == prec::Conditional ||
2100 (!SkipFirstExtraIndent && PrecedenceLevel > prec::Assignment &&
2101 !Current.isTrailingComment())) {
2102 NewParenState.Indent += Style.ContinuationIndentWidth;
2103 }
2104 if ((Previous && !Previous->opensScope()) || PrecedenceLevel != prec::Comma)
2105 NewParenState.BreakBeforeParameter = false;
2106 State.Stack.push_back(Elt: NewParenState);
2107 SkipFirstExtraIndent = false;
2108 }
2109}
2110
2111void ContinuationIndenter::moveStatePastFakeRParens(LineState &State) {
2112 for (unsigned i = 0, e = State.NextToken->FakeRParens; i != e; ++i) {
2113 unsigned VariablePos = State.Stack.back().VariablePos;
2114 if (State.Stack.size() == 1) {
2115 // Do not pop the last element.
2116 break;
2117 }
2118 State.Stack.pop_back();
2119 State.Stack.back().VariablePos = VariablePos;
2120 }
2121
2122 if (State.NextToken->ClosesRequiresClause && Style.IndentRequiresClause) {
2123 // Remove the indentation of the requires clauses (which is not in Indent,
2124 // but in LastSpace).
2125 State.Stack.back().LastSpace -= Style.IndentWidth;
2126 }
2127}
2128
2129void ContinuationIndenter::moveStatePastScopeOpener(LineState &State,
2130 bool Newline) {
2131 const FormatToken &Current = *State.NextToken;
2132 if (!Current.opensScope())
2133 return;
2134
2135 const auto &CurrentState = State.Stack.back();
2136
2137 // Don't allow '<' or '(' in C# generic type constraints to start new scopes.
2138 if (Current.isOneOf(K1: tok::less, K2: tok::l_paren) &&
2139 CurrentState.IsCSharpGenericTypeConstraint) {
2140 return;
2141 }
2142
2143 if (Current.MatchingParen && Current.is(BBK: BK_Block)) {
2144 moveStateToNewBlock(State, NewLine: Newline);
2145 return;
2146 }
2147
2148 const bool EndsInComma = [](const FormatToken *Tok) {
2149 if (!Tok)
2150 return false;
2151 const auto *Prev = Tok->getPreviousNonComment();
2152 if (!Prev)
2153 return false;
2154 return Prev->is(Kind: tok::comma);
2155 }(Current.MatchingParen);
2156
2157 IndentationAndAlignment NewIndent = 0;
2158 unsigned LastSpace = CurrentState.LastSpace;
2159 bool AvoidBinPacking;
2160 bool BreakBeforeParameter = false;
2161 unsigned NestedBlockIndent = std::max(a: CurrentState.StartOfFunctionCall,
2162 b: CurrentState.NestedBlockIndent);
2163 if (Current.isOneOf(K1: tok::l_brace, K2: TT_ArrayInitializerLSquare) ||
2164 opensProtoMessageField(LessTok: Current, Style)) {
2165 if (Current.opensBlockOrBlockTypeList(Style)) {
2166 NewIndent = Style.IndentWidth +
2167 std::min(a: State.Column, b: CurrentState.NestedBlockIndent);
2168 } else if (Current.is(Kind: tok::l_brace)) {
2169 const auto Width = Style.BracedInitializerIndentWidth;
2170 NewIndent = IndentationAndAlignment(CurrentState.LastSpace) +
2171 (Width < 0 ? Style.ContinuationIndentWidth : Width);
2172 } else {
2173 NewIndent = CurrentState.LastSpace + Style.ContinuationIndentWidth;
2174 }
2175 const FormatToken *NextNonComment = Current.getNextNonComment();
2176 AvoidBinPacking =
2177 EndsInComma || Current.is(TT: TT_DictLiteral) || Style.isProto() ||
2178 Style.PackArguments.BinPack == FormatStyle::BPAS_OnePerLine ||
2179 (NextNonComment &&
2180 NextNonComment->isOneOf(K1: TT_DesignatedInitializerPeriod,
2181 K2: TT_DesignatedInitializerLSquare));
2182 BreakBeforeParameter = EndsInComma;
2183 if (Current.ParameterCount > 1)
2184 NestedBlockIndent = std::max(a: NestedBlockIndent, b: State.Column + 1);
2185 } else {
2186 NewIndent = IndentationAndAlignment(std::max(
2187 a: CurrentState.LastSpace, b: CurrentState.StartOfFunctionCall)) +
2188 Style.ContinuationIndentWidth;
2189
2190 if (Style.isTableGen() && Current.is(TT: TT_TableGenDAGArgOpenerToBreak) &&
2191 Style.TableGenBreakInsideDAGArg == FormatStyle::DAS_BreakElements) {
2192 // For the case the next token is a TableGen DAGArg operator identifier
2193 // that is not marked to have a line break after it.
2194 // In this case the option DAS_BreakElements requires to align the
2195 // DAGArg elements to the operator.
2196 const FormatToken *Next = Current.Next;
2197 if (Next && Next->is(TT: TT_TableGenDAGArgOperatorID))
2198 NewIndent = State.Column + Next->TokenText.size() + 2;
2199 }
2200
2201 // Ensure that different different brackets force relative alignment, e.g.:
2202 // void SomeFunction(vector< // break
2203 // int> v);
2204 // FIXME: We likely want to do this for more combinations of brackets.
2205 if (Current.is(Kind: tok::less) && Current.ParentBracket == tok::l_paren) {
2206 NewIndent = std::max(a: NewIndent, b: CurrentState.Indent);
2207 LastSpace = std::max(a: LastSpace, b: CurrentState.Indent.Total);
2208 }
2209
2210 // If ObjCBinPackProtocolList is unspecified, fall back to BinPackParameters
2211 // for backwards compatibility.
2212 bool ObjCBinPackProtocolList =
2213 (Style.ObjCBinPackProtocolList == FormatStyle::BPS_Auto &&
2214 (Style.PackParameters.BinPack == FormatStyle::BPPS_BinPack ||
2215 Style.PackParameters.BinPack == FormatStyle::BPPS_UseBreakAfter)) ||
2216 Style.ObjCBinPackProtocolList == FormatStyle::BPS_Always;
2217
2218 bool BinPackDeclaration =
2219 (State.Line->Type != LT_ObjCDecl &&
2220 (Style.PackParameters.BinPack == FormatStyle::BPPS_BinPack ||
2221 Style.PackParameters.BinPack == FormatStyle::BPPS_UseBreakAfter)) ||
2222 (State.Line->Type == LT_ObjCDecl && ObjCBinPackProtocolList);
2223
2224 bool GenericSelection =
2225 Current.getPreviousNonComment() &&
2226 Current.getPreviousNonComment()->is(Kind: tok::kw__Generic);
2227
2228 AvoidBinPacking =
2229 (CurrentState.IsCSharpGenericTypeConstraint) || GenericSelection ||
2230 (Style.isJavaScript() && EndsInComma) ||
2231 (State.Line->MustBeDeclaration && !BinPackDeclaration) ||
2232 (!State.Line->MustBeDeclaration &&
2233 Style.PackArguments.BinPack == FormatStyle::BPAS_OnePerLine) ||
2234 (Style.ExperimentalAutoDetectBinPacking &&
2235 (Current.is(PPK: PPK_OnePerLine) ||
2236 (!BinPackInconclusiveFunctions && Current.is(PPK: PPK_Inconclusive))));
2237
2238 if (Current.is(TT: TT_ObjCMethodExpr) && Current.MatchingParen &&
2239 Style.ObjCBreakBeforeNestedBlockParam) {
2240 if (Style.ColumnLimit) {
2241 // If this '[' opens an ObjC call, determine whether all parameters fit
2242 // into one line and put one per line if they don't.
2243 if (getLengthToMatchingParen(Tok: Current, Stack: State.Stack) + State.Column >
2244 getColumnLimit(State)) {
2245 BreakBeforeParameter = true;
2246 }
2247 } else {
2248 // For ColumnLimit = 0, we have to figure out whether there is or has to
2249 // be a line break within this call.
2250 for (const FormatToken *Tok = &Current;
2251 Tok && Tok != Current.MatchingParen; Tok = Tok->Next) {
2252 if (Tok->MustBreakBefore ||
2253 (Tok->CanBreakBefore && Tok->NewlinesBefore > 0)) {
2254 BreakBeforeParameter = true;
2255 break;
2256 }
2257 }
2258 }
2259 }
2260
2261 if (Style.isJavaScript() && EndsInComma)
2262 BreakBeforeParameter = true;
2263 }
2264 // Generally inherit NoLineBreak from the current scope to nested scope.
2265 // However, don't do this for non-empty nested blocks, dict literals and
2266 // array literals as these follow different indentation rules.
2267 bool NoLineBreak =
2268 Current.Children.empty() &&
2269 Current.isNoneOf(Ks: TT_DictLiteral, Ks: TT_ArrayInitializerLSquare) &&
2270 (CurrentState.NoLineBreak || CurrentState.NoLineBreakInOperand ||
2271 (Current.is(TT: TT_TemplateOpener) &&
2272 CurrentState.ContainsUnwrappedBuilder));
2273 State.Stack.push_back(
2274 Elt: ParenState(&Current, NewIndent, LastSpace, AvoidBinPacking, NoLineBreak));
2275 auto &NewState = State.Stack.back();
2276 NewState.NestedBlockIndent = NestedBlockIndent;
2277 NewState.BreakBeforeParameter = BreakBeforeParameter;
2278 NewState.HasMultipleNestedBlocks = (Current.BlockParameterCount > 1);
2279
2280 if (Style.BraceWrapping.BeforeLambdaBody && Current.Next &&
2281 Current.is(Kind: tok::l_paren)) {
2282 // Search for any parameter that is a lambda.
2283 FormatToken const *next = Current.Next;
2284 while (next) {
2285 if (next->is(TT: TT_LambdaLSquare)) {
2286 NewState.HasMultipleNestedBlocks = true;
2287 break;
2288 }
2289 next = next->Next;
2290 }
2291 }
2292
2293 NewState.IsInsideObjCArrayLiteral = Current.is(TT: TT_ArrayInitializerLSquare) &&
2294 Current.Previous &&
2295 Current.Previous->is(Kind: tok::at);
2296}
2297
2298void ContinuationIndenter::moveStatePastScopeCloser(LineState &State) {
2299 const FormatToken &Current = *State.NextToken;
2300 if (!Current.closesScope())
2301 return;
2302
2303 // If we encounter a closing ), ], } or >, we can remove a level from our
2304 // stacks.
2305 if (State.Stack.size() > 1 &&
2306 (Current.isOneOf(K1: tok::r_paren, K2: tok::r_square, Ks: TT_TemplateString) ||
2307 (Current.is(Kind: tok::r_brace) && State.NextToken != State.Line->First) ||
2308 State.NextToken->is(TT: TT_TemplateCloser) ||
2309 State.NextToken->is(TT: TT_TableGenListCloser) ||
2310 (Current.is(Kind: tok::greater) && Current.is(TT: TT_DictLiteral)))) {
2311 State.Stack.pop_back();
2312 }
2313
2314 auto &CurrentState = State.Stack.back();
2315
2316 // Reevaluate whether ObjC message arguments fit into one line.
2317 // If a receiver spans multiple lines, e.g.:
2318 // [[object block:^{
2319 // return 42;
2320 // }] a:42 b:42];
2321 // BreakBeforeParameter is calculated based on an incorrect assumption
2322 // (it is checked whether the whole expression fits into one line without
2323 // considering a line break inside a message receiver).
2324 // We check whether arguments fit after receiver scope closer (into the same
2325 // line).
2326 if (CurrentState.BreakBeforeParameter && Current.MatchingParen &&
2327 Current.MatchingParen->Previous) {
2328 const FormatToken &CurrentScopeOpener = *Current.MatchingParen->Previous;
2329 if (CurrentScopeOpener.is(TT: TT_ObjCMethodExpr) &&
2330 CurrentScopeOpener.MatchingParen) {
2331 int NecessarySpaceInLine =
2332 getLengthToMatchingParen(Tok: CurrentScopeOpener, Stack: State.Stack) +
2333 CurrentScopeOpener.TotalLength - Current.TotalLength - 1;
2334 if (State.Column + Current.ColumnWidth + NecessarySpaceInLine <=
2335 Style.ColumnLimit) {
2336 CurrentState.BreakBeforeParameter = false;
2337 }
2338 }
2339 }
2340
2341 if (Current.is(Kind: tok::r_square)) {
2342 // If this ends the array subscript expr, reset the corresponding value.
2343 const FormatToken *NextNonComment = Current.getNextNonComment();
2344 if (NextNonComment && NextNonComment->isNot(Kind: tok::l_square))
2345 CurrentState.StartOfArraySubscripts = 0;
2346 }
2347}
2348
2349void ContinuationIndenter::moveStateToNewBlock(LineState &State, bool NewLine) {
2350 if (Style.LambdaBodyIndentation == FormatStyle::LBI_OuterScope &&
2351 State.NextToken->is(TT: TT_LambdaLBrace) &&
2352 !State.Line->MightBeFunctionDecl) {
2353 const auto Indent = Style.IndentWidth * Style.BraceWrapping.IndentBraces;
2354 State.Stack.back().NestedBlockIndent = State.FirstIndent + Indent;
2355 }
2356 unsigned NestedBlockIndent = State.Stack.back().NestedBlockIndent;
2357 // ObjC block sometimes follow special indentation rules.
2358 unsigned NewIndent =
2359 NestedBlockIndent + (State.NextToken->is(TT: TT_ObjCBlockLBrace)
2360 ? Style.ObjCBlockIndentWidth
2361 : Style.IndentWidth);
2362
2363 // Even when wrapping before lambda body, the left brace can still be added to
2364 // the same line. This occurs when checking whether the whole lambda body can
2365 // go on a single line. In this case we have to make sure there are no line
2366 // breaks in the body, otherwise we could just end up with a regular lambda
2367 // body without the brace wrapped.
2368 bool NoLineBreak = Style.BraceWrapping.BeforeLambdaBody && !NewLine &&
2369 State.NextToken->is(TT: TT_LambdaLBrace);
2370
2371 State.Stack.push_back(Elt: ParenState(State.NextToken, NewIndent,
2372 State.Stack.back().LastSpace,
2373 /*AvoidBinPacking=*/true, NoLineBreak));
2374 State.Stack.back().NestedBlockIndent = NestedBlockIndent;
2375 State.Stack.back().BreakBeforeParameter = true;
2376}
2377
2378static unsigned getLastLineEndColumn(StringRef Text, unsigned StartColumn,
2379 unsigned TabWidth,
2380 encoding::Encoding Encoding) {
2381 size_t LastNewlinePos = Text.find_last_of(Chars: "\n");
2382 if (LastNewlinePos == StringRef::npos) {
2383 return StartColumn +
2384 encoding::columnWidthWithTabs(Text, StartColumn, TabWidth, Encoding);
2385 } else {
2386 return encoding::columnWidthWithTabs(Text: Text.substr(Start: LastNewlinePos),
2387 /*StartColumn=*/0, TabWidth, Encoding);
2388 }
2389}
2390
2391unsigned ContinuationIndenter::reformatRawStringLiteral(
2392 const FormatToken &Current, LineState &State,
2393 const FormatStyle &RawStringStyle, bool DryRun, bool Newline) {
2394 unsigned StartColumn = State.Column - Current.ColumnWidth;
2395 StringRef OldDelimiter = *getRawStringDelimiter(TokenText: Current.TokenText);
2396 StringRef NewDelimiter =
2397 getCanonicalRawStringDelimiter(Style, Language: RawStringStyle.Language);
2398 if (NewDelimiter.empty())
2399 NewDelimiter = OldDelimiter;
2400 // The text of a raw string is between the leading 'R"delimiter(' and the
2401 // trailing 'delimiter)"'.
2402 unsigned OldPrefixSize = 3 + OldDelimiter.size();
2403 unsigned OldSuffixSize = 2 + OldDelimiter.size();
2404 // We create a virtual text environment which expects a null-terminated
2405 // string, so we cannot use StringRef.
2406 std::string RawText = std::string(
2407 Current.TokenText.substr(Start: OldPrefixSize).drop_back(N: OldSuffixSize));
2408 if (NewDelimiter != OldDelimiter) {
2409 // Don't update to the canonical delimiter 'deli' if ')deli"' occurs in the
2410 // raw string.
2411 std::string CanonicalDelimiterSuffix = (")" + NewDelimiter + "\"").str();
2412 if (StringRef(RawText).contains(Other: CanonicalDelimiterSuffix))
2413 NewDelimiter = OldDelimiter;
2414 }
2415
2416 unsigned NewPrefixSize = 3 + NewDelimiter.size();
2417 unsigned NewSuffixSize = 2 + NewDelimiter.size();
2418
2419 // The first start column is the column the raw text starts after formatting.
2420 unsigned FirstStartColumn = StartColumn + NewPrefixSize;
2421
2422 // The next start column is the intended indentation a line break inside
2423 // the raw string at level 0. It is determined by the following rules:
2424 // - if the content starts on newline, it is one level more than the current
2425 // indent, and
2426 // - if the content does not start on a newline, it is the first start
2427 // column.
2428 // These rules have the advantage that the formatted content both does not
2429 // violate the rectangle rule and visually flows within the surrounding
2430 // source.
2431 bool ContentStartsOnNewline = Current.TokenText[OldPrefixSize] == '\n';
2432 // If this token is the last parameter (checked by looking if it's followed by
2433 // `)` and is not on a newline, the base the indent off the line's nested
2434 // block indent. Otherwise, base the indent off the arguments indent, so we
2435 // can achieve:
2436 //
2437 // fffffffffff(1, 2, 3, R"pb(
2438 // key1: 1 #
2439 // key2: 2)pb");
2440 //
2441 // fffffffffff(1, 2, 3,
2442 // R"pb(
2443 // key1: 1 #
2444 // key2: 2
2445 // )pb");
2446 //
2447 // fffffffffff(1, 2, 3,
2448 // R"pb(
2449 // key1: 1 #
2450 // key2: 2
2451 // )pb",
2452 // 5);
2453 unsigned CurrentIndent =
2454 (!Newline && Current.Next && Current.Next->is(Kind: tok::r_paren))
2455 ? State.Stack.back().NestedBlockIndent
2456 : State.Stack.back().Indent.Total;
2457 unsigned NextStartColumn = ContentStartsOnNewline
2458 ? CurrentIndent + Style.IndentWidth
2459 : FirstStartColumn;
2460
2461 // The last start column is the column the raw string suffix starts if it is
2462 // put on a newline.
2463 // The last start column is the intended indentation of the raw string postfix
2464 // if it is put on a newline. It is determined by the following rules:
2465 // - if the raw string prefix starts on a newline, it is the column where
2466 // that raw string prefix starts, and
2467 // - if the raw string prefix does not start on a newline, it is the current
2468 // indent.
2469 unsigned LastStartColumn =
2470 Current.NewlinesBefore ? FirstStartColumn - NewPrefixSize : CurrentIndent;
2471
2472 std::pair<tooling::Replacements, unsigned> Fixes = internal::reformat(
2473 Style: RawStringStyle, Code: RawText, Ranges: {tooling::Range(0, RawText.size())},
2474 FirstStartColumn, NextStartColumn, LastStartColumn, FileName: "<stdin>",
2475 /*Status=*/nullptr);
2476
2477 auto NewCode = applyAllReplacements(Code: RawText, Replaces: Fixes.first);
2478 if (!NewCode)
2479 return addMultilineToken(Current, State);
2480 if (!DryRun) {
2481 if (NewDelimiter != OldDelimiter) {
2482 // In 'R"delimiter(...', the delimiter starts 2 characters after the start
2483 // of the token.
2484 SourceLocation PrefixDelimiterStart =
2485 Current.Tok.getLocation().getLocWithOffset(Offset: 2);
2486 auto PrefixErr = Whitespaces.addReplacement(Replacement: tooling::Replacement(
2487 SourceMgr, PrefixDelimiterStart, OldDelimiter.size(), NewDelimiter));
2488 if (PrefixErr) {
2489 llvm::errs()
2490 << "Failed to update the prefix delimiter of a raw string: "
2491 << llvm::toString(E: std::move(PrefixErr)) << "\n";
2492 }
2493 // In 'R"delimiter(...)delimiter"', the suffix delimiter starts at
2494 // position length - 1 - |delimiter|.
2495 SourceLocation SuffixDelimiterStart =
2496 Current.Tok.getLocation().getLocWithOffset(Offset: Current.TokenText.size() -
2497 1 - OldDelimiter.size());
2498 auto SuffixErr = Whitespaces.addReplacement(Replacement: tooling::Replacement(
2499 SourceMgr, SuffixDelimiterStart, OldDelimiter.size(), NewDelimiter));
2500 if (SuffixErr) {
2501 llvm::errs()
2502 << "Failed to update the suffix delimiter of a raw string: "
2503 << llvm::toString(E: std::move(SuffixErr)) << "\n";
2504 }
2505 }
2506 SourceLocation OriginLoc =
2507 Current.Tok.getLocation().getLocWithOffset(Offset: OldPrefixSize);
2508 for (const tooling::Replacement &Fix : Fixes.first) {
2509 auto Err = Whitespaces.addReplacement(Replacement: tooling::Replacement(
2510 SourceMgr, OriginLoc.getLocWithOffset(Offset: Fix.getOffset()),
2511 Fix.getLength(), Fix.getReplacementText()));
2512 if (Err) {
2513 llvm::errs() << "Failed to reformat raw string: "
2514 << llvm::toString(E: std::move(Err)) << "\n";
2515 }
2516 }
2517 }
2518 unsigned RawLastLineEndColumn = getLastLineEndColumn(
2519 Text: *NewCode, StartColumn: FirstStartColumn, TabWidth: Style.TabWidth, Encoding);
2520 State.Column = RawLastLineEndColumn + NewSuffixSize;
2521 // Since we're updating the column to after the raw string literal here, we
2522 // have to manually add the penalty for the prefix R"delim( over the column
2523 // limit.
2524 unsigned PrefixExcessCharacters =
2525 StartColumn + NewPrefixSize > Style.ColumnLimit
2526 ? StartColumn + NewPrefixSize - Style.ColumnLimit
2527 : 0;
2528 bool IsMultiline =
2529 ContentStartsOnNewline || (NewCode->find(c: '\n') != std::string::npos);
2530 if (IsMultiline) {
2531 // Break before further function parameters on all levels.
2532 for (ParenState &Paren : State.Stack)
2533 Paren.BreakBeforeParameter = true;
2534 }
2535 return Fixes.second + PrefixExcessCharacters * Style.PenaltyExcessCharacter;
2536}
2537
2538unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
2539 LineState &State) {
2540 // Break before further function parameters on all levels.
2541 for (ParenState &Paren : State.Stack)
2542 Paren.BreakBeforeParameter = true;
2543
2544 unsigned ColumnsUsed = State.Column;
2545 // We can only affect layout of the first and the last line, so the penalty
2546 // for all other lines is constant, and we ignore it.
2547 State.Column = Current.LastLineColumnWidth;
2548
2549 if (ColumnsUsed > getColumnLimit(State))
2550 return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
2551 return 0;
2552}
2553
2554unsigned ContinuationIndenter::handleEndOfLine(const FormatToken &Current,
2555 LineState &State, bool DryRun,
2556 bool AllowBreak, bool Newline) {
2557 unsigned Penalty = 0;
2558 // Compute the raw string style to use in case this is a raw string literal
2559 // that can be reformatted.
2560 auto RawStringStyle = getRawStringStyle(Current, State);
2561 if (RawStringStyle && !Current.Finalized) {
2562 Penalty = reformatRawStringLiteral(Current, State, RawStringStyle: *RawStringStyle, DryRun,
2563 Newline);
2564 } else if (Current.IsMultiline && Current.isNot(Kind: TT_BlockComment)) {
2565 // Don't break multi-line tokens other than block comments and raw string
2566 // literals. Instead, just update the state.
2567 Penalty = addMultilineToken(Current, State);
2568 } else if (State.Line->Type != LT_ImportStatement) {
2569 // We generally don't break import statements.
2570 LineState OriginalState = State;
2571
2572 // Whether we force the reflowing algorithm to stay strictly within the
2573 // column limit.
2574 bool Strict = false;
2575 // Whether the first non-strict attempt at reflowing did intentionally
2576 // exceed the column limit.
2577 bool Exceeded = false;
2578 std::tie(args&: Penalty, args&: Exceeded) = breakProtrudingToken(
2579 Current, State, AllowBreak, /*DryRun=*/true, Strict);
2580 if (Exceeded) {
2581 // If non-strict reflowing exceeds the column limit, try whether strict
2582 // reflowing leads to an overall lower penalty.
2583 LineState StrictState = OriginalState;
2584 unsigned StrictPenalty =
2585 breakProtrudingToken(Current, State&: StrictState, AllowBreak,
2586 /*DryRun=*/true, /*Strict=*/true)
2587 .first;
2588 Strict = StrictPenalty <= Penalty;
2589 if (Strict) {
2590 Penalty = StrictPenalty;
2591 State = std::move(StrictState);
2592 }
2593 }
2594 if (!DryRun) {
2595 // If we're not in dry-run mode, apply the changes with the decision on
2596 // strictness made above.
2597 breakProtrudingToken(Current, State&: OriginalState, AllowBreak, /*DryRun=*/false,
2598 Strict);
2599 }
2600 }
2601 if (State.Column > getColumnLimit(State)) {
2602 unsigned ExcessCharacters = State.Column - getColumnLimit(State);
2603 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
2604 }
2605 return Penalty;
2606}
2607
2608// Returns the enclosing function name of a token, or the empty string if not
2609// found.
2610static StringRef getEnclosingFunctionName(const FormatToken &Current) {
2611 // Look for: 'function(' or 'function<templates>(' before Current.
2612 auto Tok = Current.getPreviousNonComment();
2613 if (!Tok || Tok->isNot(Kind: tok::l_paren))
2614 return "";
2615 Tok = Tok->getPreviousNonComment();
2616 if (!Tok)
2617 return "";
2618 if (Tok->is(TT: TT_TemplateCloser)) {
2619 Tok = Tok->MatchingParen;
2620 if (Tok)
2621 Tok = Tok->getPreviousNonComment();
2622 }
2623 if (!Tok || Tok->isNot(Kind: tok::identifier))
2624 return "";
2625 return Tok->TokenText;
2626}
2627
2628std::optional<FormatStyle>
2629ContinuationIndenter::getRawStringStyle(const FormatToken &Current,
2630 const LineState &State) {
2631 if (!Current.isStringLiteral())
2632 return std::nullopt;
2633 auto Delimiter = getRawStringDelimiter(TokenText: Current.TokenText);
2634 if (!Delimiter)
2635 return std::nullopt;
2636 auto RawStringStyle = RawStringFormats.getDelimiterStyle(Delimiter: *Delimiter);
2637 if (!RawStringStyle && Delimiter->empty()) {
2638 RawStringStyle = RawStringFormats.getEnclosingFunctionStyle(
2639 EnclosingFunction: getEnclosingFunctionName(Current));
2640 }
2641 if (!RawStringStyle)
2642 return std::nullopt;
2643 RawStringStyle->ColumnLimit = getColumnLimit(State);
2644 return RawStringStyle;
2645}
2646
2647std::unique_ptr<BreakableToken>
2648ContinuationIndenter::createBreakableToken(const FormatToken &Current,
2649 LineState &State, bool AllowBreak) {
2650 unsigned StartColumn = State.Column - Current.ColumnWidth;
2651 if (Current.isStringLiteral()) {
2652 // Strings in JSON cannot be broken. Breaking strings in JavaScript is
2653 // disabled for now.
2654 if (Style.isJson() || Style.isJavaScript() || !Style.BreakStringLiterals ||
2655 !AllowBreak) {
2656 return nullptr;
2657 }
2658
2659 // Don't break string literals inside preprocessor directives (except for
2660 // #define directives, as their contents are stored in separate lines and
2661 // are not affected by this check).
2662 // This way we avoid breaking code with line directives and unknown
2663 // preprocessor directives that contain long string literals.
2664 if (State.Line->Type == LT_PreprocessorDirective)
2665 return nullptr;
2666 // Exempts unterminated string literals from line breaking. The user will
2667 // likely want to terminate the string before any line breaking is done.
2668 if (Current.IsUnterminatedLiteral)
2669 return nullptr;
2670 // Don't break string literals inside Objective-C array literals (doing so
2671 // raises the warning -Wobjc-string-concatenation).
2672 if (State.Stack.back().IsInsideObjCArrayLiteral)
2673 return nullptr;
2674
2675 // The "DPI"/"DPI-C" in SystemVerilog direct programming interface
2676 // imports/exports cannot be split, e.g.
2677 // `import "DPI" function foo();`
2678 // FIXME: make this use same infra as C++ import checks
2679 if (Style.isVerilog() && Current.Previous &&
2680 Current.Previous->isOneOf(K1: tok::kw_export, K2: Keywords.kw_import)) {
2681 return nullptr;
2682 }
2683 StringRef Text = Current.TokenText;
2684
2685 // We need this to address the case where there is an unbreakable tail only
2686 // if certain other formatting decisions have been taken. The
2687 // UnbreakableTailLength of Current is an overapproximation in that case and
2688 // we need to be correct here.
2689 unsigned UnbreakableTailLength = (State.NextToken && canBreak(State))
2690 ? 0
2691 : Current.UnbreakableTailLength;
2692
2693 if (Style.isVerilog() || Style.isJava() || Style.isJavaScript() ||
2694 Style.isCSharp()) {
2695 BreakableStringLiteralUsingOperators::QuoteStyleType QuoteStyle;
2696 if (Style.isJavaScript() && Text.starts_with(Prefix: "'") &&
2697 Text.ends_with(Suffix: "'")) {
2698 QuoteStyle = BreakableStringLiteralUsingOperators::SingleQuotes;
2699 } else if (Style.isCSharp() && Text.starts_with(Prefix: "@\"") &&
2700 Text.ends_with(Suffix: "\"")) {
2701 QuoteStyle = BreakableStringLiteralUsingOperators::AtDoubleQuotes;
2702 } else if (Text.starts_with(Prefix: "\"") && Text.ends_with(Suffix: "\"")) {
2703 QuoteStyle = BreakableStringLiteralUsingOperators::DoubleQuotes;
2704 } else {
2705 return nullptr;
2706 }
2707 return std::make_unique<BreakableStringLiteralUsingOperators>(
2708 args: Current, args&: QuoteStyle,
2709 /*UnindentPlus=*/args: shouldUnindentNextOperator(Tok: Current), args&: StartColumn,
2710 args&: UnbreakableTailLength, args: State.Line->InPPDirective, args&: Encoding, args&: Style);
2711 }
2712
2713 StringRef Prefix;
2714 StringRef Postfix;
2715 // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
2716 // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
2717 // reduce the overhead) for each FormatToken, which is a string, so that we
2718 // don't run multiple checks here on the hot path.
2719 if ((Text.ends_with(Suffix: Postfix = "\"") &&
2720 (Text.starts_with(Prefix: Prefix = "@\"") || Text.starts_with(Prefix: Prefix = "\"") ||
2721 Text.starts_with(Prefix: Prefix = "u\"") ||
2722 Text.starts_with(Prefix: Prefix = "U\"") ||
2723 Text.starts_with(Prefix: Prefix = "u8\"") ||
2724 Text.starts_with(Prefix: Prefix = "L\""))) ||
2725 (Text.starts_with(Prefix: Prefix = "_T(\"") &&
2726 Text.ends_with(Suffix: Postfix = "\")"))) {
2727 return std::make_unique<BreakableStringLiteral>(
2728 args: Current, args&: StartColumn, args&: Prefix, args&: Postfix, args&: UnbreakableTailLength,
2729 args: State.Line->InPPDirective, args&: Encoding, args&: Style);
2730 }
2731 } else if (Current.is(TT: TT_BlockComment)) {
2732 if (Style.ReflowComments == FormatStyle::RCS_Never ||
2733 // If a comment token switches formatting, like
2734 // /* clang-format on */, we don't want to break it further,
2735 // but we may still want to adjust its indentation.
2736 switchesFormatting(Token: Current)) {
2737 return nullptr;
2738 }
2739 return std::make_unique<BreakableBlockComment>(
2740 args: Current, args&: StartColumn, args: Current.OriginalColumn, args: !Current.Previous,
2741 args: State.Line->InPPDirective, args&: Encoding, args&: Style, args: Whitespaces.useCRLF());
2742 } else if (Current.is(TT: TT_LineComment) &&
2743 (!Current.Previous ||
2744 Current.Previous->isNot(Kind: TT_ImplicitStringLiteral))) {
2745 bool RegularComments = [&]() {
2746 for (const FormatToken *T = &Current; T && T->is(TT: TT_LineComment);
2747 T = T->Next) {
2748 if (!(T->TokenText.starts_with(Prefix: "//") || T->TokenText.starts_with(Prefix: "#")))
2749 return false;
2750 }
2751 return true;
2752 }();
2753 if (Style.ReflowComments == FormatStyle::RCS_Never ||
2754 CommentPragmasRegex.match(String: Current.TokenText.substr(Start: 2)) ||
2755 switchesFormatting(Token: Current) || !RegularComments) {
2756 return nullptr;
2757 }
2758 return std::make_unique<BreakableLineCommentSection>(
2759 args: Current, args&: StartColumn, /*InPPDirective=*/args: false, args&: Encoding, args&: Style);
2760 }
2761 return nullptr;
2762}
2763
2764std::pair<unsigned, bool>
2765ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
2766 LineState &State, bool AllowBreak,
2767 bool DryRun, bool Strict) {
2768 std::unique_ptr<const BreakableToken> Token =
2769 createBreakableToken(Current, State, AllowBreak);
2770 if (!Token)
2771 return {0, false};
2772 assert(Token->getLineCount() > 0);
2773 unsigned ColumnLimit = getColumnLimit(State);
2774 if (Current.is(TT: TT_LineComment)) {
2775 // We don't insert backslashes when breaking line comments.
2776 ColumnLimit = Style.ColumnLimit;
2777 }
2778 if (ColumnLimit == 0) {
2779 // To make the rest of the function easier set the column limit to the
2780 // maximum, if there should be no limit.
2781 ColumnLimit = std::numeric_limits<decltype(ColumnLimit)>::max();
2782 }
2783 if (Current.UnbreakableTailLength >= ColumnLimit)
2784 return {0, false};
2785 // ColumnWidth was already accounted into State.Column before calling
2786 // breakProtrudingToken.
2787 unsigned StartColumn = State.Column - Current.ColumnWidth;
2788 unsigned NewBreakPenalty = Current.isStringLiteral()
2789 ? Style.PenaltyBreakString
2790 : Style.PenaltyBreakComment;
2791 // Stores whether we intentionally decide to let a line exceed the column
2792 // limit.
2793 bool Exceeded = false;
2794 // Stores whether we introduce a break anywhere in the token.
2795 bool BreakInserted = Token->introducesBreakBeforeToken();
2796 // Store whether we inserted a new line break at the end of the previous
2797 // logical line.
2798 bool NewBreakBefore = false;
2799 // We use a conservative reflowing strategy. Reflow starts after a line is
2800 // broken or the corresponding whitespace compressed. Reflow ends as soon as a
2801 // line that doesn't get reflown with the previous line is reached.
2802 bool Reflow = false;
2803 // Keep track of where we are in the token:
2804 // Where we are in the content of the current logical line.
2805 unsigned TailOffset = 0;
2806 // The column number we're currently at.
2807 unsigned ContentStartColumn =
2808 Token->getContentStartColumn(LineIndex: 0, /*Break=*/false);
2809 // The number of columns left in the current logical line after TailOffset.
2810 unsigned RemainingTokenColumns =
2811 Token->getRemainingLength(LineIndex: 0, Offset: TailOffset, StartColumn: ContentStartColumn);
2812 // Adapt the start of the token, for example indent.
2813 if (!DryRun)
2814 Token->adaptStartOfLine(LineIndex: 0, Whitespaces);
2815
2816 unsigned ContentIndent = 0;
2817 unsigned Penalty = 0;
2818 LLVM_DEBUG(llvm::dbgs() << "Breaking protruding token at column "
2819 << StartColumn << ".\n");
2820 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
2821 LineIndex != EndIndex; ++LineIndex) {
2822 LLVM_DEBUG(llvm::dbgs()
2823 << " Line: " << LineIndex << " (Reflow: " << Reflow << ")\n");
2824 NewBreakBefore = false;
2825 // If we did reflow the previous line, we'll try reflowing again. Otherwise
2826 // we'll start reflowing if the current line is broken or whitespace is
2827 // compressed.
2828 bool TryReflow = Reflow;
2829 // Break the current token until we can fit the rest of the line.
2830 while (ContentStartColumn + RemainingTokenColumns > ColumnLimit) {
2831 LLVM_DEBUG(llvm::dbgs() << " Over limit, need: "
2832 << (ContentStartColumn + RemainingTokenColumns)
2833 << ", space: " << ColumnLimit
2834 << ", reflown prefix: " << ContentStartColumn
2835 << ", offset in line: " << TailOffset << "\n");
2836 // If the current token doesn't fit, find the latest possible split in the
2837 // current line so that breaking at it will be under the column limit.
2838 // FIXME: Use the earliest possible split while reflowing to correctly
2839 // compress whitespace within a line.
2840 BreakableToken::Split Split =
2841 Token->getSplit(LineIndex, TailOffset, ColumnLimit,
2842 ContentStartColumn, CommentPragmasRegex);
2843 if (Split.first == StringRef::npos) {
2844 // No break opportunity - update the penalty and continue with the next
2845 // logical line.
2846 if (LineIndex < EndIndex - 1) {
2847 // The last line's penalty is handled in addNextStateToQueue() or when
2848 // calling replaceWhitespaceAfterLastLine below.
2849 Penalty += Style.PenaltyExcessCharacter *
2850 (ContentStartColumn + RemainingTokenColumns - ColumnLimit);
2851 }
2852 LLVM_DEBUG(llvm::dbgs() << " No break opportunity.\n");
2853 break;
2854 }
2855 assert(Split.first != 0);
2856
2857 if (Token->supportsReflow()) {
2858 // Check whether the next natural split point after the current one can
2859 // still fit the line, either because we can compress away whitespace,
2860 // or because the penalty the excess characters introduce is lower than
2861 // the break penalty.
2862 // We only do this for tokens that support reflowing, and thus allow us
2863 // to change the whitespace arbitrarily (e.g. comments).
2864 // Other tokens, like string literals, can be broken on arbitrary
2865 // positions.
2866
2867 // First, compute the columns from TailOffset to the next possible split
2868 // position.
2869 // For example:
2870 // ColumnLimit: |
2871 // // Some text that breaks
2872 // ^ tail offset
2873 // ^-- split
2874 // ^-------- to split columns
2875 // ^--- next split
2876 // ^--------------- to next split columns
2877 unsigned ToSplitColumns = Token->getRangeLength(
2878 LineIndex, Offset: TailOffset, Length: Split.first, StartColumn: ContentStartColumn);
2879 LLVM_DEBUG(llvm::dbgs() << " ToSplit: " << ToSplitColumns << "\n");
2880
2881 BreakableToken::Split NextSplit = Token->getSplit(
2882 LineIndex, TailOffset: TailOffset + Split.first + Split.second, ColumnLimit,
2883 ContentStartColumn: ContentStartColumn + ToSplitColumns + 1, CommentPragmasRegex);
2884 // Compute the columns necessary to fit the next non-breakable sequence
2885 // into the current line.
2886 unsigned ToNextSplitColumns = 0;
2887 if (NextSplit.first == StringRef::npos) {
2888 ToNextSplitColumns = Token->getRemainingLength(LineIndex, Offset: TailOffset,
2889 StartColumn: ContentStartColumn);
2890 } else {
2891 ToNextSplitColumns = Token->getRangeLength(
2892 LineIndex, Offset: TailOffset,
2893 Length: Split.first + Split.second + NextSplit.first, StartColumn: ContentStartColumn);
2894 }
2895 // Compress the whitespace between the break and the start of the next
2896 // unbreakable sequence.
2897 ToNextSplitColumns =
2898 Token->getLengthAfterCompression(RemainingTokenColumns: ToNextSplitColumns, Split);
2899 LLVM_DEBUG(llvm::dbgs()
2900 << " ContentStartColumn: " << ContentStartColumn << "\n");
2901 LLVM_DEBUG(llvm::dbgs()
2902 << " ToNextSplit: " << ToNextSplitColumns << "\n");
2903 // If the whitespace compression makes us fit, continue on the current
2904 // line.
2905 bool ContinueOnLine =
2906 ContentStartColumn + ToNextSplitColumns <= ColumnLimit;
2907 unsigned ExcessCharactersPenalty = 0;
2908 if (!ContinueOnLine && !Strict) {
2909 // Similarly, if the excess characters' penalty is lower than the
2910 // penalty of introducing a new break, continue on the current line.
2911 ExcessCharactersPenalty =
2912 (ContentStartColumn + ToNextSplitColumns - ColumnLimit) *
2913 Style.PenaltyExcessCharacter;
2914 LLVM_DEBUG(llvm::dbgs()
2915 << " Penalty excess: " << ExcessCharactersPenalty
2916 << "\n break : " << NewBreakPenalty << "\n");
2917 if (ExcessCharactersPenalty < NewBreakPenalty) {
2918 Exceeded = true;
2919 ContinueOnLine = true;
2920 }
2921 }
2922 if (ContinueOnLine) {
2923 LLVM_DEBUG(llvm::dbgs() << " Continuing on line...\n");
2924 // The current line fits after compressing the whitespace - reflow
2925 // the next line into it if possible.
2926 TryReflow = true;
2927 if (!DryRun) {
2928 Token->compressWhitespace(LineIndex, TailOffset, Split,
2929 Whitespaces);
2930 }
2931 // When we continue on the same line, leave one space between content.
2932 ContentStartColumn += ToSplitColumns + 1;
2933 Penalty += ExcessCharactersPenalty;
2934 TailOffset += Split.first + Split.second;
2935 RemainingTokenColumns = Token->getRemainingLength(
2936 LineIndex, Offset: TailOffset, StartColumn: ContentStartColumn);
2937 continue;
2938 }
2939 }
2940 LLVM_DEBUG(llvm::dbgs() << " Breaking...\n");
2941 // Update the ContentIndent only if the current line was not reflown with
2942 // the previous line, since in that case the previous line should still
2943 // determine the ContentIndent. Also never intent the last line.
2944 if (!Reflow)
2945 ContentIndent = Token->getContentIndent(LineIndex);
2946 LLVM_DEBUG(llvm::dbgs()
2947 << " ContentIndent: " << ContentIndent << "\n");
2948 ContentStartColumn = ContentIndent + Token->getContentStartColumn(
2949 LineIndex, /*Break=*/true);
2950
2951 unsigned NewRemainingTokenColumns = Token->getRemainingLength(
2952 LineIndex, Offset: TailOffset + Split.first + Split.second,
2953 StartColumn: ContentStartColumn);
2954 if (NewRemainingTokenColumns == 0) {
2955 // No content to indent.
2956 ContentIndent = 0;
2957 ContentStartColumn =
2958 Token->getContentStartColumn(LineIndex, /*Break=*/true);
2959 NewRemainingTokenColumns = Token->getRemainingLength(
2960 LineIndex, Offset: TailOffset + Split.first + Split.second,
2961 StartColumn: ContentStartColumn);
2962 }
2963
2964 // When breaking before a tab character, it may be moved by a few columns,
2965 // but will still be expanded to the next tab stop, so we don't save any
2966 // columns.
2967 if (NewRemainingTokenColumns >= RemainingTokenColumns) {
2968 // FIXME: Do we need to adjust the penalty?
2969 break;
2970 }
2971
2972 LLVM_DEBUG(llvm::dbgs() << " Breaking at: " << TailOffset + Split.first
2973 << ", " << Split.second << "\n");
2974 if (!DryRun) {
2975 Token->insertBreak(LineIndex, TailOffset, Split, ContentIndent,
2976 Whitespaces);
2977 }
2978
2979 Penalty += NewBreakPenalty;
2980 TailOffset += Split.first + Split.second;
2981 RemainingTokenColumns = NewRemainingTokenColumns;
2982 BreakInserted = true;
2983 NewBreakBefore = true;
2984 }
2985 // In case there's another line, prepare the state for the start of the next
2986 // line.
2987 if (LineIndex + 1 != EndIndex) {
2988 unsigned NextLineIndex = LineIndex + 1;
2989 if (NewBreakBefore) {
2990 // After breaking a line, try to reflow the next line into the current
2991 // one once RemainingTokenColumns fits.
2992 TryReflow = true;
2993 }
2994 if (TryReflow) {
2995 // We decided that we want to try reflowing the next line into the
2996 // current one.
2997 // We will now adjust the state as if the reflow is successful (in
2998 // preparation for the next line), and see whether that works. If we
2999 // decide that we cannot reflow, we will later reset the state to the
3000 // start of the next line.
3001 Reflow = false;
3002 // As we did not continue breaking the line, RemainingTokenColumns is
3003 // known to fit after ContentStartColumn. Adapt ContentStartColumn to
3004 // the position at which we want to format the next line if we do
3005 // actually reflow.
3006 // When we reflow, we need to add a space between the end of the current
3007 // line and the next line's start column.
3008 ContentStartColumn += RemainingTokenColumns + 1;
3009 // Get the split that we need to reflow next logical line into the end
3010 // of the current one; the split will include any leading whitespace of
3011 // the next logical line.
3012 BreakableToken::Split SplitBeforeNext =
3013 Token->getReflowSplit(LineIndex: NextLineIndex, CommentPragmasRegex);
3014 LLVM_DEBUG(llvm::dbgs()
3015 << " Size of reflown text: " << ContentStartColumn
3016 << "\n Potential reflow split: ");
3017 if (SplitBeforeNext.first != StringRef::npos) {
3018 LLVM_DEBUG(llvm::dbgs() << SplitBeforeNext.first << ", "
3019 << SplitBeforeNext.second << "\n");
3020 TailOffset = SplitBeforeNext.first + SplitBeforeNext.second;
3021 // If the rest of the next line fits into the current line below the
3022 // column limit, we can safely reflow.
3023 RemainingTokenColumns = Token->getRemainingLength(
3024 LineIndex: NextLineIndex, Offset: TailOffset, StartColumn: ContentStartColumn);
3025 Reflow = true;
3026 if (ContentStartColumn + RemainingTokenColumns > ColumnLimit) {
3027 LLVM_DEBUG(llvm::dbgs()
3028 << " Over limit after reflow, need: "
3029 << (ContentStartColumn + RemainingTokenColumns)
3030 << ", space: " << ColumnLimit
3031 << ", reflown prefix: " << ContentStartColumn
3032 << ", offset in line: " << TailOffset << "\n");
3033 // If the whole next line does not fit, try to find a point in
3034 // the next line at which we can break so that attaching the part
3035 // of the next line to that break point onto the current line is
3036 // below the column limit.
3037 BreakableToken::Split Split =
3038 Token->getSplit(LineIndex: NextLineIndex, TailOffset, ColumnLimit,
3039 ContentStartColumn, CommentPragmasRegex);
3040 if (Split.first == StringRef::npos) {
3041 LLVM_DEBUG(llvm::dbgs() << " Did not find later break\n");
3042 Reflow = false;
3043 } else {
3044 // Check whether the first split point gets us below the column
3045 // limit. Note that we will execute this split below as part of
3046 // the normal token breaking and reflow logic within the line.
3047 unsigned ToSplitColumns = Token->getRangeLength(
3048 LineIndex: NextLineIndex, Offset: TailOffset, Length: Split.first, StartColumn: ContentStartColumn);
3049 if (ContentStartColumn + ToSplitColumns > ColumnLimit) {
3050 LLVM_DEBUG(llvm::dbgs() << " Next split protrudes, need: "
3051 << (ContentStartColumn + ToSplitColumns)
3052 << ", space: " << ColumnLimit);
3053 unsigned ExcessCharactersPenalty =
3054 (ContentStartColumn + ToSplitColumns - ColumnLimit) *
3055 Style.PenaltyExcessCharacter;
3056 if (NewBreakPenalty < ExcessCharactersPenalty)
3057 Reflow = false;
3058 }
3059 }
3060 }
3061 } else {
3062 LLVM_DEBUG(llvm::dbgs() << "not found.\n");
3063 }
3064 }
3065 if (!Reflow) {
3066 // If we didn't reflow into the next line, the only space to consider is
3067 // the next logical line. Reset our state to match the start of the next
3068 // line.
3069 TailOffset = 0;
3070 ContentStartColumn =
3071 Token->getContentStartColumn(LineIndex: NextLineIndex, /*Break=*/false);
3072 RemainingTokenColumns = Token->getRemainingLength(
3073 LineIndex: NextLineIndex, Offset: TailOffset, StartColumn: ContentStartColumn);
3074 // Adapt the start of the token, for example indent.
3075 if (!DryRun)
3076 Token->adaptStartOfLine(LineIndex: NextLineIndex, Whitespaces);
3077 } else {
3078 // If we found a reflow split and have added a new break before the next
3079 // line, we are going to remove the line break at the start of the next
3080 // logical line. For example, here we'll add a new line break after
3081 // 'text', and subsequently delete the line break between 'that' and
3082 // 'reflows'.
3083 // // some text that
3084 // // reflows
3085 // ->
3086 // // some text
3087 // // that reflows
3088 // When adding the line break, we also added the penalty for it, so we
3089 // need to subtract that penalty again when we remove the line break due
3090 // to reflowing.
3091 if (NewBreakBefore) {
3092 assert(Penalty >= NewBreakPenalty);
3093 Penalty -= NewBreakPenalty;
3094 }
3095 if (!DryRun)
3096 Token->reflow(LineIndex: NextLineIndex, Whitespaces);
3097 }
3098 }
3099 }
3100
3101 BreakableToken::Split SplitAfterLastLine =
3102 Token->getSplitAfterLastLine(TailOffset);
3103 if (SplitAfterLastLine.first != StringRef::npos) {
3104 LLVM_DEBUG(llvm::dbgs() << "Replacing whitespace after last line.\n");
3105
3106 // We add the last line's penalty here, since that line is going to be split
3107 // now.
3108 Penalty += Style.PenaltyExcessCharacter *
3109 (ContentStartColumn + RemainingTokenColumns - ColumnLimit);
3110
3111 if (!DryRun) {
3112 Token->replaceWhitespaceAfterLastLine(TailOffset, SplitAfterLastLine,
3113 Whitespaces);
3114 }
3115 ContentStartColumn =
3116 Token->getContentStartColumn(LineIndex: Token->getLineCount() - 1, /*Break=*/true);
3117 RemainingTokenColumns = Token->getRemainingLength(
3118 LineIndex: Token->getLineCount() - 1,
3119 Offset: TailOffset + SplitAfterLastLine.first + SplitAfterLastLine.second,
3120 StartColumn: ContentStartColumn);
3121 }
3122
3123 State.Column = ContentStartColumn + RemainingTokenColumns -
3124 Current.UnbreakableTailLength;
3125
3126 if (BreakInserted) {
3127 if (!DryRun)
3128 Token->updateAfterBroken(Whitespaces);
3129
3130 // If we break the token inside a parameter list, we need to break before
3131 // the next parameter on all levels, so that the next parameter is clearly
3132 // visible. Line comments already introduce a break.
3133 if (Current.isNot(Kind: TT_LineComment))
3134 for (ParenState &Paren : State.Stack)
3135 Paren.BreakBeforeParameter = true;
3136
3137 if (Current.is(TT: TT_BlockComment))
3138 State.NoContinuation = true;
3139
3140 State.Stack.back().LastSpace = StartColumn;
3141 }
3142
3143 Token->updateNextToken(State);
3144
3145 return {Penalty, Exceeded};
3146}
3147
3148unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
3149 // In preprocessor directives reserve two chars for trailing " \".
3150 return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
3151}
3152
3153bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
3154 const FormatToken &Current = *State.NextToken;
3155 if (!Current.isStringLiteral() || Current.is(TT: TT_ImplicitStringLiteral))
3156 return false;
3157 // We never consider raw string literals "multiline" for the purpose of
3158 // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
3159 // (see TokenAnnotator::mustBreakBefore().
3160 if (Current.TokenText.starts_with(Prefix: "R\""))
3161 return false;
3162 if (Current.IsMultiline)
3163 return true;
3164 if (Current.getNextNonComment() &&
3165 Current.getNextNonComment()->isStringLiteral()) {
3166 return true; // Implicit concatenation.
3167 }
3168 if (Style.ColumnLimit != 0 && Style.BreakStringLiterals &&
3169 State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
3170 Style.ColumnLimit) {
3171 return true; // String will be split.
3172 }
3173 return false;
3174}
3175
3176} // namespace format
3177} // namespace clang
3178