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