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