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