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