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