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