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