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