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