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