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