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