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