xref: /llvm-project/clang/lib/Format/WhitespaceManager.cpp (revision b4af01bada0c945906d85c364e12aceaf98b0fae)
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     alignConsecutiveTableGenBreakingDAGArgColons();
116     alignConsecutiveTableGenCondOperatorColons();
117     alignConsecutiveTableGenDefinitions();
118   }
119   alignChainedConditionals();
120   alignTrailingComments();
121   alignEscapedNewlines();
122   alignArrayInitializers();
123   generateChanges();
124 
125   return Replaces;
126 }
127 
128 void WhitespaceManager::calculateLineBreakInformation() {
129   Changes[0].PreviousEndOfTokenColumn = 0;
130   Change *LastOutsideTokenChange = &Changes[0];
131   for (unsigned I = 1, e = Changes.size(); I != e; ++I) {
132     auto &C = Changes[I];
133     auto &P = Changes[I - 1];
134     SourceLocation OriginalWhitespaceStart =
135         C.OriginalWhitespaceRange.getBegin();
136     SourceLocation PreviousOriginalWhitespaceEnd =
137         P.OriginalWhitespaceRange.getEnd();
138     unsigned OriginalWhitespaceStartOffset =
139         SourceMgr.getFileOffset(OriginalWhitespaceStart);
140     unsigned PreviousOriginalWhitespaceEndOffset =
141         SourceMgr.getFileOffset(PreviousOriginalWhitespaceEnd);
142     assert(PreviousOriginalWhitespaceEndOffset <=
143            OriginalWhitespaceStartOffset);
144     const char *const PreviousOriginalWhitespaceEndData =
145         SourceMgr.getCharacterData(PreviousOriginalWhitespaceEnd);
146     StringRef Text(PreviousOriginalWhitespaceEndData,
147                    SourceMgr.getCharacterData(OriginalWhitespaceStart) -
148                        PreviousOriginalWhitespaceEndData);
149     // Usually consecutive changes would occur in consecutive tokens. This is
150     // not the case however when analyzing some preprocessor runs of the
151     // annotated lines. For example, in this code:
152     //
153     // #if A // line 1
154     // int i = 1;
155     // #else B // line 2
156     // int i = 2;
157     // #endif // line 3
158     //
159     // one of the runs will produce the sequence of lines marked with line 1, 2
160     // and 3. So the two consecutive whitespace changes just before '// line 2'
161     // and before '#endif // line 3' span multiple lines and tokens:
162     //
163     // #else B{change X}[// line 2
164     // int i = 2;
165     // ]{change Y}#endif // line 3
166     //
167     // For this reason, if the text between consecutive changes spans multiple
168     // newlines, the token length must be adjusted to the end of the original
169     // line of the token.
170     auto NewlinePos = Text.find_first_of('\n');
171     if (NewlinePos == StringRef::npos) {
172       P.TokenLength = OriginalWhitespaceStartOffset -
173                       PreviousOriginalWhitespaceEndOffset +
174                       C.PreviousLinePostfix.size() + P.CurrentLinePrefix.size();
175     } else {
176       P.TokenLength = NewlinePos + P.CurrentLinePrefix.size();
177     }
178 
179     // If there are multiple changes in this token, sum up all the changes until
180     // the end of the line.
181     if (P.IsInsideToken && P.NewlinesBefore == 0)
182       LastOutsideTokenChange->TokenLength += P.TokenLength + P.Spaces;
183     else
184       LastOutsideTokenChange = &P;
185 
186     C.PreviousEndOfTokenColumn = P.StartOfTokenColumn + P.TokenLength;
187 
188     P.IsTrailingComment =
189         (C.NewlinesBefore > 0 || C.Tok->is(tok::eof) ||
190          (C.IsInsideToken && C.Tok->is(tok::comment))) &&
191         P.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     // except if the token is equal, then a space is needed.
466     if ((Style.PointerAlignment == FormatStyle::PAS_Right ||
467          Style.ReferenceAlignment == FormatStyle::RAS_Right) &&
468         CurrentChange.Spaces != 0 && CurrentChange.Tok->isNot(tok::equal)) {
469       const bool ReferenceNotRightAligned =
470           Style.ReferenceAlignment != FormatStyle::RAS_Right &&
471           Style.ReferenceAlignment != FormatStyle::RAS_Pointer;
472       for (int Previous = i - 1;
473            Previous >= 0 && Changes[Previous].Tok->is(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::alignConsecutiveTableGenBreakingDAGArgColons() {
983   alignConsecutiveColons(Style.AlignConsecutiveTableGenBreakingDAGArgColons,
984                          TT_TableGenDAGArgListColonToAlign);
985 }
986 
987 void WhitespaceManager::alignConsecutiveTableGenCondOperatorColons() {
988   alignConsecutiveColons(Style.AlignConsecutiveTableGenCondOperatorColons,
989                          TT_TableGenCondOperatorColon);
990 }
991 
992 void WhitespaceManager::alignConsecutiveTableGenDefinitions() {
993   alignConsecutiveColons(Style.AlignConsecutiveTableGenDefinitionColons,
994                          TT_InheritanceColon);
995 }
996 
997 void WhitespaceManager::alignConsecutiveDeclarations() {
998   if (!Style.AlignConsecutiveDeclarations.Enabled)
999     return;
1000 
1001   AlignTokens(
1002       Style,
1003       [&](Change const &C) {
1004         if (Style.AlignConsecutiveDeclarations.AlignFunctionPointers) {
1005           for (const auto *Prev = C.Tok->Previous; Prev; Prev = Prev->Previous)
1006             if (Prev->is(tok::equal))
1007               return false;
1008           if (C.Tok->is(TT_FunctionTypeLParen))
1009             return true;
1010         }
1011         if (C.Tok->is(TT_FunctionDeclarationName))
1012           return true;
1013         if (C.Tok->isNot(TT_StartOfName))
1014           return false;
1015         if (C.Tok->Previous &&
1016             C.Tok->Previous->is(TT_StatementAttributeLikeMacro))
1017           return false;
1018         // Check if there is a subsequent name that starts the same declaration.
1019         for (FormatToken *Next = C.Tok->Next; Next; Next = Next->Next) {
1020           if (Next->is(tok::comment))
1021             continue;
1022           if (Next->is(TT_PointerOrReference))
1023             return false;
1024           if (!Next->Tok.getIdentifierInfo())
1025             break;
1026           if (Next->isOneOf(TT_StartOfName, TT_FunctionDeclarationName,
1027                             tok::kw_operator)) {
1028             return false;
1029           }
1030         }
1031         return true;
1032       },
1033       Changes, /*StartAt=*/0, Style.AlignConsecutiveDeclarations);
1034 }
1035 
1036 void WhitespaceManager::alignChainedConditionals() {
1037   if (Style.BreakBeforeTernaryOperators) {
1038     AlignTokens(
1039         Style,
1040         [](Change const &C) {
1041           // Align question operators and last colon
1042           return C.Tok->is(TT_ConditionalExpr) &&
1043                  ((C.Tok->is(tok::question) && !C.NewlinesBefore) ||
1044                   (C.Tok->is(tok::colon) && C.Tok->Next &&
1045                    (C.Tok->Next->FakeLParens.size() == 0 ||
1046                     C.Tok->Next->FakeLParens.back() != prec::Conditional)));
1047         },
1048         Changes, /*StartAt=*/0);
1049   } else {
1050     static auto AlignWrappedOperand = [](Change const &C) {
1051       FormatToken *Previous = C.Tok->getPreviousNonComment();
1052       return C.NewlinesBefore && Previous && Previous->is(TT_ConditionalExpr) &&
1053              (Previous->is(tok::colon) &&
1054               (C.Tok->FakeLParens.size() == 0 ||
1055                C.Tok->FakeLParens.back() != prec::Conditional));
1056     };
1057     // Ensure we keep alignment of wrapped operands with non-wrapped operands
1058     // Since we actually align the operators, the wrapped operands need the
1059     // extra offset to be properly aligned.
1060     for (Change &C : Changes)
1061       if (AlignWrappedOperand(C))
1062         C.StartOfTokenColumn -= 2;
1063     AlignTokens(
1064         Style,
1065         [this](Change const &C) {
1066           // Align question operators if next operand is not wrapped, as
1067           // well as wrapped operands after question operator or last
1068           // colon in conditional sequence
1069           return (C.Tok->is(TT_ConditionalExpr) && C.Tok->is(tok::question) &&
1070                   &C != &Changes.back() && (&C + 1)->NewlinesBefore == 0 &&
1071                   !(&C + 1)->IsTrailingComment) ||
1072                  AlignWrappedOperand(C);
1073         },
1074         Changes, /*StartAt=*/0);
1075   }
1076 }
1077 
1078 void WhitespaceManager::alignTrailingComments() {
1079   if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Never)
1080     return;
1081 
1082   const int Size = Changes.size();
1083   int MinColumn = 0;
1084   int StartOfSequence = 0;
1085   bool BreakBeforeNext = false;
1086   int NewLineThreshold = 1;
1087   if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Always)
1088     NewLineThreshold = Style.AlignTrailingComments.OverEmptyLines + 1;
1089 
1090   for (int I = 0, MaxColumn = INT_MAX, Newlines = 0; I < Size; ++I) {
1091     auto &C = Changes[I];
1092     if (C.StartOfBlockComment)
1093       continue;
1094     Newlines += C.NewlinesBefore;
1095     if (!C.IsTrailingComment)
1096       continue;
1097 
1098     if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Leave) {
1099       const int OriginalSpaces =
1100           C.OriginalWhitespaceRange.getEnd().getRawEncoding() -
1101           C.OriginalWhitespaceRange.getBegin().getRawEncoding() -
1102           C.Tok->LastNewlineOffset;
1103       assert(OriginalSpaces >= 0);
1104       const auto RestoredLineLength =
1105           C.StartOfTokenColumn + C.TokenLength + OriginalSpaces;
1106       // If leaving comments makes the line exceed the column limit, give up to
1107       // leave the comments.
1108       if (RestoredLineLength >= Style.ColumnLimit && Style.ColumnLimit > 0)
1109         break;
1110       C.Spaces = OriginalSpaces;
1111       continue;
1112     }
1113 
1114     const int ChangeMinColumn = C.StartOfTokenColumn;
1115     int ChangeMaxColumn;
1116 
1117     // If we don't create a replacement for this change, we have to consider
1118     // it to be immovable.
1119     if (!C.CreateReplacement)
1120       ChangeMaxColumn = ChangeMinColumn;
1121     else if (Style.ColumnLimit == 0)
1122       ChangeMaxColumn = INT_MAX;
1123     else if (Style.ColumnLimit >= C.TokenLength)
1124       ChangeMaxColumn = Style.ColumnLimit - C.TokenLength;
1125     else
1126       ChangeMaxColumn = ChangeMinColumn;
1127 
1128     if (I + 1 < Size && Changes[I + 1].ContinuesPPDirective &&
1129         ChangeMaxColumn >= 2) {
1130       ChangeMaxColumn -= 2;
1131     }
1132 
1133     bool WasAlignedWithStartOfNextLine = false;
1134     if (C.NewlinesBefore >= 1) { // A comment on its own line.
1135       const auto CommentColumn =
1136           SourceMgr.getSpellingColumnNumber(C.OriginalWhitespaceRange.getEnd());
1137       for (int J = I + 1; J < Size; ++J) {
1138         if (Changes[J].Tok->is(tok::comment))
1139           continue;
1140 
1141         const auto NextColumn = SourceMgr.getSpellingColumnNumber(
1142             Changes[J].OriginalWhitespaceRange.getEnd());
1143         // The start of the next token was previously aligned with the
1144         // start of this comment.
1145         WasAlignedWithStartOfNextLine =
1146             CommentColumn == NextColumn ||
1147             CommentColumn == NextColumn + Style.IndentWidth;
1148         break;
1149       }
1150     }
1151 
1152     // We don't want to align comments which end a scope, which are here
1153     // identified by most closing braces.
1154     auto DontAlignThisComment = [](const auto *Tok) {
1155       if (Tok->is(tok::semi)) {
1156         Tok = Tok->getPreviousNonComment();
1157         if (!Tok)
1158           return false;
1159       }
1160       if (Tok->is(tok::r_paren)) {
1161         // Back up past the parentheses and a `TT_DoWhile` that may precede.
1162         Tok = Tok->MatchingParen;
1163         if (!Tok)
1164           return false;
1165         Tok = Tok->getPreviousNonComment();
1166         if (!Tok)
1167           return false;
1168         if (Tok->is(TT_DoWhile)) {
1169           const auto *Prev = Tok->getPreviousNonComment();
1170           if (!Prev) {
1171             // A do-while-loop without braces.
1172             return true;
1173           }
1174           Tok = Prev;
1175         }
1176       }
1177 
1178       if (Tok->isNot(tok::r_brace))
1179         return false;
1180 
1181       while (Tok->Previous && Tok->Previous->is(tok::r_brace))
1182         Tok = Tok->Previous;
1183       return Tok->NewlinesBefore > 0;
1184     };
1185 
1186     if (I > 0 && C.NewlinesBefore == 0 &&
1187         DontAlignThisComment(Changes[I - 1].Tok)) {
1188       alignTrailingComments(StartOfSequence, I, MinColumn);
1189       // Reset to initial values, but skip this change for the next alignment
1190       // pass.
1191       MinColumn = 0;
1192       MaxColumn = INT_MAX;
1193       StartOfSequence = I + 1;
1194     } else if (BreakBeforeNext || Newlines > NewLineThreshold ||
1195                (ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn) ||
1196                // Break the comment sequence if the previous line did not end
1197                // in a trailing comment.
1198                (C.NewlinesBefore == 1 && I > 0 &&
1199                 !Changes[I - 1].IsTrailingComment) ||
1200                WasAlignedWithStartOfNextLine) {
1201       alignTrailingComments(StartOfSequence, I, MinColumn);
1202       MinColumn = ChangeMinColumn;
1203       MaxColumn = ChangeMaxColumn;
1204       StartOfSequence = I;
1205     } else {
1206       MinColumn = std::max(MinColumn, ChangeMinColumn);
1207       MaxColumn = std::min(MaxColumn, ChangeMaxColumn);
1208     }
1209     BreakBeforeNext = (I == 0) || (C.NewlinesBefore > 1) ||
1210                       // Never start a sequence with a comment at the beginning
1211                       // of the line.
1212                       (C.NewlinesBefore == 1 && StartOfSequence == I);
1213     Newlines = 0;
1214   }
1215   alignTrailingComments(StartOfSequence, Size, MinColumn);
1216 }
1217 
1218 void WhitespaceManager::alignTrailingComments(unsigned Start, unsigned End,
1219                                               unsigned Column) {
1220   for (unsigned i = Start; i != End; ++i) {
1221     int Shift = 0;
1222     if (Changes[i].IsTrailingComment)
1223       Shift = Column - Changes[i].StartOfTokenColumn;
1224     if (Changes[i].StartOfBlockComment) {
1225       Shift = Changes[i].IndentationOffset +
1226               Changes[i].StartOfBlockComment->StartOfTokenColumn -
1227               Changes[i].StartOfTokenColumn;
1228     }
1229     if (Shift <= 0)
1230       continue;
1231     Changes[i].Spaces += Shift;
1232     if (i + 1 != Changes.size())
1233       Changes[i + 1].PreviousEndOfTokenColumn += Shift;
1234     Changes[i].StartOfTokenColumn += Shift;
1235   }
1236 }
1237 
1238 void WhitespaceManager::alignEscapedNewlines() {
1239   if (Style.AlignEscapedNewlines == FormatStyle::ENAS_DontAlign)
1240     return;
1241 
1242   bool AlignLeft = Style.AlignEscapedNewlines == FormatStyle::ENAS_Left;
1243   unsigned MaxEndOfLine = AlignLeft ? 0 : Style.ColumnLimit;
1244   unsigned StartOfMacro = 0;
1245   for (unsigned i = 1, e = Changes.size(); i < e; ++i) {
1246     Change &C = Changes[i];
1247     if (C.NewlinesBefore > 0) {
1248       if (C.ContinuesPPDirective) {
1249         MaxEndOfLine = std::max(C.PreviousEndOfTokenColumn + 2, MaxEndOfLine);
1250       } else {
1251         alignEscapedNewlines(StartOfMacro + 1, i, MaxEndOfLine);
1252         MaxEndOfLine = AlignLeft ? 0 : Style.ColumnLimit;
1253         StartOfMacro = i;
1254       }
1255     }
1256   }
1257   alignEscapedNewlines(StartOfMacro + 1, Changes.size(), MaxEndOfLine);
1258 }
1259 
1260 void WhitespaceManager::alignEscapedNewlines(unsigned Start, unsigned End,
1261                                              unsigned Column) {
1262   for (unsigned i = Start; i < End; ++i) {
1263     Change &C = Changes[i];
1264     if (C.NewlinesBefore > 0) {
1265       assert(C.ContinuesPPDirective);
1266       if (C.PreviousEndOfTokenColumn + 1 > Column)
1267         C.EscapedNewlineColumn = 0;
1268       else
1269         C.EscapedNewlineColumn = Column;
1270     }
1271   }
1272 }
1273 
1274 void WhitespaceManager::alignArrayInitializers() {
1275   if (Style.AlignArrayOfStructures == FormatStyle::AIAS_None)
1276     return;
1277 
1278   for (unsigned ChangeIndex = 1U, ChangeEnd = Changes.size();
1279        ChangeIndex < ChangeEnd; ++ChangeIndex) {
1280     auto &C = Changes[ChangeIndex];
1281     if (C.Tok->IsArrayInitializer) {
1282       bool FoundComplete = false;
1283       for (unsigned InsideIndex = ChangeIndex + 1; InsideIndex < ChangeEnd;
1284            ++InsideIndex) {
1285         if (Changes[InsideIndex].Tok == C.Tok->MatchingParen) {
1286           alignArrayInitializers(ChangeIndex, InsideIndex + 1);
1287           ChangeIndex = InsideIndex + 1;
1288           FoundComplete = true;
1289           break;
1290         }
1291       }
1292       if (!FoundComplete)
1293         ChangeIndex = ChangeEnd;
1294     }
1295   }
1296 }
1297 
1298 void WhitespaceManager::alignArrayInitializers(unsigned Start, unsigned End) {
1299 
1300   if (Style.AlignArrayOfStructures == FormatStyle::AIAS_Right)
1301     alignArrayInitializersRightJustified(getCells(Start, End));
1302   else if (Style.AlignArrayOfStructures == FormatStyle::AIAS_Left)
1303     alignArrayInitializersLeftJustified(getCells(Start, End));
1304 }
1305 
1306 void WhitespaceManager::alignArrayInitializersRightJustified(
1307     CellDescriptions &&CellDescs) {
1308   if (!CellDescs.isRectangular())
1309     return;
1310 
1311   const int BracePadding = Style.Cpp11BracedListStyle ? 0 : 1;
1312   auto &Cells = CellDescs.Cells;
1313   // Now go through and fixup the spaces.
1314   auto *CellIter = Cells.begin();
1315   for (auto i = 0U; i < CellDescs.CellCounts[0]; ++i, ++CellIter) {
1316     unsigned NetWidth = 0U;
1317     if (isSplitCell(*CellIter))
1318       NetWidth = getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces);
1319     auto CellWidth = getMaximumCellWidth(CellIter, NetWidth);
1320 
1321     if (Changes[CellIter->Index].Tok->is(tok::r_brace)) {
1322       // So in here we want to see if there is a brace that falls
1323       // on a line that was split. If so on that line we make sure that
1324       // the spaces in front of the brace are enough.
1325       const auto *Next = CellIter;
1326       do {
1327         const FormatToken *Previous = Changes[Next->Index].Tok->Previous;
1328         if (Previous && Previous->isNot(TT_LineComment)) {
1329           Changes[Next->Index].Spaces = BracePadding;
1330           Changes[Next->Index].NewlinesBefore = 0;
1331         }
1332         Next = Next->NextColumnElement;
1333       } while (Next);
1334       // Unless the array is empty, we need the position of all the
1335       // immediately adjacent cells
1336       if (CellIter != Cells.begin()) {
1337         auto ThisNetWidth =
1338             getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces);
1339         auto MaxNetWidth = getMaximumNetWidth(
1340             Cells.begin(), CellIter, CellDescs.InitialSpaces,
1341             CellDescs.CellCounts[0], CellDescs.CellCounts.size());
1342         if (ThisNetWidth < MaxNetWidth)
1343           Changes[CellIter->Index].Spaces = (MaxNetWidth - ThisNetWidth);
1344         auto RowCount = 1U;
1345         auto Offset = std::distance(Cells.begin(), CellIter);
1346         for (const auto *Next = CellIter->NextColumnElement; Next;
1347              Next = Next->NextColumnElement) {
1348           if (RowCount >= CellDescs.CellCounts.size())
1349             break;
1350           auto *Start = (Cells.begin() + RowCount * CellDescs.CellCounts[0]);
1351           auto *End = Start + Offset;
1352           ThisNetWidth = getNetWidth(Start, End, CellDescs.InitialSpaces);
1353           if (ThisNetWidth < MaxNetWidth)
1354             Changes[Next->Index].Spaces = (MaxNetWidth - ThisNetWidth);
1355           ++RowCount;
1356         }
1357       }
1358     } else {
1359       auto ThisWidth =
1360           calculateCellWidth(CellIter->Index, CellIter->EndIndex, true) +
1361           NetWidth;
1362       if (Changes[CellIter->Index].NewlinesBefore == 0) {
1363         Changes[CellIter->Index].Spaces = (CellWidth - (ThisWidth + NetWidth));
1364         Changes[CellIter->Index].Spaces += (i > 0) ? 1 : BracePadding;
1365       }
1366       alignToStartOfCell(CellIter->Index, CellIter->EndIndex);
1367       for (const auto *Next = CellIter->NextColumnElement; Next;
1368            Next = Next->NextColumnElement) {
1369         ThisWidth =
1370             calculateCellWidth(Next->Index, Next->EndIndex, true) + NetWidth;
1371         if (Changes[Next->Index].NewlinesBefore == 0) {
1372           Changes[Next->Index].Spaces = (CellWidth - ThisWidth);
1373           Changes[Next->Index].Spaces += (i > 0) ? 1 : BracePadding;
1374         }
1375         alignToStartOfCell(Next->Index, Next->EndIndex);
1376       }
1377     }
1378   }
1379 }
1380 
1381 void WhitespaceManager::alignArrayInitializersLeftJustified(
1382     CellDescriptions &&CellDescs) {
1383 
1384   if (!CellDescs.isRectangular())
1385     return;
1386 
1387   const int BracePadding = Style.Cpp11BracedListStyle ? 0 : 1;
1388   auto &Cells = CellDescs.Cells;
1389   // Now go through and fixup the spaces.
1390   auto *CellIter = Cells.begin();
1391   // The first cell of every row needs to be against the left brace.
1392   for (const auto *Next = CellIter; Next; Next = Next->NextColumnElement) {
1393     auto &Change = Changes[Next->Index];
1394     Change.Spaces =
1395         Change.NewlinesBefore == 0 ? BracePadding : CellDescs.InitialSpaces;
1396   }
1397   ++CellIter;
1398   for (auto i = 1U; i < CellDescs.CellCounts[0]; i++, ++CellIter) {
1399     auto MaxNetWidth = getMaximumNetWidth(
1400         Cells.begin(), CellIter, CellDescs.InitialSpaces,
1401         CellDescs.CellCounts[0], CellDescs.CellCounts.size());
1402     auto ThisNetWidth =
1403         getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces);
1404     if (Changes[CellIter->Index].NewlinesBefore == 0) {
1405       Changes[CellIter->Index].Spaces =
1406           MaxNetWidth - ThisNetWidth +
1407           (Changes[CellIter->Index].Tok->isNot(tok::r_brace) ? 1
1408                                                              : BracePadding);
1409     }
1410     auto RowCount = 1U;
1411     auto Offset = std::distance(Cells.begin(), CellIter);
1412     for (const auto *Next = CellIter->NextColumnElement; Next;
1413          Next = Next->NextColumnElement) {
1414       if (RowCount >= CellDescs.CellCounts.size())
1415         break;
1416       auto *Start = (Cells.begin() + RowCount * CellDescs.CellCounts[0]);
1417       auto *End = Start + Offset;
1418       auto ThisNetWidth = getNetWidth(Start, End, CellDescs.InitialSpaces);
1419       if (Changes[Next->Index].NewlinesBefore == 0) {
1420         Changes[Next->Index].Spaces =
1421             MaxNetWidth - ThisNetWidth +
1422             (Changes[Next->Index].Tok->isNot(tok::r_brace) ? 1 : BracePadding);
1423       }
1424       ++RowCount;
1425     }
1426   }
1427 }
1428 
1429 bool WhitespaceManager::isSplitCell(const CellDescription &Cell) {
1430   if (Cell.HasSplit)
1431     return true;
1432   for (const auto *Next = Cell.NextColumnElement; Next;
1433        Next = Next->NextColumnElement) {
1434     if (Next->HasSplit)
1435       return true;
1436   }
1437   return false;
1438 }
1439 
1440 WhitespaceManager::CellDescriptions WhitespaceManager::getCells(unsigned Start,
1441                                                                 unsigned End) {
1442 
1443   unsigned Depth = 0;
1444   unsigned Cell = 0;
1445   SmallVector<unsigned> CellCounts;
1446   unsigned InitialSpaces = 0;
1447   unsigned InitialTokenLength = 0;
1448   unsigned EndSpaces = 0;
1449   SmallVector<CellDescription> Cells;
1450   const FormatToken *MatchingParen = nullptr;
1451   for (unsigned i = Start; i < End; ++i) {
1452     auto &C = Changes[i];
1453     if (C.Tok->is(tok::l_brace))
1454       ++Depth;
1455     else if (C.Tok->is(tok::r_brace))
1456       --Depth;
1457     if (Depth == 2) {
1458       if (C.Tok->is(tok::l_brace)) {
1459         Cell = 0;
1460         MatchingParen = C.Tok->MatchingParen;
1461         if (InitialSpaces == 0) {
1462           InitialSpaces = C.Spaces + C.TokenLength;
1463           InitialTokenLength = C.TokenLength;
1464           auto j = i - 1;
1465           for (; Changes[j].NewlinesBefore == 0 && j > Start; --j) {
1466             InitialSpaces += Changes[j].Spaces + Changes[j].TokenLength;
1467             InitialTokenLength += Changes[j].TokenLength;
1468           }
1469           if (C.NewlinesBefore == 0) {
1470             InitialSpaces += Changes[j].Spaces + Changes[j].TokenLength;
1471             InitialTokenLength += Changes[j].TokenLength;
1472           }
1473         }
1474       } else if (C.Tok->is(tok::comma)) {
1475         if (!Cells.empty())
1476           Cells.back().EndIndex = i;
1477         if (const auto *Next = C.Tok->getNextNonComment();
1478             Next && Next->isNot(tok::r_brace)) { // dangling comma
1479           ++Cell;
1480         }
1481       }
1482     } else if (Depth == 1) {
1483       if (C.Tok == MatchingParen) {
1484         if (!Cells.empty())
1485           Cells.back().EndIndex = i;
1486         Cells.push_back(CellDescription{i, ++Cell, i + 1, false, nullptr});
1487         CellCounts.push_back(C.Tok->Previous->isNot(tok::comma) ? Cell + 1
1488                                                                 : Cell);
1489         // Go to the next non-comment and ensure there is a break in front
1490         const auto *NextNonComment = C.Tok->getNextNonComment();
1491         while (NextNonComment && NextNonComment->is(tok::comma))
1492           NextNonComment = NextNonComment->getNextNonComment();
1493         auto j = i;
1494         while (j < End && Changes[j].Tok != NextNonComment)
1495           ++j;
1496         if (j < End && Changes[j].NewlinesBefore == 0 &&
1497             Changes[j].Tok->isNot(tok::r_brace)) {
1498           Changes[j].NewlinesBefore = 1;
1499           // Account for the added token lengths
1500           Changes[j].Spaces = InitialSpaces - InitialTokenLength;
1501         }
1502       } else if (C.Tok->is(tok::comment) && C.Tok->NewlinesBefore == 0) {
1503         // Trailing comments stay at a space past the last token
1504         C.Spaces = Changes[i - 1].Tok->is(tok::comma) ? 1 : 2;
1505       } else if (C.Tok->is(tok::l_brace)) {
1506         // We need to make sure that the ending braces is aligned to the
1507         // start of our initializer
1508         auto j = i - 1;
1509         for (; j > 0 && !Changes[j].Tok->ArrayInitializerLineStart; --j)
1510           ; // Nothing the loop does the work
1511         EndSpaces = Changes[j].Spaces;
1512       }
1513     } else if (Depth == 0 && C.Tok->is(tok::r_brace)) {
1514       C.NewlinesBefore = 1;
1515       C.Spaces = EndSpaces;
1516     }
1517     if (C.Tok->StartsColumn) {
1518       // This gets us past tokens that have been split over multiple
1519       // lines
1520       bool HasSplit = false;
1521       if (Changes[i].NewlinesBefore > 0) {
1522         // So if we split a line previously and the tail line + this token is
1523         // less then the column limit we remove the split here and just put
1524         // the column start at a space past the comma
1525         //
1526         // FIXME This if branch covers the cases where the column is not
1527         // the first column. This leads to weird pathologies like the formatting
1528         // auto foo = Items{
1529         //     Section{
1530         //             0, bar(),
1531         //     }
1532         // };
1533         // Well if it doesn't lead to that it's indicative that the line
1534         // breaking should be revisited. Unfortunately alot of other options
1535         // interact with this
1536         auto j = i - 1;
1537         if ((j - 1) > Start && Changes[j].Tok->is(tok::comma) &&
1538             Changes[j - 1].NewlinesBefore > 0) {
1539           --j;
1540           auto LineLimit = Changes[j].Spaces + Changes[j].TokenLength;
1541           if (LineLimit < Style.ColumnLimit) {
1542             Changes[i].NewlinesBefore = 0;
1543             Changes[i].Spaces = 1;
1544           }
1545         }
1546       }
1547       while (Changes[i].NewlinesBefore > 0 && Changes[i].Tok == C.Tok) {
1548         Changes[i].Spaces = InitialSpaces;
1549         ++i;
1550         HasSplit = true;
1551       }
1552       if (Changes[i].Tok != C.Tok)
1553         --i;
1554       Cells.push_back(CellDescription{i, Cell, i, HasSplit, nullptr});
1555     }
1556   }
1557 
1558   return linkCells({Cells, CellCounts, InitialSpaces});
1559 }
1560 
1561 unsigned WhitespaceManager::calculateCellWidth(unsigned Start, unsigned End,
1562                                                bool WithSpaces) const {
1563   unsigned CellWidth = 0;
1564   for (auto i = Start; i < End; i++) {
1565     if (Changes[i].NewlinesBefore > 0)
1566       CellWidth = 0;
1567     CellWidth += Changes[i].TokenLength;
1568     CellWidth += (WithSpaces ? Changes[i].Spaces : 0);
1569   }
1570   return CellWidth;
1571 }
1572 
1573 void WhitespaceManager::alignToStartOfCell(unsigned Start, unsigned End) {
1574   if ((End - Start) <= 1)
1575     return;
1576   // If the line is broken anywhere in there make sure everything
1577   // is aligned to the parent
1578   for (auto i = Start + 1; i < End; i++)
1579     if (Changes[i].NewlinesBefore > 0)
1580       Changes[i].Spaces = Changes[Start].Spaces;
1581 }
1582 
1583 WhitespaceManager::CellDescriptions
1584 WhitespaceManager::linkCells(CellDescriptions &&CellDesc) {
1585   auto &Cells = CellDesc.Cells;
1586   for (auto *CellIter = Cells.begin(); CellIter != Cells.end(); ++CellIter) {
1587     if (!CellIter->NextColumnElement && (CellIter + 1) != Cells.end()) {
1588       for (auto *NextIter = CellIter + 1; NextIter != Cells.end(); ++NextIter) {
1589         if (NextIter->Cell == CellIter->Cell) {
1590           CellIter->NextColumnElement = &(*NextIter);
1591           break;
1592         }
1593       }
1594     }
1595   }
1596   return std::move(CellDesc);
1597 }
1598 
1599 void WhitespaceManager::generateChanges() {
1600   for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
1601     const Change &C = Changes[i];
1602     if (i > 0) {
1603       auto Last = Changes[i - 1].OriginalWhitespaceRange;
1604       auto New = Changes[i].OriginalWhitespaceRange;
1605       // Do not generate two replacements for the same location.  As a special
1606       // case, it is allowed if there is a replacement for the empty range
1607       // between 2 tokens and another non-empty range at the start of the second
1608       // token.  We didn't implement logic to combine replacements for 2
1609       // consecutive source ranges into a single replacement, because the
1610       // program works fine without it.
1611       //
1612       // We can't eliminate empty original whitespace ranges.  They appear when
1613       // 2 tokens have no whitespace in between in the input.  It does not
1614       // matter whether whitespace is to be added.  If no whitespace is to be
1615       // added, the replacement will be empty, and it gets eliminated after this
1616       // step in storeReplacement.  For example, if the input is `foo();`,
1617       // there will be a replacement for the range between every consecutive
1618       // pair of tokens.
1619       //
1620       // A replacement at the start of a token can be added by
1621       // BreakableStringLiteralUsingOperators::insertBreak when it adds braces
1622       // around the string literal.  Say Verilog code is being formatted and the
1623       // first line is to become the next 2 lines.
1624       //     x("long string");
1625       //     x({"long ",
1626       //        "string"});
1627       // There will be a replacement for the empty range between the parenthesis
1628       // and the string and another replacement for the quote character.  The
1629       // replacement for the empty range between the parenthesis and the quote
1630       // comes from ContinuationIndenter::addTokenOnCurrentLine when it changes
1631       // the original empty range between the parenthesis and the string to
1632       // another empty one.  The replacement for the quote character comes from
1633       // BreakableStringLiteralUsingOperators::insertBreak when it adds the
1634       // brace.  In the example, the replacement for the empty range is the same
1635       // as the original text.  However, eliminating replacements that are same
1636       // as the original does not help in general.  For example, a newline can
1637       // be inserted, causing the first line to become the next 3 lines.
1638       //     xxxxxxxxxxx("long string");
1639       //     xxxxxxxxxxx(
1640       //         {"long ",
1641       //          "string"});
1642       // In that case, the empty range between the parenthesis and the string
1643       // will be replaced by a newline and 4 spaces.  So we will still have to
1644       // deal with a replacement for an empty source range followed by a
1645       // replacement for a non-empty source range.
1646       if (Last.getBegin() == New.getBegin() &&
1647           (Last.getEnd() != Last.getBegin() ||
1648            New.getEnd() == New.getBegin())) {
1649         continue;
1650       }
1651     }
1652     if (C.CreateReplacement) {
1653       std::string ReplacementText = C.PreviousLinePostfix;
1654       if (C.ContinuesPPDirective) {
1655         appendEscapedNewlineText(ReplacementText, C.NewlinesBefore,
1656                                  C.PreviousEndOfTokenColumn,
1657                                  C.EscapedNewlineColumn);
1658       } else {
1659         appendNewlineText(ReplacementText, C.NewlinesBefore);
1660       }
1661       // FIXME: This assert should hold if we computed the column correctly.
1662       // assert((int)C.StartOfTokenColumn >= C.Spaces);
1663       appendIndentText(
1664           ReplacementText, C.Tok->IndentLevel, std::max(0, C.Spaces),
1665           std::max((int)C.StartOfTokenColumn, C.Spaces) - std::max(0, C.Spaces),
1666           C.IsAligned);
1667       ReplacementText.append(C.CurrentLinePrefix);
1668       storeReplacement(C.OriginalWhitespaceRange, ReplacementText);
1669     }
1670   }
1671 }
1672 
1673 void WhitespaceManager::storeReplacement(SourceRange Range, StringRef Text) {
1674   unsigned WhitespaceLength = SourceMgr.getFileOffset(Range.getEnd()) -
1675                               SourceMgr.getFileOffset(Range.getBegin());
1676   // Don't create a replacement, if it does not change anything.
1677   if (StringRef(SourceMgr.getCharacterData(Range.getBegin()),
1678                 WhitespaceLength) == Text) {
1679     return;
1680   }
1681   auto Err = Replaces.add(tooling::Replacement(
1682       SourceMgr, CharSourceRange::getCharRange(Range), Text));
1683   // FIXME: better error handling. For now, just print an error message in the
1684   // release version.
1685   if (Err) {
1686     llvm::errs() << llvm::toString(std::move(Err)) << "\n";
1687     assert(false);
1688   }
1689 }
1690 
1691 void WhitespaceManager::appendNewlineText(std::string &Text,
1692                                           unsigned Newlines) {
1693   if (UseCRLF) {
1694     Text.reserve(Text.size() + 2 * Newlines);
1695     for (unsigned i = 0; i < Newlines; ++i)
1696       Text.append("\r\n");
1697   } else {
1698     Text.append(Newlines, '\n');
1699   }
1700 }
1701 
1702 void WhitespaceManager::appendEscapedNewlineText(
1703     std::string &Text, unsigned Newlines, unsigned PreviousEndOfTokenColumn,
1704     unsigned EscapedNewlineColumn) {
1705   if (Newlines > 0) {
1706     unsigned Spaces =
1707         std::max<int>(1, EscapedNewlineColumn - PreviousEndOfTokenColumn - 1);
1708     for (unsigned i = 0; i < Newlines; ++i) {
1709       Text.append(Spaces, ' ');
1710       Text.append(UseCRLF ? "\\\r\n" : "\\\n");
1711       Spaces = std::max<int>(0, EscapedNewlineColumn - 1);
1712     }
1713   }
1714 }
1715 
1716 void WhitespaceManager::appendIndentText(std::string &Text,
1717                                          unsigned IndentLevel, unsigned Spaces,
1718                                          unsigned WhitespaceStartColumn,
1719                                          bool IsAligned) {
1720   switch (Style.UseTab) {
1721   case FormatStyle::UT_Never:
1722     Text.append(Spaces, ' ');
1723     break;
1724   case FormatStyle::UT_Always: {
1725     if (Style.TabWidth) {
1726       unsigned FirstTabWidth =
1727           Style.TabWidth - WhitespaceStartColumn % Style.TabWidth;
1728 
1729       // Insert only spaces when we want to end up before the next tab.
1730       if (Spaces < FirstTabWidth || Spaces == 1) {
1731         Text.append(Spaces, ' ');
1732         break;
1733       }
1734       // Align to the next tab.
1735       Spaces -= FirstTabWidth;
1736       Text.append("\t");
1737 
1738       Text.append(Spaces / Style.TabWidth, '\t');
1739       Text.append(Spaces % Style.TabWidth, ' ');
1740     } else if (Spaces == 1) {
1741       Text.append(Spaces, ' ');
1742     }
1743     break;
1744   }
1745   case FormatStyle::UT_ForIndentation:
1746     if (WhitespaceStartColumn == 0) {
1747       unsigned Indentation = IndentLevel * Style.IndentWidth;
1748       Spaces = appendTabIndent(Text, Spaces, Indentation);
1749     }
1750     Text.append(Spaces, ' ');
1751     break;
1752   case FormatStyle::UT_ForContinuationAndIndentation:
1753     if (WhitespaceStartColumn == 0)
1754       Spaces = appendTabIndent(Text, Spaces, Spaces);
1755     Text.append(Spaces, ' ');
1756     break;
1757   case FormatStyle::UT_AlignWithSpaces:
1758     if (WhitespaceStartColumn == 0) {
1759       unsigned Indentation =
1760           IsAligned ? IndentLevel * Style.IndentWidth : Spaces;
1761       Spaces = appendTabIndent(Text, Spaces, Indentation);
1762     }
1763     Text.append(Spaces, ' ');
1764     break;
1765   }
1766 }
1767 
1768 unsigned WhitespaceManager::appendTabIndent(std::string &Text, unsigned Spaces,
1769                                             unsigned Indentation) {
1770   // This happens, e.g. when a line in a block comment is indented less than the
1771   // first one.
1772   if (Indentation > Spaces)
1773     Indentation = Spaces;
1774   if (Style.TabWidth) {
1775     unsigned Tabs = Indentation / Style.TabWidth;
1776     Text.append(Tabs, '\t');
1777     Spaces -= Tabs * Style.TabWidth;
1778   }
1779   return Spaces;
1780 }
1781 
1782 } // namespace format
1783 } // namespace clang
1784