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