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