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