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