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