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