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