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