xref: /llvm-project/clang/lib/Format/WhitespaceManager.cpp (revision dba2aa265c5f2ef774c2812cf6ffdea8dd784e09)
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(/*IsExpr=*/true);
111   alignConsecutiveShortCaseStatements(/*IsExpr=*/false);
112   alignConsecutiveDeclarations();
113   alignConsecutiveBitFields();
114   alignConsecutiveAssignments();
115   if (Style.isTableGen()) {
116     alignConsecutiveTableGenBreakingDAGArgColons();
117     alignConsecutiveTableGenCondOperatorColons();
118     alignConsecutiveTableGenDefinitions();
119   }
120   alignChainedConditionals();
121   alignTrailingComments();
122   alignEscapedNewlines();
123   alignArrayInitializers();
124   generateChanges();
125 
126   return Replaces;
127 }
128 
129 void WhitespaceManager::calculateLineBreakInformation() {
130   Changes[0].PreviousEndOfTokenColumn = 0;
131   Change *LastOutsideTokenChange = &Changes[0];
132   for (unsigned I = 1, e = Changes.size(); I != e; ++I) {
133     auto &C = Changes[I];
134     auto &P = Changes[I - 1];
135     auto &PrevTokLength = P.TokenLength;
136     SourceLocation OriginalWhitespaceStart =
137         C.OriginalWhitespaceRange.getBegin();
138     SourceLocation PreviousOriginalWhitespaceEnd =
139         P.OriginalWhitespaceRange.getEnd();
140     unsigned OriginalWhitespaceStartOffset =
141         SourceMgr.getFileOffset(OriginalWhitespaceStart);
142     unsigned PreviousOriginalWhitespaceEndOffset =
143         SourceMgr.getFileOffset(PreviousOriginalWhitespaceEnd);
144     assert(PreviousOriginalWhitespaceEndOffset <=
145            OriginalWhitespaceStartOffset);
146     const char *const PreviousOriginalWhitespaceEndData =
147         SourceMgr.getCharacterData(PreviousOriginalWhitespaceEnd);
148     StringRef Text(PreviousOriginalWhitespaceEndData,
149                    SourceMgr.getCharacterData(OriginalWhitespaceStart) -
150                        PreviousOriginalWhitespaceEndData);
151     // Usually consecutive changes would occur in consecutive tokens. This is
152     // not the case however when analyzing some preprocessor runs of the
153     // annotated lines. For example, in this code:
154     //
155     // #if A // line 1
156     // int i = 1;
157     // #else B // line 2
158     // int i = 2;
159     // #endif // line 3
160     //
161     // one of the runs will produce the sequence of lines marked with line 1, 2
162     // and 3. So the two consecutive whitespace changes just before '// line 2'
163     // and before '#endif // line 3' span multiple lines and tokens:
164     //
165     // #else B{change X}[// line 2
166     // int i = 2;
167     // ]{change Y}#endif // line 3
168     //
169     // For this reason, if the text between consecutive changes spans multiple
170     // newlines, the token length must be adjusted to the end of the original
171     // line of the token.
172     auto NewlinePos = Text.find_first_of('\n');
173     if (NewlinePos == StringRef::npos) {
174       PrevTokLength = OriginalWhitespaceStartOffset -
175                       PreviousOriginalWhitespaceEndOffset +
176                       C.PreviousLinePostfix.size() + P.CurrentLinePrefix.size();
177       if (!P.IsInsideToken)
178         PrevTokLength = std::min(PrevTokLength, P.Tok->ColumnWidth);
179     } else {
180       PrevTokLength = NewlinePos + P.CurrentLinePrefix.size();
181     }
182 
183     // If there are multiple changes in this token, sum up all the changes until
184     // the end of the line.
185     if (P.IsInsideToken && P.NewlinesBefore == 0)
186       LastOutsideTokenChange->TokenLength += PrevTokLength + P.Spaces;
187     else
188       LastOutsideTokenChange = &P;
189 
190     C.PreviousEndOfTokenColumn = P.StartOfTokenColumn + PrevTokLength;
191 
192     P.IsTrailingComment =
193         (C.NewlinesBefore > 0 || C.Tok->is(tok::eof) ||
194          (C.IsInsideToken && C.Tok->is(tok::comment))) &&
195         P.Tok->is(tok::comment) &&
196         // FIXME: This is a dirty hack. The problem is that
197         // BreakableLineCommentSection does comment reflow changes and here is
198         // the aligning of trailing comments. Consider the case where we reflow
199         // the second line up in this example:
200         //
201         // // line 1
202         // // line 2
203         //
204         // That amounts to 2 changes by BreakableLineCommentSection:
205         //  - the first, delimited by (), for the whitespace between the tokens,
206         //  - and second, delimited by [], for the whitespace at the beginning
207         //  of the second token:
208         //
209         // // line 1(
210         // )[// ]line 2
211         //
212         // So in the end we have two changes like this:
213         //
214         // // line1()[ ]line 2
215         //
216         // Note that the OriginalWhitespaceStart of the second change is the
217         // same as the PreviousOriginalWhitespaceEnd of the first change.
218         // In this case, the below check ensures that the second change doesn't
219         // get treated as a trailing comment change here, since this might
220         // trigger additional whitespace to be wrongly inserted before "line 2"
221         // by the comment aligner here.
222         //
223         // For a proper solution we need a mechanism to say to WhitespaceManager
224         // that a particular change breaks the current sequence of trailing
225         // comments.
226         OriginalWhitespaceStart != PreviousOriginalWhitespaceEnd;
227   }
228   // FIXME: The last token is currently not always an eof token; in those
229   // cases, setting TokenLength of the last token to 0 is wrong.
230   Changes.back().TokenLength = 0;
231   Changes.back().IsTrailingComment = Changes.back().Tok->is(tok::comment);
232 
233   const WhitespaceManager::Change *LastBlockComment = nullptr;
234   for (auto &Change : Changes) {
235     // Reset the IsTrailingComment flag for changes inside of trailing comments
236     // so they don't get realigned later. Comment line breaks however still need
237     // to be aligned.
238     if (Change.IsInsideToken && Change.NewlinesBefore == 0)
239       Change.IsTrailingComment = false;
240     Change.StartOfBlockComment = nullptr;
241     Change.IndentationOffset = 0;
242     if (Change.Tok->is(tok::comment)) {
243       if (Change.Tok->is(TT_LineComment) || !Change.IsInsideToken) {
244         LastBlockComment = &Change;
245       } else if ((Change.StartOfBlockComment = LastBlockComment)) {
246         Change.IndentationOffset =
247             Change.StartOfTokenColumn -
248             Change.StartOfBlockComment->StartOfTokenColumn;
249       }
250     } else {
251       LastBlockComment = nullptr;
252     }
253   }
254 
255   // Compute conditional nesting level
256   // Level is increased for each conditional, unless this conditional continues
257   // a chain of conditional, i.e. starts immediately after the colon of another
258   // conditional.
259   SmallVector<bool, 16> ScopeStack;
260   int ConditionalsLevel = 0;
261   for (auto &Change : Changes) {
262     for (unsigned i = 0, e = Change.Tok->FakeLParens.size(); i != e; ++i) {
263       bool isNestedConditional =
264           Change.Tok->FakeLParens[e - 1 - i] == prec::Conditional &&
265           !(i == 0 && Change.Tok->Previous &&
266             Change.Tok->Previous->is(TT_ConditionalExpr) &&
267             Change.Tok->Previous->is(tok::colon));
268       if (isNestedConditional)
269         ++ConditionalsLevel;
270       ScopeStack.push_back(isNestedConditional);
271     }
272 
273     Change.ConditionalsLevel = ConditionalsLevel;
274 
275     for (unsigned i = Change.Tok->FakeRParens; i > 0 && ScopeStack.size(); --i)
276       if (ScopeStack.pop_back_val())
277         --ConditionalsLevel;
278   }
279 }
280 
281 // Align a single sequence of tokens, see AlignTokens below.
282 // Column - The token for which Matches returns true is moved to this column.
283 // RightJustify - Whether it is the token's right end or left end that gets
284 // moved to that column.
285 template <typename F>
286 static void
287 AlignTokenSequence(const FormatStyle &Style, unsigned Start, unsigned End,
288                    unsigned Column, bool RightJustify, F &&Matches,
289                    SmallVector<WhitespaceManager::Change, 16> &Changes) {
290   bool FoundMatchOnLine = false;
291   int Shift = 0;
292 
293   // ScopeStack keeps track of the current scope depth. It contains indices of
294   // the first token on each scope.
295   // We only run the "Matches" function on tokens from the outer-most scope.
296   // However, we do need to pay special attention to one class of tokens
297   // that are not in the outer-most scope, and that is function parameters
298   // which are split across multiple lines, as illustrated by this example:
299   //   double a(int x);
300   //   int    b(int  y,
301   //          double z);
302   // In the above example, we need to take special care to ensure that
303   // 'double z' is indented along with it's owning function 'b'.
304   // The same holds for calling a function:
305   //   double a = foo(x);
306   //   int    b = bar(foo(y),
307   //            foor(z));
308   // Similar for broken string literals:
309   //   double x = 3.14;
310   //   auto s   = "Hello"
311   //          "World";
312   // Special handling is required for 'nested' ternary operators.
313   SmallVector<unsigned, 16> ScopeStack;
314 
315   for (unsigned i = Start; i != End; ++i) {
316     auto &CurrentChange = Changes[i];
317     if (ScopeStack.size() != 0 &&
318         CurrentChange.indentAndNestingLevel() <
319             Changes[ScopeStack.back()].indentAndNestingLevel()) {
320       ScopeStack.pop_back();
321     }
322 
323     // Compare current token to previous non-comment token to ensure whether
324     // it is in a deeper scope or not.
325     unsigned PreviousNonComment = i - 1;
326     while (PreviousNonComment > Start &&
327            Changes[PreviousNonComment].Tok->is(tok::comment)) {
328       --PreviousNonComment;
329     }
330     if (i != Start && CurrentChange.indentAndNestingLevel() >
331                           Changes[PreviousNonComment].indentAndNestingLevel()) {
332       ScopeStack.push_back(i);
333     }
334 
335     bool InsideNestedScope = ScopeStack.size() != 0;
336     bool ContinuedStringLiteral = i > Start &&
337                                   CurrentChange.Tok->is(tok::string_literal) &&
338                                   Changes[i - 1].Tok->is(tok::string_literal);
339     bool SkipMatchCheck = InsideNestedScope || ContinuedStringLiteral;
340 
341     if (CurrentChange.NewlinesBefore > 0 && !SkipMatchCheck) {
342       Shift = 0;
343       FoundMatchOnLine = false;
344     }
345 
346     // If this is the first matching token to be aligned, remember by how many
347     // spaces it has to be shifted, so the rest of the changes on the line are
348     // shifted by the same amount
349     if (!FoundMatchOnLine && !SkipMatchCheck && Matches(CurrentChange)) {
350       FoundMatchOnLine = true;
351       Shift = Column - (RightJustify ? CurrentChange.TokenLength : 0) -
352               CurrentChange.StartOfTokenColumn;
353       CurrentChange.Spaces += Shift;
354       // FIXME: This is a workaround that should be removed when we fix
355       // http://llvm.org/PR53699. An assertion later below verifies this.
356       if (CurrentChange.NewlinesBefore == 0) {
357         CurrentChange.Spaces =
358             std::max(CurrentChange.Spaces,
359                      static_cast<int>(CurrentChange.Tok->SpacesRequiredBefore));
360       }
361     }
362 
363     if (Shift == 0)
364       continue;
365 
366     // This is for function parameters that are split across multiple lines,
367     // as mentioned in the ScopeStack comment.
368     if (InsideNestedScope && CurrentChange.NewlinesBefore > 0) {
369       unsigned ScopeStart = ScopeStack.back();
370       auto ShouldShiftBeAdded = [&] {
371         // Function declaration
372         if (Changes[ScopeStart - 1].Tok->is(TT_FunctionDeclarationName))
373           return true;
374 
375         // Lambda.
376         if (Changes[ScopeStart - 1].Tok->is(TT_LambdaLBrace))
377           return false;
378 
379         // Continued function declaration
380         if (ScopeStart > Start + 1 &&
381             Changes[ScopeStart - 2].Tok->is(TT_FunctionDeclarationName)) {
382           return true;
383         }
384 
385         // Continued (template) function call.
386         if (ScopeStart > Start + 1 &&
387             Changes[ScopeStart - 2].Tok->isOneOf(tok::identifier,
388                                                  TT_TemplateCloser) &&
389             Changes[ScopeStart - 1].Tok->is(tok::l_paren) &&
390             Changes[ScopeStart].Tok->isNot(TT_LambdaLSquare)) {
391           if (CurrentChange.Tok->MatchingParen &&
392               CurrentChange.Tok->MatchingParen->is(TT_LambdaLBrace)) {
393             return false;
394           }
395           if (Changes[ScopeStart].NewlinesBefore > 0)
396             return false;
397           if (CurrentChange.Tok->is(tok::l_brace) &&
398               CurrentChange.Tok->is(BK_BracedInit)) {
399             return true;
400           }
401           return Style.BinPackArguments;
402         }
403 
404         // Ternary operator
405         if (CurrentChange.Tok->is(TT_ConditionalExpr))
406           return true;
407 
408         // Period Initializer .XXX = 1.
409         if (CurrentChange.Tok->is(TT_DesignatedInitializerPeriod))
410           return true;
411 
412         // Continued ternary operator
413         if (CurrentChange.Tok->Previous &&
414             CurrentChange.Tok->Previous->is(TT_ConditionalExpr)) {
415           return true;
416         }
417 
418         // Continued direct-list-initialization using braced list.
419         if (ScopeStart > Start + 1 &&
420             Changes[ScopeStart - 2].Tok->is(tok::identifier) &&
421             Changes[ScopeStart - 1].Tok->is(tok::l_brace) &&
422             CurrentChange.Tok->is(tok::l_brace) &&
423             CurrentChange.Tok->is(BK_BracedInit)) {
424           return true;
425         }
426 
427         // Continued braced list.
428         if (ScopeStart > Start + 1 &&
429             Changes[ScopeStart - 2].Tok->isNot(tok::identifier) &&
430             Changes[ScopeStart - 1].Tok->is(tok::l_brace) &&
431             CurrentChange.Tok->isNot(tok::r_brace)) {
432           for (unsigned OuterScopeStart : llvm::reverse(ScopeStack)) {
433             // Lambda.
434             if (OuterScopeStart > Start &&
435                 Changes[OuterScopeStart - 1].Tok->is(TT_LambdaLBrace)) {
436               return false;
437             }
438           }
439           if (Changes[ScopeStart].NewlinesBefore > 0)
440             return false;
441           return true;
442         }
443 
444         // Continued template parameter.
445         if (Changes[ScopeStart - 1].Tok->is(TT_TemplateOpener))
446           return true;
447 
448         return false;
449       };
450 
451       if (ShouldShiftBeAdded())
452         CurrentChange.Spaces += Shift;
453     }
454 
455     if (ContinuedStringLiteral)
456       CurrentChange.Spaces += Shift;
457 
458     // We should not remove required spaces unless we break the line before.
459     assert(Shift > 0 || Changes[i].NewlinesBefore > 0 ||
460            CurrentChange.Spaces >=
461                static_cast<int>(Changes[i].Tok->SpacesRequiredBefore) ||
462            CurrentChange.Tok->is(tok::eof));
463 
464     CurrentChange.StartOfTokenColumn += Shift;
465     if (i + 1 != Changes.size())
466       Changes[i + 1].PreviousEndOfTokenColumn += Shift;
467 
468     // If PointerAlignment is PAS_Right, keep *s or &s next to the token,
469     // except if the token is equal, then a space is needed.
470     if ((Style.PointerAlignment == FormatStyle::PAS_Right ||
471          Style.ReferenceAlignment == FormatStyle::RAS_Right) &&
472         CurrentChange.Spaces != 0 && CurrentChange.Tok->isNot(tok::equal)) {
473       const bool ReferenceNotRightAligned =
474           Style.ReferenceAlignment != FormatStyle::RAS_Right &&
475           Style.ReferenceAlignment != FormatStyle::RAS_Pointer;
476       for (int Previous = i - 1;
477            Previous >= 0 && Changes[Previous].Tok->is(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(bool IsExpr) {
883   if (!Style.AlignConsecutiveShortCaseStatements.Enabled ||
884       !(IsExpr ? Style.AllowShortCaseExpressionOnASingleLine
885                : Style.AllowShortCaseLabelsOnASingleLine)) {
886     return;
887   }
888 
889   const auto Type = IsExpr ? TT_CaseLabelArrow : TT_CaseLabelColon;
890   const auto &Option = Style.AlignConsecutiveShortCaseStatements;
891   const bool AlignArrowOrColon =
892       IsExpr ? Option.AlignCaseArrows : Option.AlignCaseColons;
893 
894   auto Matches = [&](const Change &C) {
895     if (AlignArrowOrColon)
896       return C.Tok->is(Type);
897 
898     // Ignore 'IsInsideToken' to allow matching trailing comments which
899     // need to be reflowed as that causes the token to appear in two
900     // different changes, which will cause incorrect alignment as we'll
901     // reflow early due to detecting multiple aligning tokens per line.
902     return !C.IsInsideToken && C.Tok->Previous && C.Tok->Previous->is(Type);
903   };
904 
905   unsigned MinColumn = 0;
906 
907   // Empty case statements don't break the alignment, but don't necessarily
908   // match our predicate, so we need to track their column so they can push out
909   // our alignment.
910   unsigned MinEmptyCaseColumn = 0;
911 
912   // Start and end of the token sequence we're processing.
913   unsigned StartOfSequence = 0;
914   unsigned EndOfSequence = 0;
915 
916   // Whether a matching token has been found on the current line.
917   bool FoundMatchOnLine = false;
918 
919   bool LineIsComment = true;
920   bool LineIsEmptyCase = false;
921 
922   unsigned I = 0;
923   for (unsigned E = Changes.size(); I != E; ++I) {
924     if (Changes[I].NewlinesBefore != 0) {
925       // Whether to break the alignment sequence because of an empty line.
926       bool EmptyLineBreak =
927           (Changes[I].NewlinesBefore > 1) &&
928           !Style.AlignConsecutiveShortCaseStatements.AcrossEmptyLines;
929 
930       // Whether to break the alignment sequence because of a line without a
931       // match.
932       bool NoMatchBreak =
933           !FoundMatchOnLine &&
934           !(LineIsComment &&
935             Style.AlignConsecutiveShortCaseStatements.AcrossComments) &&
936           !LineIsEmptyCase;
937 
938       if (EmptyLineBreak || NoMatchBreak) {
939         AlignMatchingTokenSequence(StartOfSequence, EndOfSequence, MinColumn,
940                                    Matches, Changes);
941         MinEmptyCaseColumn = 0;
942       }
943 
944       // A new line starts, re-initialize line status tracking bools.
945       FoundMatchOnLine = false;
946       LineIsComment = true;
947       LineIsEmptyCase = false;
948     }
949 
950     if (Changes[I].Tok->isNot(tok::comment))
951       LineIsComment = false;
952 
953     if (Changes[I].Tok->is(Type)) {
954       LineIsEmptyCase =
955           !Changes[I].Tok->Next || Changes[I].Tok->Next->isTrailingComment();
956 
957       if (LineIsEmptyCase) {
958         if (Style.AlignConsecutiveShortCaseStatements.AlignCaseColons) {
959           MinEmptyCaseColumn =
960               std::max(MinEmptyCaseColumn, Changes[I].StartOfTokenColumn);
961         } else {
962           MinEmptyCaseColumn =
963               std::max(MinEmptyCaseColumn, Changes[I].StartOfTokenColumn + 2);
964         }
965       }
966     }
967 
968     if (!Matches(Changes[I]))
969       continue;
970 
971     if (LineIsEmptyCase)
972       continue;
973 
974     FoundMatchOnLine = true;
975 
976     if (StartOfSequence == 0)
977       StartOfSequence = I;
978 
979     EndOfSequence = I + 1;
980 
981     MinColumn = std::max(MinColumn, Changes[I].StartOfTokenColumn);
982 
983     // Allow empty case statements to push out our alignment.
984     MinColumn = std::max(MinColumn, MinEmptyCaseColumn);
985   }
986 
987   AlignMatchingTokenSequence(StartOfSequence, EndOfSequence, MinColumn, Matches,
988                              Changes);
989 }
990 
991 void WhitespaceManager::alignConsecutiveTableGenBreakingDAGArgColons() {
992   alignConsecutiveColons(Style.AlignConsecutiveTableGenBreakingDAGArgColons,
993                          TT_TableGenDAGArgListColonToAlign);
994 }
995 
996 void WhitespaceManager::alignConsecutiveTableGenCondOperatorColons() {
997   alignConsecutiveColons(Style.AlignConsecutiveTableGenCondOperatorColons,
998                          TT_TableGenCondOperatorColon);
999 }
1000 
1001 void WhitespaceManager::alignConsecutiveTableGenDefinitions() {
1002   alignConsecutiveColons(Style.AlignConsecutiveTableGenDefinitionColons,
1003                          TT_InheritanceColon);
1004 }
1005 
1006 void WhitespaceManager::alignConsecutiveDeclarations() {
1007   if (!Style.AlignConsecutiveDeclarations.Enabled)
1008     return;
1009 
1010   AlignTokens(
1011       Style,
1012       [&](Change const &C) {
1013         if (Style.AlignConsecutiveDeclarations.AlignFunctionPointers) {
1014           for (const auto *Prev = C.Tok->Previous; Prev; Prev = Prev->Previous)
1015             if (Prev->is(tok::equal))
1016               return false;
1017           if (C.Tok->is(TT_FunctionTypeLParen))
1018             return true;
1019         }
1020         if (C.Tok->is(TT_FunctionDeclarationName))
1021           return true;
1022         if (C.Tok->isNot(TT_StartOfName))
1023           return false;
1024         if (C.Tok->Previous &&
1025             C.Tok->Previous->is(TT_StatementAttributeLikeMacro))
1026           return false;
1027         // Check if there is a subsequent name that starts the same declaration.
1028         for (FormatToken *Next = C.Tok->Next; Next; Next = Next->Next) {
1029           if (Next->is(tok::comment))
1030             continue;
1031           if (Next->is(TT_PointerOrReference))
1032             return false;
1033           if (!Next->Tok.getIdentifierInfo())
1034             break;
1035           if (Next->isOneOf(TT_StartOfName, TT_FunctionDeclarationName,
1036                             tok::kw_operator)) {
1037             return false;
1038           }
1039         }
1040         return true;
1041       },
1042       Changes, /*StartAt=*/0, Style.AlignConsecutiveDeclarations);
1043 }
1044 
1045 void WhitespaceManager::alignChainedConditionals() {
1046   if (Style.BreakBeforeTernaryOperators) {
1047     AlignTokens(
1048         Style,
1049         [](Change const &C) {
1050           // Align question operators and last colon
1051           return C.Tok->is(TT_ConditionalExpr) &&
1052                  ((C.Tok->is(tok::question) && !C.NewlinesBefore) ||
1053                   (C.Tok->is(tok::colon) && C.Tok->Next &&
1054                    (C.Tok->Next->FakeLParens.size() == 0 ||
1055                     C.Tok->Next->FakeLParens.back() != prec::Conditional)));
1056         },
1057         Changes, /*StartAt=*/0);
1058   } else {
1059     static auto AlignWrappedOperand = [](Change const &C) {
1060       FormatToken *Previous = C.Tok->getPreviousNonComment();
1061       return C.NewlinesBefore && Previous && Previous->is(TT_ConditionalExpr) &&
1062              (Previous->is(tok::colon) &&
1063               (C.Tok->FakeLParens.size() == 0 ||
1064                C.Tok->FakeLParens.back() != prec::Conditional));
1065     };
1066     // Ensure we keep alignment of wrapped operands with non-wrapped operands
1067     // Since we actually align the operators, the wrapped operands need the
1068     // extra offset to be properly aligned.
1069     for (Change &C : Changes)
1070       if (AlignWrappedOperand(C))
1071         C.StartOfTokenColumn -= 2;
1072     AlignTokens(
1073         Style,
1074         [this](Change const &C) {
1075           // Align question operators if next operand is not wrapped, as
1076           // well as wrapped operands after question operator or last
1077           // colon in conditional sequence
1078           return (C.Tok->is(TT_ConditionalExpr) && C.Tok->is(tok::question) &&
1079                   &C != &Changes.back() && (&C + 1)->NewlinesBefore == 0 &&
1080                   !(&C + 1)->IsTrailingComment) ||
1081                  AlignWrappedOperand(C);
1082         },
1083         Changes, /*StartAt=*/0);
1084   }
1085 }
1086 
1087 void WhitespaceManager::alignTrailingComments() {
1088   if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Never)
1089     return;
1090 
1091   const int Size = Changes.size();
1092   int MinColumn = 0;
1093   int StartOfSequence = 0;
1094   bool BreakBeforeNext = false;
1095   int NewLineThreshold = 1;
1096   if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Always)
1097     NewLineThreshold = Style.AlignTrailingComments.OverEmptyLines + 1;
1098 
1099   for (int I = 0, MaxColumn = INT_MAX, Newlines = 0; I < Size; ++I) {
1100     auto &C = Changes[I];
1101     if (C.StartOfBlockComment)
1102       continue;
1103     Newlines += C.NewlinesBefore;
1104     if (!C.IsTrailingComment)
1105       continue;
1106 
1107     if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Leave) {
1108       const int OriginalSpaces =
1109           C.OriginalWhitespaceRange.getEnd().getRawEncoding() -
1110           C.OriginalWhitespaceRange.getBegin().getRawEncoding() -
1111           C.Tok->LastNewlineOffset;
1112       assert(OriginalSpaces >= 0);
1113       const auto RestoredLineLength =
1114           C.StartOfTokenColumn + C.TokenLength + OriginalSpaces;
1115       // If leaving comments makes the line exceed the column limit, give up to
1116       // leave the comments.
1117       if (RestoredLineLength >= Style.ColumnLimit && Style.ColumnLimit > 0)
1118         break;
1119       C.Spaces = OriginalSpaces;
1120       continue;
1121     }
1122 
1123     const int ChangeMinColumn = C.StartOfTokenColumn;
1124     int ChangeMaxColumn;
1125 
1126     // If we don't create a replacement for this change, we have to consider
1127     // it to be immovable.
1128     if (!C.CreateReplacement)
1129       ChangeMaxColumn = ChangeMinColumn;
1130     else if (Style.ColumnLimit == 0)
1131       ChangeMaxColumn = INT_MAX;
1132     else if (Style.ColumnLimit >= C.TokenLength)
1133       ChangeMaxColumn = Style.ColumnLimit - C.TokenLength;
1134     else
1135       ChangeMaxColumn = ChangeMinColumn;
1136 
1137     if (I + 1 < Size && Changes[I + 1].ContinuesPPDirective &&
1138         ChangeMaxColumn >= 2) {
1139       ChangeMaxColumn -= 2;
1140     }
1141 
1142     bool WasAlignedWithStartOfNextLine = false;
1143     if (C.NewlinesBefore >= 1) { // A comment on its own line.
1144       const auto CommentColumn =
1145           SourceMgr.getSpellingColumnNumber(C.OriginalWhitespaceRange.getEnd());
1146       for (int J = I + 1; J < Size; ++J) {
1147         if (Changes[J].Tok->is(tok::comment))
1148           continue;
1149 
1150         const auto NextColumn = SourceMgr.getSpellingColumnNumber(
1151             Changes[J].OriginalWhitespaceRange.getEnd());
1152         // The start of the next token was previously aligned with the
1153         // start of this comment.
1154         WasAlignedWithStartOfNextLine =
1155             CommentColumn == NextColumn ||
1156             CommentColumn == NextColumn + Style.IndentWidth;
1157         break;
1158       }
1159     }
1160 
1161     // We don't want to align comments which end a scope, which are here
1162     // identified by most closing braces.
1163     auto DontAlignThisComment = [](const auto *Tok) {
1164       if (Tok->is(tok::semi)) {
1165         Tok = Tok->getPreviousNonComment();
1166         if (!Tok)
1167           return false;
1168       }
1169       if (Tok->is(tok::r_paren)) {
1170         // Back up past the parentheses and a `TT_DoWhile` that may precede.
1171         Tok = Tok->MatchingParen;
1172         if (!Tok)
1173           return false;
1174         Tok = Tok->getPreviousNonComment();
1175         if (!Tok)
1176           return false;
1177         if (Tok->is(TT_DoWhile)) {
1178           const auto *Prev = Tok->getPreviousNonComment();
1179           if (!Prev) {
1180             // A do-while-loop without braces.
1181             return true;
1182           }
1183           Tok = Prev;
1184         }
1185       }
1186 
1187       if (Tok->isNot(tok::r_brace))
1188         return false;
1189 
1190       while (Tok->Previous && Tok->Previous->is(tok::r_brace))
1191         Tok = Tok->Previous;
1192       return Tok->NewlinesBefore > 0;
1193     };
1194 
1195     if (I > 0 && C.NewlinesBefore == 0 &&
1196         DontAlignThisComment(Changes[I - 1].Tok)) {
1197       alignTrailingComments(StartOfSequence, I, MinColumn);
1198       // Reset to initial values, but skip this change for the next alignment
1199       // pass.
1200       MinColumn = 0;
1201       MaxColumn = INT_MAX;
1202       StartOfSequence = I + 1;
1203     } else if (BreakBeforeNext || Newlines > NewLineThreshold ||
1204                (ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn) ||
1205                // Break the comment sequence if the previous line did not end
1206                // in a trailing comment.
1207                (C.NewlinesBefore == 1 && I > 0 &&
1208                 !Changes[I - 1].IsTrailingComment) ||
1209                WasAlignedWithStartOfNextLine) {
1210       alignTrailingComments(StartOfSequence, I, MinColumn);
1211       MinColumn = ChangeMinColumn;
1212       MaxColumn = ChangeMaxColumn;
1213       StartOfSequence = I;
1214     } else {
1215       MinColumn = std::max(MinColumn, ChangeMinColumn);
1216       MaxColumn = std::min(MaxColumn, ChangeMaxColumn);
1217     }
1218     BreakBeforeNext = (I == 0) || (C.NewlinesBefore > 1) ||
1219                       // Never start a sequence with a comment at the beginning
1220                       // of the line.
1221                       (C.NewlinesBefore == 1 && StartOfSequence == I);
1222     Newlines = 0;
1223   }
1224   alignTrailingComments(StartOfSequence, Size, MinColumn);
1225 }
1226 
1227 void WhitespaceManager::alignTrailingComments(unsigned Start, unsigned End,
1228                                               unsigned Column) {
1229   for (unsigned i = Start; i != End; ++i) {
1230     int Shift = 0;
1231     if (Changes[i].IsTrailingComment)
1232       Shift = Column - Changes[i].StartOfTokenColumn;
1233     if (Changes[i].StartOfBlockComment) {
1234       Shift = Changes[i].IndentationOffset +
1235               Changes[i].StartOfBlockComment->StartOfTokenColumn -
1236               Changes[i].StartOfTokenColumn;
1237     }
1238     if (Shift <= 0)
1239       continue;
1240     Changes[i].Spaces += Shift;
1241     if (i + 1 != Changes.size())
1242       Changes[i + 1].PreviousEndOfTokenColumn += Shift;
1243     Changes[i].StartOfTokenColumn += Shift;
1244   }
1245 }
1246 
1247 void WhitespaceManager::alignEscapedNewlines() {
1248   const auto Align = Style.AlignEscapedNewlines;
1249   if (Align == FormatStyle::ENAS_DontAlign)
1250     return;
1251 
1252   const bool WithLastLine = Align == FormatStyle::ENAS_LeftWithLastLine;
1253   const bool AlignLeft = Align == FormatStyle::ENAS_Left || WithLastLine;
1254   const auto MaxColumn = Style.ColumnLimit;
1255   unsigned MaxEndOfLine = AlignLeft ? 0 : MaxColumn;
1256   unsigned StartOfMacro = 0;
1257   for (unsigned i = 1, e = Changes.size(); i < e; ++i) {
1258     Change &C = Changes[i];
1259     if (C.NewlinesBefore == 0 && (!WithLastLine || C.Tok->isNot(tok::eof)))
1260       continue;
1261     const bool InPPDirective = C.ContinuesPPDirective;
1262     const auto BackslashColumn = C.PreviousEndOfTokenColumn + 2;
1263     if (InPPDirective ||
1264         (WithLastLine && (MaxColumn == 0 || BackslashColumn <= MaxColumn))) {
1265       MaxEndOfLine = std::max(BackslashColumn, MaxEndOfLine);
1266     }
1267     if (!InPPDirective) {
1268       alignEscapedNewlines(StartOfMacro + 1, i, MaxEndOfLine);
1269       MaxEndOfLine = AlignLeft ? 0 : MaxColumn;
1270       StartOfMacro = i;
1271     }
1272   }
1273   alignEscapedNewlines(StartOfMacro + 1, Changes.size(), MaxEndOfLine);
1274 }
1275 
1276 void WhitespaceManager::alignEscapedNewlines(unsigned Start, unsigned End,
1277                                              unsigned Column) {
1278   for (unsigned i = Start; i < End; ++i) {
1279     Change &C = Changes[i];
1280     if (C.NewlinesBefore > 0) {
1281       assert(C.ContinuesPPDirective);
1282       if (C.PreviousEndOfTokenColumn + 1 > Column)
1283         C.EscapedNewlineColumn = 0;
1284       else
1285         C.EscapedNewlineColumn = Column;
1286     }
1287   }
1288 }
1289 
1290 void WhitespaceManager::alignArrayInitializers() {
1291   if (Style.AlignArrayOfStructures == FormatStyle::AIAS_None)
1292     return;
1293 
1294   for (unsigned ChangeIndex = 1U, ChangeEnd = Changes.size();
1295        ChangeIndex < ChangeEnd; ++ChangeIndex) {
1296     auto &C = Changes[ChangeIndex];
1297     if (C.Tok->IsArrayInitializer) {
1298       bool FoundComplete = false;
1299       for (unsigned InsideIndex = ChangeIndex + 1; InsideIndex < ChangeEnd;
1300            ++InsideIndex) {
1301         if (Changes[InsideIndex].Tok == C.Tok->MatchingParen) {
1302           alignArrayInitializers(ChangeIndex, InsideIndex + 1);
1303           ChangeIndex = InsideIndex + 1;
1304           FoundComplete = true;
1305           break;
1306         }
1307       }
1308       if (!FoundComplete)
1309         ChangeIndex = ChangeEnd;
1310     }
1311   }
1312 }
1313 
1314 void WhitespaceManager::alignArrayInitializers(unsigned Start, unsigned End) {
1315 
1316   if (Style.AlignArrayOfStructures == FormatStyle::AIAS_Right)
1317     alignArrayInitializersRightJustified(getCells(Start, End));
1318   else if (Style.AlignArrayOfStructures == FormatStyle::AIAS_Left)
1319     alignArrayInitializersLeftJustified(getCells(Start, End));
1320 }
1321 
1322 void WhitespaceManager::alignArrayInitializersRightJustified(
1323     CellDescriptions &&CellDescs) {
1324   if (!CellDescs.isRectangular())
1325     return;
1326 
1327   const int BracePadding = Style.Cpp11BracedListStyle ? 0 : 1;
1328   auto &Cells = CellDescs.Cells;
1329   // Now go through and fixup the spaces.
1330   auto *CellIter = Cells.begin();
1331   for (auto i = 0U; i < CellDescs.CellCounts[0]; ++i, ++CellIter) {
1332     unsigned NetWidth = 0U;
1333     if (isSplitCell(*CellIter))
1334       NetWidth = getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces);
1335     auto CellWidth = getMaximumCellWidth(CellIter, NetWidth);
1336 
1337     if (Changes[CellIter->Index].Tok->is(tok::r_brace)) {
1338       // So in here we want to see if there is a brace that falls
1339       // on a line that was split. If so on that line we make sure that
1340       // the spaces in front of the brace are enough.
1341       const auto *Next = CellIter;
1342       do {
1343         const FormatToken *Previous = Changes[Next->Index].Tok->Previous;
1344         if (Previous && Previous->isNot(TT_LineComment)) {
1345           Changes[Next->Index].Spaces = BracePadding;
1346           Changes[Next->Index].NewlinesBefore = 0;
1347         }
1348         Next = Next->NextColumnElement;
1349       } while (Next);
1350       // Unless the array is empty, we need the position of all the
1351       // immediately adjacent cells
1352       if (CellIter != Cells.begin()) {
1353         auto ThisNetWidth =
1354             getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces);
1355         auto MaxNetWidth = getMaximumNetWidth(
1356             Cells.begin(), CellIter, CellDescs.InitialSpaces,
1357             CellDescs.CellCounts[0], CellDescs.CellCounts.size());
1358         if (ThisNetWidth < MaxNetWidth)
1359           Changes[CellIter->Index].Spaces = (MaxNetWidth - ThisNetWidth);
1360         auto RowCount = 1U;
1361         auto Offset = std::distance(Cells.begin(), CellIter);
1362         for (const auto *Next = CellIter->NextColumnElement; Next;
1363              Next = Next->NextColumnElement) {
1364           if (RowCount >= CellDescs.CellCounts.size())
1365             break;
1366           auto *Start = (Cells.begin() + RowCount * CellDescs.CellCounts[0]);
1367           auto *End = Start + Offset;
1368           ThisNetWidth = getNetWidth(Start, End, CellDescs.InitialSpaces);
1369           if (ThisNetWidth < MaxNetWidth)
1370             Changes[Next->Index].Spaces = (MaxNetWidth - ThisNetWidth);
1371           ++RowCount;
1372         }
1373       }
1374     } else {
1375       auto ThisWidth =
1376           calculateCellWidth(CellIter->Index, CellIter->EndIndex, true) +
1377           NetWidth;
1378       if (Changes[CellIter->Index].NewlinesBefore == 0) {
1379         Changes[CellIter->Index].Spaces = (CellWidth - (ThisWidth + NetWidth));
1380         Changes[CellIter->Index].Spaces += (i > 0) ? 1 : BracePadding;
1381       }
1382       alignToStartOfCell(CellIter->Index, CellIter->EndIndex);
1383       for (const auto *Next = CellIter->NextColumnElement; Next;
1384            Next = Next->NextColumnElement) {
1385         ThisWidth =
1386             calculateCellWidth(Next->Index, Next->EndIndex, true) + NetWidth;
1387         if (Changes[Next->Index].NewlinesBefore == 0) {
1388           Changes[Next->Index].Spaces = (CellWidth - ThisWidth);
1389           Changes[Next->Index].Spaces += (i > 0) ? 1 : BracePadding;
1390         }
1391         alignToStartOfCell(Next->Index, Next->EndIndex);
1392       }
1393     }
1394   }
1395 }
1396 
1397 void WhitespaceManager::alignArrayInitializersLeftJustified(
1398     CellDescriptions &&CellDescs) {
1399 
1400   if (!CellDescs.isRectangular())
1401     return;
1402 
1403   const int BracePadding = Style.Cpp11BracedListStyle ? 0 : 1;
1404   auto &Cells = CellDescs.Cells;
1405   // Now go through and fixup the spaces.
1406   auto *CellIter = Cells.begin();
1407   // The first cell of every row needs to be against the left brace.
1408   for (const auto *Next = CellIter; Next; Next = Next->NextColumnElement) {
1409     auto &Change = Changes[Next->Index];
1410     Change.Spaces =
1411         Change.NewlinesBefore == 0 ? BracePadding : CellDescs.InitialSpaces;
1412   }
1413   ++CellIter;
1414   for (auto i = 1U; i < CellDescs.CellCounts[0]; i++, ++CellIter) {
1415     auto MaxNetWidth = getMaximumNetWidth(
1416         Cells.begin(), CellIter, CellDescs.InitialSpaces,
1417         CellDescs.CellCounts[0], CellDescs.CellCounts.size());
1418     auto ThisNetWidth =
1419         getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces);
1420     if (Changes[CellIter->Index].NewlinesBefore == 0) {
1421       Changes[CellIter->Index].Spaces =
1422           MaxNetWidth - ThisNetWidth +
1423           (Changes[CellIter->Index].Tok->isNot(tok::r_brace) ? 1
1424                                                              : BracePadding);
1425     }
1426     auto RowCount = 1U;
1427     auto Offset = std::distance(Cells.begin(), CellIter);
1428     for (const auto *Next = CellIter->NextColumnElement; Next;
1429          Next = Next->NextColumnElement) {
1430       if (RowCount >= CellDescs.CellCounts.size())
1431         break;
1432       auto *Start = (Cells.begin() + RowCount * CellDescs.CellCounts[0]);
1433       auto *End = Start + Offset;
1434       auto ThisNetWidth = getNetWidth(Start, End, CellDescs.InitialSpaces);
1435       if (Changes[Next->Index].NewlinesBefore == 0) {
1436         Changes[Next->Index].Spaces =
1437             MaxNetWidth - ThisNetWidth +
1438             (Changes[Next->Index].Tok->isNot(tok::r_brace) ? 1 : BracePadding);
1439       }
1440       ++RowCount;
1441     }
1442   }
1443 }
1444 
1445 bool WhitespaceManager::isSplitCell(const CellDescription &Cell) {
1446   if (Cell.HasSplit)
1447     return true;
1448   for (const auto *Next = Cell.NextColumnElement; Next;
1449        Next = Next->NextColumnElement) {
1450     if (Next->HasSplit)
1451       return true;
1452   }
1453   return false;
1454 }
1455 
1456 WhitespaceManager::CellDescriptions WhitespaceManager::getCells(unsigned Start,
1457                                                                 unsigned End) {
1458 
1459   unsigned Depth = 0;
1460   unsigned Cell = 0;
1461   SmallVector<unsigned> CellCounts;
1462   unsigned InitialSpaces = 0;
1463   unsigned InitialTokenLength = 0;
1464   unsigned EndSpaces = 0;
1465   SmallVector<CellDescription> Cells;
1466   const FormatToken *MatchingParen = nullptr;
1467   for (unsigned i = Start; i < End; ++i) {
1468     auto &C = Changes[i];
1469     if (C.Tok->is(tok::l_brace))
1470       ++Depth;
1471     else if (C.Tok->is(tok::r_brace))
1472       --Depth;
1473     if (Depth == 2) {
1474       if (C.Tok->is(tok::l_brace)) {
1475         Cell = 0;
1476         MatchingParen = C.Tok->MatchingParen;
1477         if (InitialSpaces == 0) {
1478           InitialSpaces = C.Spaces + C.TokenLength;
1479           InitialTokenLength = C.TokenLength;
1480           auto j = i - 1;
1481           for (; Changes[j].NewlinesBefore == 0 && j > Start; --j) {
1482             InitialSpaces += Changes[j].Spaces + Changes[j].TokenLength;
1483             InitialTokenLength += Changes[j].TokenLength;
1484           }
1485           if (C.NewlinesBefore == 0) {
1486             InitialSpaces += Changes[j].Spaces + Changes[j].TokenLength;
1487             InitialTokenLength += Changes[j].TokenLength;
1488           }
1489         }
1490       } else if (C.Tok->is(tok::comma)) {
1491         if (!Cells.empty())
1492           Cells.back().EndIndex = i;
1493         if (const auto *Next = C.Tok->getNextNonComment();
1494             Next && Next->isNot(tok::r_brace)) { // dangling comma
1495           ++Cell;
1496         }
1497       }
1498     } else if (Depth == 1) {
1499       if (C.Tok == MatchingParen) {
1500         if (!Cells.empty())
1501           Cells.back().EndIndex = i;
1502         Cells.push_back(CellDescription{i, ++Cell, i + 1, false, nullptr});
1503         CellCounts.push_back(C.Tok->Previous->isNot(tok::comma) ? Cell + 1
1504                                                                 : Cell);
1505         // Go to the next non-comment and ensure there is a break in front
1506         const auto *NextNonComment = C.Tok->getNextNonComment();
1507         while (NextNonComment && NextNonComment->is(tok::comma))
1508           NextNonComment = NextNonComment->getNextNonComment();
1509         auto j = i;
1510         while (j < End && Changes[j].Tok != NextNonComment)
1511           ++j;
1512         if (j < End && Changes[j].NewlinesBefore == 0 &&
1513             Changes[j].Tok->isNot(tok::r_brace)) {
1514           Changes[j].NewlinesBefore = 1;
1515           // Account for the added token lengths
1516           Changes[j].Spaces = InitialSpaces - InitialTokenLength;
1517         }
1518       } else if (C.Tok->is(tok::comment) && C.Tok->NewlinesBefore == 0) {
1519         // Trailing comments stay at a space past the last token
1520         C.Spaces = Changes[i - 1].Tok->is(tok::comma) ? 1 : 2;
1521       } else if (C.Tok->is(tok::l_brace)) {
1522         // We need to make sure that the ending braces is aligned to the
1523         // start of our initializer
1524         auto j = i - 1;
1525         for (; j > 0 && !Changes[j].Tok->ArrayInitializerLineStart; --j)
1526           ; // Nothing the loop does the work
1527         EndSpaces = Changes[j].Spaces;
1528       }
1529     } else if (Depth == 0 && C.Tok->is(tok::r_brace)) {
1530       C.NewlinesBefore = 1;
1531       C.Spaces = EndSpaces;
1532     }
1533     if (C.Tok->StartsColumn) {
1534       // This gets us past tokens that have been split over multiple
1535       // lines
1536       bool HasSplit = false;
1537       if (Changes[i].NewlinesBefore > 0) {
1538         // So if we split a line previously and the tail line + this token is
1539         // less then the column limit we remove the split here and just put
1540         // the column start at a space past the comma
1541         //
1542         // FIXME This if branch covers the cases where the column is not
1543         // the first column. This leads to weird pathologies like the formatting
1544         // auto foo = Items{
1545         //     Section{
1546         //             0, bar(),
1547         //     }
1548         // };
1549         // Well if it doesn't lead to that it's indicative that the line
1550         // breaking should be revisited. Unfortunately alot of other options
1551         // interact with this
1552         auto j = i - 1;
1553         if ((j - 1) > Start && Changes[j].Tok->is(tok::comma) &&
1554             Changes[j - 1].NewlinesBefore > 0) {
1555           --j;
1556           auto LineLimit = Changes[j].Spaces + Changes[j].TokenLength;
1557           if (LineLimit < Style.ColumnLimit) {
1558             Changes[i].NewlinesBefore = 0;
1559             Changes[i].Spaces = 1;
1560           }
1561         }
1562       }
1563       while (Changes[i].NewlinesBefore > 0 && Changes[i].Tok == C.Tok) {
1564         Changes[i].Spaces = InitialSpaces;
1565         ++i;
1566         HasSplit = true;
1567       }
1568       if (Changes[i].Tok != C.Tok)
1569         --i;
1570       Cells.push_back(CellDescription{i, Cell, i, HasSplit, nullptr});
1571     }
1572   }
1573 
1574   return linkCells({Cells, CellCounts, InitialSpaces});
1575 }
1576 
1577 unsigned WhitespaceManager::calculateCellWidth(unsigned Start, unsigned End,
1578                                                bool WithSpaces) const {
1579   unsigned CellWidth = 0;
1580   for (auto i = Start; i < End; i++) {
1581     if (Changes[i].NewlinesBefore > 0)
1582       CellWidth = 0;
1583     CellWidth += Changes[i].TokenLength;
1584     CellWidth += (WithSpaces ? Changes[i].Spaces : 0);
1585   }
1586   return CellWidth;
1587 }
1588 
1589 void WhitespaceManager::alignToStartOfCell(unsigned Start, unsigned End) {
1590   if ((End - Start) <= 1)
1591     return;
1592   // If the line is broken anywhere in there make sure everything
1593   // is aligned to the parent
1594   for (auto i = Start + 1; i < End; i++)
1595     if (Changes[i].NewlinesBefore > 0)
1596       Changes[i].Spaces = Changes[Start].Spaces;
1597 }
1598 
1599 WhitespaceManager::CellDescriptions
1600 WhitespaceManager::linkCells(CellDescriptions &&CellDesc) {
1601   auto &Cells = CellDesc.Cells;
1602   for (auto *CellIter = Cells.begin(); CellIter != Cells.end(); ++CellIter) {
1603     if (!CellIter->NextColumnElement && (CellIter + 1) != Cells.end()) {
1604       for (auto *NextIter = CellIter + 1; NextIter != Cells.end(); ++NextIter) {
1605         if (NextIter->Cell == CellIter->Cell) {
1606           CellIter->NextColumnElement = &(*NextIter);
1607           break;
1608         }
1609       }
1610     }
1611   }
1612   return std::move(CellDesc);
1613 }
1614 
1615 void WhitespaceManager::generateChanges() {
1616   for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
1617     const Change &C = Changes[i];
1618     if (i > 0) {
1619       auto Last = Changes[i - 1].OriginalWhitespaceRange;
1620       auto New = Changes[i].OriginalWhitespaceRange;
1621       // Do not generate two replacements for the same location.  As a special
1622       // case, it is allowed if there is a replacement for the empty range
1623       // between 2 tokens and another non-empty range at the start of the second
1624       // token.  We didn't implement logic to combine replacements for 2
1625       // consecutive source ranges into a single replacement, because the
1626       // program works fine without it.
1627       //
1628       // We can't eliminate empty original whitespace ranges.  They appear when
1629       // 2 tokens have no whitespace in between in the input.  It does not
1630       // matter whether whitespace is to be added.  If no whitespace is to be
1631       // added, the replacement will be empty, and it gets eliminated after this
1632       // step in storeReplacement.  For example, if the input is `foo();`,
1633       // there will be a replacement for the range between every consecutive
1634       // pair of tokens.
1635       //
1636       // A replacement at the start of a token can be added by
1637       // BreakableStringLiteralUsingOperators::insertBreak when it adds braces
1638       // around the string literal.  Say Verilog code is being formatted and the
1639       // first line is to become the next 2 lines.
1640       //     x("long string");
1641       //     x({"long ",
1642       //        "string"});
1643       // There will be a replacement for the empty range between the parenthesis
1644       // and the string and another replacement for the quote character.  The
1645       // replacement for the empty range between the parenthesis and the quote
1646       // comes from ContinuationIndenter::addTokenOnCurrentLine when it changes
1647       // the original empty range between the parenthesis and the string to
1648       // another empty one.  The replacement for the quote character comes from
1649       // BreakableStringLiteralUsingOperators::insertBreak when it adds the
1650       // brace.  In the example, the replacement for the empty range is the same
1651       // as the original text.  However, eliminating replacements that are same
1652       // as the original does not help in general.  For example, a newline can
1653       // be inserted, causing the first line to become the next 3 lines.
1654       //     xxxxxxxxxxx("long string");
1655       //     xxxxxxxxxxx(
1656       //         {"long ",
1657       //          "string"});
1658       // In that case, the empty range between the parenthesis and the string
1659       // will be replaced by a newline and 4 spaces.  So we will still have to
1660       // deal with a replacement for an empty source range followed by a
1661       // replacement for a non-empty source range.
1662       if (Last.getBegin() == New.getBegin() &&
1663           (Last.getEnd() != Last.getBegin() ||
1664            New.getEnd() == New.getBegin())) {
1665         continue;
1666       }
1667     }
1668     if (C.CreateReplacement) {
1669       std::string ReplacementText = C.PreviousLinePostfix;
1670       if (C.ContinuesPPDirective) {
1671         appendEscapedNewlineText(ReplacementText, C.NewlinesBefore,
1672                                  C.PreviousEndOfTokenColumn,
1673                                  C.EscapedNewlineColumn);
1674       } else {
1675         appendNewlineText(ReplacementText, C.NewlinesBefore);
1676       }
1677       // FIXME: This assert should hold if we computed the column correctly.
1678       // assert((int)C.StartOfTokenColumn >= C.Spaces);
1679       appendIndentText(
1680           ReplacementText, C.Tok->IndentLevel, std::max(0, C.Spaces),
1681           std::max((int)C.StartOfTokenColumn, C.Spaces) - std::max(0, C.Spaces),
1682           C.IsAligned);
1683       ReplacementText.append(C.CurrentLinePrefix);
1684       storeReplacement(C.OriginalWhitespaceRange, ReplacementText);
1685     }
1686   }
1687 }
1688 
1689 void WhitespaceManager::storeReplacement(SourceRange Range, StringRef Text) {
1690   unsigned WhitespaceLength = SourceMgr.getFileOffset(Range.getEnd()) -
1691                               SourceMgr.getFileOffset(Range.getBegin());
1692   // Don't create a replacement, if it does not change anything.
1693   if (StringRef(SourceMgr.getCharacterData(Range.getBegin()),
1694                 WhitespaceLength) == Text) {
1695     return;
1696   }
1697   auto Err = Replaces.add(tooling::Replacement(
1698       SourceMgr, CharSourceRange::getCharRange(Range), Text));
1699   // FIXME: better error handling. For now, just print an error message in the
1700   // release version.
1701   if (Err) {
1702     llvm::errs() << llvm::toString(std::move(Err)) << "\n";
1703     assert(false);
1704   }
1705 }
1706 
1707 void WhitespaceManager::appendNewlineText(std::string &Text,
1708                                           unsigned Newlines) {
1709   if (UseCRLF) {
1710     Text.reserve(Text.size() + 2 * Newlines);
1711     for (unsigned i = 0; i < Newlines; ++i)
1712       Text.append("\r\n");
1713   } else {
1714     Text.append(Newlines, '\n');
1715   }
1716 }
1717 
1718 void WhitespaceManager::appendEscapedNewlineText(
1719     std::string &Text, unsigned Newlines, unsigned PreviousEndOfTokenColumn,
1720     unsigned EscapedNewlineColumn) {
1721   if (Newlines > 0) {
1722     unsigned Spaces =
1723         std::max<int>(1, EscapedNewlineColumn - PreviousEndOfTokenColumn - 1);
1724     for (unsigned i = 0; i < Newlines; ++i) {
1725       Text.append(Spaces, ' ');
1726       Text.append(UseCRLF ? "\\\r\n" : "\\\n");
1727       Spaces = std::max<int>(0, EscapedNewlineColumn - 1);
1728     }
1729   }
1730 }
1731 
1732 void WhitespaceManager::appendIndentText(std::string &Text,
1733                                          unsigned IndentLevel, unsigned Spaces,
1734                                          unsigned WhitespaceStartColumn,
1735                                          bool IsAligned) {
1736   switch (Style.UseTab) {
1737   case FormatStyle::UT_Never:
1738     Text.append(Spaces, ' ');
1739     break;
1740   case FormatStyle::UT_Always: {
1741     if (Style.TabWidth) {
1742       unsigned FirstTabWidth =
1743           Style.TabWidth - WhitespaceStartColumn % Style.TabWidth;
1744 
1745       // Insert only spaces when we want to end up before the next tab.
1746       if (Spaces < FirstTabWidth || Spaces == 1) {
1747         Text.append(Spaces, ' ');
1748         break;
1749       }
1750       // Align to the next tab.
1751       Spaces -= FirstTabWidth;
1752       Text.append("\t");
1753 
1754       Text.append(Spaces / Style.TabWidth, '\t');
1755       Text.append(Spaces % Style.TabWidth, ' ');
1756     } else if (Spaces == 1) {
1757       Text.append(Spaces, ' ');
1758     }
1759     break;
1760   }
1761   case FormatStyle::UT_ForIndentation:
1762     if (WhitespaceStartColumn == 0) {
1763       unsigned Indentation = IndentLevel * Style.IndentWidth;
1764       Spaces = appendTabIndent(Text, Spaces, Indentation);
1765     }
1766     Text.append(Spaces, ' ');
1767     break;
1768   case FormatStyle::UT_ForContinuationAndIndentation:
1769     if (WhitespaceStartColumn == 0)
1770       Spaces = appendTabIndent(Text, Spaces, Spaces);
1771     Text.append(Spaces, ' ');
1772     break;
1773   case FormatStyle::UT_AlignWithSpaces:
1774     if (WhitespaceStartColumn == 0) {
1775       unsigned Indentation =
1776           IsAligned ? IndentLevel * Style.IndentWidth : Spaces;
1777       Spaces = appendTabIndent(Text, Spaces, Indentation);
1778     }
1779     Text.append(Spaces, ' ');
1780     break;
1781   }
1782 }
1783 
1784 unsigned WhitespaceManager::appendTabIndent(std::string &Text, unsigned Spaces,
1785                                             unsigned Indentation) {
1786   // This happens, e.g. when a line in a block comment is indented less than the
1787   // first one.
1788   if (Indentation > Spaces)
1789     Indentation = Spaces;
1790   if (Style.TabWidth) {
1791     unsigned Tabs = Indentation / Style.TabWidth;
1792     Text.append(Tabs, '\t');
1793     Spaces -= Tabs * Style.TabWidth;
1794   }
1795   return Spaces;
1796 }
1797 
1798 } // namespace format
1799 } // namespace clang
1800