1 //===--- WhitespaceManager.cpp - Format C++ code --------------------------===//
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
7 //===----------------------------------------------------------------------===//
10 /// This file implements WhitespaceManager class.
12 //===----------------------------------------------------------------------===//
14 #include "WhitespaceManager.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallVector.h"
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());
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) {
48 void WhitespaceManager::replaceWhitespace(FormatToken &Tok, unsigned Newlines,
50 unsigned StartOfTokenColumn,
51 bool IsAligned, bool InPPDirective) {
52 if (Tok.Finalized || (Tok.MacroCtx && Tok.MacroCtx->Role == MR_ExpandedArg))
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));
61 void WhitespaceManager::addUntouchableToken(const FormatToken &Tok,
63 if (Tok.Finalized || (Tok.MacroCtx && Tok.MacroCtx->Role == MR_ExpandedArg))
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));
73 WhitespaceManager::addReplacement(const tooling::Replacement &Replacement) {
74 return Replaces.add(Replacement);
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;
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 || (Tok.MacroCtx && Tok.MacroCtx->Role == MR_ExpandedArg))
89 SourceLocation Start = Tok.getStartOfNonWhitespace().getLocWithOffset(Offset);
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));
98 const tooling::Replacements &WhitespaceManager::generateReplacements() {
102 llvm::sort(Changes, Change::IsBeforeInFile(SourceMgr));
103 calculateLineBreakInformation();
104 alignConsecutiveMacros();
105 alignConsecutiveShortCaseStatements();
106 alignConsecutiveDeclarations();
107 alignConsecutiveBitFields();
108 alignConsecutiveAssignments();
109 alignChainedConditionals();
110 alignTrailingComments();
111 alignEscapedNewlines();
112 alignArrayInitializers();
118 void WhitespaceManager::calculateLineBreakInformation() {
119 Changes[0].PreviousEndOfTokenColumn = 0;
120 Change *LastOutsideTokenChange = &Changes[0];
121 for (unsigned i = 1, e = Changes.size(); i != e; ++i) {
122 SourceLocation OriginalWhitespaceStart =
123 Changes[i].OriginalWhitespaceRange.getBegin();
124 SourceLocation PreviousOriginalWhitespaceEnd =
125 Changes[i - 1].OriginalWhitespaceRange.getEnd();
126 unsigned OriginalWhitespaceStartOffset =
127 SourceMgr.getFileOffset(OriginalWhitespaceStart);
128 unsigned PreviousOriginalWhitespaceEndOffset =
129 SourceMgr.getFileOffset(PreviousOriginalWhitespaceEnd);
130 assert(PreviousOriginalWhitespaceEndOffset <=
131 OriginalWhitespaceStartOffset);
132 const char *const PreviousOriginalWhitespaceEndData =
133 SourceMgr.getCharacterData(PreviousOriginalWhitespaceEnd);
134 StringRef Text(PreviousOriginalWhitespaceEndData,
135 SourceMgr.getCharacterData(OriginalWhitespaceStart) -
136 PreviousOriginalWhitespaceEndData);
137 // Usually consecutive changes would occur in consecutive tokens. This is
138 // not the case however when analyzing some preprocessor runs of the
139 // annotated lines. For example, in this code:
147 // one of the runs will produce the sequence of lines marked with line 1, 2
148 // and 3. So the two consecutive whitespace changes just before '// line 2'
149 // and before '#endif // line 3' span multiple lines and tokens:
151 // #else B{change X}[// line 2
153 // ]{change Y}#endif // line 3
155 // For this reason, if the text between consecutive changes spans multiple
156 // newlines, the token length must be adjusted to the end of the original
157 // line of the token.
158 auto NewlinePos = Text.find_first_of('\n');
159 if (NewlinePos == StringRef::npos) {
160 Changes[i - 1].TokenLength = OriginalWhitespaceStartOffset -
161 PreviousOriginalWhitespaceEndOffset +
162 Changes[i].PreviousLinePostfix.size() +
163 Changes[i - 1].CurrentLinePrefix.size();
165 Changes[i - 1].TokenLength =
166 NewlinePos + Changes[i - 1].CurrentLinePrefix.size();
169 // If there are multiple changes in this token, sum up all the changes until
170 // the end of the line.
171 if (Changes[i - 1].IsInsideToken && Changes[i - 1].NewlinesBefore == 0) {
172 LastOutsideTokenChange->TokenLength +=
173 Changes[i - 1].TokenLength + Changes[i - 1].Spaces;
175 LastOutsideTokenChange = &Changes[i - 1];
178 Changes[i].PreviousEndOfTokenColumn =
179 Changes[i - 1].StartOfTokenColumn + Changes[i - 1].TokenLength;
181 Changes[i - 1].IsTrailingComment =
182 (Changes[i].NewlinesBefore > 0 || Changes[i].Tok->is(tok::eof) ||
183 (Changes[i].IsInsideToken && Changes[i].Tok->is(tok::comment))) &&
184 Changes[i - 1].Tok->is(tok::comment) &&
185 // FIXME: This is a dirty hack. The problem is that
186 // BreakableLineCommentSection does comment reflow changes and here is
187 // the aligning of trailing comments. Consider the case where we reflow
188 // the second line up in this example:
193 // That amounts to 2 changes by BreakableLineCommentSection:
194 // - the first, delimited by (), for the whitespace between the tokens,
195 // - and second, delimited by [], for the whitespace at the beginning
196 // of the second token:
201 // So in the end we have two changes like this:
203 // // line1()[ ]line 2
205 // Note that the OriginalWhitespaceStart of the second change is the
206 // same as the PreviousOriginalWhitespaceEnd of the first change.
207 // In this case, the below check ensures that the second change doesn't
208 // get treated as a trailing comment change here, since this might
209 // trigger additional whitespace to be wrongly inserted before "line 2"
210 // by the comment aligner here.
212 // For a proper solution we need a mechanism to say to WhitespaceManager
213 // that a particular change breaks the current sequence of trailing
215 OriginalWhitespaceStart != PreviousOriginalWhitespaceEnd;
217 // FIXME: The last token is currently not always an eof token; in those
218 // cases, setting TokenLength of the last token to 0 is wrong.
219 Changes.back().TokenLength = 0;
220 Changes.back().IsTrailingComment = Changes.back().Tok->is(tok::comment);
222 const WhitespaceManager::Change *LastBlockComment = nullptr;
223 for (auto &Change : Changes) {
224 // Reset the IsTrailingComment flag for changes inside of trailing comments
225 // so they don't get realigned later. Comment line breaks however still need
227 if (Change.IsInsideToken && Change.NewlinesBefore == 0)
228 Change.IsTrailingComment = false;
229 Change.StartOfBlockComment = nullptr;
230 Change.IndentationOffset = 0;
231 if (Change.Tok->is(tok::comment)) {
232 if (Change.Tok->is(TT_LineComment) || !Change.IsInsideToken) {
233 LastBlockComment = &Change;
234 } else if ((Change.StartOfBlockComment = LastBlockComment)) {
235 Change.IndentationOffset =
236 Change.StartOfTokenColumn -
237 Change.StartOfBlockComment->StartOfTokenColumn;
240 LastBlockComment = nullptr;
244 // Compute conditional nesting level
245 // Level is increased for each conditional, unless this conditional continues
246 // a chain of conditional, i.e. starts immediately after the colon of another
248 SmallVector<bool, 16> ScopeStack;
249 int ConditionalsLevel = 0;
250 for (auto &Change : Changes) {
251 for (unsigned i = 0, e = Change.Tok->FakeLParens.size(); i != e; ++i) {
252 bool isNestedConditional =
253 Change.Tok->FakeLParens[e - 1 - i] == prec::Conditional &&
254 !(i == 0 && Change.Tok->Previous &&
255 Change.Tok->Previous->is(TT_ConditionalExpr) &&
256 Change.Tok->Previous->is(tok::colon));
257 if (isNestedConditional)
259 ScopeStack.push_back(isNestedConditional);
262 Change.ConditionalsLevel = ConditionalsLevel;
264 for (unsigned i = Change.Tok->FakeRParens; i > 0 && ScopeStack.size(); --i)
265 if (ScopeStack.pop_back_val())
270 // Align a single sequence of tokens, see AlignTokens below.
271 // Column - The token for which Matches returns true is moved to this column.
272 // RightJustify - Whether it is the token's right end or left end that gets
273 // moved to that column.
274 template <typename F>
276 AlignTokenSequence(const FormatStyle &Style, unsigned Start, unsigned End,
277 unsigned Column, bool RightJustify, F &&Matches,
278 SmallVector<WhitespaceManager::Change, 16> &Changes) {
279 bool FoundMatchOnLine = false;
282 // ScopeStack keeps track of the current scope depth. It contains indices of
283 // the first token on each scope.
284 // We only run the "Matches" function on tokens from the outer-most scope.
285 // However, we do need to pay special attention to one class of tokens
286 // that are not in the outer-most scope, and that is function parameters
287 // which are split across multiple lines, as illustrated by this example:
291 // In the above example, we need to take special care to ensure that
292 // 'double z' is indented along with it's owning function 'b'.
293 // The same holds for calling a function:
294 // double a = foo(x);
295 // int b = bar(foo(y),
297 // Similar for broken string literals:
301 // Special handling is required for 'nested' ternary operators.
302 SmallVector<unsigned, 16> ScopeStack;
304 for (unsigned i = Start; i != End; ++i) {
305 if (ScopeStack.size() != 0 &&
306 Changes[i].indentAndNestingLevel() <
307 Changes[ScopeStack.back()].indentAndNestingLevel()) {
308 ScopeStack.pop_back();
311 // Compare current token to previous non-comment token to ensure whether
312 // it is in a deeper scope or not.
313 unsigned PreviousNonComment = i - 1;
314 while (PreviousNonComment > Start &&
315 Changes[PreviousNonComment].Tok->is(tok::comment)) {
316 --PreviousNonComment;
318 if (i != Start && Changes[i].indentAndNestingLevel() >
319 Changes[PreviousNonComment].indentAndNestingLevel()) {
320 ScopeStack.push_back(i);
323 bool InsideNestedScope = ScopeStack.size() != 0;
324 bool ContinuedStringLiteral = i > Start &&
325 Changes[i].Tok->is(tok::string_literal) &&
326 Changes[i - 1].Tok->is(tok::string_literal);
327 bool SkipMatchCheck = InsideNestedScope || ContinuedStringLiteral;
329 if (Changes[i].NewlinesBefore > 0 && !SkipMatchCheck) {
331 FoundMatchOnLine = false;
334 // If this is the first matching token to be aligned, remember by how many
335 // spaces it has to be shifted, so the rest of the changes on the line are
336 // shifted by the same amount
337 if (!FoundMatchOnLine && !SkipMatchCheck && Matches(Changes[i])) {
338 FoundMatchOnLine = true;
339 Shift = Column - (RightJustify ? Changes[i].TokenLength : 0) -
340 Changes[i].StartOfTokenColumn;
341 Changes[i].Spaces += Shift;
342 // FIXME: This is a workaround that should be removed when we fix
343 // http://llvm.org/PR53699. An assertion later below verifies this.
344 if (Changes[i].NewlinesBefore == 0) {
346 std::max(Changes[i].Spaces,
347 static_cast<int>(Changes[i].Tok->SpacesRequiredBefore));
351 // This is for function parameters that are split across multiple lines,
352 // as mentioned in the ScopeStack comment.
353 if (InsideNestedScope && Changes[i].NewlinesBefore > 0) {
354 unsigned ScopeStart = ScopeStack.back();
355 auto ShouldShiftBeAdded = [&] {
356 // Function declaration
357 if (Changes[ScopeStart - 1].Tok->is(TT_FunctionDeclarationName))
361 if (Changes[ScopeStart - 1].Tok->is(TT_LambdaLBrace))
364 // Continued function declaration
365 if (ScopeStart > Start + 1 &&
366 Changes[ScopeStart - 2].Tok->is(TT_FunctionDeclarationName)) {
370 // Continued function call
371 if (ScopeStart > Start + 1 &&
372 Changes[ScopeStart - 2].Tok->is(tok::identifier) &&
373 Changes[ScopeStart - 1].Tok->is(tok::l_paren) &&
374 Changes[ScopeStart].Tok->isNot(TT_LambdaLSquare)) {
375 if (Changes[i].Tok->MatchingParen &&
376 Changes[i].Tok->MatchingParen->is(TT_LambdaLBrace)) {
379 if (Changes[ScopeStart].NewlinesBefore > 0)
381 if (Changes[i].Tok->is(tok::l_brace) &&
382 Changes[i].Tok->is(BK_BracedInit)) {
385 return Style.BinPackArguments;
389 if (Changes[i].Tok->is(TT_ConditionalExpr))
392 // Period Initializer .XXX = 1.
393 if (Changes[i].Tok->is(TT_DesignatedInitializerPeriod))
396 // Continued ternary operator
397 if (Changes[i].Tok->Previous &&
398 Changes[i].Tok->Previous->is(TT_ConditionalExpr)) {
402 // Continued direct-list-initialization using braced list.
403 if (ScopeStart > Start + 1 &&
404 Changes[ScopeStart - 2].Tok->is(tok::identifier) &&
405 Changes[ScopeStart - 1].Tok->is(tok::l_brace) &&
406 Changes[i].Tok->is(tok::l_brace) &&
407 Changes[i].Tok->is(BK_BracedInit)) {
411 // Continued braced list.
412 if (ScopeStart > Start + 1 &&
413 Changes[ScopeStart - 2].Tok->isNot(tok::identifier) &&
414 Changes[ScopeStart - 1].Tok->is(tok::l_brace) &&
415 Changes[i].Tok->isNot(tok::r_brace)) {
416 for (unsigned OuterScopeStart : llvm::reverse(ScopeStack)) {
418 if (OuterScopeStart > Start &&
419 Changes[OuterScopeStart - 1].Tok->is(TT_LambdaLBrace)) {
423 if (Changes[ScopeStart].NewlinesBefore > 0)
431 if (ShouldShiftBeAdded())
432 Changes[i].Spaces += Shift;
435 if (ContinuedStringLiteral)
436 Changes[i].Spaces += Shift;
438 // We should not remove required spaces unless we break the line before.
439 assert(Shift >= 0 || Changes[i].NewlinesBefore > 0 ||
441 static_cast<int>(Changes[i].Tok->SpacesRequiredBefore) ||
442 Changes[i].Tok->is(tok::eof));
444 Changes[i].StartOfTokenColumn += Shift;
445 if (i + 1 != Changes.size())
446 Changes[i + 1].PreviousEndOfTokenColumn += Shift;
448 // If PointerAlignment is PAS_Right, keep *s or &s next to the token
449 if ((Style.PointerAlignment == FormatStyle::PAS_Right ||
450 Style.ReferenceAlignment == FormatStyle::RAS_Right) &&
451 Changes[i].Spaces != 0) {
452 const bool ReferenceNotRightAligned =
453 Style.ReferenceAlignment != FormatStyle::RAS_Right &&
454 Style.ReferenceAlignment != FormatStyle::RAS_Pointer;
455 for (int Previous = i - 1;
457 Changes[Previous].Tok->getType() == TT_PointerOrReference;
460 Changes[Previous].Tok->isOneOf(tok::star, tok::amp, tok::ampamp));
461 if (Changes[Previous].Tok->isNot(tok::star)) {
462 if (ReferenceNotRightAligned)
464 } else if (Style.PointerAlignment != FormatStyle::PAS_Right) {
467 Changes[Previous + 1].Spaces -= Shift;
468 Changes[Previous].Spaces += Shift;
469 Changes[Previous].StartOfTokenColumn += Shift;
475 // Walk through a subset of the changes, starting at StartAt, and find
476 // sequences of matching tokens to align. To do so, keep track of the lines and
477 // whether or not a matching token was found on a line. If a matching token is
478 // found, extend the current sequence. If the current line cannot be part of a
479 // sequence, e.g. because there is an empty line before it or it contains only
480 // non-matching tokens, finalize the previous sequence.
481 // The value returned is the token on which we stopped, either because we
482 // exhausted all items inside Changes, or because we hit a scope level higher
483 // than our initial scope.
484 // This function is recursive. Each invocation processes only the scope level
485 // equal to the initial level, which is the level of Changes[StartAt].
486 // If we encounter a scope level greater than the initial level, then we call
487 // ourselves recursively, thereby avoiding the pollution of the current state
488 // with the alignment requirements of the nested sub-level. This recursive
489 // behavior is necessary for aligning function prototypes that have one or more
491 // If this function encounters a scope level less than the initial level,
492 // it returns the current position.
493 // There is a non-obvious subtlety in the recursive behavior: Even though we
494 // defer processing of nested levels to recursive invocations of this
495 // function, when it comes time to align a sequence of tokens, we run the
496 // alignment on the entire sequence, including the nested levels.
497 // When doing so, most of the nested tokens are skipped, because their
498 // alignment was already handled by the recursive invocations of this function.
499 // However, the special exception is that we do NOT skip function parameters
500 // that are split across multiple lines. See the test case in FormatTest.cpp
501 // that mentions "split function parameter alignment" for an example of this.
502 // When the parameter RightJustify is true, the operator will be
503 // right-justified. It is used to align compound assignments like `+=` and `=`.
504 // When RightJustify and ACS.PadOperators are true, operators in each block to
505 // be aligned will be padded on the left to the same length before aligning.
506 template <typename F>
507 static unsigned AlignTokens(const FormatStyle &Style, F &&Matches,
508 SmallVector<WhitespaceManager::Change, 16> &Changes,
510 const FormatStyle::AlignConsecutiveStyle &ACS = {},
511 bool RightJustify = false) {
512 // We arrange each line in 3 parts. The operator to be aligned (the anchor),
513 // and text to its left and right. In the aligned text the width of each part
514 // will be the maximum of that over the block that has been aligned. Maximum
515 // widths of each part so far. When RightJustify is true and ACS.PadOperators
516 // is false, the part from start of line to the right end of the anchor.
517 // Otherwise, only the part to the left of the anchor. Including the space
518 // that exists on its left from the start. Not including the padding added on
519 // the left to right-justify the anchor.
520 unsigned WidthLeft = 0;
521 // The operator to be aligned when RightJustify is true and ACS.PadOperators
522 // is false. 0 otherwise.
523 unsigned WidthAnchor = 0;
524 // Width to the right of the anchor. Plus width of the anchor when
525 // RightJustify is false.
526 unsigned WidthRight = 0;
528 // Line number of the start and the end of the current token sequence.
529 unsigned StartOfSequence = 0;
530 unsigned EndOfSequence = 0;
532 // Measure the scope level (i.e. depth of (), [], {}) of the first token, and
533 // abort when we hit any token in a higher scope than the starting one.
534 auto IndentAndNestingLevel = StartAt < Changes.size()
535 ? Changes[StartAt].indentAndNestingLevel()
536 : std::tuple<unsigned, unsigned, unsigned>();
538 // Keep track of the number of commas before the matching tokens, we will only
539 // align a sequence of matching tokens if they are preceded by the same number
541 unsigned CommasBeforeLastMatch = 0;
542 unsigned CommasBeforeMatch = 0;
544 // Whether a matching token has been found on the current line.
545 bool FoundMatchOnLine = false;
547 // Whether the current line consists purely of comments.
548 bool LineIsComment = true;
550 // Aligns a sequence of matching tokens, on the MinColumn column.
552 // Sequences start from the first matching token to align, and end at the
553 // first token of the first line that doesn't need to be aligned.
555 // We need to adjust the StartOfTokenColumn of each Change that is on a line
556 // containing any matching token to be aligned and located after such token.
557 auto AlignCurrentSequence = [&] {
558 if (StartOfSequence > 0 && StartOfSequence < EndOfSequence) {
559 AlignTokenSequence(Style, StartOfSequence, EndOfSequence,
560 WidthLeft + WidthAnchor, RightJustify, Matches,
570 unsigned i = StartAt;
571 for (unsigned e = Changes.size(); i != e; ++i) {
572 if (Changes[i].indentAndNestingLevel() < IndentAndNestingLevel)
575 if (Changes[i].NewlinesBefore != 0) {
576 CommasBeforeMatch = 0;
579 // Whether to break the alignment sequence because of an empty line.
580 bool EmptyLineBreak =
581 (Changes[i].NewlinesBefore > 1) && !ACS.AcrossEmptyLines;
583 // Whether to break the alignment sequence because of a line without a
586 !FoundMatchOnLine && !(LineIsComment && ACS.AcrossComments);
588 if (EmptyLineBreak || NoMatchBreak)
589 AlignCurrentSequence();
591 // A new line starts, re-initialize line status tracking bools.
592 // Keep the match state if a string literal is continued on this line.
593 if (i == 0 || !Changes[i].Tok->is(tok::string_literal) ||
594 !Changes[i - 1].Tok->is(tok::string_literal)) {
595 FoundMatchOnLine = false;
597 LineIsComment = true;
600 if (!Changes[i].Tok->is(tok::comment))
601 LineIsComment = false;
603 if (Changes[i].Tok->is(tok::comma)) {
605 } else if (Changes[i].indentAndNestingLevel() > IndentAndNestingLevel) {
606 // Call AlignTokens recursively, skipping over this scope block.
608 AlignTokens(Style, Matches, Changes, i, ACS, RightJustify);
613 if (!Matches(Changes[i]))
616 // If there is more than one matching token per line, or if the number of
617 // preceding commas, do not match anymore, end the sequence.
618 if (FoundMatchOnLine || CommasBeforeMatch != CommasBeforeLastMatch)
619 AlignCurrentSequence();
621 CommasBeforeLastMatch = CommasBeforeMatch;
622 FoundMatchOnLine = true;
624 if (StartOfSequence == 0)
627 unsigned ChangeWidthLeft = Changes[i].StartOfTokenColumn;
628 unsigned ChangeWidthAnchor = 0;
629 unsigned ChangeWidthRight = 0;
631 if (ACS.PadOperators)
632 ChangeWidthAnchor = Changes[i].TokenLength;
634 ChangeWidthLeft += Changes[i].TokenLength;
636 ChangeWidthRight = Changes[i].TokenLength;
637 for (unsigned j = i + 1; j != e && Changes[j].NewlinesBefore == 0; ++j) {
638 ChangeWidthRight += Changes[j].Spaces;
639 // Changes are generally 1:1 with the tokens, but a change could also be
640 // inside of a token, in which case it's counted more than once: once for
641 // the whitespace surrounding the token (!IsInsideToken) and once for
642 // each whitespace change within it (IsInsideToken).
643 // Therefore, changes inside of a token should only count the space.
644 if (!Changes[j].IsInsideToken)
645 ChangeWidthRight += Changes[j].TokenLength;
648 // If we are restricted by the maximum column width, end the sequence.
649 unsigned NewLeft = std::max(ChangeWidthLeft, WidthLeft);
650 unsigned NewAnchor = std::max(ChangeWidthAnchor, WidthAnchor);
651 unsigned NewRight = std::max(ChangeWidthRight, WidthRight);
652 // `ColumnLimit == 0` means there is no column limit.
653 if (Style.ColumnLimit != 0 &&
654 Style.ColumnLimit < NewLeft + NewAnchor + NewRight) {
655 AlignCurrentSequence();
657 WidthLeft = ChangeWidthLeft;
658 WidthAnchor = ChangeWidthAnchor;
659 WidthRight = ChangeWidthRight;
662 WidthAnchor = NewAnchor;
663 WidthRight = NewRight;
668 AlignCurrentSequence();
672 // Aligns a sequence of matching tokens, on the MinColumn column.
674 // Sequences start from the first matching token to align, and end at the
675 // first token of the first line that doesn't need to be aligned.
677 // We need to adjust the StartOfTokenColumn of each Change that is on a line
678 // containing any matching token to be aligned and located after such token.
679 static void AlignMatchingTokenSequence(
680 unsigned &StartOfSequence, unsigned &EndOfSequence, unsigned &MinColumn,
681 std::function<bool(const WhitespaceManager::Change &C)> Matches,
682 SmallVector<WhitespaceManager::Change, 16> &Changes) {
683 if (StartOfSequence > 0 && StartOfSequence < EndOfSequence) {
684 bool FoundMatchOnLine = false;
687 for (unsigned I = StartOfSequence; I != EndOfSequence; ++I) {
688 if (Changes[I].NewlinesBefore > 0) {
690 FoundMatchOnLine = false;
693 // If this is the first matching token to be aligned, remember by how many
694 // spaces it has to be shifted, so the rest of the changes on the line are
695 // shifted by the same amount.
696 if (!FoundMatchOnLine && Matches(Changes[I])) {
697 FoundMatchOnLine = true;
698 Shift = MinColumn - Changes[I].StartOfTokenColumn;
699 Changes[I].Spaces += Shift;
703 Changes[I].StartOfTokenColumn += Shift;
704 if (I + 1 != Changes.size())
705 Changes[I + 1].PreviousEndOfTokenColumn += Shift;
714 void WhitespaceManager::alignConsecutiveMacros() {
715 if (!Style.AlignConsecutiveMacros.Enabled)
718 auto AlignMacrosMatches = [](const Change &C) {
719 const FormatToken *Current = C.Tok;
720 unsigned SpacesRequiredBefore = 1;
722 if (Current->SpacesRequiredBefore == 0 || !Current->Previous)
725 Current = Current->Previous;
727 // If token is a ")", skip over the parameter list, to the
728 // token that precedes the "("
729 if (Current->is(tok::r_paren) && Current->MatchingParen) {
730 Current = Current->MatchingParen->Previous;
731 SpacesRequiredBefore = 0;
734 if (!Current || !Current->is(tok::identifier))
737 if (!Current->Previous || !Current->Previous->is(tok::pp_define))
740 // For a macro function, 0 spaces are required between the
741 // identifier and the lparen that opens the parameter list.
742 // For a simple macro, 1 space is required between the
743 // identifier and the first token of the defined value.
744 return Current->Next->SpacesRequiredBefore == SpacesRequiredBefore;
747 unsigned MinColumn = 0;
749 // Start and end of the token sequence we're processing.
750 unsigned StartOfSequence = 0;
751 unsigned EndOfSequence = 0;
753 // Whether a matching token has been found on the current line.
754 bool FoundMatchOnLine = false;
756 // Whether the current line consists only of comments
757 bool LineIsComment = true;
760 for (unsigned E = Changes.size(); I != E; ++I) {
761 if (Changes[I].NewlinesBefore != 0) {
764 // Whether to break the alignment sequence because of an empty line.
765 bool EmptyLineBreak = (Changes[I].NewlinesBefore > 1) &&
766 !Style.AlignConsecutiveMacros.AcrossEmptyLines;
768 // Whether to break the alignment sequence because of a line without a
772 !(LineIsComment && Style.AlignConsecutiveMacros.AcrossComments);
774 if (EmptyLineBreak || NoMatchBreak) {
775 AlignMatchingTokenSequence(StartOfSequence, EndOfSequence, MinColumn,
776 AlignMacrosMatches, Changes);
779 // A new line starts, re-initialize line status tracking bools.
780 FoundMatchOnLine = false;
781 LineIsComment = true;
784 if (!Changes[I].Tok->is(tok::comment))
785 LineIsComment = false;
787 if (!AlignMacrosMatches(Changes[I]))
790 FoundMatchOnLine = true;
792 if (StartOfSequence == 0)
795 unsigned ChangeMinColumn = Changes[I].StartOfTokenColumn;
796 MinColumn = std::max(MinColumn, ChangeMinColumn);
800 AlignMatchingTokenSequence(StartOfSequence, EndOfSequence, MinColumn,
801 AlignMacrosMatches, Changes);
804 void WhitespaceManager::alignConsecutiveAssignments() {
805 if (!Style.AlignConsecutiveAssignments.Enabled)
810 [&](const Change &C) {
811 // Do not align on equal signs that are first on a line.
812 if (C.NewlinesBefore > 0)
815 // Do not align on equal signs that are last on a line.
816 if (&C != &Changes.back() && (&C + 1)->NewlinesBefore > 0)
819 // Do not align operator= overloads.
820 FormatToken *Previous = C.Tok->getPreviousNonComment();
821 if (Previous && Previous->is(tok::kw_operator))
824 return Style.AlignConsecutiveAssignments.AlignCompound
825 ? C.Tok->getPrecedence() == prec::Assignment
826 : (C.Tok->is(tok::equal) ||
827 // In Verilog the '<=' is not a compound assignment, thus
828 // it is aligned even when the AlignCompound option is not
830 (Style.isVerilog() && C.Tok->is(tok::lessequal) &&
831 C.Tok->getPrecedence() == prec::Assignment));
833 Changes, /*StartAt=*/0, Style.AlignConsecutiveAssignments,
834 /*RightJustify=*/true);
837 void WhitespaceManager::alignConsecutiveBitFields() {
838 if (!Style.AlignConsecutiveBitFields.Enabled)
843 [&](Change const &C) {
844 // Do not align on ':' that is first on a line.
845 if (C.NewlinesBefore > 0)
848 // Do not align on ':' that is last on a line.
849 if (&C != &Changes.back() && (&C + 1)->NewlinesBefore > 0)
852 return C.Tok->is(TT_BitFieldColon);
854 Changes, /*StartAt=*/0, Style.AlignConsecutiveBitFields);
857 void WhitespaceManager::alignConsecutiveShortCaseStatements() {
858 if (!Style.AlignConsecutiveShortCaseStatements.Enabled ||
859 !Style.AllowShortCaseLabelsOnASingleLine) {
863 auto Matches = [&](const Change &C) {
864 if (Style.AlignConsecutiveShortCaseStatements.AlignCaseColons)
865 return C.Tok->is(TT_CaseLabelColon);
867 // Ignore 'IsInsideToken' to allow matching trailing comments which
868 // need to be reflowed as that causes the token to appear in two
869 // different changes, which will cause incorrect alignment as we'll
870 // reflow early due to detecting multiple aligning tokens per line.
871 return !C.IsInsideToken && C.Tok->Previous &&
872 C.Tok->Previous->is(TT_CaseLabelColon);
875 unsigned MinColumn = 0;
877 // Empty case statements don't break the alignment, but don't necessarily
878 // match our predicate, so we need to track their column so they can push out
880 unsigned MinEmptyCaseColumn = 0;
882 // Start and end of the token sequence we're processing.
883 unsigned StartOfSequence = 0;
884 unsigned EndOfSequence = 0;
886 // Whether a matching token has been found on the current line.
887 bool FoundMatchOnLine = false;
889 bool LineIsComment = true;
890 bool LineIsEmptyCase = false;
893 for (unsigned E = Changes.size(); I != E; ++I) {
894 if (Changes[I].NewlinesBefore != 0) {
895 // Whether to break the alignment sequence because of an empty line.
896 bool EmptyLineBreak =
897 (Changes[I].NewlinesBefore > 1) &&
898 !Style.AlignConsecutiveShortCaseStatements.AcrossEmptyLines;
900 // Whether to break the alignment sequence because of a line without a
905 Style.AlignConsecutiveShortCaseStatements.AcrossComments) &&
908 if (EmptyLineBreak || NoMatchBreak) {
909 AlignMatchingTokenSequence(StartOfSequence, EndOfSequence, MinColumn,
911 MinEmptyCaseColumn = 0;
914 // A new line starts, re-initialize line status tracking bools.
915 FoundMatchOnLine = false;
916 LineIsComment = true;
917 LineIsEmptyCase = false;
920 if (Changes[I].Tok->isNot(tok::comment))
921 LineIsComment = false;
923 if (Changes[I].Tok->is(TT_CaseLabelColon)) {
925 !Changes[I].Tok->Next || Changes[I].Tok->Next->isTrailingComment();
927 if (LineIsEmptyCase) {
928 if (Style.AlignConsecutiveShortCaseStatements.AlignCaseColons) {
930 std::max(MinEmptyCaseColumn, Changes[I].StartOfTokenColumn);
933 std::max(MinEmptyCaseColumn, Changes[I].StartOfTokenColumn + 2);
938 if (!Matches(Changes[I]))
944 FoundMatchOnLine = true;
946 if (StartOfSequence == 0)
949 EndOfSequence = I + 1;
951 MinColumn = std::max(MinColumn, Changes[I].StartOfTokenColumn);
953 // Allow empty case statements to push out our alignment.
954 MinColumn = std::max(MinColumn, MinEmptyCaseColumn);
957 AlignMatchingTokenSequence(StartOfSequence, EndOfSequence, MinColumn, Matches,
961 void WhitespaceManager::alignConsecutiveDeclarations() {
962 if (!Style.AlignConsecutiveDeclarations.Enabled)
967 [](Change const &C) {
968 if (C.Tok->is(TT_FunctionDeclarationName))
970 if (C.Tok->isNot(TT_StartOfName))
972 if (C.Tok->Previous &&
973 C.Tok->Previous->is(TT_StatementAttributeLikeMacro))
975 // Check if there is a subsequent name that starts the same declaration.
976 for (FormatToken *Next = C.Tok->Next; Next; Next = Next->Next) {
977 if (Next->is(tok::comment))
979 if (Next->is(TT_PointerOrReference))
981 if (!Next->Tok.getIdentifierInfo())
983 if (Next->isOneOf(TT_StartOfName, TT_FunctionDeclarationName,
990 Changes, /*StartAt=*/0, Style.AlignConsecutiveDeclarations);
993 void WhitespaceManager::alignChainedConditionals() {
994 if (Style.BreakBeforeTernaryOperators) {
997 [](Change const &C) {
998 // Align question operators and last colon
999 return C.Tok->is(TT_ConditionalExpr) &&
1000 ((C.Tok->is(tok::question) && !C.NewlinesBefore) ||
1001 (C.Tok->is(tok::colon) && C.Tok->Next &&
1002 (C.Tok->Next->FakeLParens.size() == 0 ||
1003 C.Tok->Next->FakeLParens.back() != prec::Conditional)));
1005 Changes, /*StartAt=*/0);
1007 static auto AlignWrappedOperand = [](Change const &C) {
1008 FormatToken *Previous = C.Tok->getPreviousNonComment();
1009 return C.NewlinesBefore && Previous && Previous->is(TT_ConditionalExpr) &&
1010 (Previous->is(tok::colon) &&
1011 (C.Tok->FakeLParens.size() == 0 ||
1012 C.Tok->FakeLParens.back() != prec::Conditional));
1014 // Ensure we keep alignment of wrapped operands with non-wrapped operands
1015 // Since we actually align the operators, the wrapped operands need the
1016 // extra offset to be properly aligned.
1017 for (Change &C : Changes)
1018 if (AlignWrappedOperand(C))
1019 C.StartOfTokenColumn -= 2;
1022 [this](Change const &C) {
1023 // Align question operators if next operand is not wrapped, as
1024 // well as wrapped operands after question operator or last
1025 // colon in conditional sequence
1026 return (C.Tok->is(TT_ConditionalExpr) && C.Tok->is(tok::question) &&
1027 &C != &Changes.back() && (&C + 1)->NewlinesBefore == 0 &&
1028 !(&C + 1)->IsTrailingComment) ||
1029 AlignWrappedOperand(C);
1031 Changes, /*StartAt=*/0);
1035 void WhitespaceManager::alignTrailingComments() {
1036 unsigned MinColumn = 0;
1037 unsigned MaxColumn = UINT_MAX;
1038 unsigned StartOfSequence = 0;
1039 bool BreakBeforeNext = false;
1040 unsigned Newlines = 0;
1041 unsigned int NewLineThreshold = 1;
1042 if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Always)
1043 NewLineThreshold = Style.AlignTrailingComments.OverEmptyLines + 1;
1045 for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
1046 if (Changes[i].StartOfBlockComment)
1048 Newlines += Changes[i].NewlinesBefore;
1049 if (!Changes[i].IsTrailingComment)
1052 if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Leave) {
1053 auto OriginalSpaces =
1054 Changes[i].OriginalWhitespaceRange.getEnd().getRawEncoding() -
1055 Changes[i].OriginalWhitespaceRange.getBegin().getRawEncoding() -
1056 Changes[i].Tok->NewlinesBefore;
1057 unsigned RestoredLineLength = Changes[i].StartOfTokenColumn +
1058 Changes[i].TokenLength + OriginalSpaces;
1059 // If leaving comments makes the line exceed the column limit, give up to
1060 // leave the comments.
1061 if (RestoredLineLength >= Style.ColumnLimit && Style.ColumnLimit != 0)
1063 Changes[i].Spaces = OriginalSpaces;
1067 unsigned ChangeMinColumn = Changes[i].StartOfTokenColumn;
1068 unsigned ChangeMaxColumn;
1070 if (Style.ColumnLimit == 0)
1071 ChangeMaxColumn = UINT_MAX;
1072 else if (Style.ColumnLimit >= Changes[i].TokenLength)
1073 ChangeMaxColumn = Style.ColumnLimit - Changes[i].TokenLength;
1075 ChangeMaxColumn = ChangeMinColumn;
1077 // If we don't create a replacement for this change, we have to consider
1078 // it to be immovable.
1079 if (!Changes[i].CreateReplacement)
1080 ChangeMaxColumn = ChangeMinColumn;
1082 if (i + 1 != e && Changes[i + 1].ContinuesPPDirective)
1083 ChangeMaxColumn -= 2;
1084 // If this comment follows an } in column 0, it probably documents the
1085 // closing of a namespace and we don't want to align it.
1086 bool FollowsRBraceInColumn0 = i > 0 && Changes[i].NewlinesBefore == 0 &&
1087 Changes[i - 1].Tok->is(tok::r_brace) &&
1088 Changes[i - 1].StartOfTokenColumn == 0;
1089 bool WasAlignedWithStartOfNextLine = false;
1090 if (Changes[i].NewlinesBefore >= 1) { // A comment on its own line.
1091 unsigned CommentColumn = SourceMgr.getSpellingColumnNumber(
1092 Changes[i].OriginalWhitespaceRange.getEnd());
1093 for (unsigned j = i + 1; j != e; ++j) {
1094 if (Changes[j].Tok->is(tok::comment))
1097 unsigned NextColumn = SourceMgr.getSpellingColumnNumber(
1098 Changes[j].OriginalWhitespaceRange.getEnd());
1099 // The start of the next token was previously aligned with the
1100 // start of this comment.
1101 WasAlignedWithStartOfNextLine =
1102 CommentColumn == NextColumn ||
1103 CommentColumn == NextColumn + Style.IndentWidth;
1107 if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Never ||
1108 FollowsRBraceInColumn0) {
1109 alignTrailingComments(StartOfSequence, i, MinColumn);
1110 MinColumn = ChangeMinColumn;
1111 MaxColumn = ChangeMinColumn;
1112 StartOfSequence = i;
1113 } else if (BreakBeforeNext || Newlines > NewLineThreshold ||
1114 (ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn) ||
1115 // Break the comment sequence if the previous line did not end
1116 // in a trailing comment.
1117 (Changes[i].NewlinesBefore == 1 && i > 0 &&
1118 !Changes[i - 1].IsTrailingComment) ||
1119 WasAlignedWithStartOfNextLine) {
1120 alignTrailingComments(StartOfSequence, i, MinColumn);
1121 MinColumn = ChangeMinColumn;
1122 MaxColumn = ChangeMaxColumn;
1123 StartOfSequence = i;
1125 MinColumn = std::max(MinColumn, ChangeMinColumn);
1126 MaxColumn = std::min(MaxColumn, ChangeMaxColumn);
1128 BreakBeforeNext = (i == 0) || (Changes[i].NewlinesBefore > 1) ||
1129 // Never start a sequence with a comment at the beginning
1131 (Changes[i].NewlinesBefore == 1 && StartOfSequence == i);
1134 alignTrailingComments(StartOfSequence, Changes.size(), MinColumn);
1137 void WhitespaceManager::alignTrailingComments(unsigned Start, unsigned End,
1139 for (unsigned i = Start; i != End; ++i) {
1141 if (Changes[i].IsTrailingComment)
1142 Shift = Column - Changes[i].StartOfTokenColumn;
1143 if (Changes[i].StartOfBlockComment) {
1144 Shift = Changes[i].IndentationOffset +
1145 Changes[i].StartOfBlockComment->StartOfTokenColumn -
1146 Changes[i].StartOfTokenColumn;
1150 Changes[i].Spaces += Shift;
1151 if (i + 1 != Changes.size())
1152 Changes[i + 1].PreviousEndOfTokenColumn += Shift;
1153 Changes[i].StartOfTokenColumn += Shift;
1157 void WhitespaceManager::alignEscapedNewlines() {
1158 if (Style.AlignEscapedNewlines == FormatStyle::ENAS_DontAlign)
1161 bool AlignLeft = Style.AlignEscapedNewlines == FormatStyle::ENAS_Left;
1162 unsigned MaxEndOfLine = AlignLeft ? 0 : Style.ColumnLimit;
1163 unsigned StartOfMacro = 0;
1164 for (unsigned i = 1, e = Changes.size(); i < e; ++i) {
1165 Change &C = Changes[i];
1166 if (C.NewlinesBefore > 0) {
1167 if (C.ContinuesPPDirective) {
1168 MaxEndOfLine = std::max(C.PreviousEndOfTokenColumn + 2, MaxEndOfLine);
1170 alignEscapedNewlines(StartOfMacro + 1, i, MaxEndOfLine);
1171 MaxEndOfLine = AlignLeft ? 0 : Style.ColumnLimit;
1176 alignEscapedNewlines(StartOfMacro + 1, Changes.size(), MaxEndOfLine);
1179 void WhitespaceManager::alignEscapedNewlines(unsigned Start, unsigned End,
1181 for (unsigned i = Start; i < End; ++i) {
1182 Change &C = Changes[i];
1183 if (C.NewlinesBefore > 0) {
1184 assert(C.ContinuesPPDirective);
1185 if (C.PreviousEndOfTokenColumn + 1 > Column)
1186 C.EscapedNewlineColumn = 0;
1188 C.EscapedNewlineColumn = Column;
1193 void WhitespaceManager::alignArrayInitializers() {
1194 if (Style.AlignArrayOfStructures == FormatStyle::AIAS_None)
1197 for (unsigned ChangeIndex = 1U, ChangeEnd = Changes.size();
1198 ChangeIndex < ChangeEnd; ++ChangeIndex) {
1199 auto &C = Changes[ChangeIndex];
1200 if (C.Tok->IsArrayInitializer) {
1201 bool FoundComplete = false;
1202 for (unsigned InsideIndex = ChangeIndex + 1; InsideIndex < ChangeEnd;
1204 if (Changes[InsideIndex].Tok == C.Tok->MatchingParen) {
1205 alignArrayInitializers(ChangeIndex, InsideIndex + 1);
1206 ChangeIndex = InsideIndex + 1;
1207 FoundComplete = true;
1212 ChangeIndex = ChangeEnd;
1217 void WhitespaceManager::alignArrayInitializers(unsigned Start, unsigned End) {
1219 if (Style.AlignArrayOfStructures == FormatStyle::AIAS_Right)
1220 alignArrayInitializersRightJustified(getCells(Start, End));
1221 else if (Style.AlignArrayOfStructures == FormatStyle::AIAS_Left)
1222 alignArrayInitializersLeftJustified(getCells(Start, End));
1225 void WhitespaceManager::alignArrayInitializersRightJustified(
1226 CellDescriptions &&CellDescs) {
1227 if (!CellDescs.isRectangular())
1230 auto &Cells = CellDescs.Cells;
1231 // Now go through and fixup the spaces.
1232 auto *CellIter = Cells.begin();
1233 for (auto i = 0U; i < CellDescs.CellCounts[0]; ++i, ++CellIter) {
1234 unsigned NetWidth = 0U;
1235 if (isSplitCell(*CellIter))
1236 NetWidth = getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces);
1237 auto CellWidth = getMaximumCellWidth(CellIter, NetWidth);
1239 if (Changes[CellIter->Index].Tok->is(tok::r_brace)) {
1240 // So in here we want to see if there is a brace that falls
1241 // on a line that was split. If so on that line we make sure that
1242 // the spaces in front of the brace are enough.
1243 const auto *Next = CellIter;
1245 const FormatToken *Previous = Changes[Next->Index].Tok->Previous;
1246 if (Previous && Previous->isNot(TT_LineComment)) {
1247 Changes[Next->Index].Spaces = 0;
1248 Changes[Next->Index].NewlinesBefore = 0;
1250 Next = Next->NextColumnElement;
1252 // Unless the array is empty, we need the position of all the
1253 // immediately adjacent cells
1254 if (CellIter != Cells.begin()) {
1256 getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces);
1257 auto MaxNetWidth = getMaximumNetWidth(
1258 Cells.begin(), CellIter, CellDescs.InitialSpaces,
1259 CellDescs.CellCounts[0], CellDescs.CellCounts.size());
1260 if (ThisNetWidth < MaxNetWidth)
1261 Changes[CellIter->Index].Spaces = (MaxNetWidth - ThisNetWidth);
1263 auto Offset = std::distance(Cells.begin(), CellIter);
1264 for (const auto *Next = CellIter->NextColumnElement; Next;
1265 Next = Next->NextColumnElement) {
1266 if (RowCount >= CellDescs.CellCounts.size())
1268 auto *Start = (Cells.begin() + RowCount * CellDescs.CellCounts[0]);
1269 auto *End = Start + Offset;
1270 ThisNetWidth = getNetWidth(Start, End, CellDescs.InitialSpaces);
1271 if (ThisNetWidth < MaxNetWidth)
1272 Changes[Next->Index].Spaces = (MaxNetWidth - ThisNetWidth);
1278 calculateCellWidth(CellIter->Index, CellIter->EndIndex, true) +
1280 if (Changes[CellIter->Index].NewlinesBefore == 0) {
1281 Changes[CellIter->Index].Spaces = (CellWidth - (ThisWidth + NetWidth));
1282 Changes[CellIter->Index].Spaces += (i > 0) ? 1 : 0;
1284 alignToStartOfCell(CellIter->Index, CellIter->EndIndex);
1285 for (const auto *Next = CellIter->NextColumnElement; Next;
1286 Next = Next->NextColumnElement) {
1288 calculateCellWidth(Next->Index, Next->EndIndex, true) + NetWidth;
1289 if (Changes[Next->Index].NewlinesBefore == 0) {
1290 Changes[Next->Index].Spaces = (CellWidth - ThisWidth);
1291 Changes[Next->Index].Spaces += (i > 0) ? 1 : 0;
1293 alignToStartOfCell(Next->Index, Next->EndIndex);
1299 void WhitespaceManager::alignArrayInitializersLeftJustified(
1300 CellDescriptions &&CellDescs) {
1302 if (!CellDescs.isRectangular())
1305 auto &Cells = CellDescs.Cells;
1306 // Now go through and fixup the spaces.
1307 auto *CellIter = Cells.begin();
1308 // The first cell needs to be against the left brace.
1309 if (Changes[CellIter->Index].NewlinesBefore == 0)
1310 Changes[CellIter->Index].Spaces = 0;
1312 Changes[CellIter->Index].Spaces = CellDescs.InitialSpaces;
1314 for (auto i = 1U; i < CellDescs.CellCounts[0]; i++, ++CellIter) {
1315 auto MaxNetWidth = getMaximumNetWidth(
1316 Cells.begin(), CellIter, CellDescs.InitialSpaces,
1317 CellDescs.CellCounts[0], CellDescs.CellCounts.size());
1319 getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces);
1320 if (Changes[CellIter->Index].NewlinesBefore == 0) {
1321 Changes[CellIter->Index].Spaces =
1322 MaxNetWidth - ThisNetWidth +
1323 (Changes[CellIter->Index].Tok->isNot(tok::r_brace) ? 1 : 0);
1326 auto Offset = std::distance(Cells.begin(), CellIter);
1327 for (const auto *Next = CellIter->NextColumnElement; Next;
1328 Next = Next->NextColumnElement) {
1329 if (RowCount >= CellDescs.CellCounts.size())
1331 auto *Start = (Cells.begin() + RowCount * CellDescs.CellCounts[0]);
1332 auto *End = Start + Offset;
1333 auto ThisNetWidth = getNetWidth(Start, End, CellDescs.InitialSpaces);
1334 if (Changes[Next->Index].NewlinesBefore == 0) {
1335 Changes[Next->Index].Spaces =
1336 MaxNetWidth - ThisNetWidth +
1337 (Changes[Next->Index].Tok->isNot(tok::r_brace) ? 1 : 0);
1344 bool WhitespaceManager::isSplitCell(const CellDescription &Cell) {
1347 for (const auto *Next = Cell.NextColumnElement; Next;
1348 Next = Next->NextColumnElement) {
1355 WhitespaceManager::CellDescriptions WhitespaceManager::getCells(unsigned Start,
1360 SmallVector<unsigned> CellCounts;
1361 unsigned InitialSpaces = 0;
1362 unsigned InitialTokenLength = 0;
1363 unsigned EndSpaces = 0;
1364 SmallVector<CellDescription> Cells;
1365 const FormatToken *MatchingParen = nullptr;
1366 for (unsigned i = Start; i < End; ++i) {
1367 auto &C = Changes[i];
1368 if (C.Tok->is(tok::l_brace))
1370 else if (C.Tok->is(tok::r_brace))
1373 if (C.Tok->is(tok::l_brace)) {
1375 MatchingParen = C.Tok->MatchingParen;
1376 if (InitialSpaces == 0) {
1377 InitialSpaces = C.Spaces + C.TokenLength;
1378 InitialTokenLength = C.TokenLength;
1380 for (; Changes[j].NewlinesBefore == 0 && j > Start; --j) {
1381 InitialSpaces += Changes[j].Spaces + Changes[j].TokenLength;
1382 InitialTokenLength += Changes[j].TokenLength;
1384 if (C.NewlinesBefore == 0) {
1385 InitialSpaces += Changes[j].Spaces + Changes[j].TokenLength;
1386 InitialTokenLength += Changes[j].TokenLength;
1389 } else if (C.Tok->is(tok::comma)) {
1391 Cells.back().EndIndex = i;
1392 if (C.Tok->getNextNonComment()->isNot(tok::r_brace)) // dangling comma
1395 } else if (Depth == 1) {
1396 if (C.Tok == MatchingParen) {
1398 Cells.back().EndIndex = i;
1399 Cells.push_back(CellDescription{i, ++Cell, i + 1, false, nullptr});
1400 CellCounts.push_back(C.Tok->Previous->isNot(tok::comma) ? Cell + 1
1402 // Go to the next non-comment and ensure there is a break in front
1403 const auto *NextNonComment = C.Tok->getNextNonComment();
1404 while (NextNonComment->is(tok::comma))
1405 NextNonComment = NextNonComment->getNextNonComment();
1407 while (Changes[j].Tok != NextNonComment && j < End)
1409 if (j < End && Changes[j].NewlinesBefore == 0 &&
1410 Changes[j].Tok->isNot(tok::r_brace)) {
1411 Changes[j].NewlinesBefore = 1;
1412 // Account for the added token lengths
1413 Changes[j].Spaces = InitialSpaces - InitialTokenLength;
1415 } else if (C.Tok->is(tok::comment)) {
1416 // Trailing comments stay at a space past the last token
1417 C.Spaces = Changes[i - 1].Tok->is(tok::comma) ? 1 : 2;
1418 } else if (C.Tok->is(tok::l_brace)) {
1419 // We need to make sure that the ending braces is aligned to the
1420 // start of our initializer
1422 for (; j > 0 && !Changes[j].Tok->ArrayInitializerLineStart; --j)
1423 ; // Nothing the loop does the work
1424 EndSpaces = Changes[j].Spaces;
1426 } else if (Depth == 0 && C.Tok->is(tok::r_brace)) {
1427 C.NewlinesBefore = 1;
1428 C.Spaces = EndSpaces;
1430 if (C.Tok->StartsColumn) {
1431 // This gets us past tokens that have been split over multiple
1433 bool HasSplit = false;
1434 if (Changes[i].NewlinesBefore > 0) {
1435 // So if we split a line previously and the tail line + this token is
1436 // less then the column limit we remove the split here and just put
1437 // the column start at a space past the comma
1439 // FIXME This if branch covers the cases where the column is not
1440 // the first column. This leads to weird pathologies like the formatting
1441 // auto foo = Items{
1446 // Well if it doesn't lead to that it's indicative that the line
1447 // breaking should be revisited. Unfortunately alot of other options
1448 // interact with this
1450 if ((j - 1) > Start && Changes[j].Tok->is(tok::comma) &&
1451 Changes[j - 1].NewlinesBefore > 0) {
1453 auto LineLimit = Changes[j].Spaces + Changes[j].TokenLength;
1454 if (LineLimit < Style.ColumnLimit) {
1455 Changes[i].NewlinesBefore = 0;
1456 Changes[i].Spaces = 1;
1460 while (Changes[i].NewlinesBefore > 0 && Changes[i].Tok == C.Tok) {
1461 Changes[i].Spaces = InitialSpaces;
1465 if (Changes[i].Tok != C.Tok)
1467 Cells.push_back(CellDescription{i, Cell, i, HasSplit, nullptr});
1471 return linkCells({Cells, CellCounts, InitialSpaces});
1474 unsigned WhitespaceManager::calculateCellWidth(unsigned Start, unsigned End,
1475 bool WithSpaces) const {
1476 unsigned CellWidth = 0;
1477 for (auto i = Start; i < End; i++) {
1478 if (Changes[i].NewlinesBefore > 0)
1480 CellWidth += Changes[i].TokenLength;
1481 CellWidth += (WithSpaces ? Changes[i].Spaces : 0);
1486 void WhitespaceManager::alignToStartOfCell(unsigned Start, unsigned End) {
1487 if ((End - Start) <= 1)
1489 // If the line is broken anywhere in there make sure everything
1490 // is aligned to the parent
1491 for (auto i = Start + 1; i < End; i++)
1492 if (Changes[i].NewlinesBefore > 0)
1493 Changes[i].Spaces = Changes[Start].Spaces;
1496 WhitespaceManager::CellDescriptions
1497 WhitespaceManager::linkCells(CellDescriptions &&CellDesc) {
1498 auto &Cells = CellDesc.Cells;
1499 for (auto *CellIter = Cells.begin(); CellIter != Cells.end(); ++CellIter) {
1500 if (!CellIter->NextColumnElement && (CellIter + 1) != Cells.end()) {
1501 for (auto *NextIter = CellIter + 1; NextIter != Cells.end(); ++NextIter) {
1502 if (NextIter->Cell == CellIter->Cell) {
1503 CellIter->NextColumnElement = &(*NextIter);
1509 return std::move(CellDesc);
1512 void WhitespaceManager::generateChanges() {
1513 for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
1514 const Change &C = Changes[i];
1515 if (i > 0 && Changes[i - 1].OriginalWhitespaceRange.getBegin() ==
1516 C.OriginalWhitespaceRange.getBegin()) {
1517 // Do not generate two replacements for the same location.
1520 if (C.CreateReplacement) {
1521 std::string ReplacementText = C.PreviousLinePostfix;
1522 if (C.ContinuesPPDirective) {
1523 appendEscapedNewlineText(ReplacementText, C.NewlinesBefore,
1524 C.PreviousEndOfTokenColumn,
1525 C.EscapedNewlineColumn);
1527 appendNewlineText(ReplacementText, C.NewlinesBefore);
1529 // FIXME: This assert should hold if we computed the column correctly.
1530 // assert((int)C.StartOfTokenColumn >= C.Spaces);
1532 ReplacementText, C.Tok->IndentLevel, std::max(0, C.Spaces),
1533 std::max((int)C.StartOfTokenColumn, C.Spaces) - std::max(0, C.Spaces),
1535 ReplacementText.append(C.CurrentLinePrefix);
1536 storeReplacement(C.OriginalWhitespaceRange, ReplacementText);
1541 void WhitespaceManager::storeReplacement(SourceRange Range, StringRef Text) {
1542 unsigned WhitespaceLength = SourceMgr.getFileOffset(Range.getEnd()) -
1543 SourceMgr.getFileOffset(Range.getBegin());
1544 // Don't create a replacement, if it does not change anything.
1545 if (StringRef(SourceMgr.getCharacterData(Range.getBegin()),
1546 WhitespaceLength) == Text) {
1549 auto Err = Replaces.add(tooling::Replacement(
1550 SourceMgr, CharSourceRange::getCharRange(Range), Text));
1551 // FIXME: better error handling. For now, just print an error message in the
1554 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
1559 void WhitespaceManager::appendNewlineText(std::string &Text,
1560 unsigned Newlines) {
1562 Text.reserve(Text.size() + 2 * Newlines);
1563 for (unsigned i = 0; i < Newlines; ++i)
1564 Text.append("\r\n");
1566 Text.append(Newlines, '\n');
1570 void WhitespaceManager::appendEscapedNewlineText(
1571 std::string &Text, unsigned Newlines, unsigned PreviousEndOfTokenColumn,
1572 unsigned EscapedNewlineColumn) {
1575 std::max<int>(1, EscapedNewlineColumn - PreviousEndOfTokenColumn - 1);
1576 for (unsigned i = 0; i < Newlines; ++i) {
1577 Text.append(Spaces, ' ');
1578 Text.append(UseCRLF ? "\\\r\n" : "\\\n");
1579 Spaces = std::max<int>(0, EscapedNewlineColumn - 1);
1584 void WhitespaceManager::appendIndentText(std::string &Text,
1585 unsigned IndentLevel, unsigned Spaces,
1586 unsigned WhitespaceStartColumn,
1588 switch (Style.UseTab) {
1589 case FormatStyle::UT_Never:
1590 Text.append(Spaces, ' ');
1592 case FormatStyle::UT_Always: {
1593 if (Style.TabWidth) {
1594 unsigned FirstTabWidth =
1595 Style.TabWidth - WhitespaceStartColumn % Style.TabWidth;
1597 // Insert only spaces when we want to end up before the next tab.
1598 if (Spaces < FirstTabWidth || Spaces == 1) {
1599 Text.append(Spaces, ' ');
1602 // Align to the next tab.
1603 Spaces -= FirstTabWidth;
1606 Text.append(Spaces / Style.TabWidth, '\t');
1607 Text.append(Spaces % Style.TabWidth, ' ');
1608 } else if (Spaces == 1) {
1609 Text.append(Spaces, ' ');
1613 case FormatStyle::UT_ForIndentation:
1614 if (WhitespaceStartColumn == 0) {
1615 unsigned Indentation = IndentLevel * Style.IndentWidth;
1616 Spaces = appendTabIndent(Text, Spaces, Indentation);
1618 Text.append(Spaces, ' ');
1620 case FormatStyle::UT_ForContinuationAndIndentation:
1621 if (WhitespaceStartColumn == 0)
1622 Spaces = appendTabIndent(Text, Spaces, Spaces);
1623 Text.append(Spaces, ' ');
1625 case FormatStyle::UT_AlignWithSpaces:
1626 if (WhitespaceStartColumn == 0) {
1627 unsigned Indentation =
1628 IsAligned ? IndentLevel * Style.IndentWidth : Spaces;
1629 Spaces = appendTabIndent(Text, Spaces, Indentation);
1631 Text.append(Spaces, ' ');
1636 unsigned WhitespaceManager::appendTabIndent(std::string &Text, unsigned Spaces,
1637 unsigned Indentation) {
1638 // This happens, e.g. when a line in a block comment is indented less than the
1640 if (Indentation > Spaces)
1641 Indentation = Spaces;
1642 if (Style.TabWidth) {
1643 unsigned Tabs = Indentation / Style.TabWidth;
1644 Text.append(Tabs, '\t');
1645 Spaces -= Tabs * Style.TabWidth;
1650 } // namespace format
1651 } // namespace clang