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