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