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