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