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