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