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 "BreakableToken.h" 16 #include "ContinuationIndenter.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 the length of everything up to the first possible line break after 29 // the ), ], } or > matching \c Tok. 30 static unsigned getLengthToMatchingParen(const FormatToken &Tok) { 31 if (!Tok.MatchingParen) 32 return 0; 33 FormatToken *End = Tok.MatchingParen; 34 while (End->Next && !End->Next->CanBreakBefore) { 35 End = End->Next; 36 } 37 return End->TotalLength - Tok.TotalLength + 1; 38 } 39 40 static unsigned getLengthToNextOperator(const FormatToken &Tok) { 41 if (!Tok.NextOperator) 42 return 0; 43 return Tok.NextOperator->TotalLength - Tok.TotalLength; 44 } 45 46 // Returns \c true if \c Tok is the "." or "->" of a call and starts the next 47 // segment of a builder type call. 48 static bool startsSegmentOfBuilderTypeCall(const FormatToken &Tok) { 49 return Tok.isMemberAccess() && Tok.Previous && Tok.Previous->closesScope(); 50 } 51 52 // Returns \c true if \c Current starts a new parameter. 53 static bool startsNextParameter(const FormatToken &Current, 54 const FormatStyle &Style) { 55 const FormatToken &Previous = *Current.Previous; 56 if (Current.is(TT_CtorInitializerComma) && 57 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) 58 return true; 59 if (Style.Language == FormatStyle::LK_Proto && Current.is(TT_SelectorName)) 60 return true; 61 return Previous.is(tok::comma) && !Current.isTrailingComment() && 62 ((Previous.isNot(TT_CtorInitializerComma) || 63 Style.BreakConstructorInitializers != 64 FormatStyle::BCIS_BeforeComma) && 65 (Previous.isNot(TT_InheritanceComma) || 66 !Style.BreakBeforeInheritanceComma)); 67 } 68 69 static bool opensProtoMessageField(const FormatToken &LessTok, 70 const FormatStyle &Style) { 71 if (LessTok.isNot(tok::less)) 72 return false; 73 return Style.Language == FormatStyle::LK_TextProto || 74 (Style.Language == FormatStyle::LK_Proto && 75 (LessTok.NestingLevel > 0 || 76 (LessTok.Previous && LessTok.Previous->is(tok::equal)))); 77 } 78 79 ContinuationIndenter::ContinuationIndenter(const FormatStyle &Style, 80 const AdditionalKeywords &Keywords, 81 const SourceManager &SourceMgr, 82 WhitespaceManager &Whitespaces, 83 encoding::Encoding Encoding, 84 bool BinPackInconclusiveFunctions) 85 : Style(Style), Keywords(Keywords), SourceMgr(SourceMgr), 86 Whitespaces(Whitespaces), Encoding(Encoding), 87 BinPackInconclusiveFunctions(BinPackInconclusiveFunctions), 88 CommentPragmasRegex(Style.CommentPragmas) {} 89 90 LineState ContinuationIndenter::getInitialState(unsigned FirstIndent, 91 const AnnotatedLine *Line, 92 bool DryRun) { 93 LineState State; 94 State.FirstIndent = FirstIndent; 95 State.Column = FirstIndent; 96 State.Line = Line; 97 State.NextToken = Line->First; 98 State.Stack.push_back(ParenState(FirstIndent, FirstIndent, 99 /*AvoidBinPacking=*/false, 100 /*NoLineBreak=*/false)); 101 State.LineContainsContinuedForLoopSection = false; 102 State.StartOfStringLiteral = 0; 103 State.StartOfLineLevel = 0; 104 State.LowestLevelOnLine = 0; 105 State.IgnoreStackForComparison = false; 106 107 if (Style.Language == FormatStyle::LK_TextProto) { 108 // We need this in order to deal with the bin packing of text fields at 109 // global scope. 110 State.Stack.back().AvoidBinPacking = true; 111 State.Stack.back().BreakBeforeParameter = true; 112 } 113 114 // The first token has already been indented and thus consumed. 115 moveStateToNextToken(State, DryRun, /*Newline=*/false); 116 return State; 117 } 118 119 bool ContinuationIndenter::canBreak(const LineState &State) { 120 const FormatToken &Current = *State.NextToken; 121 const FormatToken &Previous = *Current.Previous; 122 assert(&Previous == Current.Previous); 123 if (!Current.CanBreakBefore && 124 !(State.Stack.back().BreakBeforeClosingBrace && 125 Current.closesBlockOrBlockTypeList(Style))) 126 return false; 127 // The opening "{" of a braced list has to be on the same line as the first 128 // element if it is nested in another braced init list or function call. 129 if (!Current.MustBreakBefore && Previous.is(tok::l_brace) && 130 Previous.isNot(TT_DictLiteral) && Previous.BlockKind == BK_BracedInit && 131 Previous.Previous && 132 Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma)) 133 return false; 134 // This prevents breaks like: 135 // ... 136 // SomeParameter, OtherParameter).DoSomething( 137 // ... 138 // As they hide "DoSomething" and are generally bad for readability. 139 if (Previous.opensScope() && Previous.isNot(tok::l_brace) && 140 State.LowestLevelOnLine < State.StartOfLineLevel && 141 State.LowestLevelOnLine < Current.NestingLevel) 142 return false; 143 if (Current.isMemberAccess() && State.Stack.back().ContainsUnwrappedBuilder) 144 return false; 145 146 // Don't create a 'hanging' indent if there are multiple blocks in a single 147 // statement. 148 if (Previous.is(tok::l_brace) && State.Stack.size() > 1 && 149 State.Stack[State.Stack.size() - 2].NestedBlockInlined && 150 State.Stack[State.Stack.size() - 2].HasMultipleNestedBlocks) 151 return false; 152 153 // Don't break after very short return types (e.g. "void") as that is often 154 // unexpected. 155 if (Current.is(TT_FunctionDeclarationName) && State.Column < 6) { 156 if (Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None) 157 return false; 158 } 159 160 // If binary operators are moved to the next line (including commas for some 161 // styles of constructor initializers), that's always ok. 162 if (!Current.isOneOf(TT_BinaryOperator, tok::comma) && 163 State.Stack.back().NoLineBreakInOperand) 164 return false; 165 166 return !State.Stack.back().NoLineBreak; 167 } 168 169 bool ContinuationIndenter::mustBreak(const LineState &State) { 170 const FormatToken &Current = *State.NextToken; 171 const FormatToken &Previous = *Current.Previous; 172 if (Current.MustBreakBefore || Current.is(TT_InlineASMColon)) 173 return true; 174 if (State.Stack.back().BreakBeforeClosingBrace && 175 Current.closesBlockOrBlockTypeList(Style)) 176 return true; 177 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection) 178 return true; 179 if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) || 180 (Previous.is(TT_TemplateCloser) && Current.is(TT_StartOfName) && 181 Style.isCpp() && 182 // FIXME: This is a temporary workaround for the case where clang-format 183 // sets BreakBeforeParameter to avoid bin packing and this creates a 184 // completely unnecessary line break after a template type that isn't 185 // line-wrapped. 186 (Previous.NestingLevel == 1 || Style.BinPackParameters)) || 187 (Style.BreakBeforeTernaryOperators && Current.is(TT_ConditionalExpr) && 188 Previous.isNot(tok::question)) || 189 (!Style.BreakBeforeTernaryOperators && 190 Previous.is(TT_ConditionalExpr))) && 191 State.Stack.back().BreakBeforeParameter && !Current.isTrailingComment() && 192 !Current.isOneOf(tok::r_paren, tok::r_brace)) 193 return true; 194 if (((Previous.is(TT_DictLiteral) && Previous.is(tok::l_brace)) || 195 (Previous.is(TT_ArrayInitializerLSquare) && 196 Previous.ParameterCount > 1) || 197 opensProtoMessageField(Previous, Style)) && 198 Style.ColumnLimit > 0 && 199 getLengthToMatchingParen(Previous) + State.Column - 1 > 200 getColumnLimit(State)) 201 return true; 202 203 const FormatToken &BreakConstructorInitializersToken = 204 Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon 205 ? Previous 206 : Current; 207 if (BreakConstructorInitializersToken.is(TT_CtorInitializerColon) && 208 (State.Column + State.Line->Last->TotalLength - Previous.TotalLength > 209 getColumnLimit(State) || 210 State.Stack.back().BreakBeforeParameter) && 211 (Style.AllowShortFunctionsOnASingleLine != FormatStyle::SFS_All || 212 Style.BreakConstructorInitializers != FormatStyle::BCIS_BeforeColon || 213 Style.ColumnLimit != 0)) 214 return true; 215 216 if (Current.is(TT_ObjCMethodExpr) && !Previous.is(TT_SelectorName) && 217 State.Line->startsWith(TT_ObjCMethodSpecifier)) 218 return true; 219 if (Current.is(TT_SelectorName) && State.Stack.back().ObjCSelectorNameFound && 220 State.Stack.back().BreakBeforeParameter) 221 return true; 222 223 unsigned NewLineColumn = getNewLineColumn(State); 224 if (Current.isMemberAccess() && Style.ColumnLimit != 0 && 225 State.Column + getLengthToNextOperator(Current) > Style.ColumnLimit && 226 (State.Column > NewLineColumn || 227 Current.NestingLevel < State.StartOfLineLevel)) 228 return true; 229 230 if (startsSegmentOfBuilderTypeCall(Current) && 231 (State.Stack.back().CallContinuation != 0 || 232 State.Stack.back().BreakBeforeParameter) && 233 // JavaScript is treated different here as there is a frequent pattern: 234 // SomeFunction(function() { 235 // ... 236 // }.bind(...)); 237 // FIXME: We should find a more generic solution to this problem. 238 !(State.Column <= NewLineColumn && 239 Style.Language == FormatStyle::LK_JavaScript)) 240 return true; 241 242 if (State.Column <= NewLineColumn) 243 return false; 244 245 if (Style.AlwaysBreakBeforeMultilineStrings && 246 (NewLineColumn == State.FirstIndent + Style.ContinuationIndentWidth || 247 Previous.is(tok::comma) || Current.NestingLevel < 2) && 248 !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at) && 249 !Previous.isOneOf(TT_InlineASMColon, TT_ConditionalExpr) && 250 nextIsMultilineString(State)) 251 return true; 252 253 // Using CanBreakBefore here and below takes care of the decision whether the 254 // current style uses wrapping before or after operators for the given 255 // operator. 256 if (Previous.is(TT_BinaryOperator) && Current.CanBreakBefore) { 257 // If we need to break somewhere inside the LHS of a binary expression, we 258 // should also break after the operator. Otherwise, the formatting would 259 // hide the operator precedence, e.g. in: 260 // if (aaaaaaaaaaaaaa == 261 // bbbbbbbbbbbbbb && c) {.. 262 // For comparisons, we only apply this rule, if the LHS is a binary 263 // expression itself as otherwise, the line breaks seem superfluous. 264 // We need special cases for ">>" which we have split into two ">" while 265 // lexing in order to make template parsing easier. 266 bool IsComparison = (Previous.getPrecedence() == prec::Relational || 267 Previous.getPrecedence() == prec::Equality) && 268 Previous.Previous && 269 Previous.Previous->isNot(TT_BinaryOperator); // For >>. 270 bool LHSIsBinaryExpr = 271 Previous.Previous && Previous.Previous->EndsBinaryExpression; 272 if ((!IsComparison || LHSIsBinaryExpr) && !Current.isTrailingComment() && 273 Previous.getPrecedence() != prec::Assignment && 274 State.Stack.back().BreakBeforeParameter) 275 return true; 276 } else if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore && 277 State.Stack.back().BreakBeforeParameter) { 278 return true; 279 } 280 281 // Same as above, but for the first "<<" operator. 282 if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator) && 283 State.Stack.back().BreakBeforeParameter && 284 State.Stack.back().FirstLessLess == 0) 285 return true; 286 287 if (Current.NestingLevel == 0 && !Current.isTrailingComment()) { 288 // Always break after "template <...>" and leading annotations. This is only 289 // for cases where the entire line does not fit on a single line as a 290 // different LineFormatter would be used otherwise. 291 if (Previous.ClosesTemplateDeclaration) 292 return true; 293 if (Previous.is(TT_FunctionAnnotationRParen)) 294 return true; 295 if (Previous.is(TT_LeadingJavaAnnotation) && Current.isNot(tok::l_paren) && 296 Current.isNot(TT_LeadingJavaAnnotation)) 297 return true; 298 } 299 300 // If the return type spans multiple lines, wrap before the function name. 301 if ((Current.is(TT_FunctionDeclarationName) || 302 (Current.is(tok::kw_operator) && !Previous.is(tok::coloncolon))) && 303 !Previous.is(tok::kw_template) && State.Stack.back().BreakBeforeParameter) 304 return true; 305 306 // The following could be precomputed as they do not depend on the state. 307 // However, as they should take effect only if the UnwrappedLine does not fit 308 // into the ColumnLimit, they are checked here in the ContinuationIndenter. 309 if (Style.ColumnLimit != 0 && Previous.BlockKind == BK_Block && 310 Previous.is(tok::l_brace) && !Current.isOneOf(tok::r_brace, tok::comment)) 311 return true; 312 313 if (Current.is(tok::lessless) && 314 ((Previous.is(tok::identifier) && Previous.TokenText == "endl") || 315 (Previous.Tok.isLiteral() && (Previous.TokenText.endswith("\\n\"") || 316 Previous.TokenText == "\'\\n\'")))) 317 return true; 318 319 return false; 320 } 321 322 unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline, 323 bool DryRun, 324 unsigned ExtraSpaces) { 325 const FormatToken &Current = *State.NextToken; 326 327 assert(!State.Stack.empty()); 328 if ((Current.is(TT_ImplicitStringLiteral) && 329 (Current.Previous->Tok.getIdentifierInfo() == nullptr || 330 Current.Previous->Tok.getIdentifierInfo()->getPPKeywordID() == 331 tok::pp_not_keyword))) { 332 unsigned EndColumn = 333 SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getEnd()); 334 if (Current.LastNewlineOffset != 0) { 335 // If there is a newline within this token, the final column will solely 336 // determined by the current end column. 337 State.Column = EndColumn; 338 } else { 339 unsigned StartColumn = 340 SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getBegin()); 341 assert(EndColumn >= StartColumn); 342 State.Column += EndColumn - StartColumn; 343 } 344 moveStateToNextToken(State, DryRun, /*Newline=*/false); 345 return 0; 346 } 347 348 unsigned Penalty = 0; 349 if (Newline) 350 Penalty = addTokenOnNewLine(State, DryRun); 351 else 352 addTokenOnCurrentLine(State, DryRun, ExtraSpaces); 353 354 return moveStateToNextToken(State, DryRun, Newline) + Penalty; 355 } 356 357 void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun, 358 unsigned ExtraSpaces) { 359 FormatToken &Current = *State.NextToken; 360 const FormatToken &Previous = *State.NextToken->Previous; 361 if (Current.is(tok::equal) && 362 (State.Line->First->is(tok::kw_for) || Current.NestingLevel == 0) && 363 State.Stack.back().VariablePos == 0) { 364 State.Stack.back().VariablePos = State.Column; 365 // Move over * and & if they are bound to the variable name. 366 const FormatToken *Tok = &Previous; 367 while (Tok && State.Stack.back().VariablePos >= Tok->ColumnWidth) { 368 State.Stack.back().VariablePos -= Tok->ColumnWidth; 369 if (Tok->SpacesRequiredBefore != 0) 370 break; 371 Tok = Tok->Previous; 372 } 373 if (Previous.PartOfMultiVariableDeclStmt) 374 State.Stack.back().LastSpace = State.Stack.back().VariablePos; 375 } 376 377 unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces; 378 379 if (!DryRun) 380 Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, Spaces, 381 State.Column + Spaces); 382 383 // If "BreakBeforeInheritanceComma" mode, don't break within the inheritance 384 // declaration unless there is multiple inheritance. 385 if (Style.BreakBeforeInheritanceComma && Current.is(TT_InheritanceColon)) 386 State.Stack.back().NoLineBreak = true; 387 388 if (Current.is(TT_SelectorName) && 389 !State.Stack.back().ObjCSelectorNameFound) { 390 unsigned MinIndent = 391 std::max(State.FirstIndent + Style.ContinuationIndentWidth, 392 State.Stack.back().Indent); 393 unsigned FirstColonPos = State.Column + Spaces + Current.ColumnWidth; 394 if (Current.LongestObjCSelectorName == 0) 395 State.Stack.back().AlignColons = false; 396 else if (MinIndent + Current.LongestObjCSelectorName > FirstColonPos) 397 State.Stack.back().ColonPos = MinIndent + Current.LongestObjCSelectorName; 398 else 399 State.Stack.back().ColonPos = FirstColonPos; 400 } 401 402 // In "AlwaysBreak" mode, enforce wrapping directly after the parenthesis by 403 // disallowing any further line breaks if there is no line break after the 404 // opening parenthesis. Don't break if it doesn't conserve columns. 405 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_AlwaysBreak && 406 Previous.isOneOf(tok::l_paren, TT_TemplateOpener, tok::l_square) && 407 State.Column > getNewLineColumn(State) && 408 (!Previous.Previous || 409 !Previous.Previous->isOneOf(tok::kw_for, tok::kw_while, 410 tok::kw_switch)) && 411 // Don't do this for simple (no expressions) one-argument function calls 412 // as that feels like needlessly wasting whitespace, e.g.: 413 // 414 // caaaaaaaaaaaall( 415 // caaaaaaaaaaaall( 416 // caaaaaaaaaaaall( 417 // caaaaaaaaaaaaaaaaaaaaaaall(aaaaaaaaaaaaaa, aaaaaaaaa)))); 418 Current.FakeLParens.size() > 0 && 419 Current.FakeLParens.back() > prec::Unknown) 420 State.Stack.back().NoLineBreak = true; 421 if (Previous.is(TT_TemplateString) && Previous.opensScope()) 422 State.Stack.back().NoLineBreak = true; 423 424 if (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign && 425 Previous.opensScope() && Previous.isNot(TT_ObjCMethodExpr) && 426 (Current.isNot(TT_LineComment) || Previous.BlockKind == BK_BracedInit)) 427 State.Stack.back().Indent = State.Column + Spaces; 428 if (State.Stack.back().AvoidBinPacking && startsNextParameter(Current, Style)) 429 State.Stack.back().NoLineBreak = true; 430 if (startsSegmentOfBuilderTypeCall(Current) && 431 State.Column > getNewLineColumn(State)) 432 State.Stack.back().ContainsUnwrappedBuilder = true; 433 434 if (Current.is(TT_LambdaArrow) && Style.Language == FormatStyle::LK_Java) 435 State.Stack.back().NoLineBreak = true; 436 if (Current.isMemberAccess() && Previous.is(tok::r_paren) && 437 (Previous.MatchingParen && 438 (Previous.TotalLength - Previous.MatchingParen->TotalLength > 10))) 439 // If there is a function call with long parameters, break before trailing 440 // calls. This prevents things like: 441 // EXPECT_CALL(SomeLongParameter).Times( 442 // 2); 443 // We don't want to do this for short parameters as they can just be 444 // indexes. 445 State.Stack.back().NoLineBreak = true; 446 447 // Don't allow the RHS of an operator to be split over multiple lines unless 448 // there is a line-break right after the operator. 449 // Exclude relational operators, as there, it is always more desirable to 450 // have the LHS 'left' of the RHS. 451 const FormatToken *P = Current.getPreviousNonComment(); 452 if (!Current.is(tok::comment) && P && 453 (P->isOneOf(TT_BinaryOperator, tok::comma) || 454 (P->is(TT_ConditionalExpr) && P->is(tok::colon))) && 455 !P->isOneOf(TT_OverloadedOperator, TT_CtorInitializerComma) && 456 P->getPrecedence() != prec::Assignment && 457 P->getPrecedence() != prec::Relational) { 458 bool BreakBeforeOperator = 459 P->MustBreakBefore || P->is(tok::lessless) || 460 (P->is(TT_BinaryOperator) && 461 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None) || 462 (P->is(TT_ConditionalExpr) && Style.BreakBeforeTernaryOperators); 463 // Don't do this if there are only two operands. In these cases, there is 464 // always a nice vertical separation between them and the extra line break 465 // does not help. 466 bool HasTwoOperands = 467 P->OperatorIndex == 0 && !P->NextOperator && !P->is(TT_ConditionalExpr); 468 if ((!BreakBeforeOperator && !(HasTwoOperands && Style.AlignOperands)) || 469 (!State.Stack.back().LastOperatorWrapped && BreakBeforeOperator)) 470 State.Stack.back().NoLineBreakInOperand = true; 471 } 472 473 State.Column += Spaces; 474 if (Current.isNot(tok::comment) && Previous.is(tok::l_paren) && 475 Previous.Previous && 476 (Previous.Previous->isOneOf(tok::kw_if, tok::kw_for) || 477 Previous.Previous->endsSequence(tok::kw_constexpr, tok::kw_if))) { 478 // Treat the condition inside an if as if it was a second function 479 // parameter, i.e. let nested calls have a continuation indent. 480 State.Stack.back().LastSpace = State.Column; 481 State.Stack.back().NestedBlockIndent = State.Column; 482 } else if (!Current.isOneOf(tok::comment, tok::caret) && 483 ((Previous.is(tok::comma) && 484 !Previous.is(TT_OverloadedOperator)) || 485 (Previous.is(tok::colon) && Previous.is(TT_ObjCMethodExpr)))) { 486 State.Stack.back().LastSpace = State.Column; 487 } else if (Previous.is(TT_CtorInitializerColon) && 488 Style.BreakConstructorInitializers == 489 FormatStyle::BCIS_AfterColon) { 490 State.Stack.back().Indent = State.Column; 491 State.Stack.back().LastSpace = State.Column; 492 } else if ((Previous.isOneOf(TT_BinaryOperator, TT_ConditionalExpr, 493 TT_CtorInitializerColon)) && 494 ((Previous.getPrecedence() != prec::Assignment && 495 (Previous.isNot(tok::lessless) || Previous.OperatorIndex != 0 || 496 Previous.NextOperator)) || 497 Current.StartsBinaryExpression)) { 498 // Indent relative to the RHS of the expression unless this is a simple 499 // assignment without binary expression on the RHS. Also indent relative to 500 // unary operators and the colons of constructor initializers. 501 State.Stack.back().LastSpace = State.Column; 502 } else if (Previous.is(TT_InheritanceColon)) { 503 State.Stack.back().Indent = State.Column; 504 State.Stack.back().LastSpace = State.Column; 505 } else if (Previous.opensScope()) { 506 // If a function has a trailing call, indent all parameters from the 507 // opening parenthesis. This avoids confusing indents like: 508 // OuterFunction(InnerFunctionCall( // break 509 // ParameterToInnerFunction)) // break 510 // .SecondInnerFunctionCall(); 511 bool HasTrailingCall = false; 512 if (Previous.MatchingParen) { 513 const FormatToken *Next = Previous.MatchingParen->getNextNonComment(); 514 HasTrailingCall = Next && Next->isMemberAccess(); 515 } 516 if (HasTrailingCall && State.Stack.size() > 1 && 517 State.Stack[State.Stack.size() - 2].CallContinuation == 0) 518 State.Stack.back().LastSpace = State.Column; 519 } 520 } 521 522 unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State, 523 bool DryRun) { 524 FormatToken &Current = *State.NextToken; 525 const FormatToken &Previous = *State.NextToken->Previous; 526 527 // Extra penalty that needs to be added because of the way certain line 528 // breaks are chosen. 529 unsigned Penalty = 0; 530 531 const FormatToken *PreviousNonComment = Current.getPreviousNonComment(); 532 const FormatToken *NextNonComment = Previous.getNextNonComment(); 533 if (!NextNonComment) 534 NextNonComment = &Current; 535 // The first line break on any NestingLevel causes an extra penalty in order 536 // prefer similar line breaks. 537 if (!State.Stack.back().ContainsLineBreak) 538 Penalty += 15; 539 State.Stack.back().ContainsLineBreak = true; 540 541 Penalty += State.NextToken->SplitPenalty; 542 543 // Breaking before the first "<<" is generally not desirable if the LHS is 544 // short. Also always add the penalty if the LHS is split over multiple lines 545 // to avoid unnecessary line breaks that just work around this penalty. 546 if (NextNonComment->is(tok::lessless) && 547 State.Stack.back().FirstLessLess == 0 && 548 (State.Column <= Style.ColumnLimit / 3 || 549 State.Stack.back().BreakBeforeParameter)) 550 Penalty += Style.PenaltyBreakFirstLessLess; 551 552 State.Column = getNewLineColumn(State); 553 554 // Indent nested blocks relative to this column, unless in a very specific 555 // JavaScript special case where: 556 // 557 // var loooooong_name = 558 // function() { 559 // // code 560 // } 561 // 562 // is common and should be formatted like a free-standing function. The same 563 // goes for wrapping before the lambda return type arrow. 564 if (!Current.is(TT_LambdaArrow) && 565 (Style.Language != FormatStyle::LK_JavaScript || 566 Current.NestingLevel != 0 || !PreviousNonComment || 567 !PreviousNonComment->is(tok::equal) || 568 !Current.isOneOf(Keywords.kw_async, Keywords.kw_function))) 569 State.Stack.back().NestedBlockIndent = State.Column; 570 571 if (NextNonComment->isMemberAccess()) { 572 if (State.Stack.back().CallContinuation == 0) 573 State.Stack.back().CallContinuation = State.Column; 574 } else if (NextNonComment->is(TT_SelectorName)) { 575 if (!State.Stack.back().ObjCSelectorNameFound) { 576 if (NextNonComment->LongestObjCSelectorName == 0) { 577 State.Stack.back().AlignColons = false; 578 } else { 579 State.Stack.back().ColonPos = 580 (Style.IndentWrappedFunctionNames 581 ? std::max(State.Stack.back().Indent, 582 State.FirstIndent + Style.ContinuationIndentWidth) 583 : State.Stack.back().Indent) + 584 NextNonComment->LongestObjCSelectorName; 585 } 586 } else if (State.Stack.back().AlignColons && 587 State.Stack.back().ColonPos <= NextNonComment->ColumnWidth) { 588 State.Stack.back().ColonPos = State.Column + NextNonComment->ColumnWidth; 589 } 590 } else if (PreviousNonComment && PreviousNonComment->is(tok::colon) && 591 PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) { 592 // FIXME: This is hacky, find a better way. The problem is that in an ObjC 593 // method expression, the block should be aligned to the line starting it, 594 // e.g.: 595 // [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason 596 // ^(int *i) { 597 // // ... 598 // }]; 599 // Thus, we set LastSpace of the next higher NestingLevel, to which we move 600 // when we consume all of the "}"'s FakeRParens at the "{". 601 if (State.Stack.size() > 1) 602 State.Stack[State.Stack.size() - 2].LastSpace = 603 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 604 Style.ContinuationIndentWidth; 605 } 606 607 if ((PreviousNonComment && 608 PreviousNonComment->isOneOf(tok::comma, tok::semi) && 609 !State.Stack.back().AvoidBinPacking) || 610 Previous.is(TT_BinaryOperator)) 611 State.Stack.back().BreakBeforeParameter = false; 612 if (Previous.isOneOf(TT_TemplateCloser, TT_JavaAnnotation) && 613 Current.NestingLevel == 0) 614 State.Stack.back().BreakBeforeParameter = false; 615 if (NextNonComment->is(tok::question) || 616 (PreviousNonComment && PreviousNonComment->is(tok::question))) 617 State.Stack.back().BreakBeforeParameter = true; 618 if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore) 619 State.Stack.back().BreakBeforeParameter = false; 620 621 if (!DryRun) { 622 unsigned Newlines = std::max( 623 1u, std::min(Current.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1)); 624 bool ContinuePPDirective = 625 State.Line->InPPDirective && State.Line->Type != LT_ImportStatement; 626 Whitespaces.replaceWhitespace(Current, Newlines, State.Column, State.Column, 627 ContinuePPDirective); 628 } 629 630 if (!Current.isTrailingComment()) 631 State.Stack.back().LastSpace = State.Column; 632 if (Current.is(tok::lessless)) 633 // If we are breaking before a "<<", we always want to indent relative to 634 // RHS. This is necessary only for "<<", as we special-case it and don't 635 // always indent relative to the RHS. 636 State.Stack.back().LastSpace += 3; // 3 -> width of "<< ". 637 638 State.StartOfLineLevel = Current.NestingLevel; 639 State.LowestLevelOnLine = Current.NestingLevel; 640 641 // Any break on this level means that the parent level has been broken 642 // and we need to avoid bin packing there. 643 bool NestedBlockSpecialCase = 644 !Style.isCpp() && Current.is(tok::r_brace) && State.Stack.size() > 1 && 645 State.Stack[State.Stack.size() - 2].NestedBlockInlined; 646 if (!NestedBlockSpecialCase) 647 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) 648 State.Stack[i].BreakBeforeParameter = true; 649 650 if (PreviousNonComment && 651 !PreviousNonComment->isOneOf(tok::comma, tok::colon, tok::semi) && 652 (PreviousNonComment->isNot(TT_TemplateCloser) || 653 Current.NestingLevel != 0) && 654 !PreviousNonComment->isOneOf( 655 TT_BinaryOperator, TT_FunctionAnnotationRParen, TT_JavaAnnotation, 656 TT_LeadingJavaAnnotation) && 657 Current.isNot(TT_BinaryOperator) && !PreviousNonComment->opensScope()) 658 State.Stack.back().BreakBeforeParameter = true; 659 660 // If we break after { or the [ of an array initializer, we should also break 661 // before the corresponding } or ]. 662 if (PreviousNonComment && 663 (PreviousNonComment->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) || 664 opensProtoMessageField(*PreviousNonComment, Style) || 665 (PreviousNonComment->is(TT_TemplateString) && 666 PreviousNonComment->opensScope()))) 667 State.Stack.back().BreakBeforeClosingBrace = true; 668 669 if (State.Stack.back().AvoidBinPacking) { 670 // If we are breaking after '(', '{', '<', this is not bin packing 671 // unless AllowAllParametersOfDeclarationOnNextLine is false or this is a 672 // dict/object literal. 673 if (!Previous.isOneOf(tok::l_paren, tok::l_brace, TT_BinaryOperator) || 674 (!Style.AllowAllParametersOfDeclarationOnNextLine && 675 State.Line->MustBeDeclaration) || 676 Previous.is(TT_DictLiteral)) 677 State.Stack.back().BreakBeforeParameter = true; 678 } 679 680 return Penalty; 681 } 682 683 unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) { 684 if (!State.NextToken || !State.NextToken->Previous) 685 return 0; 686 FormatToken &Current = *State.NextToken; 687 const FormatToken &Previous = *Current.Previous; 688 // If we are continuing an expression, we want to use the continuation indent. 689 unsigned ContinuationIndent = 690 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 691 Style.ContinuationIndentWidth; 692 const FormatToken *PreviousNonComment = Current.getPreviousNonComment(); 693 const FormatToken *NextNonComment = Previous.getNextNonComment(); 694 if (!NextNonComment) 695 NextNonComment = &Current; 696 697 // Java specific bits. 698 if (Style.Language == FormatStyle::LK_Java && 699 Current.isOneOf(Keywords.kw_implements, Keywords.kw_extends)) 700 return std::max(State.Stack.back().LastSpace, 701 State.Stack.back().Indent + Style.ContinuationIndentWidth); 702 703 if (NextNonComment->is(tok::l_brace) && NextNonComment->BlockKind == BK_Block) 704 return Current.NestingLevel == 0 ? State.FirstIndent 705 : State.Stack.back().Indent; 706 if ((Current.isOneOf(tok::r_brace, tok::r_square) || 707 (Current.is(tok::greater) && 708 (Style.Language == FormatStyle::LK_Proto || 709 Style.Language == FormatStyle::LK_TextProto))) && 710 State.Stack.size() > 1) { 711 if (Current.closesBlockOrBlockTypeList(Style)) 712 return State.Stack[State.Stack.size() - 2].NestedBlockIndent; 713 if (Current.MatchingParen && 714 Current.MatchingParen->BlockKind == BK_BracedInit) 715 return State.Stack[State.Stack.size() - 2].LastSpace; 716 return State.FirstIndent; 717 } 718 // Indent a closing parenthesis at the previous level if followed by a semi or 719 // opening brace. This allows indentations such as: 720 // foo( 721 // a, 722 // ); 723 // function foo( 724 // a, 725 // ) { 726 // code(); // 727 // } 728 if (Current.is(tok::r_paren) && State.Stack.size() > 1 && 729 (!Current.Next || Current.Next->isOneOf(tok::semi, tok::l_brace))) 730 return State.Stack[State.Stack.size() - 2].LastSpace; 731 if (NextNonComment->is(TT_TemplateString) && NextNonComment->closesScope()) 732 return State.Stack[State.Stack.size() - 2].LastSpace; 733 if (Current.is(tok::identifier) && Current.Next && 734 (Current.Next->is(TT_DictLiteral) || 735 ((Style.Language == FormatStyle::LK_Proto || 736 Style.Language == FormatStyle::LK_TextProto) && 737 Current.Next->isOneOf(TT_TemplateOpener, tok::l_brace)))) 738 return State.Stack.back().Indent; 739 if (NextNonComment->is(TT_ObjCStringLiteral) && 740 State.StartOfStringLiteral != 0) 741 return State.StartOfStringLiteral - 1; 742 if (NextNonComment->isStringLiteral() && State.StartOfStringLiteral != 0) 743 return State.StartOfStringLiteral; 744 if (NextNonComment->is(tok::lessless) && 745 State.Stack.back().FirstLessLess != 0) 746 return State.Stack.back().FirstLessLess; 747 if (NextNonComment->isMemberAccess()) { 748 if (State.Stack.back().CallContinuation == 0) 749 return ContinuationIndent; 750 return State.Stack.back().CallContinuation; 751 } 752 if (State.Stack.back().QuestionColumn != 0 && 753 ((NextNonComment->is(tok::colon) && 754 NextNonComment->is(TT_ConditionalExpr)) || 755 Previous.is(TT_ConditionalExpr))) 756 return State.Stack.back().QuestionColumn; 757 if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0) 758 return State.Stack.back().VariablePos; 759 if ((PreviousNonComment && 760 (PreviousNonComment->ClosesTemplateDeclaration || 761 PreviousNonComment->isOneOf( 762 TT_AttributeParen, TT_FunctionAnnotationRParen, TT_JavaAnnotation, 763 TT_LeadingJavaAnnotation))) || 764 (!Style.IndentWrappedFunctionNames && 765 NextNonComment->isOneOf(tok::kw_operator, TT_FunctionDeclarationName))) 766 return std::max(State.Stack.back().LastSpace, State.Stack.back().Indent); 767 if (NextNonComment->is(TT_SelectorName)) { 768 if (!State.Stack.back().ObjCSelectorNameFound) { 769 if (NextNonComment->LongestObjCSelectorName == 0) 770 return State.Stack.back().Indent; 771 return (Style.IndentWrappedFunctionNames 772 ? std::max(State.Stack.back().Indent, 773 State.FirstIndent + Style.ContinuationIndentWidth) 774 : State.Stack.back().Indent) + 775 NextNonComment->LongestObjCSelectorName - 776 NextNonComment->ColumnWidth; 777 } 778 if (!State.Stack.back().AlignColons) 779 return State.Stack.back().Indent; 780 if (State.Stack.back().ColonPos > NextNonComment->ColumnWidth) 781 return State.Stack.back().ColonPos - NextNonComment->ColumnWidth; 782 return State.Stack.back().Indent; 783 } 784 if (NextNonComment->is(tok::colon) && NextNonComment->is(TT_ObjCMethodExpr)) 785 return State.Stack.back().ColonPos; 786 if (NextNonComment->is(TT_ArraySubscriptLSquare)) { 787 if (State.Stack.back().StartOfArraySubscripts != 0) 788 return State.Stack.back().StartOfArraySubscripts; 789 return ContinuationIndent; 790 } 791 792 // This ensure that we correctly format ObjC methods calls without inputs, 793 // i.e. where the last element isn't selector like: [callee method]; 794 if (NextNonComment->is(tok::identifier) && NextNonComment->FakeRParens == 0 && 795 NextNonComment->Next && NextNonComment->Next->is(TT_ObjCMethodExpr)) 796 return State.Stack.back().Indent; 797 798 if (NextNonComment->isOneOf(TT_StartOfName, TT_PointerOrReference) || 799 Previous.isOneOf(tok::coloncolon, tok::equal, TT_JsTypeColon)) 800 return ContinuationIndent; 801 if (PreviousNonComment && PreviousNonComment->is(tok::colon) && 802 PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) 803 return ContinuationIndent; 804 if (NextNonComment->is(TT_CtorInitializerComma)) 805 return State.Stack.back().Indent; 806 if (PreviousNonComment && PreviousNonComment->is(TT_CtorInitializerColon) && 807 Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon) 808 return State.Stack.back().Indent; 809 if (NextNonComment->isOneOf(TT_CtorInitializerColon, TT_InheritanceColon, 810 TT_InheritanceComma)) 811 return State.FirstIndent + Style.ConstructorInitializerIndentWidth; 812 if (Previous.is(tok::r_paren) && !Current.isBinaryOperator() && 813 !Current.isOneOf(tok::colon, tok::comment)) 814 return ContinuationIndent; 815 if (State.Stack.back().Indent == State.FirstIndent && PreviousNonComment && 816 PreviousNonComment->isNot(tok::r_brace)) 817 // Ensure that we fall back to the continuation indent width instead of 818 // just flushing continuations left. 819 return State.Stack.back().Indent + Style.ContinuationIndentWidth; 820 return State.Stack.back().Indent; 821 } 822 823 unsigned ContinuationIndenter::moveStateToNextToken(LineState &State, 824 bool DryRun, bool Newline) { 825 assert(State.Stack.size()); 826 const FormatToken &Current = *State.NextToken; 827 828 if (Current.isOneOf(tok::comma, TT_BinaryOperator)) 829 State.Stack.back().NoLineBreakInOperand = false; 830 if (Current.is(TT_InheritanceColon)) 831 State.Stack.back().AvoidBinPacking = true; 832 if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator)) { 833 if (State.Stack.back().FirstLessLess == 0) 834 State.Stack.back().FirstLessLess = State.Column; 835 else 836 State.Stack.back().LastOperatorWrapped = Newline; 837 } 838 if (Current.is(TT_BinaryOperator) && Current.isNot(tok::lessless)) 839 State.Stack.back().LastOperatorWrapped = Newline; 840 if (Current.is(TT_ConditionalExpr) && Current.Previous && 841 !Current.Previous->is(TT_ConditionalExpr)) 842 State.Stack.back().LastOperatorWrapped = Newline; 843 if (Current.is(TT_ArraySubscriptLSquare) && 844 State.Stack.back().StartOfArraySubscripts == 0) 845 State.Stack.back().StartOfArraySubscripts = State.Column; 846 if (Style.BreakBeforeTernaryOperators && Current.is(tok::question)) 847 State.Stack.back().QuestionColumn = State.Column; 848 if (!Style.BreakBeforeTernaryOperators && Current.isNot(tok::colon)) { 849 const FormatToken *Previous = Current.Previous; 850 while (Previous && Previous->isTrailingComment()) 851 Previous = Previous->Previous; 852 if (Previous && Previous->is(tok::question)) 853 State.Stack.back().QuestionColumn = State.Column; 854 } 855 if (!Current.opensScope() && !Current.closesScope() && 856 !Current.is(TT_PointerOrReference)) 857 State.LowestLevelOnLine = 858 std::min(State.LowestLevelOnLine, Current.NestingLevel); 859 if (Current.isMemberAccess()) 860 State.Stack.back().StartOfFunctionCall = 861 !Current.NextOperator ? 0 : State.Column; 862 if (Current.is(TT_SelectorName)) { 863 State.Stack.back().ObjCSelectorNameFound = true; 864 if (Style.IndentWrappedFunctionNames) { 865 State.Stack.back().Indent = 866 State.FirstIndent + Style.ContinuationIndentWidth; 867 } 868 } 869 if (Current.is(TT_CtorInitializerColon) && 870 Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon) { 871 // Indent 2 from the column, so: 872 // SomeClass::SomeClass() 873 // : First(...), ... 874 // Next(...) 875 // ^ line up here. 876 State.Stack.back().Indent = 877 State.Column + (Style.BreakConstructorInitializers == 878 FormatStyle::BCIS_BeforeComma ? 0 : 2); 879 State.Stack.back().NestedBlockIndent = State.Stack.back().Indent; 880 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine) 881 State.Stack.back().AvoidBinPacking = true; 882 State.Stack.back().BreakBeforeParameter = false; 883 } 884 if (Current.is(TT_CtorInitializerColon) && 885 Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon) { 886 State.Stack.back().Indent = 887 State.FirstIndent + Style.ConstructorInitializerIndentWidth; 888 State.Stack.back().NestedBlockIndent = State.Stack.back().Indent; 889 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine) 890 State.Stack.back().AvoidBinPacking = true; 891 } 892 if (Current.is(TT_InheritanceColon)) 893 State.Stack.back().Indent = 894 State.FirstIndent + Style.ContinuationIndentWidth; 895 if (Current.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) && Newline) 896 State.Stack.back().NestedBlockIndent = 897 State.Column + Current.ColumnWidth + 1; 898 if (Current.isOneOf(TT_LambdaLSquare, TT_LambdaArrow)) 899 State.Stack.back().LastSpace = State.Column; 900 901 // Insert scopes created by fake parenthesis. 902 const FormatToken *Previous = Current.getPreviousNonComment(); 903 904 // Add special behavior to support a format commonly used for JavaScript 905 // closures: 906 // SomeFunction(function() { 907 // foo(); 908 // bar(); 909 // }, a, b, c); 910 if (Current.isNot(tok::comment) && Previous && 911 Previous->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) && 912 !Previous->is(TT_DictLiteral) && State.Stack.size() > 1) { 913 if (State.Stack[State.Stack.size() - 2].NestedBlockInlined && Newline) 914 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) 915 State.Stack[i].NoLineBreak = true; 916 State.Stack[State.Stack.size() - 2].NestedBlockInlined = false; 917 } 918 if (Previous && (Previous->isOneOf(tok::l_paren, tok::comma, tok::colon) || 919 Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr)) && 920 !Previous->isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) { 921 State.Stack.back().NestedBlockInlined = 922 !Newline && 923 (Previous->isNot(tok::l_paren) || Previous->ParameterCount > 1); 924 } 925 926 moveStatePastFakeLParens(State, Newline); 927 moveStatePastScopeCloser(State); 928 if (Current.is(TT_TemplateString) && Current.opensScope()) 929 State.Stack.back().LastSpace = 930 (Current.IsMultiline ? Current.LastLineColumnWidth 931 : State.Column + Current.ColumnWidth) - 932 strlen("${"); 933 bool CanBreakProtrudingToken = !State.Stack.back().NoLineBreak && 934 !State.Stack.back().NoLineBreakInOperand; 935 moveStatePastScopeOpener(State, Newline); 936 moveStatePastFakeRParens(State); 937 938 if (Current.is(TT_ObjCStringLiteral) && State.StartOfStringLiteral == 0) 939 State.StartOfStringLiteral = State.Column + 1; 940 else if (Current.isStringLiteral() && State.StartOfStringLiteral == 0) 941 State.StartOfStringLiteral = State.Column; 942 else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) && 943 !Current.isStringLiteral()) 944 State.StartOfStringLiteral = 0; 945 946 State.Column += Current.ColumnWidth; 947 State.NextToken = State.NextToken->Next; 948 unsigned Penalty = 0; 949 if (CanBreakProtrudingToken) 950 Penalty = breakProtrudingToken(Current, State, DryRun); 951 if (State.Column > getColumnLimit(State)) { 952 unsigned ExcessCharacters = State.Column - getColumnLimit(State); 953 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters; 954 } 955 956 if (Current.Role) 957 Current.Role->formatFromToken(State, this, DryRun); 958 // If the previous has a special role, let it consume tokens as appropriate. 959 // It is necessary to start at the previous token for the only implemented 960 // role (comma separated list). That way, the decision whether or not to break 961 // after the "{" is already done and both options are tried and evaluated. 962 // FIXME: This is ugly, find a better way. 963 if (Previous && Previous->Role) 964 Penalty += Previous->Role->formatAfterToken(State, this, DryRun); 965 966 return Penalty; 967 } 968 969 void ContinuationIndenter::moveStatePastFakeLParens(LineState &State, 970 bool Newline) { 971 const FormatToken &Current = *State.NextToken; 972 const FormatToken *Previous = Current.getPreviousNonComment(); 973 974 // Don't add extra indentation for the first fake parenthesis after 975 // 'return', assignments or opening <({[. The indentation for these cases 976 // is special cased. 977 bool SkipFirstExtraIndent = 978 (Previous && (Previous->opensScope() || 979 Previous->isOneOf(tok::semi, tok::kw_return) || 980 (Previous->getPrecedence() == prec::Assignment && 981 Style.AlignOperands) || 982 Previous->is(TT_ObjCMethodExpr))); 983 for (SmallVectorImpl<prec::Level>::const_reverse_iterator 984 I = Current.FakeLParens.rbegin(), 985 E = Current.FakeLParens.rend(); 986 I != E; ++I) { 987 ParenState NewParenState = State.Stack.back(); 988 NewParenState.ContainsLineBreak = false; 989 NewParenState.LastOperatorWrapped = true; 990 NewParenState.NoLineBreak = 991 NewParenState.NoLineBreak || State.Stack.back().NoLineBreakInOperand; 992 993 // Don't propagate AvoidBinPacking into subexpressions of arg/param lists. 994 if (*I > prec::Comma) 995 NewParenState.AvoidBinPacking = false; 996 997 // Indent from 'LastSpace' unless these are fake parentheses encapsulating 998 // a builder type call after 'return' or, if the alignment after opening 999 // brackets is disabled. 1000 if (!Current.isTrailingComment() && 1001 (Style.AlignOperands || *I < prec::Assignment) && 1002 (!Previous || Previous->isNot(tok::kw_return) || 1003 (Style.Language != FormatStyle::LK_Java && *I > 0)) && 1004 (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign || 1005 *I != prec::Comma || Current.NestingLevel == 0)) 1006 NewParenState.Indent = 1007 std::max(std::max(State.Column, NewParenState.Indent), 1008 State.Stack.back().LastSpace); 1009 1010 // Do not indent relative to the fake parentheses inserted for "." or "->". 1011 // This is a special case to make the following to statements consistent: 1012 // OuterFunction(InnerFunctionCall( // break 1013 // ParameterToInnerFunction)); 1014 // OuterFunction(SomeObject.InnerFunctionCall( // break 1015 // ParameterToInnerFunction)); 1016 if (*I > prec::Unknown) 1017 NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column); 1018 if (*I != prec::Conditional && !Current.is(TT_UnaryOperator) && 1019 Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign) 1020 NewParenState.StartOfFunctionCall = State.Column; 1021 1022 // Always indent conditional expressions. Never indent expression where 1023 // the 'operator' is ',', ';' or an assignment (i.e. *I <= 1024 // prec::Assignment) as those have different indentation rules. Indent 1025 // other expression, unless the indentation needs to be skipped. 1026 if (*I == prec::Conditional || 1027 (!SkipFirstExtraIndent && *I > prec::Assignment && 1028 !Current.isTrailingComment())) 1029 NewParenState.Indent += Style.ContinuationIndentWidth; 1030 if ((Previous && !Previous->opensScope()) || *I != prec::Comma) 1031 NewParenState.BreakBeforeParameter = false; 1032 State.Stack.push_back(NewParenState); 1033 SkipFirstExtraIndent = false; 1034 } 1035 } 1036 1037 void ContinuationIndenter::moveStatePastFakeRParens(LineState &State) { 1038 for (unsigned i = 0, e = State.NextToken->FakeRParens; i != e; ++i) { 1039 unsigned VariablePos = State.Stack.back().VariablePos; 1040 if (State.Stack.size() == 1) { 1041 // Do not pop the last element. 1042 break; 1043 } 1044 State.Stack.pop_back(); 1045 State.Stack.back().VariablePos = VariablePos; 1046 } 1047 } 1048 1049 void ContinuationIndenter::moveStatePastScopeOpener(LineState &State, 1050 bool Newline) { 1051 const FormatToken &Current = *State.NextToken; 1052 if (!Current.opensScope()) 1053 return; 1054 1055 if (Current.MatchingParen && Current.BlockKind == BK_Block) { 1056 moveStateToNewBlock(State); 1057 return; 1058 } 1059 1060 unsigned NewIndent; 1061 unsigned LastSpace = State.Stack.back().LastSpace; 1062 bool AvoidBinPacking; 1063 bool BreakBeforeParameter = false; 1064 unsigned NestedBlockIndent = std::max(State.Stack.back().StartOfFunctionCall, 1065 State.Stack.back().NestedBlockIndent); 1066 if (Current.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) || 1067 opensProtoMessageField(Current, Style)) { 1068 if (Current.opensBlockOrBlockTypeList(Style)) { 1069 NewIndent = Style.IndentWidth + 1070 std::min(State.Column, State.Stack.back().NestedBlockIndent); 1071 } else { 1072 NewIndent = State.Stack.back().LastSpace + Style.ContinuationIndentWidth; 1073 } 1074 const FormatToken *NextNoComment = Current.getNextNonComment(); 1075 bool EndsInComma = Current.MatchingParen && 1076 Current.MatchingParen->Previous && 1077 Current.MatchingParen->Previous->is(tok::comma); 1078 AvoidBinPacking = 1079 EndsInComma || Current.is(TT_DictLiteral) || 1080 Style.Language == FormatStyle::LK_Proto || 1081 Style.Language == FormatStyle::LK_TextProto || 1082 !Style.BinPackArguments || 1083 (NextNoComment && 1084 NextNoComment->isOneOf(TT_DesignatedInitializerPeriod, 1085 TT_DesignatedInitializerLSquare)); 1086 BreakBeforeParameter = EndsInComma; 1087 if (Current.ParameterCount > 1) 1088 NestedBlockIndent = std::max(NestedBlockIndent, State.Column + 1); 1089 } else { 1090 NewIndent = Style.ContinuationIndentWidth + 1091 std::max(State.Stack.back().LastSpace, 1092 State.Stack.back().StartOfFunctionCall); 1093 1094 // Ensure that different different brackets force relative alignment, e.g.: 1095 // void SomeFunction(vector< // break 1096 // int> v); 1097 // FIXME: We likely want to do this for more combinations of brackets. 1098 // Verify that it is wanted for ObjC, too. 1099 if (Current.is(tok::less) && Current.ParentBracket == tok::l_paren) { 1100 NewIndent = std::max(NewIndent, State.Stack.back().Indent); 1101 LastSpace = std::max(LastSpace, State.Stack.back().Indent); 1102 } 1103 1104 // JavaScript template strings are special as we always want to indent 1105 // nested expressions relative to the ${}. Otherwise, this can create quite 1106 // a mess. 1107 if (Current.is(TT_TemplateString)) { 1108 unsigned Column = Current.IsMultiline 1109 ? Current.LastLineColumnWidth 1110 : State.Column + Current.ColumnWidth; 1111 NewIndent = Column; 1112 LastSpace = Column; 1113 NestedBlockIndent = Column; 1114 } 1115 1116 bool EndsInComma = 1117 Current.MatchingParen && 1118 Current.MatchingParen->getPreviousNonComment() && 1119 Current.MatchingParen->getPreviousNonComment()->is(tok::comma); 1120 1121 AvoidBinPacking = 1122 (Style.Language == FormatStyle::LK_JavaScript && EndsInComma) || 1123 (State.Line->MustBeDeclaration && !Style.BinPackParameters) || 1124 (!State.Line->MustBeDeclaration && !Style.BinPackArguments) || 1125 (Style.ExperimentalAutoDetectBinPacking && 1126 (Current.PackingKind == PPK_OnePerLine || 1127 (!BinPackInconclusiveFunctions && 1128 Current.PackingKind == PPK_Inconclusive))); 1129 1130 if (Current.is(TT_ObjCMethodExpr) && Current.MatchingParen) { 1131 if (Style.ColumnLimit) { 1132 // If this '[' opens an ObjC call, determine whether all parameters fit 1133 // into one line and put one per line if they don't. 1134 if (getLengthToMatchingParen(Current) + State.Column > 1135 getColumnLimit(State)) 1136 BreakBeforeParameter = true; 1137 } else { 1138 // For ColumnLimit = 0, we have to figure out whether there is or has to 1139 // be a line break within this call. 1140 for (const FormatToken *Tok = &Current; 1141 Tok && Tok != Current.MatchingParen; Tok = Tok->Next) { 1142 if (Tok->MustBreakBefore || 1143 (Tok->CanBreakBefore && Tok->NewlinesBefore > 0)) { 1144 BreakBeforeParameter = true; 1145 break; 1146 } 1147 } 1148 } 1149 } 1150 1151 if (Style.Language == FormatStyle::LK_JavaScript && EndsInComma) 1152 BreakBeforeParameter = true; 1153 } 1154 // Generally inherit NoLineBreak from the current scope to nested scope. 1155 // However, don't do this for non-empty nested blocks, dict literals and 1156 // array literals as these follow different indentation rules. 1157 bool NoLineBreak = 1158 Current.Children.empty() && 1159 !Current.isOneOf(TT_DictLiteral, TT_ArrayInitializerLSquare) && 1160 (State.Stack.back().NoLineBreak || 1161 State.Stack.back().NoLineBreakInOperand || 1162 (Current.is(TT_TemplateOpener) && 1163 State.Stack.back().ContainsUnwrappedBuilder)); 1164 State.Stack.push_back( 1165 ParenState(NewIndent, LastSpace, AvoidBinPacking, NoLineBreak)); 1166 State.Stack.back().NestedBlockIndent = NestedBlockIndent; 1167 State.Stack.back().BreakBeforeParameter = BreakBeforeParameter; 1168 State.Stack.back().HasMultipleNestedBlocks = Current.BlockParameterCount > 1; 1169 } 1170 1171 void ContinuationIndenter::moveStatePastScopeCloser(LineState &State) { 1172 const FormatToken &Current = *State.NextToken; 1173 if (!Current.closesScope()) 1174 return; 1175 1176 // If we encounter a closing ), ], } or >, we can remove a level from our 1177 // stacks. 1178 if (State.Stack.size() > 1 && 1179 (Current.isOneOf(tok::r_paren, tok::r_square, TT_TemplateString) || 1180 (Current.is(tok::r_brace) && State.NextToken != State.Line->First) || 1181 State.NextToken->is(TT_TemplateCloser))) 1182 State.Stack.pop_back(); 1183 1184 if (Current.is(tok::r_square)) { 1185 // If this ends the array subscript expr, reset the corresponding value. 1186 const FormatToken *NextNonComment = Current.getNextNonComment(); 1187 if (NextNonComment && NextNonComment->isNot(tok::l_square)) 1188 State.Stack.back().StartOfArraySubscripts = 0; 1189 } 1190 } 1191 1192 void ContinuationIndenter::moveStateToNewBlock(LineState &State) { 1193 unsigned NestedBlockIndent = State.Stack.back().NestedBlockIndent; 1194 // ObjC block sometimes follow special indentation rules. 1195 unsigned NewIndent = 1196 NestedBlockIndent + (State.NextToken->is(TT_ObjCBlockLBrace) 1197 ? Style.ObjCBlockIndentWidth 1198 : Style.IndentWidth); 1199 State.Stack.push_back(ParenState(NewIndent, State.Stack.back().LastSpace, 1200 /*AvoidBinPacking=*/true, 1201 /*NoLineBreak=*/false)); 1202 State.Stack.back().NestedBlockIndent = NestedBlockIndent; 1203 State.Stack.back().BreakBeforeParameter = true; 1204 } 1205 1206 unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current, 1207 LineState &State) { 1208 if (!Current.IsMultiline) 1209 return 0; 1210 1211 // Break before further function parameters on all levels. 1212 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i) 1213 State.Stack[i].BreakBeforeParameter = true; 1214 1215 unsigned ColumnsUsed = State.Column; 1216 // We can only affect layout of the first and the last line, so the penalty 1217 // for all other lines is constant, and we ignore it. 1218 State.Column = Current.LastLineColumnWidth; 1219 1220 if (ColumnsUsed > getColumnLimit(State)) 1221 return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State)); 1222 return 0; 1223 } 1224 1225 unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current, 1226 LineState &State, 1227 bool DryRun) { 1228 // Don't break multi-line tokens other than block comments. Instead, just 1229 // update the state. 1230 if (Current.isNot(TT_BlockComment) && Current.IsMultiline) 1231 return addMultilineToken(Current, State); 1232 1233 // Don't break implicit string literals or import statements. 1234 if (Current.is(TT_ImplicitStringLiteral) || 1235 State.Line->Type == LT_ImportStatement) 1236 return 0; 1237 1238 if (!Current.isStringLiteral() && !Current.is(tok::comment)) 1239 return 0; 1240 1241 std::unique_ptr<BreakableToken> Token; 1242 unsigned StartColumn = State.Column - Current.ColumnWidth; 1243 unsigned ColumnLimit = getColumnLimit(State); 1244 1245 if (Current.isStringLiteral()) { 1246 // FIXME: String literal breaking is currently disabled for Java and JS, as 1247 // it requires strings to be merged using "+" which we don't support. 1248 if (Style.Language == FormatStyle::LK_Java || 1249 Style.Language == FormatStyle::LK_JavaScript || 1250 !Style.BreakStringLiterals) 1251 return 0; 1252 1253 // Don't break string literals inside preprocessor directives (except for 1254 // #define directives, as their contents are stored in separate lines and 1255 // are not affected by this check). 1256 // This way we avoid breaking code with line directives and unknown 1257 // preprocessor directives that contain long string literals. 1258 if (State.Line->Type == LT_PreprocessorDirective) 1259 return 0; 1260 // Exempts unterminated string literals from line breaking. The user will 1261 // likely want to terminate the string before any line breaking is done. 1262 if (Current.IsUnterminatedLiteral) 1263 return 0; 1264 1265 StringRef Text = Current.TokenText; 1266 StringRef Prefix; 1267 StringRef Postfix; 1268 // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'. 1269 // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to 1270 // reduce the overhead) for each FormatToken, which is a string, so that we 1271 // don't run multiple checks here on the hot path. 1272 if ((Text.endswith(Postfix = "\"") && 1273 (Text.startswith(Prefix = "@\"") || Text.startswith(Prefix = "\"") || 1274 Text.startswith(Prefix = "u\"") || Text.startswith(Prefix = "U\"") || 1275 Text.startswith(Prefix = "u8\"") || 1276 Text.startswith(Prefix = "L\""))) || 1277 (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")"))) { 1278 Token.reset(new BreakableStringLiteral(Current, StartColumn, Prefix, 1279 Postfix, State.Line->InPPDirective, 1280 Encoding, Style)); 1281 } else { 1282 return 0; 1283 } 1284 } else if (Current.is(TT_BlockComment)) { 1285 if (!Current.isTrailingComment() || !Style.ReflowComments || 1286 // If a comment token switches formatting, like 1287 // /* clang-format on */, we don't want to break it further, 1288 // but we may still want to adjust its indentation. 1289 switchesFormatting(Current)) 1290 return addMultilineToken(Current, State); 1291 Token.reset(new BreakableBlockComment( 1292 Current, StartColumn, Current.OriginalColumn, !Current.Previous, 1293 State.Line->InPPDirective, Encoding, Style)); 1294 } else if (Current.is(TT_LineComment) && 1295 (Current.Previous == nullptr || 1296 Current.Previous->isNot(TT_ImplicitStringLiteral))) { 1297 if (!Style.ReflowComments || 1298 CommentPragmasRegex.match(Current.TokenText.substr(2)) || 1299 switchesFormatting(Current)) 1300 return 0; 1301 Token.reset(new BreakableLineCommentSection( 1302 Current, StartColumn, Current.OriginalColumn, !Current.Previous, 1303 /*InPPDirective=*/false, Encoding, Style)); 1304 // We don't insert backslashes when breaking line comments. 1305 ColumnLimit = Style.ColumnLimit; 1306 } else { 1307 return 0; 1308 } 1309 if (Current.UnbreakableTailLength >= ColumnLimit) 1310 return 0; 1311 1312 unsigned RemainingSpace = ColumnLimit - Current.UnbreakableTailLength; 1313 bool BreakInserted = false; 1314 // We use a conservative reflowing strategy. Reflow starts after a line is 1315 // broken or the corresponding whitespace compressed. Reflow ends as soon as a 1316 // line that doesn't get reflown with the previous line is reached. 1317 bool ReflowInProgress = false; 1318 unsigned Penalty = 0; 1319 unsigned RemainingTokenColumns = 0; 1320 unsigned TailOffset = 0; 1321 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount(); 1322 LineIndex != EndIndex; ++LineIndex) { 1323 BreakableToken::Split SplitBefore(StringRef::npos, 0); 1324 if (ReflowInProgress) { 1325 SplitBefore = Token->getSplitBefore(LineIndex, RemainingTokenColumns, 1326 RemainingSpace, CommentPragmasRegex); 1327 } 1328 ReflowInProgress = SplitBefore.first != StringRef::npos; 1329 TailOffset = 1330 ReflowInProgress ? (SplitBefore.first + SplitBefore.second) : 0; 1331 if (!DryRun) 1332 Token->replaceWhitespaceBefore(LineIndex, RemainingTokenColumns, 1333 RemainingSpace, SplitBefore, Whitespaces); 1334 RemainingTokenColumns = Token->getLineLengthAfterSplitBefore( 1335 LineIndex, TailOffset, RemainingTokenColumns, ColumnLimit, SplitBefore); 1336 while (RemainingTokenColumns > RemainingSpace) { 1337 BreakableToken::Split Split = Token->getSplit( 1338 LineIndex, TailOffset, ColumnLimit, CommentPragmasRegex); 1339 if (Split.first == StringRef::npos) { 1340 // The last line's penalty is handled in addNextStateToQueue(). 1341 if (LineIndex < EndIndex - 1) 1342 Penalty += Style.PenaltyExcessCharacter * 1343 (RemainingTokenColumns - RemainingSpace); 1344 break; 1345 } 1346 assert(Split.first != 0); 1347 1348 // Check if compressing the whitespace range will bring the line length 1349 // under the limit. If that is the case, we perform whitespace compression 1350 // instead of inserting a line break. 1351 unsigned RemainingTokenColumnsAfterCompression = 1352 Token->getLineLengthAfterCompression(RemainingTokenColumns, Split); 1353 if (RemainingTokenColumnsAfterCompression <= RemainingSpace) { 1354 RemainingTokenColumns = RemainingTokenColumnsAfterCompression; 1355 ReflowInProgress = true; 1356 if (!DryRun) 1357 Token->compressWhitespace(LineIndex, TailOffset, Split, Whitespaces); 1358 break; 1359 } 1360 1361 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit( 1362 LineIndex, TailOffset + Split.first + Split.second, StringRef::npos); 1363 1364 // When breaking before a tab character, it may be moved by a few columns, 1365 // but will still be expanded to the next tab stop, so we don't save any 1366 // columns. 1367 if (NewRemainingTokenColumns == RemainingTokenColumns) 1368 break; 1369 1370 assert(NewRemainingTokenColumns < RemainingTokenColumns); 1371 if (!DryRun) 1372 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces); 1373 Penalty += Current.SplitPenalty; 1374 unsigned ColumnsUsed = 1375 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first); 1376 if (ColumnsUsed > ColumnLimit) { 1377 Penalty += Style.PenaltyExcessCharacter * (ColumnsUsed - ColumnLimit); 1378 } 1379 TailOffset += Split.first + Split.second; 1380 RemainingTokenColumns = NewRemainingTokenColumns; 1381 ReflowInProgress = true; 1382 BreakInserted = true; 1383 } 1384 } 1385 1386 BreakableToken::Split SplitAfterLastLine = 1387 Token->getSplitAfterLastLine(TailOffset, ColumnLimit); 1388 if (SplitAfterLastLine.first != StringRef::npos) { 1389 if (!DryRun) 1390 Token->replaceWhitespaceAfterLastLine(TailOffset, SplitAfterLastLine, 1391 Whitespaces); 1392 RemainingTokenColumns = Token->getLineLengthAfterSplitAfterLastLine( 1393 TailOffset, SplitAfterLastLine); 1394 } 1395 1396 State.Column = RemainingTokenColumns; 1397 1398 if (BreakInserted) { 1399 // If we break the token inside a parameter list, we need to break before 1400 // the next parameter on all levels, so that the next parameter is clearly 1401 // visible. Line comments already introduce a break. 1402 if (Current.isNot(TT_LineComment)) { 1403 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i) 1404 State.Stack[i].BreakBeforeParameter = true; 1405 } 1406 1407 Penalty += Current.isStringLiteral() ? Style.PenaltyBreakString 1408 : Style.PenaltyBreakComment; 1409 1410 State.Stack.back().LastSpace = StartColumn; 1411 } 1412 1413 Token->updateNextToken(State); 1414 1415 return Penalty; 1416 } 1417 1418 unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const { 1419 // In preprocessor directives reserve two chars for trailing " \" 1420 return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0); 1421 } 1422 1423 bool ContinuationIndenter::nextIsMultilineString(const LineState &State) { 1424 const FormatToken &Current = *State.NextToken; 1425 if (!Current.isStringLiteral() || Current.is(TT_ImplicitStringLiteral)) 1426 return false; 1427 // We never consider raw string literals "multiline" for the purpose of 1428 // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased 1429 // (see TokenAnnotator::mustBreakBefore(). 1430 if (Current.TokenText.startswith("R\"")) 1431 return false; 1432 if (Current.IsMultiline) 1433 return true; 1434 if (Current.getNextNonComment() && 1435 Current.getNextNonComment()->isStringLiteral()) 1436 return true; // Implicit concatenation. 1437 if (Style.ColumnLimit != 0 && 1438 State.Column + Current.ColumnWidth + Current.UnbreakableTailLength > 1439 Style.ColumnLimit) 1440 return true; // String will be split. 1441 return false; 1442 } 1443 1444 } // namespace format 1445 } // namespace clang 1446