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