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