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