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