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