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