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 14 #define DEBUG_TYPE "format-formatter" 15 16 namespace clang { 17 namespace format { 18 19 namespace { 20 21 bool startsExternCBlock(const AnnotatedLine &Line) { 22 const FormatToken *Next = Line.First->getNextNonComment(); 23 const FormatToken *NextNext = Next ? Next->getNextNonComment() : nullptr; 24 return Line.First->is(tok::kw_extern) && Next && Next->isStringLiteral() && 25 NextNext && NextNext->is(tok::l_brace); 26 } 27 28 class LineJoiner { 29 public: 30 LineJoiner(const FormatStyle &Style, const AdditionalKeywords &Keywords) 31 : Style(Style), Keywords(Keywords) {} 32 33 /// \brief Calculates how many lines can be merged into 1 starting at \p I. 34 unsigned 35 tryFitMultipleLinesInOne(unsigned Indent, 36 SmallVectorImpl<AnnotatedLine *>::const_iterator I, 37 SmallVectorImpl<AnnotatedLine *>::const_iterator E) { 38 // We can never merge stuff if there are trailing line comments. 39 const AnnotatedLine *TheLine = *I; 40 if (TheLine->Last->is(TT_LineComment)) 41 return 0; 42 43 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit) 44 return 0; 45 46 unsigned Limit = 47 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent; 48 // If we already exceed the column limit, we set 'Limit' to 0. The different 49 // tryMerge..() functions can then decide whether to still do merging. 50 Limit = TheLine->Last->TotalLength > Limit 51 ? 0 52 : Limit - TheLine->Last->TotalLength; 53 54 if (I + 1 == E || I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore) 55 return 0; 56 57 // FIXME: TheLine->Level != 0 might or might not be the right check to do. 58 // If necessary, change to something smarter. 59 bool MergeShortFunctions = 60 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All || 61 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty && 62 I[1]->First->is(tok::r_brace)) || 63 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline && 64 TheLine->Level != 0); 65 66 if (TheLine->Last->is(TT_FunctionLBrace) && 67 TheLine->First != TheLine->Last) { 68 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0; 69 } 70 if (TheLine->Last->is(tok::l_brace)) { 71 return Style.BreakBeforeBraces == FormatStyle::BS_Attach 72 ? tryMergeSimpleBlock(I, E, Limit) 73 : 0; 74 } 75 if (I[1]->First->is(TT_FunctionLBrace) && 76 Style.BreakBeforeBraces != FormatStyle::BS_Attach) { 77 if (I[1]->Last->is(TT_LineComment)) 78 return 0; 79 80 // Check for Limit <= 2 to account for the " {". 81 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine))) 82 return 0; 83 Limit -= 2; 84 85 unsigned MergedLines = 0; 86 if (MergeShortFunctions) { 87 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit); 88 // If we managed to merge the block, count the function header, which is 89 // on a separate line. 90 if (MergedLines > 0) 91 ++MergedLines; 92 } 93 return MergedLines; 94 } 95 if (TheLine->First->is(tok::kw_if)) { 96 return Style.AllowShortIfStatementsOnASingleLine 97 ? tryMergeSimpleControlStatement(I, E, Limit) 98 : 0; 99 } 100 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) { 101 return Style.AllowShortLoopsOnASingleLine 102 ? tryMergeSimpleControlStatement(I, E, Limit) 103 : 0; 104 } 105 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) { 106 return Style.AllowShortCaseLabelsOnASingleLine 107 ? tryMergeShortCaseLabels(I, E, Limit) 108 : 0; 109 } 110 if (TheLine->InPPDirective && 111 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) { 112 return tryMergeSimplePPDirective(I, E, Limit); 113 } 114 return 0; 115 } 116 117 private: 118 unsigned 119 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I, 120 SmallVectorImpl<AnnotatedLine *>::const_iterator E, 121 unsigned Limit) { 122 if (Limit == 0) 123 return 0; 124 if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline) 125 return 0; 126 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline) 127 return 0; 128 if (1 + I[1]->Last->TotalLength > Limit) 129 return 0; 130 return 1; 131 } 132 133 unsigned tryMergeSimpleControlStatement( 134 SmallVectorImpl<AnnotatedLine *>::const_iterator I, 135 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) { 136 if (Limit == 0) 137 return 0; 138 if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman || 139 Style.BreakBeforeBraces == FormatStyle::BS_GNU) && 140 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine)) 141 return 0; 142 if (I[1]->InPPDirective != (*I)->InPPDirective || 143 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline)) 144 return 0; 145 Limit = limitConsideringMacros(I + 1, E, Limit); 146 AnnotatedLine &Line = **I; 147 if (Line.Last->isNot(tok::r_paren)) 148 return 0; 149 if (1 + I[1]->Last->TotalLength > Limit) 150 return 0; 151 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, 152 tok::kw_while, TT_LineComment)) 153 return 0; 154 // Only inline simple if's (no nested if or else). 155 if (I + 2 != E && Line.First->is(tok::kw_if) && 156 I[2]->First->is(tok::kw_else)) 157 return 0; 158 return 1; 159 } 160 161 unsigned tryMergeShortCaseLabels( 162 SmallVectorImpl<AnnotatedLine *>::const_iterator I, 163 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) { 164 if (Limit == 0 || I + 1 == E || 165 I[1]->First->isOneOf(tok::kw_case, tok::kw_default)) 166 return 0; 167 unsigned NumStmts = 0; 168 unsigned Length = 0; 169 bool InPPDirective = I[0]->InPPDirective; 170 for (; NumStmts < 3; ++NumStmts) { 171 if (I + 1 + NumStmts == E) 172 break; 173 const AnnotatedLine *Line = I[1 + NumStmts]; 174 if (Line->InPPDirective != InPPDirective) 175 break; 176 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace)) 177 break; 178 if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch, 179 tok::kw_while, tok::comment)) 180 return 0; 181 Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space. 182 } 183 if (NumStmts == 0 || NumStmts == 3 || Length > Limit) 184 return 0; 185 return NumStmts; 186 } 187 188 unsigned 189 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I, 190 SmallVectorImpl<AnnotatedLine *>::const_iterator E, 191 unsigned Limit) { 192 AnnotatedLine &Line = **I; 193 194 // Don't merge ObjC @ keywords and methods. 195 // FIXME: If an option to allow short exception handling clauses on a single 196 // line is added, change this to not return for @try and friends. 197 if (Style.Language != FormatStyle::LK_Java && 198 Line.First->isOneOf(tok::at, tok::minus, tok::plus)) 199 return 0; 200 201 // Check that the current line allows merging. This depends on whether we 202 // are in a control flow statements as well as several style flags. 203 if (Line.First->isOneOf(tok::kw_else, tok::kw_case)) 204 return 0; 205 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try, 206 tok::kw___try, tok::kw_catch, tok::kw___finally, 207 tok::kw_for, tok::r_brace) || 208 Line.First->is(Keywords.kw___except)) { 209 if (!Style.AllowShortBlocksOnASingleLine) 210 return 0; 211 if (!Style.AllowShortIfStatementsOnASingleLine && 212 Line.First->is(tok::kw_if)) 213 return 0; 214 if (!Style.AllowShortLoopsOnASingleLine && 215 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for)) 216 return 0; 217 // FIXME: Consider an option to allow short exception handling clauses on 218 // a single line. 219 // FIXME: This isn't covered by tests. 220 // FIXME: For catch, __except, __finally the first token on the line 221 // is '}', so this isn't correct here. 222 if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch, 223 Keywords.kw___except, tok::kw___finally)) 224 return 0; 225 } 226 227 FormatToken *Tok = I[1]->First; 228 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore && 229 (Tok->getNextNonComment() == nullptr || 230 Tok->getNextNonComment()->is(tok::semi))) { 231 // We merge empty blocks even if the line exceeds the column limit. 232 Tok->SpacesRequiredBefore = 0; 233 Tok->CanBreakBefore = true; 234 return 1; 235 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace) && 236 !startsExternCBlock(Line)) { 237 // We don't merge short records. 238 if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct)) 239 return 0; 240 241 // Check that we still have three lines and they fit into the limit. 242 if (I + 2 == E || I[2]->Type == LT_Invalid) 243 return 0; 244 Limit = limitConsideringMacros(I + 2, E, Limit); 245 246 if (!nextTwoLinesFitInto(I, Limit)) 247 return 0; 248 249 // Second, check that the next line does not contain any braces - if it 250 // does, readability declines when putting it into a single line. 251 if (I[1]->Last->is(TT_LineComment)) 252 return 0; 253 do { 254 if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit) 255 return 0; 256 Tok = Tok->Next; 257 } while (Tok); 258 259 // Last, check that the third line starts with a closing brace. 260 Tok = I[2]->First; 261 if (Tok->isNot(tok::r_brace)) 262 return 0; 263 264 return 2; 265 } 266 return 0; 267 } 268 269 /// Returns the modified column limit for \p I if it is inside a macro and 270 /// needs a trailing '\'. 271 unsigned 272 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I, 273 SmallVectorImpl<AnnotatedLine *>::const_iterator E, 274 unsigned Limit) { 275 if (I[0]->InPPDirective && I + 1 != E && 276 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) { 277 return Limit < 2 ? 0 : Limit - 2; 278 } 279 return Limit; 280 } 281 282 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I, 283 unsigned Limit) { 284 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore) 285 return false; 286 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit; 287 } 288 289 bool containsMustBreak(const AnnotatedLine *Line) { 290 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) { 291 if (Tok->MustBreakBefore) 292 return true; 293 } 294 return false; 295 } 296 297 const FormatStyle &Style; 298 const AdditionalKeywords &Keywords; 299 }; 300 301 class NoColumnLimitFormatter { 302 public: 303 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {} 304 305 /// \brief Formats the line starting at \p State, simply keeping all of the 306 /// input's line breaking decisions. 307 void format(unsigned FirstIndent, const AnnotatedLine *Line) { 308 LineState State = 309 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false); 310 while (State.NextToken) { 311 bool Newline = 312 Indenter->mustBreak(State) || 313 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0); 314 Indenter->addTokenToState(State, Newline, /*DryRun=*/false); 315 } 316 } 317 318 private: 319 ContinuationIndenter *Indenter; 320 }; 321 322 323 static void markFinalized(FormatToken *Tok) { 324 for (; Tok; Tok = Tok->Next) { 325 Tok->Finalized = true; 326 for (AnnotatedLine *Child : Tok->Children) 327 markFinalized(Child->First); 328 } 329 } 330 331 } // namespace 332 333 unsigned 334 UnwrappedLineFormatter::format(const SmallVectorImpl<AnnotatedLine *> &Lines, 335 bool DryRun, int AdditionalIndent, 336 bool FixBadIndentation) { 337 LineJoiner Joiner(Style, Keywords); 338 339 // Try to look up already computed penalty in DryRun-mode. 340 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey( 341 &Lines, AdditionalIndent); 342 auto CacheIt = PenaltyCache.find(CacheKey); 343 if (DryRun && CacheIt != PenaltyCache.end()) 344 return CacheIt->second; 345 346 assert(!Lines.empty()); 347 unsigned Penalty = 0; 348 std::vector<int> IndentForLevel; 349 for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i) 350 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent); 351 const AnnotatedLine *PreviousLine = nullptr; 352 for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(), 353 E = Lines.end(); 354 I != E; ++I) { 355 const AnnotatedLine &TheLine = **I; 356 const FormatToken *FirstTok = TheLine.First; 357 int Offset = getIndentOffset(*FirstTok); 358 359 // Determine indent and try to merge multiple unwrapped lines. 360 unsigned Indent; 361 if (TheLine.InPPDirective) { 362 Indent = TheLine.Level * Style.IndentWidth; 363 } else { 364 while (IndentForLevel.size() <= TheLine.Level) 365 IndentForLevel.push_back(-1); 366 IndentForLevel.resize(TheLine.Level + 1); 367 Indent = getIndent(IndentForLevel, TheLine.Level); 368 } 369 unsigned LevelIndent = Indent; 370 if (static_cast<int>(Indent) + Offset >= 0) 371 Indent += Offset; 372 373 // Merge multiple lines if possible. 374 unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E); 375 if (MergedLines > 0 && Style.ColumnLimit == 0) { 376 // Disallow line merging if there is a break at the start of one of the 377 // input lines. 378 for (unsigned i = 0; i < MergedLines; ++i) { 379 if (I[i + 1]->First->NewlinesBefore > 0) 380 MergedLines = 0; 381 } 382 } 383 if (!DryRun) { 384 for (unsigned i = 0; i < MergedLines; ++i) { 385 join(*I[i], *I[i + 1]); 386 } 387 } 388 I += MergedLines; 389 390 bool FixIndentation = 391 FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn); 392 if (TheLine.First->is(tok::eof)) { 393 if (PreviousLine && PreviousLine->Affected && !DryRun) { 394 // Remove the file's trailing whitespace. 395 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u); 396 Whitespaces->replaceWhitespace(*TheLine.First, Newlines, 397 /*IndentLevel=*/0, /*Spaces=*/0, 398 /*TargetColumn=*/0); 399 } 400 } else if (TheLine.Type != LT_Invalid && 401 (TheLine.Affected || FixIndentation)) { 402 if (FirstTok->WhitespaceRange.isValid()) { 403 if (!DryRun) 404 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level, Indent, 405 TheLine.InPPDirective); 406 } else { 407 Indent = LevelIndent = FirstTok->OriginalColumn; 408 } 409 410 // If everything fits on a single line, just put it there. 411 unsigned ColumnLimit = Style.ColumnLimit; 412 if (I + 1 != E) { 413 AnnotatedLine *NextLine = I[1]; 414 if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline) 415 ColumnLimit = getColumnLimit(TheLine.InPPDirective); 416 } 417 418 if (TheLine.Last->TotalLength + Indent <= ColumnLimit || 419 TheLine.Type == LT_ImportStatement) { 420 LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun); 421 while (State.NextToken) { 422 formatChildren(State, /*Newline=*/false, DryRun, Penalty); 423 Indenter->addTokenToState(State, /*Newline=*/false, DryRun); 424 } 425 } else if (Style.ColumnLimit == 0) { 426 // FIXME: Implement nested blocks for ColumnLimit = 0. 427 NoColumnLimitFormatter Formatter(Indenter); 428 if (!DryRun) 429 Formatter.format(Indent, &TheLine); 430 } else { 431 Penalty += format(TheLine, Indent, DryRun); 432 } 433 434 if (!TheLine.InPPDirective) 435 IndentForLevel[TheLine.Level] = LevelIndent; 436 } else if (TheLine.ChildrenAffected) { 437 format(TheLine.Children, DryRun); 438 } else { 439 // Format the first token if necessary, and notify the WhitespaceManager 440 // about the unchanged whitespace. 441 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) { 442 if (Tok == TheLine.First && (Tok->NewlinesBefore > 0 || Tok->IsFirst)) { 443 unsigned LevelIndent = Tok->OriginalColumn; 444 if (!DryRun) { 445 // Remove trailing whitespace of the previous line. 446 if ((PreviousLine && PreviousLine->Affected) || 447 TheLine.LeadingEmptyLinesAffected) { 448 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent, 449 TheLine.InPPDirective); 450 } else { 451 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective); 452 } 453 } 454 455 if (static_cast<int>(LevelIndent) - Offset >= 0) 456 LevelIndent -= Offset; 457 if (Tok->isNot(tok::comment) && !TheLine.InPPDirective) 458 IndentForLevel[TheLine.Level] = LevelIndent; 459 } else if (!DryRun) { 460 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective); 461 } 462 } 463 } 464 if (!DryRun) 465 markFinalized(TheLine.First); 466 PreviousLine = *I; 467 } 468 PenaltyCache[CacheKey] = Penalty; 469 return Penalty; 470 } 471 472 unsigned UnwrappedLineFormatter::format(const AnnotatedLine &Line, 473 unsigned FirstIndent, bool DryRun) { 474 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun); 475 476 // If the ObjC method declaration does not fit on a line, we should format 477 // it with one arg per line. 478 if (State.Line->Type == LT_ObjCMethodDecl) 479 State.Stack.back().BreakBeforeParameter = true; 480 481 // Find best solution in solution space. 482 return analyzeSolutionSpace(State, DryRun); 483 } 484 485 void UnwrappedLineFormatter::formatFirstToken(FormatToken &RootToken, 486 const AnnotatedLine *PreviousLine, 487 unsigned IndentLevel, 488 unsigned Indent, 489 bool InPPDirective) { 490 unsigned Newlines = 491 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1); 492 // Remove empty lines before "}" where applicable. 493 if (RootToken.is(tok::r_brace) && 494 (!RootToken.Next || 495 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next))) 496 Newlines = std::min(Newlines, 1u); 497 if (Newlines == 0 && !RootToken.IsFirst) 498 Newlines = 1; 499 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline) 500 Newlines = 0; 501 502 // Remove empty lines after "{". 503 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine && 504 PreviousLine->Last->is(tok::l_brace) && 505 PreviousLine->First->isNot(tok::kw_namespace) && 506 !startsExternCBlock(*PreviousLine)) 507 Newlines = 1; 508 509 // Insert extra new line before access specifiers. 510 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) && 511 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1) 512 ++Newlines; 513 514 // Remove empty lines after access specifiers. 515 if (PreviousLine && PreviousLine->First->isAccessSpecifier() && 516 (!PreviousLine->InPPDirective || !RootToken.HasUnescapedNewline)) 517 Newlines = std::min(1u, Newlines); 518 519 Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent, 520 Indent, InPPDirective && 521 !RootToken.HasUnescapedNewline); 522 } 523 524 /// \brief Get the indent of \p Level from \p IndentForLevel. 525 /// 526 /// \p IndentForLevel must contain the indent for the level \c l 527 /// at \p IndentForLevel[l], or a value < 0 if the indent for 528 /// that level is unknown. 529 unsigned UnwrappedLineFormatter::getIndent(ArrayRef<int> IndentForLevel, 530 unsigned Level) { 531 if (IndentForLevel[Level] != -1) 532 return IndentForLevel[Level]; 533 if (Level == 0) 534 return 0; 535 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth; 536 } 537 538 void UnwrappedLineFormatter::join(AnnotatedLine &A, const AnnotatedLine &B) { 539 assert(!A.Last->Next); 540 assert(!B.First->Previous); 541 if (B.Affected) 542 A.Affected = true; 543 A.Last->Next = B.First; 544 B.First->Previous = A.Last; 545 B.First->CanBreakBefore = true; 546 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore; 547 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) { 548 Tok->TotalLength += LengthA; 549 A.Last = Tok; 550 } 551 } 552 553 unsigned UnwrappedLineFormatter::analyzeSolutionSpace(LineState &InitialState, 554 bool DryRun) { 555 std::set<LineState *, CompareLineStatePointers> Seen; 556 557 // Increasing count of \c StateNode items we have created. This is used to 558 // create a deterministic order independent of the container. 559 unsigned Count = 0; 560 QueueType Queue; 561 562 // Insert start element into queue. 563 StateNode *Node = 564 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr); 565 Queue.push(QueueItem(OrderedPenalty(0, Count), Node)); 566 ++Count; 567 568 unsigned Penalty = 0; 569 570 // While not empty, take first element and follow edges. 571 while (!Queue.empty()) { 572 Penalty = Queue.top().first.first; 573 StateNode *Node = Queue.top().second; 574 if (!Node->State.NextToken) { 575 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n"); 576 break; 577 } 578 Queue.pop(); 579 580 // Cut off the analysis of certain solutions if the analysis gets too 581 // complex. See description of IgnoreStackForComparison. 582 if (Count > 10000) 583 Node->State.IgnoreStackForComparison = true; 584 585 if (!Seen.insert(&Node->State).second) 586 // State already examined with lower penalty. 587 continue; 588 589 FormatDecision LastFormat = Node->State.NextToken->Decision; 590 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue) 591 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue); 592 if (LastFormat == FD_Unformatted || LastFormat == FD_Break) 593 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue); 594 } 595 596 if (Queue.empty()) { 597 // We were unable to find a solution, do nothing. 598 // FIXME: Add diagnostic? 599 DEBUG(llvm::dbgs() << "Could not find a solution.\n"); 600 return 0; 601 } 602 603 // Reconstruct the solution. 604 if (!DryRun) 605 reconstructPath(InitialState, Queue.top().second); 606 607 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n"); 608 DEBUG(llvm::dbgs() << "---\n"); 609 610 return Penalty; 611 } 612 613 #ifndef NDEBUG 614 static void printLineState(const LineState &State) { 615 llvm::dbgs() << "State: "; 616 for (const ParenState &P : State.Stack) { 617 llvm::dbgs() << P.Indent << "|" << P.LastSpace << "|" << P.NestedBlockIndent 618 << " "; 619 } 620 llvm::dbgs() << State.NextToken->TokenText << "\n"; 621 } 622 #endif 623 624 void UnwrappedLineFormatter::reconstructPath(LineState &State, 625 StateNode *Current) { 626 std::deque<StateNode *> Path; 627 // We do not need a break before the initial token. 628 while (Current->Previous) { 629 Path.push_front(Current); 630 Current = Current->Previous; 631 } 632 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end(); 633 I != E; ++I) { 634 unsigned Penalty = 0; 635 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty); 636 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false); 637 638 DEBUG({ 639 printLineState((*I)->Previous->State); 640 if ((*I)->NewLine) { 641 llvm::dbgs() << "Penalty for placing " 642 << (*I)->Previous->State.NextToken->Tok.getName() << ": " 643 << Penalty << "\n"; 644 } 645 }); 646 } 647 } 648 649 void UnwrappedLineFormatter::addNextStateToQueue(unsigned Penalty, 650 StateNode *PreviousNode, 651 bool NewLine, unsigned *Count, 652 QueueType *Queue) { 653 if (NewLine && !Indenter->canBreak(PreviousNode->State)) 654 return; 655 if (!NewLine && Indenter->mustBreak(PreviousNode->State)) 656 return; 657 658 StateNode *Node = new (Allocator.Allocate()) 659 StateNode(PreviousNode->State, NewLine, PreviousNode); 660 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty)) 661 return; 662 663 Penalty += Indenter->addTokenToState(Node->State, NewLine, true); 664 665 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node)); 666 ++(*Count); 667 } 668 669 bool UnwrappedLineFormatter::formatChildren(LineState &State, bool NewLine, 670 bool DryRun, unsigned &Penalty) { 671 const FormatToken *LBrace = State.NextToken->getPreviousNonComment(); 672 FormatToken &Previous = *State.NextToken->Previous; 673 if (!LBrace || LBrace->isNot(tok::l_brace) || LBrace->BlockKind != BK_Block || 674 Previous.Children.size() == 0) 675 // The previous token does not open a block. Nothing to do. We don't 676 // assert so that we can simply call this function for all tokens. 677 return true; 678 679 if (NewLine) { 680 int AdditionalIndent = State.Stack.back().Indent - 681 Previous.Children[0]->Level * Style.IndentWidth; 682 683 Penalty += format(Previous.Children, DryRun, AdditionalIndent, 684 /*FixBadIndentation=*/true); 685 return true; 686 } 687 688 if (Previous.Children[0]->First->MustBreakBefore) 689 return false; 690 691 // Cannot merge multiple statements into a single line. 692 if (Previous.Children.size() > 1) 693 return false; 694 695 // Cannot merge into one line if this line ends on a comment. 696 if (Previous.is(tok::comment)) 697 return false; 698 699 // We can't put the closing "}" on a line with a trailing comment. 700 if (Previous.Children[0]->Last->isTrailingComment()) 701 return false; 702 703 // If the child line exceeds the column limit, we wouldn't want to merge it. 704 // We add +2 for the trailing " }". 705 if (Style.ColumnLimit > 0 && 706 Previous.Children[0]->Last->TotalLength + State.Column + 2 > 707 Style.ColumnLimit) 708 return false; 709 710 if (!DryRun) { 711 Whitespaces->replaceWhitespace( 712 *Previous.Children[0]->First, 713 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1, 714 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective); 715 } 716 Penalty += format(*Previous.Children[0], State.Column + 1, DryRun); 717 718 State.Column += 1 + Previous.Children[0]->Last->TotalLength; 719 return true; 720 } 721 722 } // namespace format 723 } // namespace clang 724