1 //===--- WhitespaceManager.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 /// \file 10 /// This file implements WhitespaceManager class. 11 /// 12 //===----------------------------------------------------------------------===// 13 14 #include "WhitespaceManager.h" 15 #include "llvm/ADT/STLExtras.h" 16 #include "llvm/ADT/SmallVector.h" 17 #include <algorithm> 18 19 namespace clang { 20 namespace format { 21 22 bool WhitespaceManager::Change::IsBeforeInFile::operator()( 23 const Change &C1, const Change &C2) const { 24 return SourceMgr.isBeforeInTranslationUnit( 25 C1.OriginalWhitespaceRange.getBegin(), 26 C2.OriginalWhitespaceRange.getBegin()); 27 } 28 29 WhitespaceManager::Change::Change(const FormatToken &Tok, 30 bool CreateReplacement, 31 SourceRange OriginalWhitespaceRange, 32 int Spaces, unsigned StartOfTokenColumn, 33 unsigned NewlinesBefore, 34 StringRef PreviousLinePostfix, 35 StringRef CurrentLinePrefix, bool IsAligned, 36 bool ContinuesPPDirective, bool IsInsideToken) 37 : Tok(&Tok), CreateReplacement(CreateReplacement), 38 OriginalWhitespaceRange(OriginalWhitespaceRange), 39 StartOfTokenColumn(StartOfTokenColumn), NewlinesBefore(NewlinesBefore), 40 PreviousLinePostfix(PreviousLinePostfix), 41 CurrentLinePrefix(CurrentLinePrefix), IsAligned(IsAligned), 42 ContinuesPPDirective(ContinuesPPDirective), Spaces(Spaces), 43 IsInsideToken(IsInsideToken), IsTrailingComment(false), TokenLength(0), 44 PreviousEndOfTokenColumn(0), EscapedNewlineColumn(0), 45 StartOfBlockComment(nullptr), IndentationOffset(0), ConditionalsLevel(0) { 46 } 47 48 void WhitespaceManager::replaceWhitespace(FormatToken &Tok, unsigned Newlines, 49 unsigned Spaces, 50 unsigned StartOfTokenColumn, 51 bool IsAligned, bool InPPDirective) { 52 if (Tok.Finalized) 53 return; 54 Tok.setDecision((Newlines > 0) ? FD_Break : FD_Continue); 55 Changes.push_back(Change(Tok, /*CreateReplacement=*/true, Tok.WhitespaceRange, 56 Spaces, StartOfTokenColumn, Newlines, "", "", 57 IsAligned, InPPDirective && !Tok.IsFirst, 58 /*IsInsideToken=*/false)); 59 } 60 61 void WhitespaceManager::addUntouchableToken(const FormatToken &Tok, 62 bool InPPDirective) { 63 if (Tok.Finalized) 64 return; 65 Changes.push_back(Change(Tok, /*CreateReplacement=*/false, 66 Tok.WhitespaceRange, /*Spaces=*/0, 67 Tok.OriginalColumn, Tok.NewlinesBefore, "", "", 68 /*IsAligned=*/false, InPPDirective && !Tok.IsFirst, 69 /*IsInsideToken=*/false)); 70 } 71 72 llvm::Error 73 WhitespaceManager::addReplacement(const tooling::Replacement &Replacement) { 74 return Replaces.add(Replacement); 75 } 76 77 bool WhitespaceManager::inputUsesCRLF(StringRef Text, bool DefaultToCRLF) { 78 size_t LF = Text.count('\n'); 79 size_t CR = Text.count('\r') * 2; 80 return LF == CR ? DefaultToCRLF : CR > LF; 81 } 82 83 void WhitespaceManager::replaceWhitespaceInToken( 84 const FormatToken &Tok, unsigned Offset, unsigned ReplaceChars, 85 StringRef PreviousPostfix, StringRef CurrentPrefix, bool InPPDirective, 86 unsigned Newlines, int Spaces) { 87 if (Tok.Finalized) 88 return; 89 SourceLocation Start = Tok.getStartOfNonWhitespace().getLocWithOffset(Offset); 90 Changes.push_back( 91 Change(Tok, /*CreateReplacement=*/true, 92 SourceRange(Start, Start.getLocWithOffset(ReplaceChars)), Spaces, 93 std::max(0, Spaces), Newlines, PreviousPostfix, CurrentPrefix, 94 /*IsAligned=*/true, InPPDirective && !Tok.IsFirst, 95 /*IsInsideToken=*/true)); 96 } 97 98 const tooling::Replacements &WhitespaceManager::generateReplacements() { 99 if (Changes.empty()) 100 return Replaces; 101 102 llvm::sort(Changes, Change::IsBeforeInFile(SourceMgr)); 103 calculateLineBreakInformation(); 104 alignConsecutiveMacros(); 105 alignConsecutiveDeclarations(); 106 alignConsecutiveBitFields(); 107 alignConsecutiveAssignments(); 108 alignChainedConditionals(); 109 alignTrailingComments(); 110 alignEscapedNewlines(); 111 alignArrayInitializers(); 112 generateChanges(); 113 114 return Replaces; 115 } 116 117 void WhitespaceManager::calculateLineBreakInformation() { 118 Changes[0].PreviousEndOfTokenColumn = 0; 119 Change *LastOutsideTokenChange = &Changes[0]; 120 for (unsigned i = 1, e = Changes.size(); i != e; ++i) { 121 SourceLocation OriginalWhitespaceStart = 122 Changes[i].OriginalWhitespaceRange.getBegin(); 123 SourceLocation PreviousOriginalWhitespaceEnd = 124 Changes[i - 1].OriginalWhitespaceRange.getEnd(); 125 unsigned OriginalWhitespaceStartOffset = 126 SourceMgr.getFileOffset(OriginalWhitespaceStart); 127 unsigned PreviousOriginalWhitespaceEndOffset = 128 SourceMgr.getFileOffset(PreviousOriginalWhitespaceEnd); 129 assert(PreviousOriginalWhitespaceEndOffset <= 130 OriginalWhitespaceStartOffset); 131 const char *const PreviousOriginalWhitespaceEndData = 132 SourceMgr.getCharacterData(PreviousOriginalWhitespaceEnd); 133 StringRef Text(PreviousOriginalWhitespaceEndData, 134 SourceMgr.getCharacterData(OriginalWhitespaceStart) - 135 PreviousOriginalWhitespaceEndData); 136 // Usually consecutive changes would occur in consecutive tokens. This is 137 // not the case however when analyzing some preprocessor runs of the 138 // annotated lines. For example, in this code: 139 // 140 // #if A // line 1 141 // int i = 1; 142 // #else B // line 2 143 // int i = 2; 144 // #endif // line 3 145 // 146 // one of the runs will produce the sequence of lines marked with line 1, 2 147 // and 3. So the two consecutive whitespace changes just before '// line 2' 148 // and before '#endif // line 3' span multiple lines and tokens: 149 // 150 // #else B{change X}[// line 2 151 // int i = 2; 152 // ]{change Y}#endif // line 3 153 // 154 // For this reason, if the text between consecutive changes spans multiple 155 // newlines, the token length must be adjusted to the end of the original 156 // line of the token. 157 auto NewlinePos = Text.find_first_of('\n'); 158 if (NewlinePos == StringRef::npos) { 159 Changes[i - 1].TokenLength = OriginalWhitespaceStartOffset - 160 PreviousOriginalWhitespaceEndOffset + 161 Changes[i].PreviousLinePostfix.size() + 162 Changes[i - 1].CurrentLinePrefix.size(); 163 } else { 164 Changes[i - 1].TokenLength = 165 NewlinePos + Changes[i - 1].CurrentLinePrefix.size(); 166 } 167 168 // If there are multiple changes in this token, sum up all the changes until 169 // the end of the line. 170 if (Changes[i - 1].IsInsideToken && Changes[i - 1].NewlinesBefore == 0) 171 LastOutsideTokenChange->TokenLength += 172 Changes[i - 1].TokenLength + Changes[i - 1].Spaces; 173 else 174 LastOutsideTokenChange = &Changes[i - 1]; 175 176 Changes[i].PreviousEndOfTokenColumn = 177 Changes[i - 1].StartOfTokenColumn + Changes[i - 1].TokenLength; 178 179 Changes[i - 1].IsTrailingComment = 180 (Changes[i].NewlinesBefore > 0 || Changes[i].Tok->is(tok::eof) || 181 (Changes[i].IsInsideToken && Changes[i].Tok->is(tok::comment))) && 182 Changes[i - 1].Tok->is(tok::comment) && 183 // FIXME: This is a dirty hack. The problem is that 184 // BreakableLineCommentSection does comment reflow changes and here is 185 // the aligning of trailing comments. Consider the case where we reflow 186 // the second line up in this example: 187 // 188 // // line 1 189 // // line 2 190 // 191 // That amounts to 2 changes by BreakableLineCommentSection: 192 // - the first, delimited by (), for the whitespace between the tokens, 193 // - and second, delimited by [], for the whitespace at the beginning 194 // of the second token: 195 // 196 // // line 1( 197 // )[// ]line 2 198 // 199 // So in the end we have two changes like this: 200 // 201 // // line1()[ ]line 2 202 // 203 // Note that the OriginalWhitespaceStart of the second change is the 204 // same as the PreviousOriginalWhitespaceEnd of the first change. 205 // In this case, the below check ensures that the second change doesn't 206 // get treated as a trailing comment change here, since this might 207 // trigger additional whitespace to be wrongly inserted before "line 2" 208 // by the comment aligner here. 209 // 210 // For a proper solution we need a mechanism to say to WhitespaceManager 211 // that a particular change breaks the current sequence of trailing 212 // comments. 213 OriginalWhitespaceStart != PreviousOriginalWhitespaceEnd; 214 } 215 // FIXME: The last token is currently not always an eof token; in those 216 // cases, setting TokenLength of the last token to 0 is wrong. 217 Changes.back().TokenLength = 0; 218 Changes.back().IsTrailingComment = Changes.back().Tok->is(tok::comment); 219 220 const WhitespaceManager::Change *LastBlockComment = nullptr; 221 for (auto &Change : Changes) { 222 // Reset the IsTrailingComment flag for changes inside of trailing comments 223 // so they don't get realigned later. Comment line breaks however still need 224 // to be aligned. 225 if (Change.IsInsideToken && Change.NewlinesBefore == 0) 226 Change.IsTrailingComment = false; 227 Change.StartOfBlockComment = nullptr; 228 Change.IndentationOffset = 0; 229 if (Change.Tok->is(tok::comment)) { 230 if (Change.Tok->is(TT_LineComment) || !Change.IsInsideToken) 231 LastBlockComment = &Change; 232 else { 233 if ((Change.StartOfBlockComment = LastBlockComment)) 234 Change.IndentationOffset = 235 Change.StartOfTokenColumn - 236 Change.StartOfBlockComment->StartOfTokenColumn; 237 } 238 } else { 239 LastBlockComment = nullptr; 240 } 241 } 242 243 // Compute conditional nesting level 244 // Level is increased for each conditional, unless this conditional continues 245 // a chain of conditional, i.e. starts immediately after the colon of another 246 // conditional. 247 SmallVector<bool, 16> ScopeStack; 248 int ConditionalsLevel = 0; 249 for (auto &Change : Changes) { 250 for (unsigned i = 0, e = Change.Tok->FakeLParens.size(); i != e; ++i) { 251 bool isNestedConditional = 252 Change.Tok->FakeLParens[e - 1 - i] == prec::Conditional && 253 !(i == 0 && Change.Tok->Previous && 254 Change.Tok->Previous->is(TT_ConditionalExpr) && 255 Change.Tok->Previous->is(tok::colon)); 256 if (isNestedConditional) 257 ++ConditionalsLevel; 258 ScopeStack.push_back(isNestedConditional); 259 } 260 261 Change.ConditionalsLevel = ConditionalsLevel; 262 263 for (unsigned i = Change.Tok->FakeRParens; i > 0 && ScopeStack.size(); 264 --i) { 265 if (ScopeStack.pop_back_val()) 266 --ConditionalsLevel; 267 } 268 } 269 } 270 271 // Align a single sequence of tokens, see AlignTokens below. 272 template <typename F> 273 static void 274 AlignTokenSequence(const FormatStyle &Style, unsigned Start, unsigned End, 275 unsigned Column, F &&Matches, 276 SmallVector<WhitespaceManager::Change, 16> &Changes) { 277 bool FoundMatchOnLine = false; 278 int Shift = 0; 279 280 // ScopeStack keeps track of the current scope depth. It contains indices of 281 // the first token on each scope. 282 // We only run the "Matches" function on tokens from the outer-most scope. 283 // However, we do need to pay special attention to one class of tokens 284 // that are not in the outer-most scope, and that is function parameters 285 // which are split across multiple lines, as illustrated by this example: 286 // double a(int x); 287 // int b(int y, 288 // double z); 289 // In the above example, we need to take special care to ensure that 290 // 'double z' is indented along with it's owning function 'b'. 291 // The same holds for calling a function: 292 // double a = foo(x); 293 // int b = bar(foo(y), 294 // foor(z)); 295 // Similar for broken string literals: 296 // double x = 3.14; 297 // auto s = "Hello" 298 // "World"; 299 // Special handling is required for 'nested' ternary operators. 300 SmallVector<unsigned, 16> ScopeStack; 301 302 for (unsigned i = Start; i != End; ++i) { 303 if (ScopeStack.size() != 0 && 304 Changes[i].indentAndNestingLevel() < 305 Changes[ScopeStack.back()].indentAndNestingLevel()) 306 ScopeStack.pop_back(); 307 308 // Compare current token to previous non-comment token to ensure whether 309 // it is in a deeper scope or not. 310 unsigned PreviousNonComment = i - 1; 311 while (PreviousNonComment > Start && 312 Changes[PreviousNonComment].Tok->is(tok::comment)) 313 --PreviousNonComment; 314 if (i != Start && Changes[i].indentAndNestingLevel() > 315 Changes[PreviousNonComment].indentAndNestingLevel()) 316 ScopeStack.push_back(i); 317 318 bool InsideNestedScope = ScopeStack.size() != 0; 319 bool ContinuedStringLiteral = i > Start && 320 Changes[i].Tok->is(tok::string_literal) && 321 Changes[i - 1].Tok->is(tok::string_literal); 322 bool SkipMatchCheck = InsideNestedScope || ContinuedStringLiteral; 323 324 if (Changes[i].NewlinesBefore > 0 && !SkipMatchCheck) { 325 Shift = 0; 326 FoundMatchOnLine = false; 327 } 328 329 // If this is the first matching token to be aligned, remember by how many 330 // spaces it has to be shifted, so the rest of the changes on the line are 331 // shifted by the same amount 332 if (!FoundMatchOnLine && !SkipMatchCheck && Matches(Changes[i])) { 333 FoundMatchOnLine = true; 334 Shift = Column - Changes[i].StartOfTokenColumn; 335 Changes[i].Spaces += Shift; 336 } 337 338 // This is for function parameters that are split across multiple lines, 339 // as mentioned in the ScopeStack comment. 340 if (InsideNestedScope && Changes[i].NewlinesBefore > 0) { 341 unsigned ScopeStart = ScopeStack.back(); 342 auto ShouldShiftBeAdded = [&] { 343 // Function declaration 344 if (Changes[ScopeStart - 1].Tok->is(TT_FunctionDeclarationName)) 345 return true; 346 347 // Continued function declaration 348 if (ScopeStart > Start + 1 && 349 Changes[ScopeStart - 2].Tok->is(TT_FunctionDeclarationName)) 350 return true; 351 352 // Continued function call 353 if (ScopeStart > Start + 1 && 354 Changes[ScopeStart - 2].Tok->is(tok::identifier) && 355 Changes[ScopeStart - 1].Tok->is(tok::l_paren)) 356 return Style.BinPackArguments; 357 358 // Ternary operator 359 if (Changes[i].Tok->is(TT_ConditionalExpr)) 360 return true; 361 362 // Period Initializer .XXX = 1. 363 if (Changes[i].Tok->is(TT_DesignatedInitializerPeriod)) 364 return true; 365 366 // Continued ternary operator 367 if (Changes[i].Tok->Previous && 368 Changes[i].Tok->Previous->is(TT_ConditionalExpr)) 369 return true; 370 371 // Continued braced list. 372 if (ScopeStart > Start + 1 && 373 Changes[ScopeStart - 2].Tok->isNot(tok::identifier) && 374 Changes[ScopeStart - 1].Tok->is(tok::l_brace) && 375 Changes[i].Tok->isNot(tok::r_brace)) 376 return true; 377 378 return false; 379 }; 380 381 if (ShouldShiftBeAdded()) 382 Changes[i].Spaces += Shift; 383 } 384 385 if (ContinuedStringLiteral) 386 Changes[i].Spaces += Shift; 387 388 Changes[i].StartOfTokenColumn += Shift; 389 if (i + 1 != Changes.size()) 390 Changes[i + 1].PreviousEndOfTokenColumn += Shift; 391 392 // If PointerAlignment is PAS_Right, keep *s or &s next to the token 393 if (Style.PointerAlignment == FormatStyle::PAS_Right && 394 Changes[i].Spaces != 0) { 395 for (int Previous = i - 1; 396 Previous >= 0 && 397 Changes[Previous].Tok->getType() == TT_PointerOrReference; 398 --Previous) { 399 Changes[Previous + 1].Spaces -= Shift; 400 Changes[Previous].Spaces += Shift; 401 } 402 } 403 } 404 } 405 406 // Walk through a subset of the changes, starting at StartAt, and find 407 // sequences of matching tokens to align. To do so, keep track of the lines and 408 // whether or not a matching token was found on a line. If a matching token is 409 // found, extend the current sequence. If the current line cannot be part of a 410 // sequence, e.g. because there is an empty line before it or it contains only 411 // non-matching tokens, finalize the previous sequence. 412 // The value returned is the token on which we stopped, either because we 413 // exhausted all items inside Changes, or because we hit a scope level higher 414 // than our initial scope. 415 // This function is recursive. Each invocation processes only the scope level 416 // equal to the initial level, which is the level of Changes[StartAt]. 417 // If we encounter a scope level greater than the initial level, then we call 418 // ourselves recursively, thereby avoiding the pollution of the current state 419 // with the alignment requirements of the nested sub-level. This recursive 420 // behavior is necessary for aligning function prototypes that have one or more 421 // arguments. 422 // If this function encounters a scope level less than the initial level, 423 // it returns the current position. 424 // There is a non-obvious subtlety in the recursive behavior: Even though we 425 // defer processing of nested levels to recursive invocations of this 426 // function, when it comes time to align a sequence of tokens, we run the 427 // alignment on the entire sequence, including the nested levels. 428 // When doing so, most of the nested tokens are skipped, because their 429 // alignment was already handled by the recursive invocations of this function. 430 // However, the special exception is that we do NOT skip function parameters 431 // that are split across multiple lines. See the test case in FormatTest.cpp 432 // that mentions "split function parameter alignment" for an example of this. 433 template <typename F> 434 static unsigned AlignTokens( 435 const FormatStyle &Style, F &&Matches, 436 SmallVector<WhitespaceManager::Change, 16> &Changes, unsigned StartAt, 437 const FormatStyle::AlignConsecutiveStyle &ACS = FormatStyle::ACS_None) { 438 unsigned MinColumn = 0; 439 unsigned MaxColumn = UINT_MAX; 440 441 // Line number of the start and the end of the current token sequence. 442 unsigned StartOfSequence = 0; 443 unsigned EndOfSequence = 0; 444 445 // Measure the scope level (i.e. depth of (), [], {}) of the first token, and 446 // abort when we hit any token in a higher scope than the starting one. 447 auto IndentAndNestingLevel = StartAt < Changes.size() 448 ? Changes[StartAt].indentAndNestingLevel() 449 : std::tuple<unsigned, unsigned, unsigned>(); 450 451 // Keep track of the number of commas before the matching tokens, we will only 452 // align a sequence of matching tokens if they are preceded by the same number 453 // of commas. 454 unsigned CommasBeforeLastMatch = 0; 455 unsigned CommasBeforeMatch = 0; 456 457 // Whether a matching token has been found on the current line. 458 bool FoundMatchOnLine = false; 459 460 // Whether the current line consists purely of comments. 461 bool LineIsComment = true; 462 463 // Aligns a sequence of matching tokens, on the MinColumn column. 464 // 465 // Sequences start from the first matching token to align, and end at the 466 // first token of the first line that doesn't need to be aligned. 467 // 468 // We need to adjust the StartOfTokenColumn of each Change that is on a line 469 // containing any matching token to be aligned and located after such token. 470 auto AlignCurrentSequence = [&] { 471 if (StartOfSequence > 0 && StartOfSequence < EndOfSequence) 472 AlignTokenSequence(Style, StartOfSequence, EndOfSequence, MinColumn, 473 Matches, Changes); 474 MinColumn = 0; 475 MaxColumn = UINT_MAX; 476 StartOfSequence = 0; 477 EndOfSequence = 0; 478 }; 479 480 unsigned i = StartAt; 481 for (unsigned e = Changes.size(); i != e; ++i) { 482 if (Changes[i].indentAndNestingLevel() < IndentAndNestingLevel) 483 break; 484 485 if (Changes[i].NewlinesBefore != 0) { 486 CommasBeforeMatch = 0; 487 EndOfSequence = i; 488 489 // Whether to break the alignment sequence because of an empty line. 490 bool EmptyLineBreak = 491 (Changes[i].NewlinesBefore > 1) && 492 (ACS != FormatStyle::ACS_AcrossEmptyLines) && 493 (ACS != FormatStyle::ACS_AcrossEmptyLinesAndComments); 494 495 // Whether to break the alignment sequence because of a line without a 496 // match. 497 bool NoMatchBreak = 498 !FoundMatchOnLine && 499 !(LineIsComment && 500 ((ACS == FormatStyle::ACS_AcrossComments) || 501 (ACS == FormatStyle::ACS_AcrossEmptyLinesAndComments))); 502 503 if (EmptyLineBreak || NoMatchBreak) 504 AlignCurrentSequence(); 505 506 // A new line starts, re-initialize line status tracking bools. 507 // Keep the match state if a string literal is continued on this line. 508 if (i == 0 || !Changes[i].Tok->is(tok::string_literal) || 509 !Changes[i - 1].Tok->is(tok::string_literal)) 510 FoundMatchOnLine = false; 511 LineIsComment = true; 512 } 513 514 if (!Changes[i].Tok->is(tok::comment)) { 515 LineIsComment = false; 516 } 517 518 if (Changes[i].Tok->is(tok::comma)) { 519 ++CommasBeforeMatch; 520 } else if (Changes[i].indentAndNestingLevel() > IndentAndNestingLevel) { 521 // Call AlignTokens recursively, skipping over this scope block. 522 unsigned StoppedAt = AlignTokens(Style, Matches, Changes, i, ACS); 523 i = StoppedAt - 1; 524 continue; 525 } 526 527 if (!Matches(Changes[i])) 528 continue; 529 530 // If there is more than one matching token per line, or if the number of 531 // preceding commas, do not match anymore, end the sequence. 532 if (FoundMatchOnLine || CommasBeforeMatch != CommasBeforeLastMatch) 533 AlignCurrentSequence(); 534 535 CommasBeforeLastMatch = CommasBeforeMatch; 536 FoundMatchOnLine = true; 537 538 if (StartOfSequence == 0) 539 StartOfSequence = i; 540 541 unsigned ChangeMinColumn = Changes[i].StartOfTokenColumn; 542 int LineLengthAfter = Changes[i].TokenLength; 543 for (unsigned j = i + 1; j != e && Changes[j].NewlinesBefore == 0; ++j) { 544 LineLengthAfter += Changes[j].Spaces; 545 // Changes are generally 1:1 with the tokens, but a change could also be 546 // inside of a token, in which case it's counted more than once: once for 547 // the whitespace surrounding the token (!IsInsideToken) and once for 548 // each whitespace change within it (IsInsideToken). 549 // Therefore, changes inside of a token should only count the space. 550 if (!Changes[j].IsInsideToken) 551 LineLengthAfter += Changes[j].TokenLength; 552 } 553 unsigned ChangeMaxColumn = Style.ColumnLimit - LineLengthAfter; 554 555 // If we are restricted by the maximum column width, end the sequence. 556 if (ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn || 557 CommasBeforeLastMatch != CommasBeforeMatch) { 558 AlignCurrentSequence(); 559 StartOfSequence = i; 560 } 561 562 MinColumn = std::max(MinColumn, ChangeMinColumn); 563 MaxColumn = std::min(MaxColumn, ChangeMaxColumn); 564 } 565 566 EndOfSequence = i; 567 AlignCurrentSequence(); 568 return i; 569 } 570 571 // Aligns a sequence of matching tokens, on the MinColumn column. 572 // 573 // Sequences start from the first matching token to align, and end at the 574 // first token of the first line that doesn't need to be aligned. 575 // 576 // We need to adjust the StartOfTokenColumn of each Change that is on a line 577 // containing any matching token to be aligned and located after such token. 578 static void AlignMacroSequence( 579 unsigned &StartOfSequence, unsigned &EndOfSequence, unsigned &MinColumn, 580 unsigned &MaxColumn, bool &FoundMatchOnLine, 581 std::function<bool(const WhitespaceManager::Change &C)> AlignMacrosMatches, 582 SmallVector<WhitespaceManager::Change, 16> &Changes) { 583 if (StartOfSequence > 0 && StartOfSequence < EndOfSequence) { 584 585 FoundMatchOnLine = false; 586 int Shift = 0; 587 588 for (unsigned I = StartOfSequence; I != EndOfSequence; ++I) { 589 if (Changes[I].NewlinesBefore > 0) { 590 Shift = 0; 591 FoundMatchOnLine = false; 592 } 593 594 // If this is the first matching token to be aligned, remember by how many 595 // spaces it has to be shifted, so the rest of the changes on the line are 596 // shifted by the same amount 597 if (!FoundMatchOnLine && AlignMacrosMatches(Changes[I])) { 598 FoundMatchOnLine = true; 599 Shift = MinColumn - Changes[I].StartOfTokenColumn; 600 Changes[I].Spaces += Shift; 601 } 602 603 assert(Shift >= 0); 604 Changes[I].StartOfTokenColumn += Shift; 605 if (I + 1 != Changes.size()) 606 Changes[I + 1].PreviousEndOfTokenColumn += Shift; 607 } 608 } 609 610 MinColumn = 0; 611 MaxColumn = UINT_MAX; 612 StartOfSequence = 0; 613 EndOfSequence = 0; 614 } 615 616 void WhitespaceManager::alignConsecutiveMacros() { 617 if (Style.AlignConsecutiveMacros == FormatStyle::ACS_None) 618 return; 619 620 auto AlignMacrosMatches = [](const Change &C) { 621 const FormatToken *Current = C.Tok; 622 unsigned SpacesRequiredBefore = 1; 623 624 if (Current->SpacesRequiredBefore == 0 || !Current->Previous) 625 return false; 626 627 Current = Current->Previous; 628 629 // If token is a ")", skip over the parameter list, to the 630 // token that precedes the "(" 631 if (Current->is(tok::r_paren) && Current->MatchingParen) { 632 Current = Current->MatchingParen->Previous; 633 SpacesRequiredBefore = 0; 634 } 635 636 if (!Current || !Current->is(tok::identifier)) 637 return false; 638 639 if (!Current->Previous || !Current->Previous->is(tok::pp_define)) 640 return false; 641 642 // For a macro function, 0 spaces are required between the 643 // identifier and the lparen that opens the parameter list. 644 // For a simple macro, 1 space is required between the 645 // identifier and the first token of the defined value. 646 return Current->Next->SpacesRequiredBefore == SpacesRequiredBefore; 647 }; 648 649 unsigned MinColumn = 0; 650 unsigned MaxColumn = UINT_MAX; 651 652 // Start and end of the token sequence we're processing. 653 unsigned StartOfSequence = 0; 654 unsigned EndOfSequence = 0; 655 656 // Whether a matching token has been found on the current line. 657 bool FoundMatchOnLine = false; 658 659 // Whether the current line consists only of comments 660 bool LineIsComment = true; 661 662 unsigned I = 0; 663 for (unsigned E = Changes.size(); I != E; ++I) { 664 if (Changes[I].NewlinesBefore != 0) { 665 EndOfSequence = I; 666 667 // Whether to break the alignment sequence because of an empty line. 668 bool EmptyLineBreak = 669 (Changes[I].NewlinesBefore > 1) && 670 (Style.AlignConsecutiveMacros != FormatStyle::ACS_AcrossEmptyLines) && 671 (Style.AlignConsecutiveMacros != 672 FormatStyle::ACS_AcrossEmptyLinesAndComments); 673 674 // Whether to break the alignment sequence because of a line without a 675 // match. 676 bool NoMatchBreak = 677 !FoundMatchOnLine && 678 !(LineIsComment && ((Style.AlignConsecutiveMacros == 679 FormatStyle::ACS_AcrossComments) || 680 (Style.AlignConsecutiveMacros == 681 FormatStyle::ACS_AcrossEmptyLinesAndComments))); 682 683 if (EmptyLineBreak || NoMatchBreak) 684 AlignMacroSequence(StartOfSequence, EndOfSequence, MinColumn, MaxColumn, 685 FoundMatchOnLine, AlignMacrosMatches, Changes); 686 687 // A new line starts, re-initialize line status tracking bools. 688 FoundMatchOnLine = false; 689 LineIsComment = true; 690 } 691 692 if (!Changes[I].Tok->is(tok::comment)) { 693 LineIsComment = false; 694 } 695 696 if (!AlignMacrosMatches(Changes[I])) 697 continue; 698 699 FoundMatchOnLine = true; 700 701 if (StartOfSequence == 0) 702 StartOfSequence = I; 703 704 unsigned ChangeMinColumn = Changes[I].StartOfTokenColumn; 705 int LineLengthAfter = -Changes[I].Spaces; 706 for (unsigned j = I; j != E && Changes[j].NewlinesBefore == 0; ++j) 707 LineLengthAfter += Changes[j].Spaces + Changes[j].TokenLength; 708 unsigned ChangeMaxColumn = Style.ColumnLimit - LineLengthAfter; 709 710 MinColumn = std::max(MinColumn, ChangeMinColumn); 711 MaxColumn = std::min(MaxColumn, ChangeMaxColumn); 712 } 713 714 EndOfSequence = I; 715 AlignMacroSequence(StartOfSequence, EndOfSequence, MinColumn, MaxColumn, 716 FoundMatchOnLine, AlignMacrosMatches, Changes); 717 } 718 719 void WhitespaceManager::alignConsecutiveAssignments() { 720 if (Style.AlignConsecutiveAssignments == FormatStyle::ACS_None) 721 return; 722 723 AlignTokens( 724 Style, 725 [&](const Change &C) { 726 // Do not align on equal signs that are first on a line. 727 if (C.NewlinesBefore > 0) 728 return false; 729 730 // Do not align on equal signs that are last on a line. 731 if (&C != &Changes.back() && (&C + 1)->NewlinesBefore > 0) 732 return false; 733 734 // Do not align operator= overloads. 735 FormatToken *Previous = C.Tok->getPreviousNonComment(); 736 if (Previous && Previous->is(tok::kw_operator)) 737 return false; 738 739 return C.Tok->is(tok::equal); 740 }, 741 Changes, /*StartAt=*/0, Style.AlignConsecutiveAssignments); 742 } 743 744 void WhitespaceManager::alignConsecutiveBitFields() { 745 if (Style.AlignConsecutiveBitFields == FormatStyle::ACS_None) 746 return; 747 748 AlignTokens( 749 Style, 750 [&](Change const &C) { 751 // Do not align on ':' that is first on a line. 752 if (C.NewlinesBefore > 0) 753 return false; 754 755 // Do not align on ':' that is last on a line. 756 if (&C != &Changes.back() && (&C + 1)->NewlinesBefore > 0) 757 return false; 758 759 return C.Tok->is(TT_BitFieldColon); 760 }, 761 Changes, /*StartAt=*/0, Style.AlignConsecutiveBitFields); 762 } 763 764 void WhitespaceManager::alignConsecutiveDeclarations() { 765 if (Style.AlignConsecutiveDeclarations == FormatStyle::ACS_None) 766 return; 767 768 AlignTokens( 769 Style, 770 [](Change const &C) { 771 // tok::kw_operator is necessary for aligning operator overload 772 // definitions. 773 if (C.Tok->isOneOf(TT_FunctionDeclarationName, tok::kw_operator)) 774 return true; 775 if (C.Tok->isNot(TT_StartOfName)) 776 return false; 777 if (C.Tok->Previous && 778 C.Tok->Previous->is(TT_StatementAttributeLikeMacro)) 779 return false; 780 // Check if there is a subsequent name that starts the same declaration. 781 for (FormatToken *Next = C.Tok->Next; Next; Next = Next->Next) { 782 if (Next->is(tok::comment)) 783 continue; 784 if (Next->is(TT_PointerOrReference)) 785 return false; 786 if (!Next->Tok.getIdentifierInfo()) 787 break; 788 if (Next->isOneOf(TT_StartOfName, TT_FunctionDeclarationName, 789 tok::kw_operator)) 790 return false; 791 } 792 return true; 793 }, 794 Changes, /*StartAt=*/0, Style.AlignConsecutiveDeclarations); 795 } 796 797 void WhitespaceManager::alignChainedConditionals() { 798 if (Style.BreakBeforeTernaryOperators) { 799 AlignTokens( 800 Style, 801 [](Change const &C) { 802 // Align question operators and last colon 803 return C.Tok->is(TT_ConditionalExpr) && 804 ((C.Tok->is(tok::question) && !C.NewlinesBefore) || 805 (C.Tok->is(tok::colon) && C.Tok->Next && 806 (C.Tok->Next->FakeLParens.size() == 0 || 807 C.Tok->Next->FakeLParens.back() != prec::Conditional))); 808 }, 809 Changes, /*StartAt=*/0); 810 } else { 811 static auto AlignWrappedOperand = [](Change const &C) { 812 FormatToken *Previous = C.Tok->getPreviousNonComment(); 813 return C.NewlinesBefore && Previous && Previous->is(TT_ConditionalExpr) && 814 (Previous->is(tok::colon) && 815 (C.Tok->FakeLParens.size() == 0 || 816 C.Tok->FakeLParens.back() != prec::Conditional)); 817 }; 818 // Ensure we keep alignment of wrapped operands with non-wrapped operands 819 // Since we actually align the operators, the wrapped operands need the 820 // extra offset to be properly aligned. 821 for (Change &C : Changes) { 822 if (AlignWrappedOperand(C)) 823 C.StartOfTokenColumn -= 2; 824 } 825 AlignTokens( 826 Style, 827 [this](Change const &C) { 828 // Align question operators if next operand is not wrapped, as 829 // well as wrapped operands after question operator or last 830 // colon in conditional sequence 831 return (C.Tok->is(TT_ConditionalExpr) && C.Tok->is(tok::question) && 832 &C != &Changes.back() && (&C + 1)->NewlinesBefore == 0 && 833 !(&C + 1)->IsTrailingComment) || 834 AlignWrappedOperand(C); 835 }, 836 Changes, /*StartAt=*/0); 837 } 838 } 839 840 void WhitespaceManager::alignTrailingComments() { 841 unsigned MinColumn = 0; 842 unsigned MaxColumn = UINT_MAX; 843 unsigned StartOfSequence = 0; 844 bool BreakBeforeNext = false; 845 unsigned Newlines = 0; 846 for (unsigned i = 0, e = Changes.size(); i != e; ++i) { 847 if (Changes[i].StartOfBlockComment) 848 continue; 849 Newlines += Changes[i].NewlinesBefore; 850 if (!Changes[i].IsTrailingComment) 851 continue; 852 853 unsigned ChangeMinColumn = Changes[i].StartOfTokenColumn; 854 unsigned ChangeMaxColumn; 855 856 if (Style.ColumnLimit == 0) 857 ChangeMaxColumn = UINT_MAX; 858 else if (Style.ColumnLimit >= Changes[i].TokenLength) 859 ChangeMaxColumn = Style.ColumnLimit - Changes[i].TokenLength; 860 else 861 ChangeMaxColumn = ChangeMinColumn; 862 863 // If we don't create a replacement for this change, we have to consider 864 // it to be immovable. 865 if (!Changes[i].CreateReplacement) 866 ChangeMaxColumn = ChangeMinColumn; 867 868 if (i + 1 != e && Changes[i + 1].ContinuesPPDirective) 869 ChangeMaxColumn -= 2; 870 // If this comment follows an } in column 0, it probably documents the 871 // closing of a namespace and we don't want to align it. 872 bool FollowsRBraceInColumn0 = i > 0 && Changes[i].NewlinesBefore == 0 && 873 Changes[i - 1].Tok->is(tok::r_brace) && 874 Changes[i - 1].StartOfTokenColumn == 0; 875 bool WasAlignedWithStartOfNextLine = false; 876 if (Changes[i].NewlinesBefore == 1) { // A comment on its own line. 877 unsigned CommentColumn = SourceMgr.getSpellingColumnNumber( 878 Changes[i].OriginalWhitespaceRange.getEnd()); 879 for (unsigned j = i + 1; j != e; ++j) { 880 if (Changes[j].Tok->is(tok::comment)) 881 continue; 882 883 unsigned NextColumn = SourceMgr.getSpellingColumnNumber( 884 Changes[j].OriginalWhitespaceRange.getEnd()); 885 // The start of the next token was previously aligned with the 886 // start of this comment. 887 WasAlignedWithStartOfNextLine = 888 CommentColumn == NextColumn || 889 CommentColumn == NextColumn + Style.IndentWidth; 890 break; 891 } 892 } 893 if (!Style.AlignTrailingComments || FollowsRBraceInColumn0) { 894 alignTrailingComments(StartOfSequence, i, MinColumn); 895 MinColumn = ChangeMinColumn; 896 MaxColumn = ChangeMinColumn; 897 StartOfSequence = i; 898 } else if (BreakBeforeNext || Newlines > 1 || 899 (ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn) || 900 // Break the comment sequence if the previous line did not end 901 // in a trailing comment. 902 (Changes[i].NewlinesBefore == 1 && i > 0 && 903 !Changes[i - 1].IsTrailingComment) || 904 WasAlignedWithStartOfNextLine) { 905 alignTrailingComments(StartOfSequence, i, MinColumn); 906 MinColumn = ChangeMinColumn; 907 MaxColumn = ChangeMaxColumn; 908 StartOfSequence = i; 909 } else { 910 MinColumn = std::max(MinColumn, ChangeMinColumn); 911 MaxColumn = std::min(MaxColumn, ChangeMaxColumn); 912 } 913 BreakBeforeNext = (i == 0) || (Changes[i].NewlinesBefore > 1) || 914 // Never start a sequence with a comment at the beginning 915 // of the line. 916 (Changes[i].NewlinesBefore == 1 && StartOfSequence == i); 917 Newlines = 0; 918 } 919 alignTrailingComments(StartOfSequence, Changes.size(), MinColumn); 920 } 921 922 void WhitespaceManager::alignTrailingComments(unsigned Start, unsigned End, 923 unsigned Column) { 924 for (unsigned i = Start; i != End; ++i) { 925 int Shift = 0; 926 if (Changes[i].IsTrailingComment) { 927 Shift = Column - Changes[i].StartOfTokenColumn; 928 } 929 if (Changes[i].StartOfBlockComment) { 930 Shift = Changes[i].IndentationOffset + 931 Changes[i].StartOfBlockComment->StartOfTokenColumn - 932 Changes[i].StartOfTokenColumn; 933 } 934 if (Shift < 0) 935 continue; 936 Changes[i].Spaces += Shift; 937 if (i + 1 != Changes.size()) 938 Changes[i + 1].PreviousEndOfTokenColumn += Shift; 939 Changes[i].StartOfTokenColumn += Shift; 940 } 941 } 942 943 void WhitespaceManager::alignEscapedNewlines() { 944 if (Style.AlignEscapedNewlines == FormatStyle::ENAS_DontAlign) 945 return; 946 947 bool AlignLeft = Style.AlignEscapedNewlines == FormatStyle::ENAS_Left; 948 unsigned MaxEndOfLine = AlignLeft ? 0 : Style.ColumnLimit; 949 unsigned StartOfMacro = 0; 950 for (unsigned i = 1, e = Changes.size(); i < e; ++i) { 951 Change &C = Changes[i]; 952 if (C.NewlinesBefore > 0) { 953 if (C.ContinuesPPDirective) { 954 MaxEndOfLine = std::max(C.PreviousEndOfTokenColumn + 2, MaxEndOfLine); 955 } else { 956 alignEscapedNewlines(StartOfMacro + 1, i, MaxEndOfLine); 957 MaxEndOfLine = AlignLeft ? 0 : Style.ColumnLimit; 958 StartOfMacro = i; 959 } 960 } 961 } 962 alignEscapedNewlines(StartOfMacro + 1, Changes.size(), MaxEndOfLine); 963 } 964 965 void WhitespaceManager::alignEscapedNewlines(unsigned Start, unsigned End, 966 unsigned Column) { 967 for (unsigned i = Start; i < End; ++i) { 968 Change &C = Changes[i]; 969 if (C.NewlinesBefore > 0) { 970 assert(C.ContinuesPPDirective); 971 if (C.PreviousEndOfTokenColumn + 1 > Column) 972 C.EscapedNewlineColumn = 0; 973 else 974 C.EscapedNewlineColumn = Column; 975 } 976 } 977 } 978 979 void WhitespaceManager::alignArrayInitializers() { 980 if (Style.AlignArrayOfStructures == FormatStyle::AIAS_None) 981 return; 982 983 for (unsigned ChangeIndex = 1U, ChangeEnd = Changes.size(); 984 ChangeIndex < ChangeEnd; ++ChangeIndex) { 985 auto &C = Changes[ChangeIndex]; 986 if (C.Tok->IsArrayInitializer) { 987 bool FoundComplete = false; 988 for (unsigned InsideIndex = ChangeIndex + 1; InsideIndex < ChangeEnd; 989 ++InsideIndex) { 990 if (Changes[InsideIndex].Tok == C.Tok->MatchingParen) { 991 alignArrayInitializers(ChangeIndex, InsideIndex + 1); 992 ChangeIndex = InsideIndex + 1; 993 FoundComplete = true; 994 break; 995 } 996 } 997 if (!FoundComplete) 998 ChangeIndex = ChangeEnd; 999 } 1000 } 1001 } 1002 1003 void WhitespaceManager::alignArrayInitializers(unsigned Start, unsigned End) { 1004 1005 if (Style.AlignArrayOfStructures == FormatStyle::AIAS_Right) 1006 alignArrayInitializersRightJustified(getCells(Start, End)); 1007 else if (Style.AlignArrayOfStructures == FormatStyle::AIAS_Left) 1008 alignArrayInitializersLeftJustified(getCells(Start, End)); 1009 } 1010 1011 void WhitespaceManager::alignArrayInitializersRightJustified( 1012 CellDescriptions &&CellDescs) { 1013 auto &Cells = CellDescs.Cells; 1014 1015 // Now go through and fixup the spaces. 1016 auto *CellIter = Cells.begin(); 1017 for (auto i = 0U; i < CellDescs.CellCount; i++, ++CellIter) { 1018 unsigned NetWidth = 0U; 1019 if (isSplitCell(*CellIter)) 1020 NetWidth = getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces); 1021 auto CellWidth = getMaximumCellWidth(CellIter, NetWidth); 1022 1023 if (Changes[CellIter->Index].Tok->is(tok::r_brace)) { 1024 // So in here we want to see if there is a brace that falls 1025 // on a line that was split. If so on that line we make sure that 1026 // the spaces in front of the brace are enough. 1027 Changes[CellIter->Index].NewlinesBefore = 0; 1028 Changes[CellIter->Index].Spaces = 0; 1029 for (const auto *Next = CellIter->NextColumnElement; Next != nullptr; 1030 Next = Next->NextColumnElement) { 1031 Changes[Next->Index].Spaces = 0; 1032 Changes[Next->Index].NewlinesBefore = 0; 1033 } 1034 // Unless the array is empty, we need the position of all the 1035 // immediately adjacent cells 1036 if (CellIter != Cells.begin()) { 1037 auto ThisNetWidth = 1038 getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces); 1039 auto MaxNetWidth = 1040 getMaximumNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces, 1041 CellDescs.CellCount); 1042 if (ThisNetWidth < MaxNetWidth) 1043 Changes[CellIter->Index].Spaces = (MaxNetWidth - ThisNetWidth); 1044 auto RowCount = 1U; 1045 auto Offset = std::distance(Cells.begin(), CellIter); 1046 for (const auto *Next = CellIter->NextColumnElement; Next != nullptr; 1047 Next = Next->NextColumnElement) { 1048 auto *Start = (Cells.begin() + RowCount * CellDescs.CellCount); 1049 auto *End = Start + Offset; 1050 ThisNetWidth = getNetWidth(Start, End, CellDescs.InitialSpaces); 1051 if (ThisNetWidth < MaxNetWidth) 1052 Changes[Next->Index].Spaces = (MaxNetWidth - ThisNetWidth); 1053 ++RowCount; 1054 } 1055 } 1056 } else { 1057 auto ThisWidth = 1058 calculateCellWidth(CellIter->Index, CellIter->EndIndex, true) + 1059 NetWidth; 1060 if (Changes[CellIter->Index].NewlinesBefore == 0) { 1061 Changes[CellIter->Index].Spaces = (CellWidth - (ThisWidth + NetWidth)); 1062 Changes[CellIter->Index].Spaces += (i > 0) ? 1 : 0; 1063 } 1064 alignToStartOfCell(CellIter->Index, CellIter->EndIndex); 1065 for (const auto *Next = CellIter->NextColumnElement; Next != nullptr; 1066 Next = Next->NextColumnElement) { 1067 ThisWidth = 1068 calculateCellWidth(Next->Index, Next->EndIndex, true) + NetWidth; 1069 if (Changes[Next->Index].NewlinesBefore == 0) { 1070 Changes[Next->Index].Spaces = (CellWidth - ThisWidth); 1071 Changes[Next->Index].Spaces += (i > 0) ? 1 : 0; 1072 } 1073 alignToStartOfCell(Next->Index, Next->EndIndex); 1074 } 1075 } 1076 } 1077 } 1078 1079 void WhitespaceManager::alignArrayInitializersLeftJustified( 1080 CellDescriptions &&CellDescs) { 1081 auto &Cells = CellDescs.Cells; 1082 1083 // Now go through and fixup the spaces. 1084 auto *CellIter = Cells.begin(); 1085 // The first cell needs to be against the left brace. 1086 if (Changes[CellIter->Index].NewlinesBefore == 0) 1087 Changes[CellIter->Index].Spaces = 0; 1088 else 1089 Changes[CellIter->Index].Spaces = CellDescs.InitialSpaces; 1090 ++CellIter; 1091 for (auto i = 1U; i < CellDescs.CellCount; i++, ++CellIter) { 1092 auto MaxNetWidth = getMaximumNetWidth( 1093 Cells.begin(), CellIter, CellDescs.InitialSpaces, CellDescs.CellCount); 1094 auto ThisNetWidth = 1095 getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces); 1096 if (Changes[CellIter->Index].NewlinesBefore == 0) { 1097 Changes[CellIter->Index].Spaces = 1098 MaxNetWidth - ThisNetWidth + 1099 (Changes[CellIter->Index].Tok->isNot(tok::r_brace) ? 1 : 0); 1100 } 1101 auto RowCount = 1U; 1102 auto Offset = std::distance(Cells.begin(), CellIter); 1103 for (const auto *Next = CellIter->NextColumnElement; Next != nullptr; 1104 Next = Next->NextColumnElement) { 1105 auto *Start = (Cells.begin() + RowCount * CellDescs.CellCount); 1106 auto *End = Start + Offset; 1107 auto ThisNetWidth = getNetWidth(Start, End, CellDescs.InitialSpaces); 1108 if (Changes[Next->Index].NewlinesBefore == 0) { 1109 Changes[Next->Index].Spaces = 1110 MaxNetWidth - ThisNetWidth + 1111 (Changes[Next->Index].Tok->isNot(tok::r_brace) ? 1 : 0); 1112 } 1113 ++RowCount; 1114 } 1115 } 1116 } 1117 1118 bool WhitespaceManager::isSplitCell(const CellDescription &Cell) { 1119 if (Cell.HasSplit) 1120 return true; 1121 for (const auto *Next = Cell.NextColumnElement; Next != nullptr; 1122 Next = Next->NextColumnElement) { 1123 if (Next->HasSplit) 1124 return true; 1125 } 1126 return false; 1127 } 1128 1129 WhitespaceManager::CellDescriptions WhitespaceManager::getCells(unsigned Start, 1130 unsigned End) { 1131 1132 unsigned Depth = 0; 1133 unsigned Cell = 0; 1134 unsigned CellCount = 0; 1135 unsigned InitialSpaces = 0; 1136 unsigned InitialTokenLength = 0; 1137 unsigned EndSpaces = 0; 1138 SmallVector<CellDescription> Cells; 1139 const FormatToken *MatchingParen = nullptr; 1140 for (unsigned i = Start; i < End; ++i) { 1141 auto &C = Changes[i]; 1142 if (C.Tok->is(tok::l_brace)) 1143 ++Depth; 1144 else if (C.Tok->is(tok::r_brace)) 1145 --Depth; 1146 if (Depth == 2) { 1147 if (C.Tok->is(tok::l_brace)) { 1148 Cell = 0; 1149 MatchingParen = C.Tok->MatchingParen; 1150 if (InitialSpaces == 0) { 1151 InitialSpaces = C.Spaces + C.TokenLength; 1152 InitialTokenLength = C.TokenLength; 1153 auto j = i - 1; 1154 for (; Changes[j].NewlinesBefore == 0 && j > Start; --j) { 1155 InitialSpaces += Changes[j].Spaces + Changes[j].TokenLength; 1156 InitialTokenLength += Changes[j].TokenLength; 1157 } 1158 if (C.NewlinesBefore == 0) { 1159 InitialSpaces += Changes[j].Spaces + Changes[j].TokenLength; 1160 InitialTokenLength += Changes[j].TokenLength; 1161 } 1162 } 1163 } else if (C.Tok->is(tok::comma)) { 1164 if (!Cells.empty()) 1165 Cells.back().EndIndex = i; 1166 if (C.Tok->getNextNonComment()->isNot(tok::r_brace)) // dangling comma 1167 ++Cell; 1168 } 1169 } else if (Depth == 1) { 1170 if (C.Tok == MatchingParen) { 1171 if (!Cells.empty()) 1172 Cells.back().EndIndex = i; 1173 Cells.push_back(CellDescription{i, ++Cell, i + 1, false, nullptr}); 1174 CellCount = C.Tok->Previous->isNot(tok::comma) ? Cell + 1 : Cell; 1175 // Go to the next non-comment and ensure there is a break in front 1176 const auto *NextNonComment = C.Tok->getNextNonComment(); 1177 while (NextNonComment->is(tok::comma)) 1178 NextNonComment = NextNonComment->getNextNonComment(); 1179 auto j = i; 1180 while (Changes[j].Tok != NextNonComment && j < End) 1181 ++j; 1182 if (j < End && Changes[j].NewlinesBefore == 0 && 1183 Changes[j].Tok->isNot(tok::r_brace)) { 1184 Changes[j].NewlinesBefore = 1; 1185 // Account for the added token lengths 1186 Changes[j].Spaces = InitialSpaces - InitialTokenLength; 1187 } 1188 } else if (C.Tok->is(tok::comment)) { 1189 // Trailing comments stay at a space past the last token 1190 C.Spaces = Changes[i - 1].Tok->is(tok::comma) ? 1 : 2; 1191 } else if (C.Tok->is(tok::l_brace)) { 1192 // We need to make sure that the ending braces is aligned to the 1193 // start of our initializer 1194 auto j = i - 1; 1195 for (; j > 0 && !Changes[j].Tok->ArrayInitializerLineStart; --j) 1196 ; // Nothing the loop does the work 1197 EndSpaces = Changes[j].Spaces; 1198 } 1199 } else if (Depth == 0 && C.Tok->is(tok::r_brace)) { 1200 C.NewlinesBefore = 1; 1201 C.Spaces = EndSpaces; 1202 } 1203 if (C.Tok->StartsColumn) { 1204 // This gets us past tokens that have been split over multiple 1205 // lines 1206 bool HasSplit = false; 1207 if (Changes[i].NewlinesBefore > 0) { 1208 // So if we split a line previously and the tail line + this token is 1209 // less then the column limit we remove the split here and just put 1210 // the column start at a space past the comma 1211 // 1212 // FIXME This if branch covers the cases where the column is not 1213 // the first column. This leads to weird pathologies like the formatting 1214 // auto foo = Items{ 1215 // Section{ 1216 // 0, bar(), 1217 // } 1218 // }; 1219 // Well if it doesn't lead to that it's indicative that the line 1220 // breaking should be revisited. Unfortunately alot of other options 1221 // interact with this 1222 auto j = i - 1; 1223 if ((j - 1) > Start && Changes[j].Tok->is(tok::comma) && 1224 Changes[j - 1].NewlinesBefore > 0) { 1225 --j; 1226 auto LineLimit = Changes[j].Spaces + Changes[j].TokenLength; 1227 if (LineLimit < Style.ColumnLimit) { 1228 Changes[i].NewlinesBefore = 0; 1229 Changes[i].Spaces = 1; 1230 } 1231 } 1232 } 1233 while (Changes[i].NewlinesBefore > 0 && Changes[i].Tok == C.Tok) { 1234 Changes[i].Spaces = InitialSpaces; 1235 ++i; 1236 HasSplit = true; 1237 } 1238 if (Changes[i].Tok != C.Tok) 1239 --i; 1240 Cells.push_back(CellDescription{i, Cell, i, HasSplit, nullptr}); 1241 } 1242 } 1243 1244 return linkCells({Cells, CellCount, InitialSpaces}); 1245 } 1246 1247 unsigned WhitespaceManager::calculateCellWidth(unsigned Start, unsigned End, 1248 bool WithSpaces) const { 1249 unsigned CellWidth = 0; 1250 for (auto i = Start; i < End; i++) { 1251 if (Changes[i].NewlinesBefore > 0) 1252 CellWidth = 0; 1253 CellWidth += Changes[i].TokenLength; 1254 CellWidth += (WithSpaces ? Changes[i].Spaces : 0); 1255 } 1256 return CellWidth; 1257 } 1258 1259 void WhitespaceManager::alignToStartOfCell(unsigned Start, unsigned End) { 1260 if ((End - Start) <= 1) 1261 return; 1262 // If the line is broken anywhere in there make sure everything 1263 // is aligned to the parent 1264 for (auto i = Start + 1; i < End; i++) { 1265 if (Changes[i].NewlinesBefore > 0) 1266 Changes[i].Spaces = Changes[Start].Spaces; 1267 } 1268 } 1269 1270 WhitespaceManager::CellDescriptions 1271 WhitespaceManager::linkCells(CellDescriptions &&CellDesc) { 1272 auto &Cells = CellDesc.Cells; 1273 for (auto *CellIter = Cells.begin(); CellIter != Cells.end(); ++CellIter) { 1274 if (CellIter->NextColumnElement == nullptr && 1275 ((CellIter + 1) != Cells.end())) { 1276 for (auto *NextIter = CellIter + 1; NextIter != Cells.end(); ++NextIter) { 1277 if (NextIter->Cell == CellIter->Cell) { 1278 CellIter->NextColumnElement = &(*NextIter); 1279 break; 1280 } 1281 } 1282 } 1283 } 1284 return std::move(CellDesc); 1285 } 1286 1287 void WhitespaceManager::generateChanges() { 1288 for (unsigned i = 0, e = Changes.size(); i != e; ++i) { 1289 const Change &C = Changes[i]; 1290 if (i > 0 && Changes[i - 1].OriginalWhitespaceRange.getBegin() == 1291 C.OriginalWhitespaceRange.getBegin()) { 1292 // Do not generate two replacements for the same location. 1293 continue; 1294 } 1295 if (C.CreateReplacement) { 1296 std::string ReplacementText = C.PreviousLinePostfix; 1297 if (C.ContinuesPPDirective) 1298 appendEscapedNewlineText(ReplacementText, C.NewlinesBefore, 1299 C.PreviousEndOfTokenColumn, 1300 C.EscapedNewlineColumn); 1301 else 1302 appendNewlineText(ReplacementText, C.NewlinesBefore); 1303 // FIXME: This assert should hold if we computed the column correctly. 1304 // assert((int)C.StartOfTokenColumn >= C.Spaces); 1305 appendIndentText( 1306 ReplacementText, C.Tok->IndentLevel, std::max(0, C.Spaces), 1307 std::max((int)C.StartOfTokenColumn, C.Spaces) - std::max(0, C.Spaces), 1308 C.IsAligned); 1309 ReplacementText.append(C.CurrentLinePrefix); 1310 storeReplacement(C.OriginalWhitespaceRange, ReplacementText); 1311 } 1312 } 1313 } 1314 1315 void WhitespaceManager::storeReplacement(SourceRange Range, StringRef Text) { 1316 unsigned WhitespaceLength = SourceMgr.getFileOffset(Range.getEnd()) - 1317 SourceMgr.getFileOffset(Range.getBegin()); 1318 // Don't create a replacement, if it does not change anything. 1319 if (StringRef(SourceMgr.getCharacterData(Range.getBegin()), 1320 WhitespaceLength) == Text) 1321 return; 1322 auto Err = Replaces.add(tooling::Replacement( 1323 SourceMgr, CharSourceRange::getCharRange(Range), Text)); 1324 // FIXME: better error handling. For now, just print an error message in the 1325 // release version. 1326 if (Err) { 1327 llvm::errs() << llvm::toString(std::move(Err)) << "\n"; 1328 assert(false); 1329 } 1330 } 1331 1332 void WhitespaceManager::appendNewlineText(std::string &Text, 1333 unsigned Newlines) { 1334 for (unsigned i = 0; i < Newlines; ++i) 1335 Text.append(UseCRLF ? "\r\n" : "\n"); 1336 } 1337 1338 void WhitespaceManager::appendEscapedNewlineText( 1339 std::string &Text, unsigned Newlines, unsigned PreviousEndOfTokenColumn, 1340 unsigned EscapedNewlineColumn) { 1341 if (Newlines > 0) { 1342 unsigned Spaces = 1343 std::max<int>(1, EscapedNewlineColumn - PreviousEndOfTokenColumn - 1); 1344 for (unsigned i = 0; i < Newlines; ++i) { 1345 Text.append(Spaces, ' '); 1346 Text.append(UseCRLF ? "\\\r\n" : "\\\n"); 1347 Spaces = std::max<int>(0, EscapedNewlineColumn - 1); 1348 } 1349 } 1350 } 1351 1352 void WhitespaceManager::appendIndentText(std::string &Text, 1353 unsigned IndentLevel, unsigned Spaces, 1354 unsigned WhitespaceStartColumn, 1355 bool IsAligned) { 1356 switch (Style.UseTab) { 1357 case FormatStyle::UT_Never: 1358 Text.append(Spaces, ' '); 1359 break; 1360 case FormatStyle::UT_Always: { 1361 if (Style.TabWidth) { 1362 unsigned FirstTabWidth = 1363 Style.TabWidth - WhitespaceStartColumn % Style.TabWidth; 1364 1365 // Insert only spaces when we want to end up before the next tab. 1366 if (Spaces < FirstTabWidth || Spaces == 1) { 1367 Text.append(Spaces, ' '); 1368 break; 1369 } 1370 // Align to the next tab. 1371 Spaces -= FirstTabWidth; 1372 Text.append("\t"); 1373 1374 Text.append(Spaces / Style.TabWidth, '\t'); 1375 Text.append(Spaces % Style.TabWidth, ' '); 1376 } else if (Spaces == 1) { 1377 Text.append(Spaces, ' '); 1378 } 1379 break; 1380 } 1381 case FormatStyle::UT_ForIndentation: 1382 if (WhitespaceStartColumn == 0) { 1383 unsigned Indentation = IndentLevel * Style.IndentWidth; 1384 Spaces = appendTabIndent(Text, Spaces, Indentation); 1385 } 1386 Text.append(Spaces, ' '); 1387 break; 1388 case FormatStyle::UT_ForContinuationAndIndentation: 1389 if (WhitespaceStartColumn == 0) 1390 Spaces = appendTabIndent(Text, Spaces, Spaces); 1391 Text.append(Spaces, ' '); 1392 break; 1393 case FormatStyle::UT_AlignWithSpaces: 1394 if (WhitespaceStartColumn == 0) { 1395 unsigned Indentation = 1396 IsAligned ? IndentLevel * Style.IndentWidth : Spaces; 1397 Spaces = appendTabIndent(Text, Spaces, Indentation); 1398 } 1399 Text.append(Spaces, ' '); 1400 break; 1401 } 1402 } 1403 1404 unsigned WhitespaceManager::appendTabIndent(std::string &Text, unsigned Spaces, 1405 unsigned Indentation) { 1406 // This happens, e.g. when a line in a block comment is indented less than the 1407 // first one. 1408 if (Indentation > Spaces) 1409 Indentation = Spaces; 1410 if (Style.TabWidth) { 1411 unsigned Tabs = Indentation / Style.TabWidth; 1412 Text.append(Tabs, '\t'); 1413 Spaces -= Tabs * Style.TabWidth; 1414 } 1415 return Spaces; 1416 } 1417 1418 } // namespace format 1419 } // namespace clang 1420