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