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