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