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 ((PreviousNonComment && 527 PreviousNonComment->isOneOf(tok::comma, tok::semi) && 528 !State.Stack.back().AvoidBinPacking) || 529 Previous.is(TT_BinaryOperator)) 530 State.Stack.back().BreakBeforeParameter = false; 531 if (Previous.isOneOf(TT_TemplateCloser, TT_JavaAnnotation) && 532 Current.NestingLevel == 0) 533 State.Stack.back().BreakBeforeParameter = false; 534 if (NextNonComment->is(tok::question) || 535 (PreviousNonComment && PreviousNonComment->is(tok::question))) 536 State.Stack.back().BreakBeforeParameter = true; 537 if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore) 538 State.Stack.back().BreakBeforeParameter = false; 539 540 if (!DryRun) { 541 unsigned Newlines = std::max( 542 1u, std::min(Current.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1)); 543 Whitespaces.replaceWhitespace(Current, Newlines, 544 State.Stack.back().IndentLevel, State.Column, 545 State.Column, State.Line->InPPDirective); 546 } 547 548 if (!Current.isTrailingComment()) 549 State.Stack.back().LastSpace = State.Column; 550 if (Current.is(tok::lessless)) 551 // If we are breaking before a "<<", we always want to indent relative to 552 // RHS. This is necessary only for "<<", as we special-case it and don't 553 // always indent relative to the RHS. 554 State.Stack.back().LastSpace += 3; // 3 -> width of "<< ". 555 556 State.StartOfLineLevel = Current.NestingLevel; 557 State.LowestLevelOnLine = Current.NestingLevel; 558 559 // Any break on this level means that the parent level has been broken 560 // and we need to avoid bin packing there. 561 bool NestedBlockSpecialCase = 562 Style.Language != FormatStyle::LK_Cpp && 563 Current.is(tok::r_brace) && State.Stack.size() > 1 && 564 State.Stack[State.Stack.size() - 2].NestedBlockInlined; 565 if (!NestedBlockSpecialCase) 566 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) 567 State.Stack[i].BreakBeforeParameter = true; 568 569 if (PreviousNonComment && 570 !PreviousNonComment->isOneOf(tok::comma, tok::semi) && 571 (PreviousNonComment->isNot(TT_TemplateCloser) || 572 Current.NestingLevel != 0) && 573 !PreviousNonComment->isOneOf( 574 TT_BinaryOperator, TT_FunctionAnnotationRParen, TT_JavaAnnotation, 575 TT_LeadingJavaAnnotation) && 576 Current.isNot(TT_BinaryOperator) && !PreviousNonComment->opensScope()) 577 State.Stack.back().BreakBeforeParameter = true; 578 579 // If we break after { or the [ of an array initializer, we should also break 580 // before the corresponding } or ]. 581 if (PreviousNonComment && 582 (PreviousNonComment->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare))) 583 State.Stack.back().BreakBeforeClosingBrace = true; 584 585 if (State.Stack.back().AvoidBinPacking) { 586 // If we are breaking after '(', '{', '<', this is not bin packing 587 // unless AllowAllParametersOfDeclarationOnNextLine is false or this is a 588 // dict/object literal. 589 if (!Previous.isOneOf(tok::l_paren, tok::l_brace, TT_BinaryOperator) || 590 (!Style.AllowAllParametersOfDeclarationOnNextLine && 591 State.Line->MustBeDeclaration) || 592 Previous.is(TT_DictLiteral)) 593 State.Stack.back().BreakBeforeParameter = true; 594 } 595 596 return Penalty; 597 } 598 599 unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) { 600 if (!State.NextToken || !State.NextToken->Previous) 601 return 0; 602 FormatToken &Current = *State.NextToken; 603 const FormatToken &Previous = *Current.Previous; 604 // If we are continuing an expression, we want to use the continuation indent. 605 unsigned ContinuationIndent = 606 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 607 Style.ContinuationIndentWidth; 608 const FormatToken *PreviousNonComment = Current.getPreviousNonComment(); 609 const FormatToken *NextNonComment = Previous.getNextNonComment(); 610 if (!NextNonComment) 611 NextNonComment = &Current; 612 613 // Java specific bits. 614 if (Style.Language == FormatStyle::LK_Java && 615 Current.isOneOf(Keywords.kw_implements, Keywords.kw_extends)) 616 return std::max(State.Stack.back().LastSpace, 617 State.Stack.back().Indent + Style.ContinuationIndentWidth); 618 619 if (NextNonComment->is(tok::l_brace) && NextNonComment->BlockKind == BK_Block) 620 return Current.NestingLevel == 0 ? State.FirstIndent 621 : State.Stack.back().Indent; 622 if (Current.isOneOf(tok::r_brace, tok::r_square) && State.Stack.size() > 1) { 623 if (Current.closesBlockOrBlockTypeList(Style)) 624 return State.Stack[State.Stack.size() - 2].NestedBlockIndent; 625 if (Current.MatchingParen && 626 Current.MatchingParen->BlockKind == BK_BracedInit) 627 return State.Stack[State.Stack.size() - 2].LastSpace; 628 return State.FirstIndent; 629 } 630 if (Current.is(tok::identifier) && Current.Next && 631 Current.Next->is(TT_DictLiteral)) 632 return State.Stack.back().Indent; 633 if (NextNonComment->isStringLiteral() && State.StartOfStringLiteral != 0) 634 return State.StartOfStringLiteral; 635 if (NextNonComment->is(TT_ObjCStringLiteral) && 636 State.StartOfStringLiteral != 0) 637 return State.StartOfStringLiteral - 1; 638 if (NextNonComment->is(tok::lessless) && 639 State.Stack.back().FirstLessLess != 0) 640 return State.Stack.back().FirstLessLess; 641 if (NextNonComment->isMemberAccess()) { 642 if (State.Stack.back().CallContinuation == 0) 643 return ContinuationIndent; 644 return State.Stack.back().CallContinuation; 645 } 646 if (State.Stack.back().QuestionColumn != 0 && 647 ((NextNonComment->is(tok::colon) && 648 NextNonComment->is(TT_ConditionalExpr)) || 649 Previous.is(TT_ConditionalExpr))) 650 return State.Stack.back().QuestionColumn; 651 if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0) 652 return State.Stack.back().VariablePos; 653 if ((PreviousNonComment && 654 (PreviousNonComment->ClosesTemplateDeclaration || 655 PreviousNonComment->isOneOf( 656 TT_AttributeParen, TT_FunctionAnnotationRParen, TT_JavaAnnotation, 657 TT_LeadingJavaAnnotation))) || 658 (!Style.IndentWrappedFunctionNames && 659 NextNonComment->isOneOf(tok::kw_operator, TT_FunctionDeclarationName))) 660 return std::max(State.Stack.back().LastSpace, State.Stack.back().Indent); 661 if (NextNonComment->is(TT_SelectorName)) { 662 if (!State.Stack.back().ObjCSelectorNameFound) { 663 if (NextNonComment->LongestObjCSelectorName == 0) 664 return State.Stack.back().Indent; 665 return (Style.IndentWrappedFunctionNames 666 ? std::max(State.Stack.back().Indent, 667 State.FirstIndent + Style.ContinuationIndentWidth) 668 : State.Stack.back().Indent) + 669 NextNonComment->LongestObjCSelectorName - 670 NextNonComment->ColumnWidth; 671 } 672 if (!State.Stack.back().AlignColons) 673 return State.Stack.back().Indent; 674 if (State.Stack.back().ColonPos > NextNonComment->ColumnWidth) 675 return State.Stack.back().ColonPos - NextNonComment->ColumnWidth; 676 return State.Stack.back().Indent; 677 } 678 if (NextNonComment->is(tok::colon) && NextNonComment->is(TT_ObjCMethodExpr)) 679 return State.Stack.back().ColonPos; 680 if (NextNonComment->is(TT_ArraySubscriptLSquare)) { 681 if (State.Stack.back().StartOfArraySubscripts != 0) 682 return State.Stack.back().StartOfArraySubscripts; 683 return ContinuationIndent; 684 } 685 686 // This ensure that we correctly format ObjC methods calls without inputs, 687 // i.e. where the last element isn't selector like: [callee method]; 688 if (NextNonComment->is(tok::identifier) && NextNonComment->FakeRParens == 0 && 689 NextNonComment->Next && NextNonComment->Next->is(TT_ObjCMethodExpr)) 690 return State.Stack.back().Indent; 691 692 if (NextNonComment->isOneOf(TT_StartOfName, TT_PointerOrReference) || 693 Previous.isOneOf(tok::coloncolon, tok::equal, TT_JsTypeColon)) 694 return ContinuationIndent; 695 if (PreviousNonComment && PreviousNonComment->is(tok::colon) && 696 PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) 697 return ContinuationIndent; 698 if (NextNonComment->is(TT_CtorInitializerColon)) 699 return State.FirstIndent + Style.ConstructorInitializerIndentWidth; 700 if (NextNonComment->is(TT_CtorInitializerComma)) 701 return State.Stack.back().Indent; 702 if (Previous.is(tok::r_paren) && !Current.isBinaryOperator() && 703 !Current.isOneOf(tok::colon, tok::comment)) 704 return ContinuationIndent; 705 if (State.Stack.back().Indent == State.FirstIndent && PreviousNonComment && 706 PreviousNonComment->isNot(tok::r_brace)) 707 // Ensure that we fall back to the continuation indent width instead of 708 // just flushing continuations left. 709 return State.Stack.back().Indent + Style.ContinuationIndentWidth; 710 return State.Stack.back().Indent; 711 } 712 713 unsigned ContinuationIndenter::moveStateToNextToken(LineState &State, 714 bool DryRun, bool Newline) { 715 assert(State.Stack.size()); 716 const FormatToken &Current = *State.NextToken; 717 718 if (Current.is(TT_InheritanceColon)) 719 State.Stack.back().AvoidBinPacking = true; 720 if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator)) { 721 if (State.Stack.back().FirstLessLess == 0) 722 State.Stack.back().FirstLessLess = State.Column; 723 else 724 State.Stack.back().LastOperatorWrapped = Newline; 725 } 726 if ((Current.is(TT_BinaryOperator) && Current.isNot(tok::lessless)) || 727 Current.is(TT_ConditionalExpr)) 728 State.Stack.back().LastOperatorWrapped = Newline; 729 if (Current.is(TT_ArraySubscriptLSquare) && 730 State.Stack.back().StartOfArraySubscripts == 0) 731 State.Stack.back().StartOfArraySubscripts = State.Column; 732 if (Style.BreakBeforeTernaryOperators && Current.is(tok::question)) 733 State.Stack.back().QuestionColumn = State.Column; 734 if (!Style.BreakBeforeTernaryOperators && Current.isNot(tok::colon)) { 735 const FormatToken *Previous = Current.Previous; 736 while (Previous && Previous->isTrailingComment()) 737 Previous = Previous->Previous; 738 if (Previous && Previous->is(tok::question)) 739 State.Stack.back().QuestionColumn = State.Column; 740 } 741 if (!Current.opensScope() && !Current.closesScope()) 742 State.LowestLevelOnLine = 743 std::min(State.LowestLevelOnLine, Current.NestingLevel); 744 if (Current.isMemberAccess()) 745 State.Stack.back().StartOfFunctionCall = 746 !Current.NextOperator ? 0 : State.Column; 747 if (Current.is(TT_SelectorName)) { 748 State.Stack.back().ObjCSelectorNameFound = true; 749 if (Style.IndentWrappedFunctionNames) { 750 State.Stack.back().Indent = 751 State.FirstIndent + Style.ContinuationIndentWidth; 752 } 753 } 754 if (Current.is(TT_CtorInitializerColon)) { 755 // Indent 2 from the column, so: 756 // SomeClass::SomeClass() 757 // : First(...), ... 758 // Next(...) 759 // ^ line up here. 760 State.Stack.back().Indent = 761 State.Column + (Style.BreakConstructorInitializersBeforeComma ? 0 : 2); 762 State.Stack.back().NestedBlockIndent = State.Stack.back().Indent; 763 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine) 764 State.Stack.back().AvoidBinPacking = true; 765 State.Stack.back().BreakBeforeParameter = false; 766 } 767 if (Current.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) && Newline) 768 State.Stack.back().NestedBlockIndent = 769 State.Column + Current.ColumnWidth + 1; 770 771 // Insert scopes created by fake parenthesis. 772 const FormatToken *Previous = Current.getPreviousNonComment(); 773 774 // Add special behavior to support a format commonly used for JavaScript 775 // closures: 776 // SomeFunction(function() { 777 // foo(); 778 // bar(); 779 // }, a, b, c); 780 if (Current.isNot(tok::comment) && Previous && 781 Previous->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) && 782 !Previous->is(TT_DictLiteral) && State.Stack.size() > 1) { 783 if (State.Stack[State.Stack.size() - 2].NestedBlockInlined && Newline) 784 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) 785 State.Stack[i].NoLineBreak = true; 786 State.Stack[State.Stack.size() - 2].NestedBlockInlined = false; 787 } 788 if (Previous && (Previous->isOneOf(tok::l_paren, tok::comma, tok::colon) || 789 Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr)) && 790 !Previous->isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) { 791 State.Stack.back().NestedBlockInlined = 792 !Newline && 793 (Previous->isNot(tok::l_paren) || Previous->ParameterCount > 1); 794 } 795 796 moveStatePastFakeLParens(State, Newline); 797 moveStatePastScopeOpener(State, Newline); 798 moveStatePastScopeCloser(State); 799 moveStatePastFakeRParens(State); 800 801 if (Current.isStringLiteral() && State.StartOfStringLiteral == 0) 802 State.StartOfStringLiteral = State.Column; 803 if (Current.is(TT_ObjCStringLiteral) && State.StartOfStringLiteral == 0) 804 State.StartOfStringLiteral = State.Column + 1; 805 else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) && 806 !Current.isStringLiteral()) 807 State.StartOfStringLiteral = 0; 808 809 State.Column += Current.ColumnWidth; 810 State.NextToken = State.NextToken->Next; 811 unsigned Penalty = breakProtrudingToken(Current, State, DryRun); 812 if (State.Column > getColumnLimit(State)) { 813 unsigned ExcessCharacters = State.Column - getColumnLimit(State); 814 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters; 815 } 816 817 if (Current.Role) 818 Current.Role->formatFromToken(State, this, DryRun); 819 // If the previous has a special role, let it consume tokens as appropriate. 820 // It is necessary to start at the previous token for the only implemented 821 // role (comma separated list). That way, the decision whether or not to break 822 // after the "{" is already done and both options are tried and evaluated. 823 // FIXME: This is ugly, find a better way. 824 if (Previous && Previous->Role) 825 Penalty += Previous->Role->formatAfterToken(State, this, DryRun); 826 827 return Penalty; 828 } 829 830 void ContinuationIndenter::moveStatePastFakeLParens(LineState &State, 831 bool Newline) { 832 const FormatToken &Current = *State.NextToken; 833 const FormatToken *Previous = Current.getPreviousNonComment(); 834 835 // Don't add extra indentation for the first fake parenthesis after 836 // 'return', assignments or opening <({[. The indentation for these cases 837 // is special cased. 838 bool SkipFirstExtraIndent = 839 (Previous && (Previous->opensScope() || 840 Previous->isOneOf(tok::semi, tok::kw_return) || 841 (Previous->getPrecedence() == prec::Assignment && 842 Style.AlignOperands) || 843 Previous->is(TT_ObjCMethodExpr))); 844 for (SmallVectorImpl<prec::Level>::const_reverse_iterator 845 I = Current.FakeLParens.rbegin(), 846 E = Current.FakeLParens.rend(); 847 I != E; ++I) { 848 ParenState NewParenState = State.Stack.back(); 849 NewParenState.ContainsLineBreak = false; 850 851 // Indent from 'LastSpace' unless these are fake parentheses encapsulating 852 // a builder type call after 'return' or, if the alignment after opening 853 // brackets is disabled. 854 if (!Current.isTrailingComment() && 855 (Style.AlignOperands || *I < prec::Assignment) && 856 (!Previous || Previous->isNot(tok::kw_return) || 857 (Style.Language != FormatStyle::LK_Java && *I > 0)) && 858 (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign || 859 *I != prec::Comma || Current.NestingLevel == 0)) 860 NewParenState.Indent = 861 std::max(std::max(State.Column, NewParenState.Indent), 862 State.Stack.back().LastSpace); 863 864 // Don't allow the RHS of an operator to be split over multiple lines unless 865 // there is a line-break right after the operator. 866 // Exclude relational operators, as there, it is always more desirable to 867 // have the LHS 'left' of the RHS. 868 if (Previous && Previous->getPrecedence() != prec::Assignment && 869 Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr, tok::comma) && 870 Previous->getPrecedence() != prec::Relational) { 871 bool BreakBeforeOperator = 872 Previous->is(tok::lessless) || 873 (Previous->is(TT_BinaryOperator) && 874 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None) || 875 (Previous->is(TT_ConditionalExpr) && 876 Style.BreakBeforeTernaryOperators); 877 if ((!Newline && !BreakBeforeOperator) || 878 (!State.Stack.back().LastOperatorWrapped && BreakBeforeOperator)) 879 NewParenState.NoLineBreak = true; 880 } 881 882 // Do not indent relative to the fake parentheses inserted for "." or "->". 883 // This is a special case to make the following to statements consistent: 884 // OuterFunction(InnerFunctionCall( // break 885 // ParameterToInnerFunction)); 886 // OuterFunction(SomeObject.InnerFunctionCall( // break 887 // ParameterToInnerFunction)); 888 if (*I > prec::Unknown) 889 NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column); 890 if (*I != prec::Conditional && !Current.is(TT_UnaryOperator) && 891 Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign) 892 NewParenState.StartOfFunctionCall = State.Column; 893 894 // Always indent conditional expressions. Never indent expression where 895 // the 'operator' is ',', ';' or an assignment (i.e. *I <= 896 // prec::Assignment) as those have different indentation rules. Indent 897 // other expression, unless the indentation needs to be skipped. 898 if (*I == prec::Conditional || 899 (!SkipFirstExtraIndent && *I > prec::Assignment && 900 !Current.isTrailingComment())) 901 NewParenState.Indent += Style.ContinuationIndentWidth; 902 if ((Previous && !Previous->opensScope()) || *I != prec::Comma) 903 NewParenState.BreakBeforeParameter = false; 904 State.Stack.push_back(NewParenState); 905 SkipFirstExtraIndent = false; 906 } 907 } 908 909 void ContinuationIndenter::moveStatePastFakeRParens(LineState &State) { 910 for (unsigned i = 0, e = State.NextToken->FakeRParens; i != e; ++i) { 911 unsigned VariablePos = State.Stack.back().VariablePos; 912 if (State.Stack.size() == 1) { 913 // Do not pop the last element. 914 break; 915 } 916 State.Stack.pop_back(); 917 State.Stack.back().VariablePos = VariablePos; 918 } 919 } 920 921 void ContinuationIndenter::moveStatePastScopeOpener(LineState &State, 922 bool Newline) { 923 const FormatToken &Current = *State.NextToken; 924 if (!Current.opensScope()) 925 return; 926 927 if (Current.MatchingParen && Current.BlockKind == BK_Block) { 928 moveStateToNewBlock(State); 929 return; 930 } 931 932 unsigned NewIndent; 933 unsigned NewIndentLevel = State.Stack.back().IndentLevel; 934 unsigned LastSpace = State.Stack.back().LastSpace; 935 bool AvoidBinPacking; 936 bool BreakBeforeParameter = false; 937 unsigned NestedBlockIndent = std::max(State.Stack.back().StartOfFunctionCall, 938 State.Stack.back().NestedBlockIndent); 939 if (Current.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare)) { 940 if (Current.opensBlockOrBlockTypeList(Style)) { 941 NewIndent = State.Stack.back().NestedBlockIndent + Style.IndentWidth; 942 NewIndent = std::min(State.Column + 2, NewIndent); 943 ++NewIndentLevel; 944 } else { 945 NewIndent = State.Stack.back().LastSpace + Style.ContinuationIndentWidth; 946 } 947 const FormatToken *NextNoComment = Current.getNextNonComment(); 948 bool EndsInComma = Current.MatchingParen && 949 Current.MatchingParen->Previous && 950 Current.MatchingParen->Previous->is(tok::comma); 951 AvoidBinPacking = 952 (Current.is(TT_ArrayInitializerLSquare) && EndsInComma) || 953 Current.is(TT_DictLiteral) || 954 Style.Language == FormatStyle::LK_Proto || !Style.BinPackArguments || 955 (NextNoComment && NextNoComment->is(TT_DesignatedInitializerPeriod)); 956 if (Current.ParameterCount > 1) 957 NestedBlockIndent = std::max(NestedBlockIndent, State.Column + 1); 958 } else { 959 NewIndent = Style.ContinuationIndentWidth + 960 std::max(State.Stack.back().LastSpace, 961 State.Stack.back().StartOfFunctionCall); 962 963 // Ensure that different different brackets force relative alignment, e.g.: 964 // void SomeFunction(vector< // break 965 // int> v); 966 // FIXME: We likely want to do this for more combinations of brackets. 967 // Verify that it is wanted for ObjC, too. 968 if (Current.Tok.getKind() == tok::less && 969 Current.ParentBracket == tok::l_paren) { 970 NewIndent = std::max(NewIndent, State.Stack.back().Indent); 971 LastSpace = std::max(LastSpace, State.Stack.back().Indent); 972 } 973 974 AvoidBinPacking = 975 (State.Line->MustBeDeclaration && !Style.BinPackParameters) || 976 (!State.Line->MustBeDeclaration && !Style.BinPackArguments) || 977 (Style.ExperimentalAutoDetectBinPacking && 978 (Current.PackingKind == PPK_OnePerLine || 979 (!BinPackInconclusiveFunctions && 980 Current.PackingKind == PPK_Inconclusive))); 981 if (Current.is(TT_ObjCMethodExpr) && Current.MatchingParen) { 982 if (Style.ColumnLimit) { 983 // If this '[' opens an ObjC call, determine whether all parameters fit 984 // into one line and put one per line if they don't. 985 if (getLengthToMatchingParen(Current) + State.Column > 986 getColumnLimit(State)) 987 BreakBeforeParameter = true; 988 } else { 989 // For ColumnLimit = 0, we have to figure out whether there is or has to 990 // be a line break within this call. 991 for (const FormatToken *Tok = &Current; 992 Tok && Tok != Current.MatchingParen; Tok = Tok->Next) { 993 if (Tok->MustBreakBefore || 994 (Tok->CanBreakBefore && Tok->NewlinesBefore > 0)) { 995 BreakBeforeParameter = true; 996 break; 997 } 998 } 999 } 1000 } 1001 } 1002 // Generally inherit NoLineBreak from the current scope to nested scope. 1003 // However, don't do this for non-empty nested blocks, dict literals and 1004 // array literals as these follow different indentation rules. 1005 bool NoLineBreak = 1006 Current.Children.empty() && 1007 !Current.isOneOf(TT_DictLiteral, TT_ArrayInitializerLSquare) && 1008 (State.Stack.back().NoLineBreak || 1009 (Current.is(TT_TemplateOpener) && 1010 State.Stack.back().ContainsUnwrappedBuilder)); 1011 State.Stack.push_back(ParenState(NewIndent, NewIndentLevel, LastSpace, 1012 AvoidBinPacking, NoLineBreak)); 1013 State.Stack.back().NestedBlockIndent = NestedBlockIndent; 1014 State.Stack.back().BreakBeforeParameter = BreakBeforeParameter; 1015 State.Stack.back().HasMultipleNestedBlocks = Current.BlockParameterCount > 1; 1016 } 1017 1018 void ContinuationIndenter::moveStatePastScopeCloser(LineState &State) { 1019 const FormatToken &Current = *State.NextToken; 1020 if (!Current.closesScope()) 1021 return; 1022 1023 // If we encounter a closing ), ], } or >, we can remove a level from our 1024 // stacks. 1025 if (State.Stack.size() > 1 && 1026 (Current.isOneOf(tok::r_paren, tok::r_square) || 1027 (Current.is(tok::r_brace) && State.NextToken != State.Line->First) || 1028 State.NextToken->is(TT_TemplateCloser))) 1029 State.Stack.pop_back(); 1030 1031 if (Current.is(tok::r_square)) { 1032 // If this ends the array subscript expr, reset the corresponding value. 1033 const FormatToken *NextNonComment = Current.getNextNonComment(); 1034 if (NextNonComment && NextNonComment->isNot(tok::l_square)) 1035 State.Stack.back().StartOfArraySubscripts = 0; 1036 } 1037 } 1038 1039 void ContinuationIndenter::moveStateToNewBlock(LineState &State) { 1040 unsigned NestedBlockIndent = State.Stack.back().NestedBlockIndent; 1041 // ObjC block sometimes follow special indentation rules. 1042 unsigned NewIndent = 1043 NestedBlockIndent + (State.NextToken->is(TT_ObjCBlockLBrace) 1044 ? Style.ObjCBlockIndentWidth 1045 : Style.IndentWidth); 1046 State.Stack.push_back(ParenState( 1047 NewIndent, /*NewIndentLevel=*/State.Stack.back().IndentLevel + 1, 1048 State.Stack.back().LastSpace, /*AvoidBinPacking=*/true, 1049 /*NoLineBreak=*/false)); 1050 State.Stack.back().NestedBlockIndent = NestedBlockIndent; 1051 State.Stack.back().BreakBeforeParameter = true; 1052 } 1053 1054 unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current, 1055 LineState &State) { 1056 if (!Current.IsMultiline) 1057 return 0; 1058 1059 // Break before further function parameters on all levels. 1060 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i) 1061 State.Stack[i].BreakBeforeParameter = true; 1062 1063 unsigned ColumnsUsed = State.Column; 1064 // We can only affect layout of the first and the last line, so the penalty 1065 // for all other lines is constant, and we ignore it. 1066 State.Column = Current.LastLineColumnWidth; 1067 1068 if (ColumnsUsed > getColumnLimit(State)) 1069 return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State)); 1070 return 0; 1071 } 1072 1073 unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current, 1074 LineState &State, 1075 bool DryRun) { 1076 // Don't break multi-line tokens other than block comments. Instead, just 1077 // update the state. 1078 if (Current.isNot(TT_BlockComment) && Current.IsMultiline) 1079 return addMultilineToken(Current, State); 1080 1081 // Don't break implicit string literals or import statements. 1082 if (Current.is(TT_ImplicitStringLiteral) || 1083 State.Line->Type == LT_ImportStatement) 1084 return 0; 1085 1086 if (!Current.isStringLiteral() && !Current.is(tok::comment)) 1087 return 0; 1088 1089 std::unique_ptr<BreakableToken> Token; 1090 unsigned StartColumn = State.Column - Current.ColumnWidth; 1091 unsigned ColumnLimit = getColumnLimit(State); 1092 1093 if (Current.isStringLiteral()) { 1094 // FIXME: String literal breaking is currently disabled for Java and JS, as 1095 // it requires strings to be merged using "+" which we don't support. 1096 if (Style.Language == FormatStyle::LK_Java || 1097 Style.Language == FormatStyle::LK_JavaScript || 1098 !Style.BreakStringLiterals) 1099 return 0; 1100 1101 // Don't break string literals inside preprocessor directives (except for 1102 // #define directives, as their contents are stored in separate lines and 1103 // are not affected by this check). 1104 // This way we avoid breaking code with line directives and unknown 1105 // preprocessor directives that contain long string literals. 1106 if (State.Line->Type == LT_PreprocessorDirective) 1107 return 0; 1108 // Exempts unterminated string literals from line breaking. The user will 1109 // likely want to terminate the string before any line breaking is done. 1110 if (Current.IsUnterminatedLiteral) 1111 return 0; 1112 1113 StringRef Text = Current.TokenText; 1114 StringRef Prefix; 1115 StringRef Postfix; 1116 bool IsNSStringLiteral = false; 1117 // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'. 1118 // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to 1119 // reduce the overhead) for each FormatToken, which is a string, so that we 1120 // don't run multiple checks here on the hot path. 1121 if (Text.startswith("\"") && Current.Previous && 1122 Current.Previous->is(tok::at)) { 1123 IsNSStringLiteral = true; 1124 Prefix = "@\""; 1125 } 1126 if ((Text.endswith(Postfix = "\"") && 1127 (IsNSStringLiteral || Text.startswith(Prefix = "\"") || 1128 Text.startswith(Prefix = "u\"") || Text.startswith(Prefix = "U\"") || 1129 Text.startswith(Prefix = "u8\"") || 1130 Text.startswith(Prefix = "L\""))) || 1131 (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")"))) { 1132 Token.reset(new BreakableStringLiteral( 1133 Current, State.Line->Level, StartColumn, Prefix, Postfix, 1134 State.Line->InPPDirective, Encoding, Style)); 1135 } else { 1136 return 0; 1137 } 1138 } else if (Current.is(TT_BlockComment)) { 1139 if (!Current.isTrailingComment() || !Style.ReflowComments || 1140 CommentPragmasRegex.match(Current.TokenText.substr(2))) 1141 return addMultilineToken(Current, State); 1142 Token.reset(new BreakableBlockComment( 1143 Current, State.Line->Level, StartColumn, Current.OriginalColumn, 1144 !Current.Previous, State.Line->InPPDirective, Encoding, Style)); 1145 } else if (Current.is(TT_LineComment) && 1146 (Current.Previous == nullptr || 1147 Current.Previous->isNot(TT_ImplicitStringLiteral))) { 1148 if (!Style.ReflowComments || 1149 CommentPragmasRegex.match(Current.TokenText.substr(2))) 1150 return 0; 1151 Token.reset(new BreakableLineComment(Current, State.Line->Level, 1152 StartColumn, /*InPPDirective=*/false, 1153 Encoding, Style)); 1154 // We don't insert backslashes when breaking line comments. 1155 ColumnLimit = Style.ColumnLimit; 1156 } else { 1157 return 0; 1158 } 1159 if (Current.UnbreakableTailLength >= ColumnLimit) 1160 return 0; 1161 1162 unsigned RemainingSpace = ColumnLimit - Current.UnbreakableTailLength; 1163 bool BreakInserted = false; 1164 unsigned Penalty = 0; 1165 unsigned RemainingTokenColumns = 0; 1166 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount(); 1167 LineIndex != EndIndex; ++LineIndex) { 1168 if (!DryRun) 1169 Token->replaceWhitespaceBefore(LineIndex, Whitespaces); 1170 unsigned TailOffset = 0; 1171 RemainingTokenColumns = 1172 Token->getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos); 1173 while (RemainingTokenColumns > RemainingSpace) { 1174 BreakableToken::Split Split = 1175 Token->getSplit(LineIndex, TailOffset, ColumnLimit); 1176 if (Split.first == StringRef::npos) { 1177 // The last line's penalty is handled in addNextStateToQueue(). 1178 if (LineIndex < EndIndex - 1) 1179 Penalty += Style.PenaltyExcessCharacter * 1180 (RemainingTokenColumns - RemainingSpace); 1181 break; 1182 } 1183 assert(Split.first != 0); 1184 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit( 1185 LineIndex, TailOffset + Split.first + Split.second, StringRef::npos); 1186 1187 // We can remove extra whitespace instead of breaking the line. 1188 if (RemainingTokenColumns + 1 - Split.second <= RemainingSpace) { 1189 RemainingTokenColumns = 0; 1190 if (!DryRun) 1191 Token->replaceWhitespace(LineIndex, TailOffset, Split, Whitespaces); 1192 break; 1193 } 1194 1195 // When breaking before a tab character, it may be moved by a few columns, 1196 // but will still be expanded to the next tab stop, so we don't save any 1197 // columns. 1198 if (NewRemainingTokenColumns == RemainingTokenColumns) 1199 break; 1200 1201 assert(NewRemainingTokenColumns < RemainingTokenColumns); 1202 if (!DryRun) 1203 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces); 1204 Penalty += Current.SplitPenalty; 1205 unsigned ColumnsUsed = 1206 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first); 1207 if (ColumnsUsed > ColumnLimit) { 1208 Penalty += Style.PenaltyExcessCharacter * (ColumnsUsed - ColumnLimit); 1209 } 1210 TailOffset += Split.first + Split.second; 1211 RemainingTokenColumns = NewRemainingTokenColumns; 1212 BreakInserted = true; 1213 } 1214 } 1215 1216 State.Column = RemainingTokenColumns; 1217 1218 if (BreakInserted) { 1219 // If we break the token inside a parameter list, we need to break before 1220 // the next parameter on all levels, so that the next parameter is clearly 1221 // visible. Line comments already introduce a break. 1222 if (Current.isNot(TT_LineComment)) { 1223 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i) 1224 State.Stack[i].BreakBeforeParameter = true; 1225 } 1226 1227 Penalty += Current.isStringLiteral() ? Style.PenaltyBreakString 1228 : Style.PenaltyBreakComment; 1229 1230 State.Stack.back().LastSpace = StartColumn; 1231 } 1232 return Penalty; 1233 } 1234 1235 unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const { 1236 // In preprocessor directives reserve two chars for trailing " \" 1237 return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0); 1238 } 1239 1240 bool ContinuationIndenter::nextIsMultilineString(const LineState &State) { 1241 const FormatToken &Current = *State.NextToken; 1242 if (!Current.isStringLiteral() || Current.is(TT_ImplicitStringLiteral)) 1243 return false; 1244 // We never consider raw string literals "multiline" for the purpose of 1245 // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased 1246 // (see TokenAnnotator::mustBreakBefore(). 1247 if (Current.TokenText.startswith("R\"")) 1248 return false; 1249 if (Current.IsMultiline) 1250 return true; 1251 if (Current.getNextNonComment() && 1252 Current.getNextNonComment()->isStringLiteral()) 1253 return true; // Implicit concatenation. 1254 if (Style.ColumnLimit != 0 && 1255 State.Column + Current.ColumnWidth + Current.UnbreakableTailLength > 1256 Style.ColumnLimit) 1257 return true; // String will be split. 1258 return false; 1259 } 1260 1261 } // namespace format 1262 } // namespace clang 1263