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