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