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