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