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