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