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