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