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