1 //===--- UnwrappedLineFormatter.cpp - Format C++ code ---------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "UnwrappedLineFormatter.h" 10 #include "NamespaceEndCommentsFixer.h" 11 #include "WhitespaceManager.h" 12 #include "llvm/Support/Debug.h" 13 #include <queue> 14 15 #define DEBUG_TYPE "format-formatter" 16 17 namespace clang { 18 namespace format { 19 20 namespace { 21 22 bool startsExternCBlock(const AnnotatedLine &Line) { 23 const FormatToken *Next = Line.First->getNextNonComment(); 24 const FormatToken *NextNext = Next ? Next->getNextNonComment() : nullptr; 25 return Line.startsWith(tok::kw_extern) && Next && Next->isStringLiteral() && 26 NextNext && NextNext->is(tok::l_brace); 27 } 28 29 bool isRecordLBrace(const FormatToken &Tok) { 30 return Tok.isOneOf(TT_ClassLBrace, TT_EnumLBrace, TT_RecordLBrace, 31 TT_StructLBrace, TT_UnionLBrace); 32 } 33 34 /// Tracks the indent level of \c AnnotatedLines across levels. 35 /// 36 /// \c nextLine must be called for each \c AnnotatedLine, after which \c 37 /// getIndent() will return the indent for the last line \c nextLine was called 38 /// with. 39 /// If the line is not formatted (and thus the indent does not change), calling 40 /// \c adjustToUnmodifiedLine after the call to \c nextLine will cause 41 /// subsequent lines on the same level to be indented at the same level as the 42 /// given line. 43 class LevelIndentTracker { 44 public: 45 LevelIndentTracker(const FormatStyle &Style, 46 const AdditionalKeywords &Keywords, unsigned StartLevel, 47 int AdditionalIndent) 48 : Style(Style), Keywords(Keywords), AdditionalIndent(AdditionalIndent) { 49 for (unsigned i = 0; i != StartLevel; ++i) 50 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent); 51 } 52 53 /// Returns the indent for the current line. 54 unsigned getIndent() const { return Indent; } 55 56 /// Update the indent state given that \p Line is going to be formatted 57 /// next. 58 void nextLine(const AnnotatedLine &Line) { 59 Offset = getIndentOffset(*Line.First); 60 // Update the indent level cache size so that we can rely on it 61 // having the right size in adjustToUnmodifiedline. 62 while (IndentForLevel.size() <= Line.Level) 63 IndentForLevel.push_back(-1); 64 if (Line.InPPDirective) { 65 unsigned IndentWidth = 66 (Style.PPIndentWidth >= 0) ? Style.PPIndentWidth : Style.IndentWidth; 67 Indent = Line.Level * IndentWidth + AdditionalIndent; 68 } else { 69 IndentForLevel.resize(Line.Level + 1); 70 Indent = getIndent(Line.Level); 71 } 72 if (static_cast<int>(Indent) + Offset >= 0) 73 Indent += Offset; 74 if (Line.First->is(TT_CSharpGenericTypeConstraint)) 75 Indent = Line.Level * Style.IndentWidth + Style.ContinuationIndentWidth; 76 } 77 78 /// Update the indent state given that \p Line indent should be 79 /// skipped. 80 void skipLine(const AnnotatedLine &Line) { 81 while (IndentForLevel.size() <= Line.Level) 82 IndentForLevel.push_back(Indent); 83 } 84 85 /// Update the level indent to adapt to the given \p Line. 86 /// 87 /// When a line is not formatted, we move the subsequent lines on the same 88 /// level to the same indent. 89 /// Note that \c nextLine must have been called before this method. 90 void adjustToUnmodifiedLine(const AnnotatedLine &Line) { 91 unsigned LevelIndent = Line.First->OriginalColumn; 92 if (static_cast<int>(LevelIndent) - Offset >= 0) 93 LevelIndent -= Offset; 94 if ((!Line.First->is(tok::comment) || IndentForLevel[Line.Level] == -1) && 95 !Line.InPPDirective) 96 IndentForLevel[Line.Level] = LevelIndent; 97 } 98 99 private: 100 /// Get the offset of the line relatively to the level. 101 /// 102 /// For example, 'public:' labels in classes are offset by 1 or 2 103 /// characters to the left from their level. 104 int getIndentOffset(const FormatToken &RootToken) { 105 if (Style.Language == FormatStyle::LK_Java || Style.isJavaScript() || 106 Style.isCSharp()) 107 return 0; 108 109 auto IsAccessModifier = [this, &RootToken]() { 110 if (RootToken.isAccessSpecifier(Style.isCpp())) 111 return true; 112 else if (RootToken.isObjCAccessSpecifier()) 113 return true; 114 // Handle Qt signals. 115 else if ((RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) && 116 RootToken.Next && RootToken.Next->is(tok::colon))) 117 return true; 118 else if (RootToken.Next && 119 RootToken.Next->isOneOf(Keywords.kw_slots, Keywords.kw_qslots) && 120 RootToken.Next->Next && RootToken.Next->Next->is(tok::colon)) 121 return true; 122 // Handle malformed access specifier e.g. 'private' without trailing ':'. 123 else if (!RootToken.Next && RootToken.isAccessSpecifier(false)) 124 return true; 125 return false; 126 }; 127 128 if (IsAccessModifier()) { 129 // The AccessModifierOffset may be overridden by IndentAccessModifiers, 130 // in which case we take a negative value of the IndentWidth to simulate 131 // the upper indent level. 132 return Style.IndentAccessModifiers ? -Style.IndentWidth 133 : Style.AccessModifierOffset; 134 } 135 return 0; 136 } 137 138 /// Get the indent of \p Level from \p IndentForLevel. 139 /// 140 /// \p IndentForLevel must contain the indent for the level \c l 141 /// at \p IndentForLevel[l], or a value < 0 if the indent for 142 /// that level is unknown. 143 unsigned getIndent(unsigned Level) const { 144 if (IndentForLevel[Level] != -1) 145 return IndentForLevel[Level]; 146 if (Level == 0) 147 return 0; 148 return getIndent(Level - 1) + Style.IndentWidth; 149 } 150 151 const FormatStyle &Style; 152 const AdditionalKeywords &Keywords; 153 const unsigned AdditionalIndent; 154 155 /// The indent in characters for each level. 156 std::vector<int> IndentForLevel; 157 158 /// Offset of the current line relative to the indent level. 159 /// 160 /// For example, the 'public' keywords is often indented with a negative 161 /// offset. 162 int Offset = 0; 163 164 /// The current line's indent. 165 unsigned Indent = 0; 166 }; 167 168 const FormatToken *getMatchingNamespaceToken( 169 const AnnotatedLine *Line, 170 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) { 171 if (!Line->startsWith(tok::r_brace)) 172 return nullptr; 173 size_t StartLineIndex = Line->MatchingOpeningBlockLineIndex; 174 if (StartLineIndex == UnwrappedLine::kInvalidIndex) 175 return nullptr; 176 assert(StartLineIndex < AnnotatedLines.size()); 177 return AnnotatedLines[StartLineIndex]->First->getNamespaceToken(); 178 } 179 180 StringRef getNamespaceTokenText(const AnnotatedLine *Line) { 181 const FormatToken *NamespaceToken = Line->First->getNamespaceToken(); 182 return NamespaceToken ? NamespaceToken->TokenText : StringRef(); 183 } 184 185 StringRef getMatchingNamespaceTokenText( 186 const AnnotatedLine *Line, 187 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) { 188 const FormatToken *NamespaceToken = 189 getMatchingNamespaceToken(Line, AnnotatedLines); 190 return NamespaceToken ? NamespaceToken->TokenText : StringRef(); 191 } 192 193 class LineJoiner { 194 public: 195 LineJoiner(const FormatStyle &Style, const AdditionalKeywords &Keywords, 196 const SmallVectorImpl<AnnotatedLine *> &Lines) 197 : Style(Style), Keywords(Keywords), End(Lines.end()), Next(Lines.begin()), 198 AnnotatedLines(Lines) {} 199 200 /// Returns the next line, merging multiple lines into one if possible. 201 const AnnotatedLine *getNextMergedLine(bool DryRun, 202 LevelIndentTracker &IndentTracker) { 203 if (Next == End) 204 return nullptr; 205 const AnnotatedLine *Current = *Next; 206 IndentTracker.nextLine(*Current); 207 unsigned MergedLines = tryFitMultipleLinesInOne(IndentTracker, Next, End); 208 if (MergedLines > 0 && Style.ColumnLimit == 0) 209 // Disallow line merging if there is a break at the start of one of the 210 // input lines. 211 for (unsigned i = 0; i < MergedLines; ++i) 212 if (Next[i + 1]->First->NewlinesBefore > 0) 213 MergedLines = 0; 214 if (!DryRun) 215 for (unsigned i = 0; i < MergedLines; ++i) 216 join(*Next[0], *Next[i + 1]); 217 Next = Next + MergedLines + 1; 218 return Current; 219 } 220 221 private: 222 /// Calculates how many lines can be merged into 1 starting at \p I. 223 unsigned 224 tryFitMultipleLinesInOne(LevelIndentTracker &IndentTracker, 225 SmallVectorImpl<AnnotatedLine *>::const_iterator I, 226 SmallVectorImpl<AnnotatedLine *>::const_iterator E) { 227 const unsigned Indent = IndentTracker.getIndent(); 228 229 // Can't join the last line with anything. 230 if (I + 1 == E) 231 return 0; 232 // We can never merge stuff if there are trailing line comments. 233 const AnnotatedLine *TheLine = *I; 234 if (TheLine->Last->is(TT_LineComment)) 235 return 0; 236 const auto &NextLine = *I[1]; 237 if (NextLine.Type == LT_Invalid || NextLine.First->MustBreakBefore) 238 return 0; 239 if (TheLine->InPPDirective && 240 (!NextLine.InPPDirective || NextLine.First->HasUnescapedNewline)) 241 return 0; 242 243 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit) 244 return 0; 245 246 unsigned Limit = 247 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent; 248 // If we already exceed the column limit, we set 'Limit' to 0. The different 249 // tryMerge..() functions can then decide whether to still do merging. 250 Limit = TheLine->Last->TotalLength > Limit 251 ? 0 252 : Limit - TheLine->Last->TotalLength; 253 254 if (TheLine->Last->is(TT_FunctionLBrace) && 255 TheLine->First == TheLine->Last && 256 !Style.BraceWrapping.SplitEmptyFunction && 257 NextLine.First->is(tok::r_brace)) 258 return tryMergeSimpleBlock(I, E, Limit); 259 260 const auto *PreviousLine = I != AnnotatedLines.begin() ? I[-1] : nullptr; 261 // Handle empty record blocks where the brace has already been wrapped. 262 if (PreviousLine && TheLine->Last->is(tok::l_brace) && 263 TheLine->First == TheLine->Last) { 264 bool EmptyBlock = NextLine.First->is(tok::r_brace); 265 266 const FormatToken *Tok = PreviousLine->First; 267 if (Tok && Tok->is(tok::comment)) 268 Tok = Tok->getNextNonComment(); 269 270 if (Tok && Tok->getNamespaceToken()) 271 return !Style.BraceWrapping.SplitEmptyNamespace && EmptyBlock 272 ? tryMergeSimpleBlock(I, E, Limit) 273 : 0; 274 275 if (Tok && Tok->is(tok::kw_typedef)) 276 Tok = Tok->getNextNonComment(); 277 if (Tok && Tok->isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union, 278 tok::kw_extern, Keywords.kw_interface)) 279 return !Style.BraceWrapping.SplitEmptyRecord && EmptyBlock 280 ? tryMergeSimpleBlock(I, E, Limit) 281 : 0; 282 283 if (Tok && Tok->is(tok::kw_template) && 284 Style.BraceWrapping.SplitEmptyRecord && EmptyBlock) 285 return 0; 286 } 287 288 auto ShouldMergeShortFunctions = [this, &I, &NextLine, PreviousLine, 289 TheLine]() { 290 if (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All) 291 return true; 292 if (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty && 293 NextLine.First->is(tok::r_brace)) 294 return true; 295 296 if (Style.AllowShortFunctionsOnASingleLine & 297 FormatStyle::SFS_InlineOnly) { 298 // Just checking TheLine->Level != 0 is not enough, because it 299 // provokes treating functions inside indented namespaces as short. 300 if (Style.isJavaScript() && TheLine->Last->is(TT_FunctionLBrace)) 301 return true; 302 303 if (TheLine->Level != 0) { 304 if (!PreviousLine) 305 return false; 306 307 // TODO: Use IndentTracker to avoid loop? 308 // Find the last line with lower level. 309 const AnnotatedLine *Line = nullptr; 310 for (auto J = I - 1; J >= AnnotatedLines.begin(); --J) { 311 assert(*J); 312 if (!(*J)->InPPDirective && !(*J)->isComment() && 313 (*J)->Level < TheLine->Level) { 314 Line = *J; 315 break; 316 } 317 } 318 319 if (!Line) 320 return false; 321 322 // Check if the found line starts a record. 323 const FormatToken *LastNonComment = Line->Last; 324 assert(LastNonComment); 325 if (LastNonComment->is(tok::comment)) { 326 LastNonComment = LastNonComment->getPreviousNonComment(); 327 // There must be another token (usually `{`), because we chose a 328 // non-PPDirective and non-comment line that has a smaller level. 329 assert(LastNonComment); 330 } 331 return isRecordLBrace(*LastNonComment); 332 } 333 } 334 335 return false; 336 }; 337 338 bool MergeShortFunctions = ShouldMergeShortFunctions(); 339 340 const FormatToken *FirstNonComment = TheLine->First; 341 if (FirstNonComment->is(tok::comment)) { 342 FirstNonComment = FirstNonComment->getNextNonComment(); 343 if (!FirstNonComment) 344 return 0; 345 } 346 // FIXME: There are probably cases where we should use FirstNonComment 347 // instead of TheLine->First. 348 349 if (Style.CompactNamespaces) { 350 if (auto nsToken = TheLine->First->getNamespaceToken()) { 351 int i = 0; 352 unsigned closingLine = TheLine->MatchingClosingBlockLineIndex - 1; 353 for (; I + 1 + i != E && 354 nsToken->TokenText == getNamespaceTokenText(I[i + 1]) && 355 closingLine == I[i + 1]->MatchingClosingBlockLineIndex && 356 I[i + 1]->Last->TotalLength < Limit; 357 i++, --closingLine) { 358 // No extra indent for compacted namespaces. 359 IndentTracker.skipLine(*I[i + 1]); 360 361 Limit -= I[i + 1]->Last->TotalLength; 362 } 363 return i; 364 } 365 366 if (auto nsToken = getMatchingNamespaceToken(TheLine, AnnotatedLines)) { 367 int i = 0; 368 unsigned openingLine = TheLine->MatchingOpeningBlockLineIndex - 1; 369 for (; I + 1 + i != E && 370 nsToken->TokenText == 371 getMatchingNamespaceTokenText(I[i + 1], AnnotatedLines) && 372 openingLine == I[i + 1]->MatchingOpeningBlockLineIndex; 373 i++, --openingLine) { 374 // No space between consecutive braces. 375 I[i + 1]->First->SpacesRequiredBefore = !I[i]->Last->is(tok::r_brace); 376 377 // Indent like the outer-most namespace. 378 IndentTracker.nextLine(*I[i + 1]); 379 } 380 return i; 381 } 382 } 383 384 // Try to merge a function block with left brace unwrapped. 385 if (TheLine->Last->is(TT_FunctionLBrace) && TheLine->First != TheLine->Last) 386 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0; 387 // Try to merge a control statement block with left brace unwrapped. 388 if (TheLine->Last->is(tok::l_brace) && FirstNonComment != TheLine->Last && 389 FirstNonComment->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for, 390 TT_ForEachMacro)) { 391 return Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never 392 ? tryMergeSimpleBlock(I, E, Limit) 393 : 0; 394 } 395 // Try to merge a control statement block with left brace wrapped. 396 if (NextLine.First->is(tok::l_brace)) { 397 if ((TheLine->First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while, 398 tok::kw_for, tok::kw_switch, tok::kw_try, 399 tok::kw_do, TT_ForEachMacro) || 400 (TheLine->First->is(tok::r_brace) && TheLine->First->Next && 401 TheLine->First->Next->isOneOf(tok::kw_else, tok::kw_catch))) && 402 Style.BraceWrapping.AfterControlStatement == 403 FormatStyle::BWACS_MultiLine) { 404 // If possible, merge the next line's wrapped left brace with the 405 // current line. Otherwise, leave it on the next line, as this is a 406 // multi-line control statement. 407 return (Style.ColumnLimit == 0 || 408 TheLine->Last->TotalLength <= Style.ColumnLimit) 409 ? 1 410 : 0; 411 } 412 if (TheLine->First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while, 413 tok::kw_for, TT_ForEachMacro)) { 414 return (Style.BraceWrapping.AfterControlStatement == 415 FormatStyle::BWACS_Always) 416 ? tryMergeSimpleBlock(I, E, Limit) 417 : 0; 418 } 419 if (TheLine->First->isOneOf(tok::kw_else, tok::kw_catch) && 420 Style.BraceWrapping.AfterControlStatement == 421 FormatStyle::BWACS_MultiLine) { 422 // This case if different from the upper BWACS_MultiLine processing 423 // in that a preceding r_brace is not on the same line as else/catch 424 // most likely because of BeforeElse/BeforeCatch set to true. 425 // If the line length doesn't fit ColumnLimit, leave l_brace on the 426 // next line to respect the BWACS_MultiLine. 427 return (Style.ColumnLimit == 0 || 428 TheLine->Last->TotalLength <= Style.ColumnLimit) 429 ? 1 430 : 0; 431 } 432 } 433 if (PreviousLine && TheLine->First->is(tok::l_brace)) { 434 switch (PreviousLine->First->Tok.getKind()) { 435 case tok::at: 436 // Don't merge block with left brace wrapped after ObjC special blocks. 437 if (PreviousLine->First->Next) { 438 tok::ObjCKeywordKind kwId = 439 PreviousLine->First->Next->Tok.getObjCKeywordID(); 440 if (kwId == tok::objc_autoreleasepool || 441 kwId == tok::objc_synchronized) 442 return 0; 443 } 444 break; 445 446 case tok::kw_case: 447 case tok::kw_default: 448 // Don't merge block with left brace wrapped after case labels. 449 return 0; 450 451 default: 452 break; 453 } 454 } 455 456 // Don't merge an empty template class or struct if SplitEmptyRecords 457 // is defined. 458 if (PreviousLine && Style.BraceWrapping.SplitEmptyRecord && 459 TheLine->Last->is(tok::l_brace) && PreviousLine->Last) { 460 const FormatToken *Previous = PreviousLine->Last; 461 if (Previous) { 462 if (Previous->is(tok::comment)) 463 Previous = Previous->getPreviousNonComment(); 464 if (Previous) { 465 if (Previous->is(tok::greater) && !PreviousLine->InPPDirective) 466 return 0; 467 if (Previous->is(tok::identifier)) { 468 const FormatToken *PreviousPrevious = 469 Previous->getPreviousNonComment(); 470 if (PreviousPrevious && 471 PreviousPrevious->isOneOf(tok::kw_class, tok::kw_struct)) 472 return 0; 473 } 474 } 475 } 476 } 477 478 if (TheLine->Last->is(tok::l_brace)) { 479 bool ShouldMerge = false; 480 // Try to merge records. 481 if (TheLine->Last->is(TT_EnumLBrace)) { 482 ShouldMerge = Style.AllowShortEnumsOnASingleLine; 483 } else if (TheLine->Last->isOneOf(TT_ClassLBrace, TT_StructLBrace)) { 484 // NOTE: We use AfterClass (whereas AfterStruct exists) for both classes 485 // and structs, but it seems that wrapping is still handled correctly 486 // elsewhere. 487 ShouldMerge = !Style.BraceWrapping.AfterClass || 488 (NextLine.First->is(tok::r_brace) && 489 !Style.BraceWrapping.SplitEmptyRecord); 490 } else { 491 // Try to merge a block with left brace unwrapped that wasn't yet 492 // covered. 493 assert(TheLine->InPPDirective || 494 !TheLine->First->isOneOf(tok::kw_class, tok::kw_enum, 495 tok::kw_struct)); 496 ShouldMerge = !Style.BraceWrapping.AfterFunction || 497 (NextLine.First->is(tok::r_brace) && 498 !Style.BraceWrapping.SplitEmptyFunction); 499 } 500 return ShouldMerge ? tryMergeSimpleBlock(I, E, Limit) : 0; 501 } 502 503 // Try to merge a function block with left brace wrapped. 504 if (NextLine.First->is(TT_FunctionLBrace) && 505 Style.BraceWrapping.AfterFunction) { 506 if (NextLine.Last->is(TT_LineComment)) 507 return 0; 508 509 // Check for Limit <= 2 to account for the " {". 510 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine))) 511 return 0; 512 Limit -= 2; 513 514 unsigned MergedLines = 0; 515 if (MergeShortFunctions || 516 (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty && 517 NextLine.First == NextLine.Last && I + 2 != E && 518 I[2]->First->is(tok::r_brace))) { 519 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit); 520 // If we managed to merge the block, count the function header, which is 521 // on a separate line. 522 if (MergedLines > 0) 523 ++MergedLines; 524 } 525 return MergedLines; 526 } 527 auto IsElseLine = [&TheLine]() -> bool { 528 const FormatToken *First = TheLine->First; 529 if (First->is(tok::kw_else)) 530 return true; 531 532 return First->is(tok::r_brace) && First->Next && 533 First->Next->is(tok::kw_else); 534 }; 535 if (TheLine->First->is(tok::kw_if) || 536 (IsElseLine() && (Style.AllowShortIfStatementsOnASingleLine == 537 FormatStyle::SIS_AllIfsAndElse))) { 538 return Style.AllowShortIfStatementsOnASingleLine 539 ? tryMergeSimpleControlStatement(I, E, Limit) 540 : 0; 541 } 542 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while, tok::kw_do, 543 TT_ForEachMacro)) { 544 return Style.AllowShortLoopsOnASingleLine 545 ? tryMergeSimpleControlStatement(I, E, Limit) 546 : 0; 547 } 548 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) { 549 return Style.AllowShortCaseLabelsOnASingleLine 550 ? tryMergeShortCaseLabels(I, E, Limit) 551 : 0; 552 } 553 if (TheLine->InPPDirective && 554 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) 555 return tryMergeSimplePPDirective(I, E, Limit); 556 return 0; 557 } 558 559 unsigned 560 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I, 561 SmallVectorImpl<AnnotatedLine *>::const_iterator E, 562 unsigned Limit) { 563 if (Limit == 0) 564 return 0; 565 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline) 566 return 0; 567 if (1 + I[1]->Last->TotalLength > Limit) 568 return 0; 569 return 1; 570 } 571 572 unsigned tryMergeSimpleControlStatement( 573 SmallVectorImpl<AnnotatedLine *>::const_iterator I, 574 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) { 575 if (Limit == 0) 576 return 0; 577 if (Style.BraceWrapping.AfterControlStatement == 578 FormatStyle::BWACS_Always && 579 I[1]->First->is(tok::l_brace) && 580 Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never) 581 return 0; 582 if (I[1]->InPPDirective != (*I)->InPPDirective || 583 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline)) 584 return 0; 585 Limit = limitConsideringMacros(I + 1, E, Limit); 586 AnnotatedLine &Line = **I; 587 if (!Line.First->is(tok::kw_do) && !Line.First->is(tok::kw_else) && 588 !Line.Last->is(tok::kw_else) && Line.Last->isNot(tok::r_paren)) 589 return 0; 590 // Only merge `do while` if `do` is the only statement on the line. 591 if (Line.First->is(tok::kw_do) && !Line.Last->is(tok::kw_do)) 592 return 0; 593 if (1 + I[1]->Last->TotalLength > Limit) 594 return 0; 595 // Don't merge with loops, ifs, a single semicolon or a line comment. 596 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while, 597 TT_ForEachMacro, TT_LineComment)) 598 return 0; 599 // Only inline simple if's (no nested if or else), unless specified 600 if (Style.AllowShortIfStatementsOnASingleLine == 601 FormatStyle::SIS_WithoutElse) { 602 if (I + 2 != E && Line.startsWith(tok::kw_if) && 603 I[2]->First->is(tok::kw_else)) 604 return 0; 605 } 606 return 1; 607 } 608 609 unsigned 610 tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I, 611 SmallVectorImpl<AnnotatedLine *>::const_iterator E, 612 unsigned Limit) { 613 if (Limit == 0 || I + 1 == E || 614 I[1]->First->isOneOf(tok::kw_case, tok::kw_default)) 615 return 0; 616 if (I[0]->Last->is(tok::l_brace) || I[1]->First->is(tok::l_brace)) 617 return 0; 618 unsigned NumStmts = 0; 619 unsigned Length = 0; 620 bool EndsWithComment = false; 621 bool InPPDirective = I[0]->InPPDirective; 622 const unsigned Level = I[0]->Level; 623 for (; NumStmts < 3; ++NumStmts) { 624 if (I + 1 + NumStmts == E) 625 break; 626 const AnnotatedLine *Line = I[1 + NumStmts]; 627 if (Line->InPPDirective != InPPDirective) 628 break; 629 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace)) 630 break; 631 if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch, 632 tok::kw_while) || 633 EndsWithComment) 634 return 0; 635 if (Line->First->is(tok::comment)) { 636 if (Level != Line->Level) 637 return 0; 638 SmallVectorImpl<AnnotatedLine *>::const_iterator J = I + 2 + NumStmts; 639 for (; J != E; ++J) { 640 Line = *J; 641 if (Line->InPPDirective != InPPDirective) 642 break; 643 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace)) 644 break; 645 if (Line->First->isNot(tok::comment) || Level != Line->Level) 646 return 0; 647 } 648 break; 649 } 650 if (Line->Last->is(tok::comment)) 651 EndsWithComment = true; 652 Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space. 653 } 654 if (NumStmts == 0 || NumStmts == 3 || Length > Limit) 655 return 0; 656 return NumStmts; 657 } 658 659 unsigned 660 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I, 661 SmallVectorImpl<AnnotatedLine *>::const_iterator E, 662 unsigned Limit) { 663 // Don't merge with a preprocessor directive. 664 if (I[1]->Type == LT_PreprocessorDirective) 665 return 0; 666 667 AnnotatedLine &Line = **I; 668 669 // Don't merge ObjC @ keywords and methods. 670 // FIXME: If an option to allow short exception handling clauses on a single 671 // line is added, change this to not return for @try and friends. 672 if (Style.Language != FormatStyle::LK_Java && 673 Line.First->isOneOf(tok::at, tok::minus, tok::plus)) 674 return 0; 675 676 // Check that the current line allows merging. This depends on whether we 677 // are in a control flow statements as well as several style flags. 678 if (Line.First->is(tok::kw_case) || 679 (Line.First->Next && Line.First->Next->is(tok::kw_else))) 680 return 0; 681 // default: in switch statement 682 if (Line.First->is(tok::kw_default)) { 683 const FormatToken *Tok = Line.First->getNextNonComment(); 684 if (Tok && Tok->is(tok::colon)) 685 return 0; 686 } 687 if (Line.First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while, tok::kw_do, 688 tok::kw_try, tok::kw___try, tok::kw_catch, 689 tok::kw___finally, tok::kw_for, TT_ForEachMacro, 690 tok::r_brace, Keywords.kw___except)) { 691 if (Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never) 692 return 0; 693 if (Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Empty && 694 !I[1]->First->is(tok::r_brace)) 695 return 0; 696 // Don't merge when we can't except the case when 697 // the control statement block is empty 698 if (!Style.AllowShortIfStatementsOnASingleLine && 699 Line.First->isOneOf(tok::kw_if, tok::kw_else) && 700 !Style.BraceWrapping.AfterControlStatement && 701 !I[1]->First->is(tok::r_brace)) 702 return 0; 703 if (!Style.AllowShortIfStatementsOnASingleLine && 704 Line.First->isOneOf(tok::kw_if, tok::kw_else) && 705 Style.BraceWrapping.AfterControlStatement == 706 FormatStyle::BWACS_Always && 707 I + 2 != E && !I[2]->First->is(tok::r_brace)) 708 return 0; 709 if (!Style.AllowShortLoopsOnASingleLine && 710 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for, 711 TT_ForEachMacro) && 712 !Style.BraceWrapping.AfterControlStatement && 713 !I[1]->First->is(tok::r_brace)) 714 return 0; 715 if (!Style.AllowShortLoopsOnASingleLine && 716 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for, 717 TT_ForEachMacro) && 718 Style.BraceWrapping.AfterControlStatement == 719 FormatStyle::BWACS_Always && 720 I + 2 != E && !I[2]->First->is(tok::r_brace)) 721 return 0; 722 // FIXME: Consider an option to allow short exception handling clauses on 723 // a single line. 724 // FIXME: This isn't covered by tests. 725 // FIXME: For catch, __except, __finally the first token on the line 726 // is '}', so this isn't correct here. 727 if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch, 728 Keywords.kw___except, tok::kw___finally)) 729 return 0; 730 } 731 732 if (Line.Last->is(tok::l_brace)) { 733 FormatToken *Tok = I[1]->First; 734 auto ShouldMerge = [Tok]() { 735 if (Tok->isNot(tok::r_brace) || Tok->MustBreakBefore) 736 return false; 737 const FormatToken *Next = Tok->getNextNonComment(); 738 return !Next || Next->is(tok::semi); 739 }; 740 741 if (ShouldMerge()) { 742 // We merge empty blocks even if the line exceeds the column limit. 743 Tok->SpacesRequiredBefore = Style.SpaceInEmptyBlock ? 1 : 0; 744 Tok->CanBreakBefore = true; 745 return 1; 746 } else if (Limit != 0 && !Line.startsWithNamespace() && 747 !startsExternCBlock(Line)) { 748 // We don't merge short records. 749 if (isRecordLBrace(*Line.Last)) 750 return 0; 751 752 // Check that we still have three lines and they fit into the limit. 753 if (I + 2 == E || I[2]->Type == LT_Invalid) 754 return 0; 755 Limit = limitConsideringMacros(I + 2, E, Limit); 756 757 if (!nextTwoLinesFitInto(I, Limit)) 758 return 0; 759 760 // Second, check that the next line does not contain any braces - if it 761 // does, readability declines when putting it into a single line. 762 if (I[1]->Last->is(TT_LineComment)) 763 return 0; 764 do { 765 if (Tok->is(tok::l_brace) && Tok->isNot(BK_BracedInit)) 766 return 0; 767 Tok = Tok->Next; 768 } while (Tok); 769 770 // Last, check that the third line starts with a closing brace. 771 Tok = I[2]->First; 772 if (Tok->isNot(tok::r_brace)) 773 return 0; 774 775 // Don't merge "if (a) { .. } else {". 776 if (Tok->Next && Tok->Next->is(tok::kw_else)) 777 return 0; 778 779 // Don't merge a trailing multi-line control statement block like: 780 // } else if (foo && 781 // bar) 782 // { <-- current Line 783 // baz(); 784 // } 785 if (Line.First == Line.Last && Line.First->isNot(TT_FunctionLBrace) && 786 Style.BraceWrapping.AfterControlStatement == 787 FormatStyle::BWACS_MultiLine) 788 return 0; 789 790 return 2; 791 } 792 } else if (I[1]->First->is(tok::l_brace)) { 793 if (I[1]->Last->is(TT_LineComment)) 794 return 0; 795 796 // Check for Limit <= 2 to account for the " {". 797 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(*I))) 798 return 0; 799 Limit -= 2; 800 unsigned MergedLines = 0; 801 if (Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never || 802 (I[1]->First == I[1]->Last && I + 2 != E && 803 I[2]->First->is(tok::r_brace))) { 804 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit); 805 // If we managed to merge the block, count the statement header, which 806 // is on a separate line. 807 if (MergedLines > 0) 808 ++MergedLines; 809 } 810 return MergedLines; 811 } 812 return 0; 813 } 814 815 /// Returns the modified column limit for \p I if it is inside a macro and 816 /// needs a trailing '\'. 817 unsigned 818 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I, 819 SmallVectorImpl<AnnotatedLine *>::const_iterator E, 820 unsigned Limit) { 821 if (I[0]->InPPDirective && I + 1 != E && 822 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) 823 return Limit < 2 ? 0 : Limit - 2; 824 return Limit; 825 } 826 827 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I, 828 unsigned Limit) { 829 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore) 830 return false; 831 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit; 832 } 833 834 bool containsMustBreak(const AnnotatedLine *Line) { 835 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) 836 if (Tok->MustBreakBefore) 837 return true; 838 return false; 839 } 840 841 void join(AnnotatedLine &A, const AnnotatedLine &B) { 842 assert(!A.Last->Next); 843 assert(!B.First->Previous); 844 if (B.Affected) 845 A.Affected = true; 846 A.Last->Next = B.First; 847 B.First->Previous = A.Last; 848 B.First->CanBreakBefore = true; 849 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore; 850 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) { 851 Tok->TotalLength += LengthA; 852 A.Last = Tok; 853 } 854 } 855 856 const FormatStyle &Style; 857 const AdditionalKeywords &Keywords; 858 const SmallVectorImpl<AnnotatedLine *>::const_iterator End; 859 860 SmallVectorImpl<AnnotatedLine *>::const_iterator Next; 861 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines; 862 }; 863 864 static void markFinalized(FormatToken *Tok) { 865 for (; Tok; Tok = Tok->Next) { 866 Tok->Finalized = true; 867 for (AnnotatedLine *Child : Tok->Children) 868 markFinalized(Child->First); 869 } 870 } 871 872 #ifndef NDEBUG 873 static void printLineState(const LineState &State) { 874 llvm::dbgs() << "State: "; 875 for (const ParenState &P : State.Stack) { 876 llvm::dbgs() << (P.Tok ? P.Tok->TokenText : "F") << "|" << P.Indent << "|" 877 << P.LastSpace << "|" << P.NestedBlockIndent << " "; 878 } 879 llvm::dbgs() << State.NextToken->TokenText << "\n"; 880 } 881 #endif 882 883 /// Base class for classes that format one \c AnnotatedLine. 884 class LineFormatter { 885 public: 886 LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces, 887 const FormatStyle &Style, 888 UnwrappedLineFormatter *BlockFormatter) 889 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style), 890 BlockFormatter(BlockFormatter) {} 891 virtual ~LineFormatter() {} 892 893 /// Formats an \c AnnotatedLine and returns the penalty. 894 /// 895 /// If \p DryRun is \c false, directly applies the changes. 896 virtual unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent, 897 unsigned FirstStartColumn, bool DryRun) = 0; 898 899 protected: 900 /// If the \p State's next token is an r_brace closing a nested block, 901 /// format the nested block before it. 902 /// 903 /// Returns \c true if all children could be placed successfully and adapts 904 /// \p Penalty as well as \p State. If \p DryRun is false, also directly 905 /// creates changes using \c Whitespaces. 906 /// 907 /// The crucial idea here is that children always get formatted upon 908 /// encountering the closing brace right after the nested block. Now, if we 909 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is 910 /// \c false), the entire block has to be kept on the same line (which is only 911 /// possible if it fits on the line, only contains a single statement, etc. 912 /// 913 /// If \p NewLine is true, we format the nested block on separate lines, i.e. 914 /// break after the "{", format all lines with correct indentation and the put 915 /// the closing "}" on yet another new line. 916 /// 917 /// This enables us to keep the simple structure of the 918 /// \c UnwrappedLineFormatter, where we only have two options for each token: 919 /// break or don't break. 920 bool formatChildren(LineState &State, bool NewLine, bool DryRun, 921 unsigned &Penalty) { 922 const FormatToken *LBrace = State.NextToken->getPreviousNonComment(); 923 FormatToken &Previous = *State.NextToken->Previous; 924 if (!LBrace || LBrace->isNot(tok::l_brace) || LBrace->isNot(BK_Block) || 925 Previous.Children.size() == 0) 926 // The previous token does not open a block. Nothing to do. We don't 927 // assert so that we can simply call this function for all tokens. 928 return true; 929 930 if (NewLine) { 931 const ParenState &P = State.Stack.back(); 932 933 int AdditionalIndent = 934 P.Indent - Previous.Children[0]->Level * Style.IndentWidth; 935 936 if (Style.LambdaBodyIndentation == FormatStyle::LBI_OuterScope && 937 P.NestedBlockIndent == P.LastSpace) { 938 if (State.NextToken->MatchingParen && 939 State.NextToken->MatchingParen->is(TT_LambdaLBrace)) 940 State.Stack.pop_back(); 941 if (LBrace->is(TT_LambdaLBrace)) 942 AdditionalIndent = 0; 943 } 944 945 Penalty += 946 BlockFormatter->format(Previous.Children, DryRun, AdditionalIndent, 947 /*FixBadIndentation=*/true); 948 return true; 949 } 950 951 if (Previous.Children[0]->First->MustBreakBefore) 952 return false; 953 954 // Cannot merge into one line if this line ends on a comment. 955 if (Previous.is(tok::comment)) 956 return false; 957 958 // Cannot merge multiple statements into a single line. 959 if (Previous.Children.size() > 1) 960 return false; 961 962 const AnnotatedLine *Child = Previous.Children[0]; 963 // We can't put the closing "}" on a line with a trailing comment. 964 if (Child->Last->isTrailingComment()) 965 return false; 966 967 // If the child line exceeds the column limit, we wouldn't want to merge it. 968 // We add +2 for the trailing " }". 969 if (Style.ColumnLimit > 0 && 970 Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit) 971 return false; 972 973 if (!DryRun) { 974 Whitespaces->replaceWhitespace( 975 *Child->First, /*Newlines=*/0, /*Spaces=*/1, 976 /*StartOfTokenColumn=*/State.Column, /*IsAligned=*/false, 977 State.Line->InPPDirective); 978 } 979 Penalty += 980 formatLine(*Child, State.Column + 1, /*FirstStartColumn=*/0, DryRun); 981 982 State.Column += 1 + Child->Last->TotalLength; 983 return true; 984 } 985 986 ContinuationIndenter *Indenter; 987 988 private: 989 WhitespaceManager *Whitespaces; 990 const FormatStyle &Style; 991 UnwrappedLineFormatter *BlockFormatter; 992 }; 993 994 /// Formatter that keeps the existing line breaks. 995 class NoColumnLimitLineFormatter : public LineFormatter { 996 public: 997 NoColumnLimitLineFormatter(ContinuationIndenter *Indenter, 998 WhitespaceManager *Whitespaces, 999 const FormatStyle &Style, 1000 UnwrappedLineFormatter *BlockFormatter) 1001 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {} 1002 1003 /// Formats the line, simply keeping all of the input's line breaking 1004 /// decisions. 1005 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent, 1006 unsigned FirstStartColumn, bool DryRun) override { 1007 assert(!DryRun); 1008 LineState State = Indenter->getInitialState(FirstIndent, FirstStartColumn, 1009 &Line, /*DryRun=*/false); 1010 while (State.NextToken) { 1011 bool Newline = 1012 Indenter->mustBreak(State) || 1013 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0); 1014 unsigned Penalty = 0; 1015 formatChildren(State, Newline, /*DryRun=*/false, Penalty); 1016 Indenter->addTokenToState(State, Newline, /*DryRun=*/false); 1017 } 1018 return 0; 1019 } 1020 }; 1021 1022 /// Formatter that puts all tokens into a single line without breaks. 1023 class NoLineBreakFormatter : public LineFormatter { 1024 public: 1025 NoLineBreakFormatter(ContinuationIndenter *Indenter, 1026 WhitespaceManager *Whitespaces, const FormatStyle &Style, 1027 UnwrappedLineFormatter *BlockFormatter) 1028 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {} 1029 1030 /// Puts all tokens into a single line. 1031 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent, 1032 unsigned FirstStartColumn, bool DryRun) override { 1033 unsigned Penalty = 0; 1034 LineState State = 1035 Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun); 1036 while (State.NextToken) { 1037 formatChildren(State, /*NewLine=*/false, DryRun, Penalty); 1038 Indenter->addTokenToState( 1039 State, /*Newline=*/State.NextToken->MustBreakBefore, DryRun); 1040 } 1041 return Penalty; 1042 } 1043 }; 1044 1045 /// Finds the best way to break lines. 1046 class OptimizingLineFormatter : public LineFormatter { 1047 public: 1048 OptimizingLineFormatter(ContinuationIndenter *Indenter, 1049 WhitespaceManager *Whitespaces, 1050 const FormatStyle &Style, 1051 UnwrappedLineFormatter *BlockFormatter) 1052 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {} 1053 1054 /// Formats the line by finding the best line breaks with line lengths 1055 /// below the column limit. 1056 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent, 1057 unsigned FirstStartColumn, bool DryRun) override { 1058 LineState State = 1059 Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun); 1060 1061 // If the ObjC method declaration does not fit on a line, we should format 1062 // it with one arg per line. 1063 if (State.Line->Type == LT_ObjCMethodDecl) 1064 State.Stack.back().BreakBeforeParameter = true; 1065 1066 // Find best solution in solution space. 1067 return analyzeSolutionSpace(State, DryRun); 1068 } 1069 1070 private: 1071 struct CompareLineStatePointers { 1072 bool operator()(LineState *obj1, LineState *obj2) const { 1073 return *obj1 < *obj2; 1074 } 1075 }; 1076 1077 /// A pair of <penalty, count> that is used to prioritize the BFS on. 1078 /// 1079 /// In case of equal penalties, we want to prefer states that were inserted 1080 /// first. During state generation we make sure that we insert states first 1081 /// that break the line as late as possible. 1082 typedef std::pair<unsigned, unsigned> OrderedPenalty; 1083 1084 /// An edge in the solution space from \c Previous->State to \c State, 1085 /// inserting a newline dependent on the \c NewLine. 1086 struct StateNode { 1087 StateNode(const LineState &State, bool NewLine, StateNode *Previous) 1088 : State(State), NewLine(NewLine), Previous(Previous) {} 1089 LineState State; 1090 bool NewLine; 1091 StateNode *Previous; 1092 }; 1093 1094 /// An item in the prioritized BFS search queue. The \c StateNode's 1095 /// \c State has the given \c OrderedPenalty. 1096 typedef std::pair<OrderedPenalty, StateNode *> QueueItem; 1097 1098 /// The BFS queue type. 1099 typedef std::priority_queue<QueueItem, std::vector<QueueItem>, 1100 std::greater<QueueItem>> 1101 QueueType; 1102 1103 /// Analyze the entire solution space starting from \p InitialState. 1104 /// 1105 /// This implements a variant of Dijkstra's algorithm on the graph that spans 1106 /// the solution space (\c LineStates are the nodes). The algorithm tries to 1107 /// find the shortest path (the one with lowest penalty) from \p InitialState 1108 /// to a state where all tokens are placed. Returns the penalty. 1109 /// 1110 /// If \p DryRun is \c false, directly applies the changes. 1111 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun) { 1112 std::set<LineState *, CompareLineStatePointers> Seen; 1113 1114 // Increasing count of \c StateNode items we have created. This is used to 1115 // create a deterministic order independent of the container. 1116 unsigned Count = 0; 1117 QueueType Queue; 1118 1119 // Insert start element into queue. 1120 StateNode *RootNode = 1121 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr); 1122 Queue.push(QueueItem(OrderedPenalty(0, Count), RootNode)); 1123 ++Count; 1124 1125 unsigned Penalty = 0; 1126 1127 // While not empty, take first element and follow edges. 1128 while (!Queue.empty()) { 1129 Penalty = Queue.top().first.first; 1130 StateNode *Node = Queue.top().second; 1131 if (!Node->State.NextToken) { 1132 LLVM_DEBUG(llvm::dbgs() 1133 << "\n---\nPenalty for line: " << Penalty << "\n"); 1134 break; 1135 } 1136 Queue.pop(); 1137 1138 // Cut off the analysis of certain solutions if the analysis gets too 1139 // complex. See description of IgnoreStackForComparison. 1140 if (Count > 50000) 1141 Node->State.IgnoreStackForComparison = true; 1142 1143 if (!Seen.insert(&Node->State).second) 1144 // State already examined with lower penalty. 1145 continue; 1146 1147 FormatDecision LastFormat = Node->State.NextToken->getDecision(); 1148 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue) 1149 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue); 1150 if (LastFormat == FD_Unformatted || LastFormat == FD_Break) 1151 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue); 1152 } 1153 1154 if (Queue.empty()) { 1155 // We were unable to find a solution, do nothing. 1156 // FIXME: Add diagnostic? 1157 LLVM_DEBUG(llvm::dbgs() << "Could not find a solution.\n"); 1158 return 0; 1159 } 1160 1161 // Reconstruct the solution. 1162 if (!DryRun) 1163 reconstructPath(InitialState, Queue.top().second); 1164 1165 LLVM_DEBUG(llvm::dbgs() 1166 << "Total number of analyzed states: " << Count << "\n"); 1167 LLVM_DEBUG(llvm::dbgs() << "---\n"); 1168 1169 return Penalty; 1170 } 1171 1172 /// Add the following state to the analysis queue \c Queue. 1173 /// 1174 /// Assume the current state is \p PreviousNode and has been reached with a 1175 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true. 1176 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode, 1177 bool NewLine, unsigned *Count, QueueType *Queue) { 1178 if (NewLine && !Indenter->canBreak(PreviousNode->State)) 1179 return; 1180 if (!NewLine && Indenter->mustBreak(PreviousNode->State)) 1181 return; 1182 1183 StateNode *Node = new (Allocator.Allocate()) 1184 StateNode(PreviousNode->State, NewLine, PreviousNode); 1185 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty)) 1186 return; 1187 1188 Penalty += Indenter->addTokenToState(Node->State, NewLine, true); 1189 1190 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node)); 1191 ++(*Count); 1192 } 1193 1194 /// Applies the best formatting by reconstructing the path in the 1195 /// solution space that leads to \c Best. 1196 void reconstructPath(LineState &State, StateNode *Best) { 1197 llvm::SmallVector<StateNode *> Path; 1198 // We do not need a break before the initial token. 1199 while (Best->Previous) { 1200 Path.push_back(Best); 1201 Best = Best->Previous; 1202 } 1203 for (const auto &Node : llvm::reverse(Path)) { 1204 unsigned Penalty = 0; 1205 formatChildren(State, Node->NewLine, /*DryRun=*/false, Penalty); 1206 Penalty += Indenter->addTokenToState(State, Node->NewLine, false); 1207 1208 LLVM_DEBUG({ 1209 printLineState(Node->Previous->State); 1210 if (Node->NewLine) 1211 llvm::dbgs() << "Penalty for placing " 1212 << Node->Previous->State.NextToken->Tok.getName() 1213 << " on a new line: " << Penalty << "\n"; 1214 }); 1215 } 1216 } 1217 1218 llvm::SpecificBumpPtrAllocator<StateNode> Allocator; 1219 }; 1220 1221 } // anonymous namespace 1222 1223 unsigned UnwrappedLineFormatter::format( 1224 const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun, 1225 int AdditionalIndent, bool FixBadIndentation, unsigned FirstStartColumn, 1226 unsigned NextStartColumn, unsigned LastStartColumn) { 1227 LineJoiner Joiner(Style, Keywords, Lines); 1228 1229 // Try to look up already computed penalty in DryRun-mode. 1230 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey( 1231 &Lines, AdditionalIndent); 1232 auto CacheIt = PenaltyCache.find(CacheKey); 1233 if (DryRun && CacheIt != PenaltyCache.end()) 1234 return CacheIt->second; 1235 1236 assert(!Lines.empty()); 1237 unsigned Penalty = 0; 1238 LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level, 1239 AdditionalIndent); 1240 const AnnotatedLine *PrevPrevLine = nullptr; 1241 const AnnotatedLine *PreviousLine = nullptr; 1242 const AnnotatedLine *NextLine = nullptr; 1243 1244 // The minimum level of consecutive lines that have been formatted. 1245 unsigned RangeMinLevel = UINT_MAX; 1246 1247 bool FirstLine = true; 1248 for (const AnnotatedLine *Line = 1249 Joiner.getNextMergedLine(DryRun, IndentTracker); 1250 Line; PrevPrevLine = PreviousLine, PreviousLine = Line, Line = NextLine, 1251 FirstLine = false) { 1252 assert(Line->First); 1253 const AnnotatedLine &TheLine = *Line; 1254 unsigned Indent = IndentTracker.getIndent(); 1255 1256 // We continue formatting unchanged lines to adjust their indent, e.g. if a 1257 // scope was added. However, we need to carefully stop doing this when we 1258 // exit the scope of affected lines to prevent indenting a the entire 1259 // remaining file if it currently missing a closing brace. 1260 bool PreviousRBrace = 1261 PreviousLine && PreviousLine->startsWith(tok::r_brace); 1262 bool ContinueFormatting = 1263 TheLine.Level > RangeMinLevel || 1264 (TheLine.Level == RangeMinLevel && !PreviousRBrace && 1265 !TheLine.startsWith(tok::r_brace)); 1266 1267 bool FixIndentation = (FixBadIndentation || ContinueFormatting) && 1268 Indent != TheLine.First->OriginalColumn; 1269 bool ShouldFormat = TheLine.Affected || FixIndentation; 1270 // We cannot format this line; if the reason is that the line had a 1271 // parsing error, remember that. 1272 if (ShouldFormat && TheLine.Type == LT_Invalid && Status) { 1273 Status->FormatComplete = false; 1274 Status->Line = 1275 SourceMgr.getSpellingLineNumber(TheLine.First->Tok.getLocation()); 1276 } 1277 1278 if (ShouldFormat && TheLine.Type != LT_Invalid) { 1279 if (!DryRun) { 1280 bool LastLine = TheLine.First->is(tok::eof); 1281 formatFirstToken(TheLine, PreviousLine, PrevPrevLine, Lines, Indent, 1282 LastLine ? LastStartColumn : NextStartColumn + Indent); 1283 } 1284 1285 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker); 1286 unsigned ColumnLimit = getColumnLimit(TheLine.InPPDirective, NextLine); 1287 bool FitsIntoOneLine = 1288 TheLine.Last->TotalLength + Indent <= ColumnLimit || 1289 (TheLine.Type == LT_ImportStatement && 1290 (!Style.isJavaScript() || !Style.JavaScriptWrapImports)) || 1291 (Style.isCSharp() && 1292 TheLine.InPPDirective); // don't split #regions in C# 1293 if (Style.ColumnLimit == 0) 1294 NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this) 1295 .formatLine(TheLine, NextStartColumn + Indent, 1296 FirstLine ? FirstStartColumn : 0, DryRun); 1297 else if (FitsIntoOneLine) 1298 Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this) 1299 .formatLine(TheLine, NextStartColumn + Indent, 1300 FirstLine ? FirstStartColumn : 0, DryRun); 1301 else 1302 Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this) 1303 .formatLine(TheLine, NextStartColumn + Indent, 1304 FirstLine ? FirstStartColumn : 0, DryRun); 1305 RangeMinLevel = std::min(RangeMinLevel, TheLine.Level); 1306 } else { 1307 // If no token in the current line is affected, we still need to format 1308 // affected children. 1309 if (TheLine.ChildrenAffected) 1310 for (const FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) 1311 if (!Tok->Children.empty()) 1312 format(Tok->Children, DryRun); 1313 1314 // Adapt following lines on the current indent level to the same level 1315 // unless the current \c AnnotatedLine is not at the beginning of a line. 1316 bool StartsNewLine = 1317 TheLine.First->NewlinesBefore > 0 || TheLine.First->IsFirst; 1318 if (StartsNewLine) 1319 IndentTracker.adjustToUnmodifiedLine(TheLine); 1320 if (!DryRun) { 1321 bool ReformatLeadingWhitespace = 1322 StartsNewLine && ((PreviousLine && PreviousLine->Affected) || 1323 TheLine.LeadingEmptyLinesAffected); 1324 // Format the first token. 1325 if (ReformatLeadingWhitespace) 1326 formatFirstToken(TheLine, PreviousLine, PrevPrevLine, Lines, 1327 TheLine.First->OriginalColumn, 1328 TheLine.First->OriginalColumn); 1329 else 1330 Whitespaces->addUntouchableToken(*TheLine.First, 1331 TheLine.InPPDirective); 1332 1333 // Notify the WhitespaceManager about the unchanged whitespace. 1334 for (FormatToken *Tok = TheLine.First->Next; Tok; Tok = Tok->Next) 1335 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective); 1336 } 1337 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker); 1338 RangeMinLevel = UINT_MAX; 1339 } 1340 if (!DryRun) 1341 markFinalized(TheLine.First); 1342 } 1343 PenaltyCache[CacheKey] = Penalty; 1344 return Penalty; 1345 } 1346 1347 void UnwrappedLineFormatter::formatFirstToken( 1348 const AnnotatedLine &Line, const AnnotatedLine *PreviousLine, 1349 const AnnotatedLine *PrevPrevLine, 1350 const SmallVectorImpl<AnnotatedLine *> &Lines, unsigned Indent, 1351 unsigned NewlineIndent) { 1352 FormatToken &RootToken = *Line.First; 1353 if (RootToken.is(tok::eof)) { 1354 unsigned Newlines = std::min(RootToken.NewlinesBefore, 1u); 1355 unsigned TokenIndent = Newlines ? NewlineIndent : 0; 1356 Whitespaces->replaceWhitespace(RootToken, Newlines, TokenIndent, 1357 TokenIndent); 1358 return; 1359 } 1360 unsigned Newlines = 1361 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1); 1362 // Remove empty lines before "}" where applicable. 1363 if (RootToken.is(tok::r_brace) && 1364 (!RootToken.Next || 1365 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)) && 1366 // Do not remove empty lines before namespace closing "}". 1367 !getNamespaceToken(&Line, Lines)) 1368 Newlines = std::min(Newlines, 1u); 1369 // Remove empty lines at the start of nested blocks (lambdas/arrow functions) 1370 if (PreviousLine == nullptr && Line.Level > 0) 1371 Newlines = std::min(Newlines, 1u); 1372 if (Newlines == 0 && !RootToken.IsFirst) 1373 Newlines = 1; 1374 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline) 1375 Newlines = 0; 1376 1377 // Remove empty lines after "{". 1378 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine && 1379 PreviousLine->Last->is(tok::l_brace) && 1380 !PreviousLine->startsWithNamespace() && 1381 !(PrevPrevLine && PrevPrevLine->startsWithNamespace() && 1382 PreviousLine->startsWith(tok::l_brace)) && 1383 !startsExternCBlock(*PreviousLine)) 1384 Newlines = 1; 1385 1386 // Insert or remove empty line before access specifiers. 1387 if (PreviousLine && RootToken.isAccessSpecifier()) { 1388 switch (Style.EmptyLineBeforeAccessModifier) { 1389 case FormatStyle::ELBAMS_Never: 1390 if (Newlines > 1) 1391 Newlines = 1; 1392 break; 1393 case FormatStyle::ELBAMS_Leave: 1394 Newlines = std::max(RootToken.NewlinesBefore, 1u); 1395 break; 1396 case FormatStyle::ELBAMS_LogicalBlock: 1397 if (PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) && Newlines <= 1) 1398 Newlines = 2; 1399 if (PreviousLine->First->isAccessSpecifier()) 1400 Newlines = 1; // Previous is an access modifier remove all new lines. 1401 break; 1402 case FormatStyle::ELBAMS_Always: { 1403 const FormatToken *previousToken; 1404 if (PreviousLine->Last->is(tok::comment)) 1405 previousToken = PreviousLine->Last->getPreviousNonComment(); 1406 else 1407 previousToken = PreviousLine->Last; 1408 if ((!previousToken || !previousToken->is(tok::l_brace)) && Newlines <= 1) 1409 Newlines = 2; 1410 } break; 1411 } 1412 } 1413 1414 // Insert or remove empty line after access specifiers. 1415 if (PreviousLine && PreviousLine->First->isAccessSpecifier() && 1416 (!PreviousLine->InPPDirective || !RootToken.HasUnescapedNewline)) { 1417 // EmptyLineBeforeAccessModifier is handling the case when two access 1418 // modifiers follow each other. 1419 if (!RootToken.isAccessSpecifier()) { 1420 switch (Style.EmptyLineAfterAccessModifier) { 1421 case FormatStyle::ELAAMS_Never: 1422 Newlines = 1; 1423 break; 1424 case FormatStyle::ELAAMS_Leave: 1425 Newlines = std::max(Newlines, 1u); 1426 break; 1427 case FormatStyle::ELAAMS_Always: 1428 if (RootToken.is(tok::r_brace)) // Do not add at end of class. 1429 Newlines = 1u; 1430 else 1431 Newlines = std::max(Newlines, 2u); 1432 break; 1433 } 1434 } 1435 } 1436 1437 if (Newlines) 1438 Indent = NewlineIndent; 1439 1440 // Preprocessor directives get indented before the hash only if specified. In 1441 // Javascript import statements are indented like normal statements. 1442 if (!Style.isJavaScript() && 1443 Style.IndentPPDirectives != FormatStyle::PPDIS_BeforeHash && 1444 (Line.Type == LT_PreprocessorDirective || 1445 Line.Type == LT_ImportStatement)) 1446 Indent = 0; 1447 1448 Whitespaces->replaceWhitespace(RootToken, Newlines, Indent, Indent, 1449 /*IsAligned=*/false, 1450 Line.InPPDirective && 1451 !RootToken.HasUnescapedNewline); 1452 } 1453 1454 unsigned 1455 UnwrappedLineFormatter::getColumnLimit(bool InPPDirective, 1456 const AnnotatedLine *NextLine) const { 1457 // In preprocessor directives reserve two chars for trailing " \" if the 1458 // next line continues the preprocessor directive. 1459 bool ContinuesPPDirective = 1460 InPPDirective && 1461 // If there is no next line, this is likely a child line and the parent 1462 // continues the preprocessor directive. 1463 (!NextLine || 1464 (NextLine->InPPDirective && 1465 // If there is an unescaped newline between this line and the next, the 1466 // next line starts a new preprocessor directive. 1467 !NextLine->First->HasUnescapedNewline)); 1468 return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0); 1469 } 1470 1471 } // namespace format 1472 } // namespace clang 1473