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 // Lambda. 348 if (Changes[ScopeStart - 1].Tok->is(TT_LambdaLBrace)) 349 return false; 350 351 // Continued function declaration 352 if (ScopeStart > Start + 1 && 353 Changes[ScopeStart - 2].Tok->is(TT_FunctionDeclarationName)) 354 return true; 355 356 // Continued function call 357 if (ScopeStart > Start + 1 && 358 Changes[ScopeStart - 2].Tok->is(tok::identifier) && 359 Changes[ScopeStart - 1].Tok->is(tok::l_paren) && 360 Changes[ScopeStart].Tok->isNot(TT_LambdaLSquare)) { 361 if (Changes[i].Tok->MatchingParen && 362 Changes[i].Tok->MatchingParen->is(TT_LambdaLBrace)) 363 return false; 364 return Style.BinPackArguments; 365 } 366 367 // Ternary operator 368 if (Changes[i].Tok->is(TT_ConditionalExpr)) 369 return true; 370 371 // Period Initializer .XXX = 1. 372 if (Changes[i].Tok->is(TT_DesignatedInitializerPeriod)) 373 return true; 374 375 // Continued ternary operator 376 if (Changes[i].Tok->Previous && 377 Changes[i].Tok->Previous->is(TT_ConditionalExpr)) 378 return true; 379 380 // Continued braced list. 381 if (ScopeStart > Start + 1 && 382 Changes[ScopeStart - 2].Tok->isNot(tok::identifier) && 383 Changes[ScopeStart - 1].Tok->is(tok::l_brace) && 384 Changes[i].Tok->isNot(tok::r_brace)) { 385 for (unsigned OuterScopeStart : llvm::reverse(ScopeStack)) { 386 // Lambda. 387 if (OuterScopeStart > Start && 388 Changes[OuterScopeStart - 1].Tok->is(TT_LambdaLBrace)) 389 return false; 390 } 391 return true; 392 } 393 394 return false; 395 }; 396 397 if (ShouldShiftBeAdded()) 398 Changes[i].Spaces += Shift; 399 } 400 401 if (ContinuedStringLiteral) 402 Changes[i].Spaces += Shift; 403 404 Changes[i].StartOfTokenColumn += Shift; 405 if (i + 1 != Changes.size()) 406 Changes[i + 1].PreviousEndOfTokenColumn += Shift; 407 408 // If PointerAlignment is PAS_Right, keep *s or &s next to the token 409 if (Style.PointerAlignment == FormatStyle::PAS_Right && 410 Changes[i].Spaces != 0) { 411 for (int Previous = i - 1; 412 Previous >= 0 && 413 Changes[Previous].Tok->getType() == TT_PointerOrReference; 414 --Previous) { 415 Changes[Previous + 1].Spaces -= Shift; 416 Changes[Previous].Spaces += Shift; 417 } 418 } 419 } 420 } 421 422 // Walk through a subset of the changes, starting at StartAt, and find 423 // sequences of matching tokens to align. To do so, keep track of the lines and 424 // whether or not a matching token was found on a line. If a matching token is 425 // found, extend the current sequence. If the current line cannot be part of a 426 // sequence, e.g. because there is an empty line before it or it contains only 427 // non-matching tokens, finalize the previous sequence. 428 // The value returned is the token on which we stopped, either because we 429 // exhausted all items inside Changes, or because we hit a scope level higher 430 // than our initial scope. 431 // This function is recursive. Each invocation processes only the scope level 432 // equal to the initial level, which is the level of Changes[StartAt]. 433 // If we encounter a scope level greater than the initial level, then we call 434 // ourselves recursively, thereby avoiding the pollution of the current state 435 // with the alignment requirements of the nested sub-level. This recursive 436 // behavior is necessary for aligning function prototypes that have one or more 437 // arguments. 438 // If this function encounters a scope level less than the initial level, 439 // it returns the current position. 440 // There is a non-obvious subtlety in the recursive behavior: Even though we 441 // defer processing of nested levels to recursive invocations of this 442 // function, when it comes time to align a sequence of tokens, we run the 443 // alignment on the entire sequence, including the nested levels. 444 // When doing so, most of the nested tokens are skipped, because their 445 // alignment was already handled by the recursive invocations of this function. 446 // However, the special exception is that we do NOT skip function parameters 447 // that are split across multiple lines. See the test case in FormatTest.cpp 448 // that mentions "split function parameter alignment" for an example of this. 449 template <typename F> 450 static unsigned AlignTokens( 451 const FormatStyle &Style, F &&Matches, 452 SmallVector<WhitespaceManager::Change, 16> &Changes, unsigned StartAt, 453 const FormatStyle::AlignConsecutiveStyle &ACS = FormatStyle::ACS_None) { 454 unsigned MinColumn = 0; 455 unsigned MaxColumn = UINT_MAX; 456 457 // Line number of the start and the end of the current token sequence. 458 unsigned StartOfSequence = 0; 459 unsigned EndOfSequence = 0; 460 461 // Measure the scope level (i.e. depth of (), [], {}) of the first token, and 462 // abort when we hit any token in a higher scope than the starting one. 463 auto IndentAndNestingLevel = StartAt < Changes.size() 464 ? Changes[StartAt].indentAndNestingLevel() 465 : std::tuple<unsigned, unsigned, unsigned>(); 466 467 // Keep track of the number of commas before the matching tokens, we will only 468 // align a sequence of matching tokens if they are preceded by the same number 469 // of commas. 470 unsigned CommasBeforeLastMatch = 0; 471 unsigned CommasBeforeMatch = 0; 472 473 // Whether a matching token has been found on the current line. 474 bool FoundMatchOnLine = false; 475 476 // Whether the current line consists purely of comments. 477 bool LineIsComment = true; 478 479 // Aligns a sequence of matching tokens, on the MinColumn column. 480 // 481 // Sequences start from the first matching token to align, and end at the 482 // first token of the first line that doesn't need to be aligned. 483 // 484 // We need to adjust the StartOfTokenColumn of each Change that is on a line 485 // containing any matching token to be aligned and located after such token. 486 auto AlignCurrentSequence = [&] { 487 if (StartOfSequence > 0 && StartOfSequence < EndOfSequence) 488 AlignTokenSequence(Style, StartOfSequence, EndOfSequence, MinColumn, 489 Matches, Changes); 490 MinColumn = 0; 491 MaxColumn = UINT_MAX; 492 StartOfSequence = 0; 493 EndOfSequence = 0; 494 }; 495 496 unsigned i = StartAt; 497 for (unsigned e = Changes.size(); i != e; ++i) { 498 if (Changes[i].indentAndNestingLevel() < IndentAndNestingLevel) 499 break; 500 501 if (Changes[i].NewlinesBefore != 0) { 502 CommasBeforeMatch = 0; 503 EndOfSequence = i; 504 505 // Whether to break the alignment sequence because of an empty line. 506 bool EmptyLineBreak = 507 (Changes[i].NewlinesBefore > 1) && 508 (ACS != FormatStyle::ACS_AcrossEmptyLines) && 509 (ACS != FormatStyle::ACS_AcrossEmptyLinesAndComments); 510 511 // Whether to break the alignment sequence because of a line without a 512 // match. 513 bool NoMatchBreak = 514 !FoundMatchOnLine && 515 !(LineIsComment && 516 ((ACS == FormatStyle::ACS_AcrossComments) || 517 (ACS == FormatStyle::ACS_AcrossEmptyLinesAndComments))); 518 519 if (EmptyLineBreak || NoMatchBreak) 520 AlignCurrentSequence(); 521 522 // A new line starts, re-initialize line status tracking bools. 523 // Keep the match state if a string literal is continued on this line. 524 if (i == 0 || !Changes[i].Tok->is(tok::string_literal) || 525 !Changes[i - 1].Tok->is(tok::string_literal)) 526 FoundMatchOnLine = false; 527 LineIsComment = true; 528 } 529 530 if (!Changes[i].Tok->is(tok::comment)) { 531 LineIsComment = false; 532 } 533 534 if (Changes[i].Tok->is(tok::comma)) { 535 ++CommasBeforeMatch; 536 } else if (Changes[i].indentAndNestingLevel() > IndentAndNestingLevel) { 537 // Call AlignTokens recursively, skipping over this scope block. 538 unsigned StoppedAt = AlignTokens(Style, Matches, Changes, i, ACS); 539 i = StoppedAt - 1; 540 continue; 541 } 542 543 if (!Matches(Changes[i])) 544 continue; 545 546 // If there is more than one matching token per line, or if the number of 547 // preceding commas, do not match anymore, end the sequence. 548 if (FoundMatchOnLine || CommasBeforeMatch != CommasBeforeLastMatch) 549 AlignCurrentSequence(); 550 551 CommasBeforeLastMatch = CommasBeforeMatch; 552 FoundMatchOnLine = true; 553 554 if (StartOfSequence == 0) 555 StartOfSequence = i; 556 557 unsigned ChangeMinColumn = Changes[i].StartOfTokenColumn; 558 int LineLengthAfter = Changes[i].TokenLength; 559 for (unsigned j = i + 1; j != e && Changes[j].NewlinesBefore == 0; ++j) { 560 LineLengthAfter += Changes[j].Spaces; 561 // Changes are generally 1:1 with the tokens, but a change could also be 562 // inside of a token, in which case it's counted more than once: once for 563 // the whitespace surrounding the token (!IsInsideToken) and once for 564 // each whitespace change within it (IsInsideToken). 565 // Therefore, changes inside of a token should only count the space. 566 if (!Changes[j].IsInsideToken) 567 LineLengthAfter += Changes[j].TokenLength; 568 } 569 unsigned ChangeMaxColumn = Style.ColumnLimit - LineLengthAfter; 570 571 // If we are restricted by the maximum column width, end the sequence. 572 if (ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn || 573 CommasBeforeLastMatch != CommasBeforeMatch) { 574 AlignCurrentSequence(); 575 StartOfSequence = i; 576 } 577 578 MinColumn = std::max(MinColumn, ChangeMinColumn); 579 MaxColumn = std::min(MaxColumn, ChangeMaxColumn); 580 } 581 582 EndOfSequence = i; 583 AlignCurrentSequence(); 584 return i; 585 } 586 587 // Aligns a sequence of matching tokens, on the MinColumn column. 588 // 589 // Sequences start from the first matching token to align, and end at the 590 // first token of the first line that doesn't need to be aligned. 591 // 592 // We need to adjust the StartOfTokenColumn of each Change that is on a line 593 // containing any matching token to be aligned and located after such token. 594 static void AlignMacroSequence( 595 unsigned &StartOfSequence, unsigned &EndOfSequence, unsigned &MinColumn, 596 unsigned &MaxColumn, bool &FoundMatchOnLine, 597 std::function<bool(const WhitespaceManager::Change &C)> AlignMacrosMatches, 598 SmallVector<WhitespaceManager::Change, 16> &Changes) { 599 if (StartOfSequence > 0 && StartOfSequence < EndOfSequence) { 600 601 FoundMatchOnLine = false; 602 int Shift = 0; 603 604 for (unsigned I = StartOfSequence; I != EndOfSequence; ++I) { 605 if (Changes[I].NewlinesBefore > 0) { 606 Shift = 0; 607 FoundMatchOnLine = false; 608 } 609 610 // If this is the first matching token to be aligned, remember by how many 611 // spaces it has to be shifted, so the rest of the changes on the line are 612 // shifted by the same amount 613 if (!FoundMatchOnLine && AlignMacrosMatches(Changes[I])) { 614 FoundMatchOnLine = true; 615 Shift = MinColumn - Changes[I].StartOfTokenColumn; 616 Changes[I].Spaces += Shift; 617 } 618 619 assert(Shift >= 0); 620 Changes[I].StartOfTokenColumn += Shift; 621 if (I + 1 != Changes.size()) 622 Changes[I + 1].PreviousEndOfTokenColumn += Shift; 623 } 624 } 625 626 MinColumn = 0; 627 MaxColumn = UINT_MAX; 628 StartOfSequence = 0; 629 EndOfSequence = 0; 630 } 631 632 void WhitespaceManager::alignConsecutiveMacros() { 633 if (Style.AlignConsecutiveMacros == FormatStyle::ACS_None) 634 return; 635 636 auto AlignMacrosMatches = [](const Change &C) { 637 const FormatToken *Current = C.Tok; 638 unsigned SpacesRequiredBefore = 1; 639 640 if (Current->SpacesRequiredBefore == 0 || !Current->Previous) 641 return false; 642 643 Current = Current->Previous; 644 645 // If token is a ")", skip over the parameter list, to the 646 // token that precedes the "(" 647 if (Current->is(tok::r_paren) && Current->MatchingParen) { 648 Current = Current->MatchingParen->Previous; 649 SpacesRequiredBefore = 0; 650 } 651 652 if (!Current || !Current->is(tok::identifier)) 653 return false; 654 655 if (!Current->Previous || !Current->Previous->is(tok::pp_define)) 656 return false; 657 658 // For a macro function, 0 spaces are required between the 659 // identifier and the lparen that opens the parameter list. 660 // For a simple macro, 1 space is required between the 661 // identifier and the first token of the defined value. 662 return Current->Next->SpacesRequiredBefore == SpacesRequiredBefore; 663 }; 664 665 unsigned MinColumn = 0; 666 unsigned MaxColumn = UINT_MAX; 667 668 // Start and end of the token sequence we're processing. 669 unsigned StartOfSequence = 0; 670 unsigned EndOfSequence = 0; 671 672 // Whether a matching token has been found on the current line. 673 bool FoundMatchOnLine = false; 674 675 // Whether the current line consists only of comments 676 bool LineIsComment = true; 677 678 unsigned I = 0; 679 for (unsigned E = Changes.size(); I != E; ++I) { 680 if (Changes[I].NewlinesBefore != 0) { 681 EndOfSequence = I; 682 683 // Whether to break the alignment sequence because of an empty line. 684 bool EmptyLineBreak = 685 (Changes[I].NewlinesBefore > 1) && 686 (Style.AlignConsecutiveMacros != FormatStyle::ACS_AcrossEmptyLines) && 687 (Style.AlignConsecutiveMacros != 688 FormatStyle::ACS_AcrossEmptyLinesAndComments); 689 690 // Whether to break the alignment sequence because of a line without a 691 // match. 692 bool NoMatchBreak = 693 !FoundMatchOnLine && 694 !(LineIsComment && ((Style.AlignConsecutiveMacros == 695 FormatStyle::ACS_AcrossComments) || 696 (Style.AlignConsecutiveMacros == 697 FormatStyle::ACS_AcrossEmptyLinesAndComments))); 698 699 if (EmptyLineBreak || NoMatchBreak) 700 AlignMacroSequence(StartOfSequence, EndOfSequence, MinColumn, MaxColumn, 701 FoundMatchOnLine, AlignMacrosMatches, Changes); 702 703 // A new line starts, re-initialize line status tracking bools. 704 FoundMatchOnLine = false; 705 LineIsComment = true; 706 } 707 708 if (!Changes[I].Tok->is(tok::comment)) { 709 LineIsComment = false; 710 } 711 712 if (!AlignMacrosMatches(Changes[I])) 713 continue; 714 715 FoundMatchOnLine = true; 716 717 if (StartOfSequence == 0) 718 StartOfSequence = I; 719 720 unsigned ChangeMinColumn = Changes[I].StartOfTokenColumn; 721 int LineLengthAfter = -Changes[I].Spaces; 722 for (unsigned j = I; j != E && Changes[j].NewlinesBefore == 0; ++j) 723 LineLengthAfter += Changes[j].Spaces + Changes[j].TokenLength; 724 unsigned ChangeMaxColumn = Style.ColumnLimit - LineLengthAfter; 725 726 MinColumn = std::max(MinColumn, ChangeMinColumn); 727 MaxColumn = std::min(MaxColumn, ChangeMaxColumn); 728 } 729 730 EndOfSequence = I; 731 AlignMacroSequence(StartOfSequence, EndOfSequence, MinColumn, MaxColumn, 732 FoundMatchOnLine, AlignMacrosMatches, Changes); 733 } 734 735 void WhitespaceManager::alignConsecutiveAssignments() { 736 if (Style.AlignConsecutiveAssignments == FormatStyle::ACS_None) 737 return; 738 739 AlignTokens( 740 Style, 741 [&](const Change &C) { 742 // Do not align on equal signs that are first on a line. 743 if (C.NewlinesBefore > 0) 744 return false; 745 746 // Do not align on equal signs that are last on a line. 747 if (&C != &Changes.back() && (&C + 1)->NewlinesBefore > 0) 748 return false; 749 750 // Do not align operator= overloads. 751 FormatToken *Previous = C.Tok->getPreviousNonComment(); 752 if (Previous && Previous->is(tok::kw_operator)) 753 return false; 754 755 return C.Tok->is(tok::equal); 756 }, 757 Changes, /*StartAt=*/0, Style.AlignConsecutiveAssignments); 758 } 759 760 void WhitespaceManager::alignConsecutiveBitFields() { 761 if (Style.AlignConsecutiveBitFields == FormatStyle::ACS_None) 762 return; 763 764 AlignTokens( 765 Style, 766 [&](Change const &C) { 767 // Do not align on ':' that is first on a line. 768 if (C.NewlinesBefore > 0) 769 return false; 770 771 // Do not align on ':' that is last on a line. 772 if (&C != &Changes.back() && (&C + 1)->NewlinesBefore > 0) 773 return false; 774 775 return C.Tok->is(TT_BitFieldColon); 776 }, 777 Changes, /*StartAt=*/0, Style.AlignConsecutiveBitFields); 778 } 779 780 void WhitespaceManager::alignConsecutiveDeclarations() { 781 if (Style.AlignConsecutiveDeclarations == FormatStyle::ACS_None) 782 return; 783 784 AlignTokens( 785 Style, 786 [](Change const &C) { 787 // tok::kw_operator is necessary for aligning operator overload 788 // definitions. 789 if (C.Tok->isOneOf(TT_FunctionDeclarationName, tok::kw_operator)) 790 return true; 791 if (C.Tok->isNot(TT_StartOfName)) 792 return false; 793 if (C.Tok->Previous && 794 C.Tok->Previous->is(TT_StatementAttributeLikeMacro)) 795 return false; 796 // Check if there is a subsequent name that starts the same declaration. 797 for (FormatToken *Next = C.Tok->Next; Next; Next = Next->Next) { 798 if (Next->is(tok::comment)) 799 continue; 800 if (Next->is(TT_PointerOrReference)) 801 return false; 802 if (!Next->Tok.getIdentifierInfo()) 803 break; 804 if (Next->isOneOf(TT_StartOfName, TT_FunctionDeclarationName, 805 tok::kw_operator)) 806 return false; 807 } 808 return true; 809 }, 810 Changes, /*StartAt=*/0, Style.AlignConsecutiveDeclarations); 811 } 812 813 void WhitespaceManager::alignChainedConditionals() { 814 if (Style.BreakBeforeTernaryOperators) { 815 AlignTokens( 816 Style, 817 [](Change const &C) { 818 // Align question operators and last colon 819 return C.Tok->is(TT_ConditionalExpr) && 820 ((C.Tok->is(tok::question) && !C.NewlinesBefore) || 821 (C.Tok->is(tok::colon) && C.Tok->Next && 822 (C.Tok->Next->FakeLParens.size() == 0 || 823 C.Tok->Next->FakeLParens.back() != prec::Conditional))); 824 }, 825 Changes, /*StartAt=*/0); 826 } else { 827 static auto AlignWrappedOperand = [](Change const &C) { 828 FormatToken *Previous = C.Tok->getPreviousNonComment(); 829 return C.NewlinesBefore && Previous && Previous->is(TT_ConditionalExpr) && 830 (Previous->is(tok::colon) && 831 (C.Tok->FakeLParens.size() == 0 || 832 C.Tok->FakeLParens.back() != prec::Conditional)); 833 }; 834 // Ensure we keep alignment of wrapped operands with non-wrapped operands 835 // Since we actually align the operators, the wrapped operands need the 836 // extra offset to be properly aligned. 837 for (Change &C : Changes) { 838 if (AlignWrappedOperand(C)) 839 C.StartOfTokenColumn -= 2; 840 } 841 AlignTokens( 842 Style, 843 [this](Change const &C) { 844 // Align question operators if next operand is not wrapped, as 845 // well as wrapped operands after question operator or last 846 // colon in conditional sequence 847 return (C.Tok->is(TT_ConditionalExpr) && C.Tok->is(tok::question) && 848 &C != &Changes.back() && (&C + 1)->NewlinesBefore == 0 && 849 !(&C + 1)->IsTrailingComment) || 850 AlignWrappedOperand(C); 851 }, 852 Changes, /*StartAt=*/0); 853 } 854 } 855 856 void WhitespaceManager::alignTrailingComments() { 857 unsigned MinColumn = 0; 858 unsigned MaxColumn = UINT_MAX; 859 unsigned StartOfSequence = 0; 860 bool BreakBeforeNext = false; 861 unsigned Newlines = 0; 862 for (unsigned i = 0, e = Changes.size(); i != e; ++i) { 863 if (Changes[i].StartOfBlockComment) 864 continue; 865 Newlines += Changes[i].NewlinesBefore; 866 if (!Changes[i].IsTrailingComment) 867 continue; 868 869 unsigned ChangeMinColumn = Changes[i].StartOfTokenColumn; 870 unsigned ChangeMaxColumn; 871 872 if (Style.ColumnLimit == 0) 873 ChangeMaxColumn = UINT_MAX; 874 else if (Style.ColumnLimit >= Changes[i].TokenLength) 875 ChangeMaxColumn = Style.ColumnLimit - Changes[i].TokenLength; 876 else 877 ChangeMaxColumn = ChangeMinColumn; 878 879 // If we don't create a replacement for this change, we have to consider 880 // it to be immovable. 881 if (!Changes[i].CreateReplacement) 882 ChangeMaxColumn = ChangeMinColumn; 883 884 if (i + 1 != e && Changes[i + 1].ContinuesPPDirective) 885 ChangeMaxColumn -= 2; 886 // If this comment follows an } in column 0, it probably documents the 887 // closing of a namespace and we don't want to align it. 888 bool FollowsRBraceInColumn0 = i > 0 && Changes[i].NewlinesBefore == 0 && 889 Changes[i - 1].Tok->is(tok::r_brace) && 890 Changes[i - 1].StartOfTokenColumn == 0; 891 bool WasAlignedWithStartOfNextLine = false; 892 if (Changes[i].NewlinesBefore == 1) { // A comment on its own line. 893 unsigned CommentColumn = SourceMgr.getSpellingColumnNumber( 894 Changes[i].OriginalWhitespaceRange.getEnd()); 895 for (unsigned j = i + 1; j != e; ++j) { 896 if (Changes[j].Tok->is(tok::comment)) 897 continue; 898 899 unsigned NextColumn = SourceMgr.getSpellingColumnNumber( 900 Changes[j].OriginalWhitespaceRange.getEnd()); 901 // The start of the next token was previously aligned with the 902 // start of this comment. 903 WasAlignedWithStartOfNextLine = 904 CommentColumn == NextColumn || 905 CommentColumn == NextColumn + Style.IndentWidth; 906 break; 907 } 908 } 909 if (!Style.AlignTrailingComments || FollowsRBraceInColumn0) { 910 alignTrailingComments(StartOfSequence, i, MinColumn); 911 MinColumn = ChangeMinColumn; 912 MaxColumn = ChangeMinColumn; 913 StartOfSequence = i; 914 } else if (BreakBeforeNext || Newlines > 1 || 915 (ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn) || 916 // Break the comment sequence if the previous line did not end 917 // in a trailing comment. 918 (Changes[i].NewlinesBefore == 1 && i > 0 && 919 !Changes[i - 1].IsTrailingComment) || 920 WasAlignedWithStartOfNextLine) { 921 alignTrailingComments(StartOfSequence, i, MinColumn); 922 MinColumn = ChangeMinColumn; 923 MaxColumn = ChangeMaxColumn; 924 StartOfSequence = i; 925 } else { 926 MinColumn = std::max(MinColumn, ChangeMinColumn); 927 MaxColumn = std::min(MaxColumn, ChangeMaxColumn); 928 } 929 BreakBeforeNext = (i == 0) || (Changes[i].NewlinesBefore > 1) || 930 // Never start a sequence with a comment at the beginning 931 // of the line. 932 (Changes[i].NewlinesBefore == 1 && StartOfSequence == i); 933 Newlines = 0; 934 } 935 alignTrailingComments(StartOfSequence, Changes.size(), MinColumn); 936 } 937 938 void WhitespaceManager::alignTrailingComments(unsigned Start, unsigned End, 939 unsigned Column) { 940 for (unsigned i = Start; i != End; ++i) { 941 int Shift = 0; 942 if (Changes[i].IsTrailingComment) { 943 Shift = Column - Changes[i].StartOfTokenColumn; 944 } 945 if (Changes[i].StartOfBlockComment) { 946 Shift = Changes[i].IndentationOffset + 947 Changes[i].StartOfBlockComment->StartOfTokenColumn - 948 Changes[i].StartOfTokenColumn; 949 } 950 if (Shift < 0) 951 continue; 952 Changes[i].Spaces += Shift; 953 if (i + 1 != Changes.size()) 954 Changes[i + 1].PreviousEndOfTokenColumn += Shift; 955 Changes[i].StartOfTokenColumn += Shift; 956 } 957 } 958 959 void WhitespaceManager::alignEscapedNewlines() { 960 if (Style.AlignEscapedNewlines == FormatStyle::ENAS_DontAlign) 961 return; 962 963 bool AlignLeft = Style.AlignEscapedNewlines == FormatStyle::ENAS_Left; 964 unsigned MaxEndOfLine = AlignLeft ? 0 : Style.ColumnLimit; 965 unsigned StartOfMacro = 0; 966 for (unsigned i = 1, e = Changes.size(); i < e; ++i) { 967 Change &C = Changes[i]; 968 if (C.NewlinesBefore > 0) { 969 if (C.ContinuesPPDirective) { 970 MaxEndOfLine = std::max(C.PreviousEndOfTokenColumn + 2, MaxEndOfLine); 971 } else { 972 alignEscapedNewlines(StartOfMacro + 1, i, MaxEndOfLine); 973 MaxEndOfLine = AlignLeft ? 0 : Style.ColumnLimit; 974 StartOfMacro = i; 975 } 976 } 977 } 978 alignEscapedNewlines(StartOfMacro + 1, Changes.size(), MaxEndOfLine); 979 } 980 981 void WhitespaceManager::alignEscapedNewlines(unsigned Start, unsigned End, 982 unsigned Column) { 983 for (unsigned i = Start; i < End; ++i) { 984 Change &C = Changes[i]; 985 if (C.NewlinesBefore > 0) { 986 assert(C.ContinuesPPDirective); 987 if (C.PreviousEndOfTokenColumn + 1 > Column) 988 C.EscapedNewlineColumn = 0; 989 else 990 C.EscapedNewlineColumn = Column; 991 } 992 } 993 } 994 995 void WhitespaceManager::alignArrayInitializers() { 996 if (Style.AlignArrayOfStructures == FormatStyle::AIAS_None) 997 return; 998 999 for (unsigned ChangeIndex = 1U, ChangeEnd = Changes.size(); 1000 ChangeIndex < ChangeEnd; ++ChangeIndex) { 1001 auto &C = Changes[ChangeIndex]; 1002 if (C.Tok->IsArrayInitializer) { 1003 bool FoundComplete = false; 1004 for (unsigned InsideIndex = ChangeIndex + 1; InsideIndex < ChangeEnd; 1005 ++InsideIndex) { 1006 if (Changes[InsideIndex].Tok == C.Tok->MatchingParen) { 1007 alignArrayInitializers(ChangeIndex, InsideIndex + 1); 1008 ChangeIndex = InsideIndex + 1; 1009 FoundComplete = true; 1010 break; 1011 } 1012 } 1013 if (!FoundComplete) 1014 ChangeIndex = ChangeEnd; 1015 } 1016 } 1017 } 1018 1019 void WhitespaceManager::alignArrayInitializers(unsigned Start, unsigned End) { 1020 1021 if (Style.AlignArrayOfStructures == FormatStyle::AIAS_Right) 1022 alignArrayInitializersRightJustified(getCells(Start, End)); 1023 else if (Style.AlignArrayOfStructures == FormatStyle::AIAS_Left) 1024 alignArrayInitializersLeftJustified(getCells(Start, End)); 1025 } 1026 1027 void WhitespaceManager::alignArrayInitializersRightJustified( 1028 CellDescriptions &&CellDescs) { 1029 auto &Cells = CellDescs.Cells; 1030 1031 // Now go through and fixup the spaces. 1032 auto *CellIter = Cells.begin(); 1033 for (auto i = 0U; i < CellDescs.CellCount; ++i, ++CellIter) { 1034 unsigned NetWidth = 0U; 1035 if (isSplitCell(*CellIter)) 1036 NetWidth = getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces); 1037 auto CellWidth = getMaximumCellWidth(CellIter, NetWidth); 1038 1039 if (Changes[CellIter->Index].Tok->is(tok::r_brace)) { 1040 // So in here we want to see if there is a brace that falls 1041 // on a line that was split. If so on that line we make sure that 1042 // the spaces in front of the brace are enough. 1043 Changes[CellIter->Index].NewlinesBefore = 0; 1044 Changes[CellIter->Index].Spaces = 0; 1045 for (const auto *Next = CellIter->NextColumnElement; Next != nullptr; 1046 Next = Next->NextColumnElement) { 1047 Changes[Next->Index].Spaces = 0; 1048 Changes[Next->Index].NewlinesBefore = 0; 1049 } 1050 // Unless the array is empty, we need the position of all the 1051 // immediately adjacent cells 1052 if (CellIter != Cells.begin()) { 1053 auto ThisNetWidth = 1054 getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces); 1055 auto MaxNetWidth = 1056 getMaximumNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces, 1057 CellDescs.CellCount); 1058 if (ThisNetWidth < MaxNetWidth) 1059 Changes[CellIter->Index].Spaces = (MaxNetWidth - ThisNetWidth); 1060 auto RowCount = 1U; 1061 auto Offset = std::distance(Cells.begin(), CellIter); 1062 for (const auto *Next = CellIter->NextColumnElement; Next != nullptr; 1063 Next = Next->NextColumnElement) { 1064 auto *Start = (Cells.begin() + RowCount * CellDescs.CellCount); 1065 auto *End = Start + Offset; 1066 ThisNetWidth = getNetWidth(Start, End, CellDescs.InitialSpaces); 1067 if (ThisNetWidth < MaxNetWidth) 1068 Changes[Next->Index].Spaces = (MaxNetWidth - ThisNetWidth); 1069 ++RowCount; 1070 } 1071 } 1072 } else { 1073 auto ThisWidth = 1074 calculateCellWidth(CellIter->Index, CellIter->EndIndex, true) + 1075 NetWidth; 1076 if (Changes[CellIter->Index].NewlinesBefore == 0) { 1077 Changes[CellIter->Index].Spaces = (CellWidth - (ThisWidth + NetWidth)); 1078 Changes[CellIter->Index].Spaces += (i > 0) ? 1 : 0; 1079 } 1080 alignToStartOfCell(CellIter->Index, CellIter->EndIndex); 1081 for (const auto *Next = CellIter->NextColumnElement; Next != nullptr; 1082 Next = Next->NextColumnElement) { 1083 ThisWidth = 1084 calculateCellWidth(Next->Index, Next->EndIndex, true) + NetWidth; 1085 if (Changes[Next->Index].NewlinesBefore == 0) { 1086 Changes[Next->Index].Spaces = (CellWidth - ThisWidth); 1087 Changes[Next->Index].Spaces += (i > 0) ? 1 : 0; 1088 } 1089 alignToStartOfCell(Next->Index, Next->EndIndex); 1090 } 1091 } 1092 } 1093 } 1094 1095 void WhitespaceManager::alignArrayInitializersLeftJustified( 1096 CellDescriptions &&CellDescs) { 1097 auto &Cells = CellDescs.Cells; 1098 1099 // Now go through and fixup the spaces. 1100 auto *CellIter = Cells.begin(); 1101 // The first cell needs to be against the left brace. 1102 if (Changes[CellIter->Index].NewlinesBefore == 0) 1103 Changes[CellIter->Index].Spaces = 0; 1104 else 1105 Changes[CellIter->Index].Spaces = CellDescs.InitialSpaces; 1106 ++CellIter; 1107 for (auto i = 1U; i < CellDescs.CellCount; i++, ++CellIter) { 1108 auto MaxNetWidth = getMaximumNetWidth( 1109 Cells.begin(), CellIter, CellDescs.InitialSpaces, CellDescs.CellCount); 1110 auto ThisNetWidth = 1111 getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces); 1112 if (Changes[CellIter->Index].NewlinesBefore == 0) { 1113 Changes[CellIter->Index].Spaces = 1114 MaxNetWidth - ThisNetWidth + 1115 (Changes[CellIter->Index].Tok->isNot(tok::r_brace) ? 1 : 0); 1116 } 1117 auto RowCount = 1U; 1118 auto Offset = std::distance(Cells.begin(), CellIter); 1119 for (const auto *Next = CellIter->NextColumnElement; Next != nullptr; 1120 Next = Next->NextColumnElement) { 1121 auto *Start = (Cells.begin() + RowCount * CellDescs.CellCount); 1122 auto *End = Start + Offset; 1123 auto ThisNetWidth = getNetWidth(Start, End, CellDescs.InitialSpaces); 1124 if (Changes[Next->Index].NewlinesBefore == 0) { 1125 Changes[Next->Index].Spaces = 1126 MaxNetWidth - ThisNetWidth + 1127 (Changes[Next->Index].Tok->isNot(tok::r_brace) ? 1 : 0); 1128 } 1129 ++RowCount; 1130 } 1131 } 1132 } 1133 1134 bool WhitespaceManager::isSplitCell(const CellDescription &Cell) { 1135 if (Cell.HasSplit) 1136 return true; 1137 for (const auto *Next = Cell.NextColumnElement; Next != nullptr; 1138 Next = Next->NextColumnElement) { 1139 if (Next->HasSplit) 1140 return true; 1141 } 1142 return false; 1143 } 1144 1145 WhitespaceManager::CellDescriptions WhitespaceManager::getCells(unsigned Start, 1146 unsigned End) { 1147 1148 unsigned Depth = 0; 1149 unsigned Cell = 0; 1150 unsigned CellCount = 0; 1151 unsigned InitialSpaces = 0; 1152 unsigned InitialTokenLength = 0; 1153 unsigned EndSpaces = 0; 1154 SmallVector<CellDescription> Cells; 1155 const FormatToken *MatchingParen = nullptr; 1156 for (unsigned i = Start; i < End; ++i) { 1157 auto &C = Changes[i]; 1158 if (C.Tok->is(tok::l_brace)) 1159 ++Depth; 1160 else if (C.Tok->is(tok::r_brace)) 1161 --Depth; 1162 if (Depth == 2) { 1163 if (C.Tok->is(tok::l_brace)) { 1164 Cell = 0; 1165 MatchingParen = C.Tok->MatchingParen; 1166 if (InitialSpaces == 0) { 1167 InitialSpaces = C.Spaces + C.TokenLength; 1168 InitialTokenLength = C.TokenLength; 1169 auto j = i - 1; 1170 for (; Changes[j].NewlinesBefore == 0 && j > Start; --j) { 1171 InitialSpaces += Changes[j].Spaces + Changes[j].TokenLength; 1172 InitialTokenLength += Changes[j].TokenLength; 1173 } 1174 if (C.NewlinesBefore == 0) { 1175 InitialSpaces += Changes[j].Spaces + Changes[j].TokenLength; 1176 InitialTokenLength += Changes[j].TokenLength; 1177 } 1178 } 1179 } else if (C.Tok->is(tok::comma)) { 1180 if (!Cells.empty()) 1181 Cells.back().EndIndex = i; 1182 if (C.Tok->getNextNonComment()->isNot(tok::r_brace)) // dangling comma 1183 ++Cell; 1184 } 1185 } else if (Depth == 1) { 1186 if (C.Tok == MatchingParen) { 1187 if (!Cells.empty()) 1188 Cells.back().EndIndex = i; 1189 Cells.push_back(CellDescription{i, ++Cell, i + 1, false, nullptr}); 1190 CellCount = C.Tok->Previous->isNot(tok::comma) ? Cell + 1 : Cell; 1191 // Go to the next non-comment and ensure there is a break in front 1192 const auto *NextNonComment = C.Tok->getNextNonComment(); 1193 while (NextNonComment->is(tok::comma)) 1194 NextNonComment = NextNonComment->getNextNonComment(); 1195 auto j = i; 1196 while (Changes[j].Tok != NextNonComment && j < End) 1197 ++j; 1198 if (j < End && Changes[j].NewlinesBefore == 0 && 1199 Changes[j].Tok->isNot(tok::r_brace)) { 1200 Changes[j].NewlinesBefore = 1; 1201 // Account for the added token lengths 1202 Changes[j].Spaces = InitialSpaces - InitialTokenLength; 1203 } 1204 } else if (C.Tok->is(tok::comment)) { 1205 // Trailing comments stay at a space past the last token 1206 C.Spaces = Changes[i - 1].Tok->is(tok::comma) ? 1 : 2; 1207 } else if (C.Tok->is(tok::l_brace)) { 1208 // We need to make sure that the ending braces is aligned to the 1209 // start of our initializer 1210 auto j = i - 1; 1211 for (; j > 0 && !Changes[j].Tok->ArrayInitializerLineStart; --j) 1212 ; // Nothing the loop does the work 1213 EndSpaces = Changes[j].Spaces; 1214 } 1215 } else if (Depth == 0 && C.Tok->is(tok::r_brace)) { 1216 C.NewlinesBefore = 1; 1217 C.Spaces = EndSpaces; 1218 } 1219 if (C.Tok->StartsColumn) { 1220 // This gets us past tokens that have been split over multiple 1221 // lines 1222 bool HasSplit = false; 1223 if (Changes[i].NewlinesBefore > 0) { 1224 // So if we split a line previously and the tail line + this token is 1225 // less then the column limit we remove the split here and just put 1226 // the column start at a space past the comma 1227 // 1228 // FIXME This if branch covers the cases where the column is not 1229 // the first column. This leads to weird pathologies like the formatting 1230 // auto foo = Items{ 1231 // Section{ 1232 // 0, bar(), 1233 // } 1234 // }; 1235 // Well if it doesn't lead to that it's indicative that the line 1236 // breaking should be revisited. Unfortunately alot of other options 1237 // interact with this 1238 auto j = i - 1; 1239 if ((j - 1) > Start && Changes[j].Tok->is(tok::comma) && 1240 Changes[j - 1].NewlinesBefore > 0) { 1241 --j; 1242 auto LineLimit = Changes[j].Spaces + Changes[j].TokenLength; 1243 if (LineLimit < Style.ColumnLimit) { 1244 Changes[i].NewlinesBefore = 0; 1245 Changes[i].Spaces = 1; 1246 } 1247 } 1248 } 1249 while (Changes[i].NewlinesBefore > 0 && Changes[i].Tok == C.Tok) { 1250 Changes[i].Spaces = InitialSpaces; 1251 ++i; 1252 HasSplit = true; 1253 } 1254 if (Changes[i].Tok != C.Tok) 1255 --i; 1256 Cells.push_back(CellDescription{i, Cell, i, HasSplit, nullptr}); 1257 } 1258 } 1259 1260 return linkCells({Cells, CellCount, InitialSpaces}); 1261 } 1262 1263 unsigned WhitespaceManager::calculateCellWidth(unsigned Start, unsigned End, 1264 bool WithSpaces) const { 1265 unsigned CellWidth = 0; 1266 for (auto i = Start; i < End; i++) { 1267 if (Changes[i].NewlinesBefore > 0) 1268 CellWidth = 0; 1269 CellWidth += Changes[i].TokenLength; 1270 CellWidth += (WithSpaces ? Changes[i].Spaces : 0); 1271 } 1272 return CellWidth; 1273 } 1274 1275 void WhitespaceManager::alignToStartOfCell(unsigned Start, unsigned End) { 1276 if ((End - Start) <= 1) 1277 return; 1278 // If the line is broken anywhere in there make sure everything 1279 // is aligned to the parent 1280 for (auto i = Start + 1; i < End; i++) { 1281 if (Changes[i].NewlinesBefore > 0) 1282 Changes[i].Spaces = Changes[Start].Spaces; 1283 } 1284 } 1285 1286 WhitespaceManager::CellDescriptions 1287 WhitespaceManager::linkCells(CellDescriptions &&CellDesc) { 1288 auto &Cells = CellDesc.Cells; 1289 for (auto *CellIter = Cells.begin(); CellIter != Cells.end(); ++CellIter) { 1290 if (CellIter->NextColumnElement == nullptr && 1291 ((CellIter + 1) != Cells.end())) { 1292 for (auto *NextIter = CellIter + 1; NextIter != Cells.end(); ++NextIter) { 1293 if (NextIter->Cell == CellIter->Cell) { 1294 CellIter->NextColumnElement = &(*NextIter); 1295 break; 1296 } 1297 } 1298 } 1299 } 1300 return std::move(CellDesc); 1301 } 1302 1303 void WhitespaceManager::generateChanges() { 1304 for (unsigned i = 0, e = Changes.size(); i != e; ++i) { 1305 const Change &C = Changes[i]; 1306 if (i > 0 && Changes[i - 1].OriginalWhitespaceRange.getBegin() == 1307 C.OriginalWhitespaceRange.getBegin()) { 1308 // Do not generate two replacements for the same location. 1309 continue; 1310 } 1311 if (C.CreateReplacement) { 1312 std::string ReplacementText = C.PreviousLinePostfix; 1313 if (C.ContinuesPPDirective) 1314 appendEscapedNewlineText(ReplacementText, C.NewlinesBefore, 1315 C.PreviousEndOfTokenColumn, 1316 C.EscapedNewlineColumn); 1317 else 1318 appendNewlineText(ReplacementText, C.NewlinesBefore); 1319 // FIXME: This assert should hold if we computed the column correctly. 1320 // assert((int)C.StartOfTokenColumn >= C.Spaces); 1321 appendIndentText( 1322 ReplacementText, C.Tok->IndentLevel, std::max(0, C.Spaces), 1323 std::max((int)C.StartOfTokenColumn, C.Spaces) - std::max(0, C.Spaces), 1324 C.IsAligned); 1325 ReplacementText.append(C.CurrentLinePrefix); 1326 storeReplacement(C.OriginalWhitespaceRange, ReplacementText); 1327 } 1328 } 1329 } 1330 1331 void WhitespaceManager::storeReplacement(SourceRange Range, StringRef Text) { 1332 unsigned WhitespaceLength = SourceMgr.getFileOffset(Range.getEnd()) - 1333 SourceMgr.getFileOffset(Range.getBegin()); 1334 // Don't create a replacement, if it does not change anything. 1335 if (StringRef(SourceMgr.getCharacterData(Range.getBegin()), 1336 WhitespaceLength) == Text) 1337 return; 1338 auto Err = Replaces.add(tooling::Replacement( 1339 SourceMgr, CharSourceRange::getCharRange(Range), Text)); 1340 // FIXME: better error handling. For now, just print an error message in the 1341 // release version. 1342 if (Err) { 1343 llvm::errs() << llvm::toString(std::move(Err)) << "\n"; 1344 assert(false); 1345 } 1346 } 1347 1348 void WhitespaceManager::appendNewlineText(std::string &Text, 1349 unsigned Newlines) { 1350 if (UseCRLF) { 1351 Text.reserve(Text.size() + 2 * Newlines); 1352 for (unsigned i = 0; i < Newlines; ++i) 1353 Text.append("\r\n"); 1354 } else { 1355 Text.append(Newlines, '\n'); 1356 } 1357 } 1358 1359 void WhitespaceManager::appendEscapedNewlineText( 1360 std::string &Text, unsigned Newlines, unsigned PreviousEndOfTokenColumn, 1361 unsigned EscapedNewlineColumn) { 1362 if (Newlines > 0) { 1363 unsigned Spaces = 1364 std::max<int>(1, EscapedNewlineColumn - PreviousEndOfTokenColumn - 1); 1365 for (unsigned i = 0; i < Newlines; ++i) { 1366 Text.append(Spaces, ' '); 1367 Text.append(UseCRLF ? "\\\r\n" : "\\\n"); 1368 Spaces = std::max<int>(0, EscapedNewlineColumn - 1); 1369 } 1370 } 1371 } 1372 1373 void WhitespaceManager::appendIndentText(std::string &Text, 1374 unsigned IndentLevel, unsigned Spaces, 1375 unsigned WhitespaceStartColumn, 1376 bool IsAligned) { 1377 switch (Style.UseTab) { 1378 case FormatStyle::UT_Never: 1379 Text.append(Spaces, ' '); 1380 break; 1381 case FormatStyle::UT_Always: { 1382 if (Style.TabWidth) { 1383 unsigned FirstTabWidth = 1384 Style.TabWidth - WhitespaceStartColumn % Style.TabWidth; 1385 1386 // Insert only spaces when we want to end up before the next tab. 1387 if (Spaces < FirstTabWidth || Spaces == 1) { 1388 Text.append(Spaces, ' '); 1389 break; 1390 } 1391 // Align to the next tab. 1392 Spaces -= FirstTabWidth; 1393 Text.append("\t"); 1394 1395 Text.append(Spaces / Style.TabWidth, '\t'); 1396 Text.append(Spaces % Style.TabWidth, ' '); 1397 } else if (Spaces == 1) { 1398 Text.append(Spaces, ' '); 1399 } 1400 break; 1401 } 1402 case FormatStyle::UT_ForIndentation: 1403 if (WhitespaceStartColumn == 0) { 1404 unsigned Indentation = IndentLevel * Style.IndentWidth; 1405 Spaces = appendTabIndent(Text, Spaces, Indentation); 1406 } 1407 Text.append(Spaces, ' '); 1408 break; 1409 case FormatStyle::UT_ForContinuationAndIndentation: 1410 if (WhitespaceStartColumn == 0) 1411 Spaces = appendTabIndent(Text, Spaces, Spaces); 1412 Text.append(Spaces, ' '); 1413 break; 1414 case FormatStyle::UT_AlignWithSpaces: 1415 if (WhitespaceStartColumn == 0) { 1416 unsigned Indentation = 1417 IsAligned ? IndentLevel * Style.IndentWidth : Spaces; 1418 Spaces = appendTabIndent(Text, Spaces, Indentation); 1419 } 1420 Text.append(Spaces, ' '); 1421 break; 1422 } 1423 } 1424 1425 unsigned WhitespaceManager::appendTabIndent(std::string &Text, unsigned Spaces, 1426 unsigned Indentation) { 1427 // This happens, e.g. when a line in a block comment is indented less than the 1428 // first one. 1429 if (Indentation > Spaces) 1430 Indentation = Spaces; 1431 if (Style.TabWidth) { 1432 unsigned Tabs = Indentation / Style.TabWidth; 1433 Text.append(Tabs, '\t'); 1434 Spaces -= Tabs * Style.TabWidth; 1435 } 1436 return Spaces; 1437 } 1438 1439 } // namespace format 1440 } // namespace clang 1441