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