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