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