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