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