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 17 namespace clang { 18 namespace format { 19 20 bool WhitespaceManager::Change::IsBeforeInFile::operator()( 21 const Change &C1, const Change &C2) const { 22 return SourceMgr.isBeforeInTranslationUnit( 23 C1.OriginalWhitespaceRange.getBegin(), 24 C2.OriginalWhitespaceRange.getBegin()); 25 } 26 27 WhitespaceManager::Change::Change(const FormatToken &Tok, 28 bool CreateReplacement, 29 SourceRange OriginalWhitespaceRange, 30 int Spaces, unsigned StartOfTokenColumn, 31 unsigned NewlinesBefore, 32 StringRef PreviousLinePostfix, 33 StringRef CurrentLinePrefix, bool IsAligned, 34 bool ContinuesPPDirective, bool IsInsideToken) 35 : Tok(&Tok), CreateReplacement(CreateReplacement), 36 OriginalWhitespaceRange(OriginalWhitespaceRange), 37 StartOfTokenColumn(StartOfTokenColumn), NewlinesBefore(NewlinesBefore), 38 PreviousLinePostfix(PreviousLinePostfix), 39 CurrentLinePrefix(CurrentLinePrefix), IsAligned(IsAligned), 40 ContinuesPPDirective(ContinuesPPDirective), Spaces(Spaces), 41 IsInsideToken(IsInsideToken), IsTrailingComment(false), TokenLength(0), 42 PreviousEndOfTokenColumn(0), EscapedNewlineColumn(0), 43 StartOfBlockComment(nullptr), IndentationOffset(0) {} 44 45 void WhitespaceManager::replaceWhitespace(FormatToken &Tok, unsigned Newlines, 46 unsigned Spaces, 47 unsigned StartOfTokenColumn, 48 bool IsAligned, bool InPPDirective) { 49 if (Tok.Finalized) 50 return; 51 Tok.Decision = (Newlines > 0) ? FD_Break : FD_Continue; 52 Changes.push_back(Change(Tok, /*CreateReplacement=*/true, Tok.WhitespaceRange, 53 Spaces, StartOfTokenColumn, Newlines, "", "", 54 IsAligned, InPPDirective && !Tok.IsFirst, 55 /*IsInsideToken=*/false)); 56 } 57 58 void WhitespaceManager::addUntouchableToken(const FormatToken &Tok, 59 bool InPPDirective) { 60 if (Tok.Finalized) 61 return; 62 Changes.push_back(Change(Tok, /*CreateReplacement=*/false, 63 Tok.WhitespaceRange, /*Spaces=*/0, 64 Tok.OriginalColumn, Tok.NewlinesBefore, "", "", 65 /*IsAligned=*/false, InPPDirective && !Tok.IsFirst, 66 /*IsInsideToken=*/false)); 67 } 68 69 llvm::Error 70 WhitespaceManager::addReplacement(const tooling::Replacement &Replacement) { 71 return Replaces.add(Replacement); 72 } 73 74 void WhitespaceManager::replaceWhitespaceInToken( 75 const FormatToken &Tok, unsigned Offset, unsigned ReplaceChars, 76 StringRef PreviousPostfix, StringRef CurrentPrefix, bool InPPDirective, 77 unsigned Newlines, int Spaces) { 78 if (Tok.Finalized) 79 return; 80 SourceLocation Start = Tok.getStartOfNonWhitespace().getLocWithOffset(Offset); 81 Changes.push_back( 82 Change(Tok, /*CreateReplacement=*/true, 83 SourceRange(Start, Start.getLocWithOffset(ReplaceChars)), Spaces, 84 std::max(0, Spaces), Newlines, PreviousPostfix, CurrentPrefix, 85 /*IsAligned=*/true, InPPDirective && !Tok.IsFirst, 86 /*IsInsideToken=*/true)); 87 } 88 89 const tooling::Replacements &WhitespaceManager::generateReplacements() { 90 if (Changes.empty()) 91 return Replaces; 92 93 llvm::sort(Changes, Change::IsBeforeInFile(SourceMgr)); 94 calculateLineBreakInformation(); 95 alignConsecutiveMacros(); 96 alignConsecutiveDeclarations(); 97 alignConsecutiveAssignments(); 98 alignTrailingComments(); 99 alignEscapedNewlines(); 100 generateChanges(); 101 102 return Replaces; 103 } 104 105 void WhitespaceManager::calculateLineBreakInformation() { 106 Changes[0].PreviousEndOfTokenColumn = 0; 107 Change *LastOutsideTokenChange = &Changes[0]; 108 for (unsigned i = 1, e = Changes.size(); i != e; ++i) { 109 SourceLocation OriginalWhitespaceStart = 110 Changes[i].OriginalWhitespaceRange.getBegin(); 111 SourceLocation PreviousOriginalWhitespaceEnd = 112 Changes[i - 1].OriginalWhitespaceRange.getEnd(); 113 unsigned OriginalWhitespaceStartOffset = 114 SourceMgr.getFileOffset(OriginalWhitespaceStart); 115 unsigned PreviousOriginalWhitespaceEndOffset = 116 SourceMgr.getFileOffset(PreviousOriginalWhitespaceEnd); 117 assert(PreviousOriginalWhitespaceEndOffset <= 118 OriginalWhitespaceStartOffset); 119 const char *const PreviousOriginalWhitespaceEndData = 120 SourceMgr.getCharacterData(PreviousOriginalWhitespaceEnd); 121 StringRef Text(PreviousOriginalWhitespaceEndData, 122 SourceMgr.getCharacterData(OriginalWhitespaceStart) - 123 PreviousOriginalWhitespaceEndData); 124 // Usually consecutive changes would occur in consecutive tokens. This is 125 // not the case however when analyzing some preprocessor runs of the 126 // annotated lines. For example, in this code: 127 // 128 // #if A // line 1 129 // int i = 1; 130 // #else B // line 2 131 // int i = 2; 132 // #endif // line 3 133 // 134 // one of the runs will produce the sequence of lines marked with line 1, 2 135 // and 3. So the two consecutive whitespace changes just before '// line 2' 136 // and before '#endif // line 3' span multiple lines and tokens: 137 // 138 // #else B{change X}[// line 2 139 // int i = 2; 140 // ]{change Y}#endif // line 3 141 // 142 // For this reason, if the text between consecutive changes spans multiple 143 // newlines, the token length must be adjusted to the end of the original 144 // line of the token. 145 auto NewlinePos = Text.find_first_of('\n'); 146 if (NewlinePos == StringRef::npos) { 147 Changes[i - 1].TokenLength = OriginalWhitespaceStartOffset - 148 PreviousOriginalWhitespaceEndOffset + 149 Changes[i].PreviousLinePostfix.size() + 150 Changes[i - 1].CurrentLinePrefix.size(); 151 } else { 152 Changes[i - 1].TokenLength = 153 NewlinePos + Changes[i - 1].CurrentLinePrefix.size(); 154 } 155 156 // If there are multiple changes in this token, sum up all the changes until 157 // the end of the line. 158 if (Changes[i - 1].IsInsideToken && Changes[i - 1].NewlinesBefore == 0) 159 LastOutsideTokenChange->TokenLength += 160 Changes[i - 1].TokenLength + Changes[i - 1].Spaces; 161 else 162 LastOutsideTokenChange = &Changes[i - 1]; 163 164 Changes[i].PreviousEndOfTokenColumn = 165 Changes[i - 1].StartOfTokenColumn + Changes[i - 1].TokenLength; 166 167 Changes[i - 1].IsTrailingComment = 168 (Changes[i].NewlinesBefore > 0 || Changes[i].Tok->is(tok::eof) || 169 (Changes[i].IsInsideToken && Changes[i].Tok->is(tok::comment))) && 170 Changes[i - 1].Tok->is(tok::comment) && 171 // FIXME: This is a dirty hack. The problem is that 172 // BreakableLineCommentSection does comment reflow changes and here is 173 // the aligning of trailing comments. Consider the case where we reflow 174 // the second line up in this example: 175 // 176 // // line 1 177 // // line 2 178 // 179 // That amounts to 2 changes by BreakableLineCommentSection: 180 // - the first, delimited by (), for the whitespace between the tokens, 181 // - and second, delimited by [], for the whitespace at the beginning 182 // of the second token: 183 // 184 // // line 1( 185 // )[// ]line 2 186 // 187 // So in the end we have two changes like this: 188 // 189 // // line1()[ ]line 2 190 // 191 // Note that the OriginalWhitespaceStart of the second change is the 192 // same as the PreviousOriginalWhitespaceEnd of the first change. 193 // In this case, the below check ensures that the second change doesn't 194 // get treated as a trailing comment change here, since this might 195 // trigger additional whitespace to be wrongly inserted before "line 2" 196 // by the comment aligner here. 197 // 198 // For a proper solution we need a mechanism to say to WhitespaceManager 199 // that a particular change breaks the current sequence of trailing 200 // comments. 201 OriginalWhitespaceStart != PreviousOriginalWhitespaceEnd; 202 } 203 // FIXME: The last token is currently not always an eof token; in those 204 // cases, setting TokenLength of the last token to 0 is wrong. 205 Changes.back().TokenLength = 0; 206 Changes.back().IsTrailingComment = Changes.back().Tok->is(tok::comment); 207 208 const WhitespaceManager::Change *LastBlockComment = nullptr; 209 for (auto &Change : Changes) { 210 // Reset the IsTrailingComment flag for changes inside of trailing comments 211 // so they don't get realigned later. Comment line breaks however still need 212 // to be aligned. 213 if (Change.IsInsideToken && Change.NewlinesBefore == 0) 214 Change.IsTrailingComment = false; 215 Change.StartOfBlockComment = nullptr; 216 Change.IndentationOffset = 0; 217 if (Change.Tok->is(tok::comment)) { 218 if (Change.Tok->is(TT_LineComment) || !Change.IsInsideToken) 219 LastBlockComment = &Change; 220 else { 221 if ((Change.StartOfBlockComment = LastBlockComment)) 222 Change.IndentationOffset = 223 Change.StartOfTokenColumn - 224 Change.StartOfBlockComment->StartOfTokenColumn; 225 } 226 } else { 227 LastBlockComment = nullptr; 228 } 229 } 230 } 231 232 // Align a single sequence of tokens, see AlignTokens below. 233 template <typename F> 234 static void 235 AlignTokenSequence(unsigned Start, unsigned End, unsigned Column, F &&Matches, 236 SmallVector<WhitespaceManager::Change, 16> &Changes) { 237 bool FoundMatchOnLine = false; 238 int Shift = 0; 239 240 // ScopeStack keeps track of the current scope depth. It contains indices of 241 // the first token on each scope. 242 // We only run the "Matches" function on tokens from the outer-most scope. 243 // However, we do need to pay special attention to one class of tokens 244 // that are not in the outer-most scope, and that is function parameters 245 // which are split across multiple lines, as illustrated by this example: 246 // double a(int x); 247 // int b(int y, 248 // double z); 249 // In the above example, we need to take special care to ensure that 250 // 'double z' is indented along with it's owning function 'b'. 251 SmallVector<unsigned, 16> ScopeStack; 252 253 for (unsigned i = Start; i != End; ++i) { 254 if (ScopeStack.size() != 0 && 255 Changes[i].indentAndNestingLevel() < 256 Changes[ScopeStack.back()].indentAndNestingLevel()) 257 ScopeStack.pop_back(); 258 259 // Compare current token to previous non-comment token to ensure whether 260 // it is in a deeper scope or not. 261 unsigned PreviousNonComment = i - 1; 262 while (PreviousNonComment > Start && 263 Changes[PreviousNonComment].Tok->is(tok::comment)) 264 PreviousNonComment--; 265 if (i != Start && Changes[i].indentAndNestingLevel() > 266 Changes[PreviousNonComment].indentAndNestingLevel()) 267 ScopeStack.push_back(i); 268 269 bool InsideNestedScope = ScopeStack.size() != 0; 270 271 if (Changes[i].NewlinesBefore > 0 && !InsideNestedScope) { 272 Shift = 0; 273 FoundMatchOnLine = false; 274 } 275 276 // If this is the first matching token to be aligned, remember by how many 277 // spaces it has to be shifted, so the rest of the changes on the line are 278 // shifted by the same amount 279 if (!FoundMatchOnLine && !InsideNestedScope && Matches(Changes[i])) { 280 FoundMatchOnLine = true; 281 Shift = Column - Changes[i].StartOfTokenColumn; 282 Changes[i].Spaces += Shift; 283 } 284 285 // This is for function parameters that are split across multiple lines, 286 // as mentioned in the ScopeStack comment. 287 if (InsideNestedScope && Changes[i].NewlinesBefore > 0) { 288 unsigned ScopeStart = ScopeStack.back(); 289 if (Changes[ScopeStart - 1].Tok->is(TT_FunctionDeclarationName) || 290 (ScopeStart > Start + 1 && 291 Changes[ScopeStart - 2].Tok->is(TT_FunctionDeclarationName))) 292 Changes[i].Spaces += Shift; 293 } 294 295 assert(Shift >= 0); 296 Changes[i].StartOfTokenColumn += Shift; 297 if (i + 1 != Changes.size()) 298 Changes[i + 1].PreviousEndOfTokenColumn += Shift; 299 } 300 } 301 302 // Walk through a subset of the changes, starting at StartAt, and find 303 // sequences of matching tokens to align. To do so, keep track of the lines and 304 // whether or not a matching token was found on a line. If a matching token is 305 // found, extend the current sequence. If the current line cannot be part of a 306 // sequence, e.g. because there is an empty line before it or it contains only 307 // non-matching tokens, finalize the previous sequence. 308 // The value returned is the token on which we stopped, either because we 309 // exhausted all items inside Changes, or because we hit a scope level higher 310 // than our initial scope. 311 // This function is recursive. Each invocation processes only the scope level 312 // equal to the initial level, which is the level of Changes[StartAt]. 313 // If we encounter a scope level greater than the initial level, then we call 314 // ourselves recursively, thereby avoiding the pollution of the current state 315 // with the alignment requirements of the nested sub-level. This recursive 316 // behavior is necessary for aligning function prototypes that have one or more 317 // arguments. 318 // If this function encounters a scope level less than the initial level, 319 // it returns the current position. 320 // There is a non-obvious subtlety in the recursive behavior: Even though we 321 // defer processing of nested levels to recursive invocations of this 322 // function, when it comes time to align a sequence of tokens, we run the 323 // alignment on the entire sequence, including the nested levels. 324 // When doing so, most of the nested tokens are skipped, because their 325 // alignment was already handled by the recursive invocations of this function. 326 // However, the special exception is that we do NOT skip function parameters 327 // that are split across multiple lines. See the test case in FormatTest.cpp 328 // that mentions "split function parameter alignment" for an example of this. 329 template <typename F> 330 static unsigned AlignTokens(const FormatStyle &Style, F &&Matches, 331 SmallVector<WhitespaceManager::Change, 16> &Changes, 332 unsigned StartAt) { 333 unsigned MinColumn = 0; 334 unsigned MaxColumn = UINT_MAX; 335 336 // Line number of the start and the end of the current token sequence. 337 unsigned StartOfSequence = 0; 338 unsigned EndOfSequence = 0; 339 340 // Measure the scope level (i.e. depth of (), [], {}) of the first token, and 341 // abort when we hit any token in a higher scope than the starting one. 342 auto IndentAndNestingLevel = StartAt < Changes.size() 343 ? Changes[StartAt].indentAndNestingLevel() 344 : std::pair<unsigned, unsigned>(0, 0); 345 346 // Keep track of the number of commas before the matching tokens, we will only 347 // align a sequence of matching tokens if they are preceded by the same number 348 // of commas. 349 unsigned CommasBeforeLastMatch = 0; 350 unsigned CommasBeforeMatch = 0; 351 352 // Whether a matching token has been found on the current line. 353 bool FoundMatchOnLine = false; 354 355 // Aligns a sequence of matching tokens, on the MinColumn column. 356 // 357 // Sequences start from the first matching token to align, and end at the 358 // first token of the first line that doesn't need to be aligned. 359 // 360 // We need to adjust the StartOfTokenColumn of each Change that is on a line 361 // containing any matching token to be aligned and located after such token. 362 auto AlignCurrentSequence = [&] { 363 if (StartOfSequence > 0 && StartOfSequence < EndOfSequence) 364 AlignTokenSequence(StartOfSequence, EndOfSequence, MinColumn, Matches, 365 Changes); 366 MinColumn = 0; 367 MaxColumn = UINT_MAX; 368 StartOfSequence = 0; 369 EndOfSequence = 0; 370 }; 371 372 unsigned i = StartAt; 373 for (unsigned e = Changes.size(); i != e; ++i) { 374 if (Changes[i].indentAndNestingLevel() < IndentAndNestingLevel) 375 break; 376 377 if (Changes[i].NewlinesBefore != 0) { 378 CommasBeforeMatch = 0; 379 EndOfSequence = i; 380 // If there is a blank line, there is a forced-align-break (eg, 381 // preprocessor), or if the last line didn't contain any matching token, 382 // the sequence ends here. 383 if (Changes[i].NewlinesBefore > 1 || 384 Changes[i].Tok->MustBreakAlignBefore || !FoundMatchOnLine) 385 AlignCurrentSequence(); 386 387 FoundMatchOnLine = false; 388 } 389 390 if (Changes[i].Tok->is(tok::comma)) { 391 ++CommasBeforeMatch; 392 } else if (Changes[i].indentAndNestingLevel() > IndentAndNestingLevel) { 393 // Call AlignTokens recursively, skipping over this scope block. 394 unsigned StoppedAt = AlignTokens(Style, Matches, Changes, i); 395 i = StoppedAt - 1; 396 continue; 397 } 398 399 if (!Matches(Changes[i])) 400 continue; 401 402 // If there is more than one matching token per line, or if the number of 403 // preceding commas, do not match anymore, end the sequence. 404 if (FoundMatchOnLine || CommasBeforeMatch != CommasBeforeLastMatch) 405 AlignCurrentSequence(); 406 407 CommasBeforeLastMatch = CommasBeforeMatch; 408 FoundMatchOnLine = true; 409 410 if (StartOfSequence == 0) 411 StartOfSequence = i; 412 413 unsigned ChangeMinColumn = Changes[i].StartOfTokenColumn; 414 int LineLengthAfter = -Changes[i].Spaces; 415 for (unsigned j = i; j != e && Changes[j].NewlinesBefore == 0; ++j) 416 LineLengthAfter += Changes[j].Spaces + Changes[j].TokenLength; 417 unsigned ChangeMaxColumn = Style.ColumnLimit - LineLengthAfter; 418 419 // If we are restricted by the maximum column width, end the sequence. 420 if (ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn || 421 CommasBeforeLastMatch != CommasBeforeMatch) { 422 AlignCurrentSequence(); 423 StartOfSequence = i; 424 } 425 426 MinColumn = std::max(MinColumn, ChangeMinColumn); 427 MaxColumn = std::min(MaxColumn, ChangeMaxColumn); 428 } 429 430 EndOfSequence = i; 431 AlignCurrentSequence(); 432 return i; 433 } 434 435 // Aligns a sequence of matching tokens, on the MinColumn column. 436 // 437 // Sequences start from the first matching token to align, and end at the 438 // first token of the first line that doesn't need to be aligned. 439 // 440 // We need to adjust the StartOfTokenColumn of each Change that is on a line 441 // containing any matching token to be aligned and located after such token. 442 static void AlignMacroSequence( 443 unsigned &StartOfSequence, unsigned &EndOfSequence, unsigned &MinColumn, 444 unsigned &MaxColumn, bool &FoundMatchOnLine, 445 std::function<bool(const WhitespaceManager::Change &C)> AlignMacrosMatches, 446 SmallVector<WhitespaceManager::Change, 16> &Changes) { 447 if (StartOfSequence > 0 && StartOfSequence < EndOfSequence) { 448 449 FoundMatchOnLine = false; 450 int Shift = 0; 451 452 for (unsigned I = StartOfSequence; I != EndOfSequence; ++I) { 453 if (Changes[I].NewlinesBefore > 0) { 454 Shift = 0; 455 FoundMatchOnLine = false; 456 } 457 458 // If this is the first matching token to be aligned, remember by how many 459 // spaces it has to be shifted, so the rest of the changes on the line are 460 // shifted by the same amount 461 if (!FoundMatchOnLine && AlignMacrosMatches(Changes[I])) { 462 FoundMatchOnLine = true; 463 Shift = MinColumn - Changes[I].StartOfTokenColumn; 464 Changes[I].Spaces += Shift; 465 } 466 467 assert(Shift >= 0); 468 Changes[I].StartOfTokenColumn += Shift; 469 if (I + 1 != Changes.size()) 470 Changes[I + 1].PreviousEndOfTokenColumn += Shift; 471 } 472 } 473 474 MinColumn = 0; 475 MaxColumn = UINT_MAX; 476 StartOfSequence = 0; 477 EndOfSequence = 0; 478 } 479 480 void WhitespaceManager::alignConsecutiveMacros() { 481 if (!Style.AlignConsecutiveMacros) 482 return; 483 484 auto AlignMacrosMatches = [](const Change &C) { 485 const FormatToken *Current = C.Tok; 486 unsigned SpacesRequiredBefore = 1; 487 488 if (Current->SpacesRequiredBefore == 0 || !Current->Previous) 489 return false; 490 491 Current = Current->Previous; 492 493 // If token is a ")", skip over the parameter list, to the 494 // token that precedes the "(" 495 if (Current->is(tok::r_paren) && Current->MatchingParen) { 496 Current = Current->MatchingParen->Previous; 497 SpacesRequiredBefore = 0; 498 } 499 500 if (!Current || !Current->is(tok::identifier)) 501 return false; 502 503 if (!Current->Previous || !Current->Previous->is(tok::pp_define)) 504 return false; 505 506 // For a macro function, 0 spaces are required between the 507 // identifier and the lparen that opens the parameter list. 508 // For a simple macro, 1 space is required between the 509 // identifier and the first token of the defined value. 510 return Current->Next->SpacesRequiredBefore == SpacesRequiredBefore; 511 }; 512 513 unsigned MinColumn = 0; 514 unsigned MaxColumn = UINT_MAX; 515 516 // Start and end of the token sequence we're processing. 517 unsigned StartOfSequence = 0; 518 unsigned EndOfSequence = 0; 519 520 // Whether a matching token has been found on the current line. 521 bool FoundMatchOnLine = false; 522 523 unsigned I = 0; 524 for (unsigned E = Changes.size(); I != E; ++I) { 525 if (Changes[I].NewlinesBefore != 0) { 526 EndOfSequence = I; 527 // If there is a blank line, or if the last line didn't contain any 528 // matching token, the sequence ends here. 529 if (Changes[I].NewlinesBefore > 1 || !FoundMatchOnLine) 530 AlignMacroSequence(StartOfSequence, EndOfSequence, MinColumn, MaxColumn, 531 FoundMatchOnLine, AlignMacrosMatches, Changes); 532 533 FoundMatchOnLine = false; 534 } 535 536 if (!AlignMacrosMatches(Changes[I])) 537 continue; 538 539 FoundMatchOnLine = true; 540 541 if (StartOfSequence == 0) 542 StartOfSequence = I; 543 544 unsigned ChangeMinColumn = Changes[I].StartOfTokenColumn; 545 int LineLengthAfter = -Changes[I].Spaces; 546 for (unsigned j = I; j != E && Changes[j].NewlinesBefore == 0; ++j) 547 LineLengthAfter += Changes[j].Spaces + Changes[j].TokenLength; 548 unsigned ChangeMaxColumn = Style.ColumnLimit - LineLengthAfter; 549 550 MinColumn = std::max(MinColumn, ChangeMinColumn); 551 MaxColumn = std::min(MaxColumn, ChangeMaxColumn); 552 } 553 554 EndOfSequence = I; 555 AlignMacroSequence(StartOfSequence, EndOfSequence, MinColumn, MaxColumn, 556 FoundMatchOnLine, AlignMacrosMatches, Changes); 557 } 558 559 void WhitespaceManager::alignConsecutiveAssignments() { 560 if (!Style.AlignConsecutiveAssignments) 561 return; 562 563 AlignTokens( 564 Style, 565 [&](const Change &C) { 566 // Do not align on equal signs that are first on a line. 567 if (C.NewlinesBefore > 0) 568 return false; 569 570 // Do not align on equal signs that are last on a line. 571 if (&C != &Changes.back() && (&C + 1)->NewlinesBefore > 0) 572 return false; 573 574 return C.Tok->is(tok::equal); 575 }, 576 Changes, /*StartAt=*/0); 577 } 578 579 void WhitespaceManager::alignConsecutiveDeclarations() { 580 if (!Style.AlignConsecutiveDeclarations) 581 return; 582 583 // FIXME: Currently we don't handle properly the PointerAlignment: Right 584 // The * and & are not aligned and are left dangling. Something has to be done 585 // about it, but it raises the question of alignment of code like: 586 // const char* const* v1; 587 // float const* v2; 588 // SomeVeryLongType const& v3; 589 AlignTokens( 590 Style, 591 [](Change const &C) { 592 // tok::kw_operator is necessary for aligning operator overload 593 // definitions. 594 if (C.Tok->isOneOf(TT_FunctionDeclarationName, tok::kw_operator)) 595 return true; 596 if (C.Tok->isNot(TT_StartOfName)) 597 return false; 598 // Check if there is a subsequent name that starts the same declaration. 599 for (FormatToken *Next = C.Tok->Next; Next; Next = Next->Next) { 600 if (Next->is(tok::comment)) 601 continue; 602 if (!Next->Tok.getIdentifierInfo()) 603 break; 604 if (Next->isOneOf(TT_StartOfName, TT_FunctionDeclarationName, 605 tok::kw_operator)) 606 return false; 607 } 608 return true; 609 }, 610 Changes, /*StartAt=*/0); 611 } 612 613 void WhitespaceManager::alignTrailingComments() { 614 unsigned MinColumn = 0; 615 unsigned MaxColumn = UINT_MAX; 616 unsigned StartOfSequence = 0; 617 bool BreakBeforeNext = false; 618 unsigned Newlines = 0; 619 for (unsigned i = 0, e = Changes.size(); i != e; ++i) { 620 if (Changes[i].StartOfBlockComment) 621 continue; 622 Newlines += Changes[i].NewlinesBefore; 623 if (Changes[i].Tok->MustBreakAlignBefore) 624 BreakBeforeNext = true; 625 if (!Changes[i].IsTrailingComment) 626 continue; 627 628 unsigned ChangeMinColumn = Changes[i].StartOfTokenColumn; 629 unsigned ChangeMaxColumn; 630 631 if (Style.ColumnLimit == 0) 632 ChangeMaxColumn = UINT_MAX; 633 else if (Style.ColumnLimit >= Changes[i].TokenLength) 634 ChangeMaxColumn = Style.ColumnLimit - Changes[i].TokenLength; 635 else 636 ChangeMaxColumn = ChangeMinColumn; 637 638 // If we don't create a replacement for this change, we have to consider 639 // it to be immovable. 640 if (!Changes[i].CreateReplacement) 641 ChangeMaxColumn = ChangeMinColumn; 642 643 if (i + 1 != e && Changes[i + 1].ContinuesPPDirective) 644 ChangeMaxColumn -= 2; 645 // If this comment follows an } in column 0, it probably documents the 646 // closing of a namespace and we don't want to align it. 647 bool FollowsRBraceInColumn0 = i > 0 && Changes[i].NewlinesBefore == 0 && 648 Changes[i - 1].Tok->is(tok::r_brace) && 649 Changes[i - 1].StartOfTokenColumn == 0; 650 bool WasAlignedWithStartOfNextLine = false; 651 if (Changes[i].NewlinesBefore == 1) { // A comment on its own line. 652 unsigned CommentColumn = SourceMgr.getSpellingColumnNumber( 653 Changes[i].OriginalWhitespaceRange.getEnd()); 654 for (unsigned j = i + 1; j != e; ++j) { 655 if (Changes[j].Tok->is(tok::comment)) 656 continue; 657 658 unsigned NextColumn = SourceMgr.getSpellingColumnNumber( 659 Changes[j].OriginalWhitespaceRange.getEnd()); 660 // The start of the next token was previously aligned with the 661 // start of this comment. 662 WasAlignedWithStartOfNextLine = 663 CommentColumn == NextColumn || 664 CommentColumn == NextColumn + Style.IndentWidth; 665 break; 666 } 667 } 668 if (!Style.AlignTrailingComments || FollowsRBraceInColumn0) { 669 alignTrailingComments(StartOfSequence, i, MinColumn); 670 MinColumn = ChangeMinColumn; 671 MaxColumn = ChangeMinColumn; 672 StartOfSequence = i; 673 } else if (BreakBeforeNext || Newlines > 1 || 674 (ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn) || 675 // Break the comment sequence if the previous line did not end 676 // in a trailing comment. 677 (Changes[i].NewlinesBefore == 1 && i > 0 && 678 !Changes[i - 1].IsTrailingComment) || 679 WasAlignedWithStartOfNextLine) { 680 alignTrailingComments(StartOfSequence, i, MinColumn); 681 MinColumn = ChangeMinColumn; 682 MaxColumn = ChangeMaxColumn; 683 StartOfSequence = i; 684 } else { 685 MinColumn = std::max(MinColumn, ChangeMinColumn); 686 MaxColumn = std::min(MaxColumn, ChangeMaxColumn); 687 } 688 BreakBeforeNext = (i == 0) || (Changes[i].NewlinesBefore > 1) || 689 // Never start a sequence with a comment at the beginning 690 // of the line. 691 (Changes[i].NewlinesBefore == 1 && StartOfSequence == i); 692 Newlines = 0; 693 } 694 alignTrailingComments(StartOfSequence, Changes.size(), MinColumn); 695 } 696 697 void WhitespaceManager::alignTrailingComments(unsigned Start, unsigned End, 698 unsigned Column) { 699 for (unsigned i = Start; i != End; ++i) { 700 int Shift = 0; 701 if (Changes[i].IsTrailingComment) { 702 Shift = Column - Changes[i].StartOfTokenColumn; 703 } 704 if (Changes[i].StartOfBlockComment) { 705 Shift = Changes[i].IndentationOffset + 706 Changes[i].StartOfBlockComment->StartOfTokenColumn - 707 Changes[i].StartOfTokenColumn; 708 } 709 assert(Shift >= 0); 710 Changes[i].Spaces += Shift; 711 if (i + 1 != Changes.size()) 712 Changes[i + 1].PreviousEndOfTokenColumn += Shift; 713 Changes[i].StartOfTokenColumn += Shift; 714 } 715 } 716 717 void WhitespaceManager::alignEscapedNewlines() { 718 if (Style.AlignEscapedNewlines == FormatStyle::ENAS_DontAlign) 719 return; 720 721 bool AlignLeft = Style.AlignEscapedNewlines == FormatStyle::ENAS_Left; 722 unsigned MaxEndOfLine = AlignLeft ? 0 : Style.ColumnLimit; 723 unsigned StartOfMacro = 0; 724 for (unsigned i = 1, e = Changes.size(); i < e; ++i) { 725 Change &C = Changes[i]; 726 if (C.NewlinesBefore > 0) { 727 if (C.ContinuesPPDirective) { 728 MaxEndOfLine = std::max(C.PreviousEndOfTokenColumn + 2, MaxEndOfLine); 729 } else { 730 alignEscapedNewlines(StartOfMacro + 1, i, MaxEndOfLine); 731 MaxEndOfLine = AlignLeft ? 0 : Style.ColumnLimit; 732 StartOfMacro = i; 733 } 734 } 735 } 736 alignEscapedNewlines(StartOfMacro + 1, Changes.size(), MaxEndOfLine); 737 } 738 739 void WhitespaceManager::alignEscapedNewlines(unsigned Start, unsigned End, 740 unsigned Column) { 741 for (unsigned i = Start; i < End; ++i) { 742 Change &C = Changes[i]; 743 if (C.NewlinesBefore > 0) { 744 assert(C.ContinuesPPDirective); 745 if (C.PreviousEndOfTokenColumn + 1 > Column) 746 C.EscapedNewlineColumn = 0; 747 else 748 C.EscapedNewlineColumn = Column; 749 } 750 } 751 } 752 753 void WhitespaceManager::generateChanges() { 754 for (unsigned i = 0, e = Changes.size(); i != e; ++i) { 755 const Change &C = Changes[i]; 756 if (i > 0) { 757 assert(Changes[i - 1].OriginalWhitespaceRange.getBegin() != 758 C.OriginalWhitespaceRange.getBegin() && 759 "Generating two replacements for the same location"); 760 } 761 if (C.CreateReplacement) { 762 std::string ReplacementText = C.PreviousLinePostfix; 763 if (C.ContinuesPPDirective) 764 appendEscapedNewlineText(ReplacementText, C.NewlinesBefore, 765 C.PreviousEndOfTokenColumn, 766 C.EscapedNewlineColumn); 767 else 768 appendNewlineText(ReplacementText, C.NewlinesBefore); 769 appendIndentText( 770 ReplacementText, C.Tok->IndentLevel, std::max(0, C.Spaces), 771 C.StartOfTokenColumn - std::max(0, C.Spaces), C.IsAligned); 772 ReplacementText.append(C.CurrentLinePrefix); 773 storeReplacement(C.OriginalWhitespaceRange, ReplacementText); 774 } 775 } 776 } 777 778 void WhitespaceManager::storeReplacement(SourceRange Range, StringRef Text) { 779 unsigned WhitespaceLength = SourceMgr.getFileOffset(Range.getEnd()) - 780 SourceMgr.getFileOffset(Range.getBegin()); 781 // Don't create a replacement, if it does not change anything. 782 if (StringRef(SourceMgr.getCharacterData(Range.getBegin()), 783 WhitespaceLength) == Text) 784 return; 785 auto Err = Replaces.add(tooling::Replacement( 786 SourceMgr, CharSourceRange::getCharRange(Range), Text)); 787 // FIXME: better error handling. For now, just print an error message in the 788 // release version. 789 if (Err) { 790 llvm::errs() << llvm::toString(std::move(Err)) << "\n"; 791 assert(false); 792 } 793 } 794 795 void WhitespaceManager::appendNewlineText(std::string &Text, 796 unsigned Newlines) { 797 for (unsigned i = 0; i < Newlines; ++i) 798 Text.append(UseCRLF ? "\r\n" : "\n"); 799 } 800 801 void WhitespaceManager::appendEscapedNewlineText( 802 std::string &Text, unsigned Newlines, unsigned PreviousEndOfTokenColumn, 803 unsigned EscapedNewlineColumn) { 804 if (Newlines > 0) { 805 unsigned Spaces = 806 std::max<int>(1, EscapedNewlineColumn - PreviousEndOfTokenColumn - 1); 807 for (unsigned i = 0; i < Newlines; ++i) { 808 Text.append(Spaces, ' '); 809 Text.append(UseCRLF ? "\\\r\n" : "\\\n"); 810 Spaces = std::max<int>(0, EscapedNewlineColumn - 1); 811 } 812 } 813 } 814 815 void WhitespaceManager::appendIndentText(std::string &Text, 816 unsigned IndentLevel, unsigned Spaces, 817 unsigned WhitespaceStartColumn, 818 bool IsAligned) { 819 switch (Style.UseTab) { 820 case FormatStyle::UT_Never: 821 Text.append(Spaces, ' '); 822 break; 823 case FormatStyle::UT_Always: { 824 if (Style.TabWidth) { 825 unsigned FirstTabWidth = 826 Style.TabWidth - WhitespaceStartColumn % Style.TabWidth; 827 828 // Insert only spaces when we want to end up before the next tab. 829 if (Spaces < FirstTabWidth || Spaces == 1) { 830 Text.append(Spaces, ' '); 831 break; 832 } 833 // Align to the next tab. 834 Spaces -= FirstTabWidth; 835 Text.append("\t"); 836 837 Text.append(Spaces / Style.TabWidth, '\t'); 838 Text.append(Spaces % Style.TabWidth, ' '); 839 } else if (Spaces == 1) { 840 Text.append(Spaces, ' '); 841 } 842 break; 843 } 844 case FormatStyle::UT_ForIndentation: 845 if (WhitespaceStartColumn == 0) { 846 unsigned Indentation = IndentLevel * Style.IndentWidth; 847 Spaces = appendTabIndent(Text, Spaces, Indentation); 848 } 849 Text.append(Spaces, ' '); 850 break; 851 case FormatStyle::UT_ForContinuationAndIndentation: 852 if (WhitespaceStartColumn == 0) 853 Spaces = appendTabIndent(Text, Spaces, Spaces); 854 Text.append(Spaces, ' '); 855 break; 856 case FormatStyle::UT_AlignWithSpaces: 857 if (WhitespaceStartColumn == 0) { 858 unsigned Indentation = 859 IsAligned ? IndentLevel * Style.IndentWidth : Spaces; 860 Spaces = appendTabIndent(Text, Spaces, Indentation); 861 } 862 Text.append(Spaces, ' '); 863 break; 864 } 865 } 866 867 unsigned WhitespaceManager::appendTabIndent(std::string &Text, unsigned Spaces, 868 unsigned Indentation) { 869 // This happens, e.g. when a line in a block comment is indented less than the 870 // first one. 871 if (Indentation > Spaces) 872 Indentation = Spaces; 873 if (Style.TabWidth) { 874 unsigned Tabs = Indentation / Style.TabWidth; 875 Text.append(Tabs, '\t'); 876 Spaces -= Tabs * Style.TabWidth; 877 } 878 return Spaces; 879 } 880 881 } // namespace format 882 } // namespace clang 883