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