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