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