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