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