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