xref: /llvm-project/clang/lib/Format/WhitespaceManager.cpp (revision d650ccf6390bb1e4454dd735cfcec9eda9af8ca3)
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)
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)
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 void WhitespaceManager::replaceWhitespaceInToken(
78     const FormatToken &Tok, unsigned Offset, unsigned ReplaceChars,
79     StringRef PreviousPostfix, StringRef CurrentPrefix, bool InPPDirective,
80     unsigned Newlines, int Spaces) {
81   if (Tok.Finalized)
82     return;
83   SourceLocation Start = Tok.getStartOfNonWhitespace().getLocWithOffset(Offset);
84   Changes.push_back(
85       Change(Tok, /*CreateReplacement=*/true,
86              SourceRange(Start, Start.getLocWithOffset(ReplaceChars)), Spaces,
87              std::max(0, Spaces), Newlines, PreviousPostfix, CurrentPrefix,
88              /*IsAligned=*/true, InPPDirective && !Tok.IsFirst,
89              /*IsInsideToken=*/true));
90 }
91 
92 const tooling::Replacements &WhitespaceManager::generateReplacements() {
93   if (Changes.empty())
94     return Replaces;
95 
96   llvm::sort(Changes, Change::IsBeforeInFile(SourceMgr));
97   calculateLineBreakInformation();
98   alignConsecutiveMacros();
99   alignConsecutiveDeclarations();
100   alignConsecutiveBitFields();
101   alignConsecutiveAssignments();
102   alignChainedConditionals();
103   alignTrailingComments();
104   alignEscapedNewlines();
105   alignArrayInitializers();
106   generateChanges();
107 
108   return Replaces;
109 }
110 
111 void WhitespaceManager::calculateLineBreakInformation() {
112   Changes[0].PreviousEndOfTokenColumn = 0;
113   Change *LastOutsideTokenChange = &Changes[0];
114   for (unsigned i = 1, e = Changes.size(); i != e; ++i) {
115     SourceLocation OriginalWhitespaceStart =
116         Changes[i].OriginalWhitespaceRange.getBegin();
117     SourceLocation PreviousOriginalWhitespaceEnd =
118         Changes[i - 1].OriginalWhitespaceRange.getEnd();
119     unsigned OriginalWhitespaceStartOffset =
120         SourceMgr.getFileOffset(OriginalWhitespaceStart);
121     unsigned PreviousOriginalWhitespaceEndOffset =
122         SourceMgr.getFileOffset(PreviousOriginalWhitespaceEnd);
123     assert(PreviousOriginalWhitespaceEndOffset <=
124            OriginalWhitespaceStartOffset);
125     const char *const PreviousOriginalWhitespaceEndData =
126         SourceMgr.getCharacterData(PreviousOriginalWhitespaceEnd);
127     StringRef Text(PreviousOriginalWhitespaceEndData,
128                    SourceMgr.getCharacterData(OriginalWhitespaceStart) -
129                        PreviousOriginalWhitespaceEndData);
130     // Usually consecutive changes would occur in consecutive tokens. This is
131     // not the case however when analyzing some preprocessor runs of the
132     // annotated lines. For example, in this code:
133     //
134     // #if A // line 1
135     // int i = 1;
136     // #else B // line 2
137     // int i = 2;
138     // #endif // line 3
139     //
140     // one of the runs will produce the sequence of lines marked with line 1, 2
141     // and 3. So the two consecutive whitespace changes just before '// line 2'
142     // and before '#endif // line 3' span multiple lines and tokens:
143     //
144     // #else B{change X}[// line 2
145     // int i = 2;
146     // ]{change Y}#endif // line 3
147     //
148     // For this reason, if the text between consecutive changes spans multiple
149     // newlines, the token length must be adjusted to the end of the original
150     // line of the token.
151     auto NewlinePos = Text.find_first_of('\n');
152     if (NewlinePos == StringRef::npos) {
153       Changes[i - 1].TokenLength = OriginalWhitespaceStartOffset -
154                                    PreviousOriginalWhitespaceEndOffset +
155                                    Changes[i].PreviousLinePostfix.size() +
156                                    Changes[i - 1].CurrentLinePrefix.size();
157     } else {
158       Changes[i - 1].TokenLength =
159           NewlinePos + Changes[i - 1].CurrentLinePrefix.size();
160     }
161 
162     // If there are multiple changes in this token, sum up all the changes until
163     // the end of the line.
164     if (Changes[i - 1].IsInsideToken && Changes[i - 1].NewlinesBefore == 0)
165       LastOutsideTokenChange->TokenLength +=
166           Changes[i - 1].TokenLength + Changes[i - 1].Spaces;
167     else
168       LastOutsideTokenChange = &Changes[i - 1];
169 
170     Changes[i].PreviousEndOfTokenColumn =
171         Changes[i - 1].StartOfTokenColumn + Changes[i - 1].TokenLength;
172 
173     Changes[i - 1].IsTrailingComment =
174         (Changes[i].NewlinesBefore > 0 || Changes[i].Tok->is(tok::eof) ||
175          (Changes[i].IsInsideToken && Changes[i].Tok->is(tok::comment))) &&
176         Changes[i - 1].Tok->is(tok::comment) &&
177         // FIXME: This is a dirty hack. The problem is that
178         // BreakableLineCommentSection does comment reflow changes and here is
179         // the aligning of trailing comments. Consider the case where we reflow
180         // the second line up in this example:
181         //
182         // // line 1
183         // // line 2
184         //
185         // That amounts to 2 changes by BreakableLineCommentSection:
186         //  - the first, delimited by (), for the whitespace between the tokens,
187         //  - and second, delimited by [], for the whitespace at the beginning
188         //  of the second token:
189         //
190         // // line 1(
191         // )[// ]line 2
192         //
193         // So in the end we have two changes like this:
194         //
195         // // line1()[ ]line 2
196         //
197         // Note that the OriginalWhitespaceStart of the second change is the
198         // same as the PreviousOriginalWhitespaceEnd of the first change.
199         // In this case, the below check ensures that the second change doesn't
200         // get treated as a trailing comment change here, since this might
201         // trigger additional whitespace to be wrongly inserted before "line 2"
202         // by the comment aligner here.
203         //
204         // For a proper solution we need a mechanism to say to WhitespaceManager
205         // that a particular change breaks the current sequence of trailing
206         // comments.
207         OriginalWhitespaceStart != PreviousOriginalWhitespaceEnd;
208   }
209   // FIXME: The last token is currently not always an eof token; in those
210   // cases, setting TokenLength of the last token to 0 is wrong.
211   Changes.back().TokenLength = 0;
212   Changes.back().IsTrailingComment = Changes.back().Tok->is(tok::comment);
213 
214   const WhitespaceManager::Change *LastBlockComment = nullptr;
215   for (auto &Change : Changes) {
216     // Reset the IsTrailingComment flag for changes inside of trailing comments
217     // so they don't get realigned later. Comment line breaks however still need
218     // to be aligned.
219     if (Change.IsInsideToken && Change.NewlinesBefore == 0)
220       Change.IsTrailingComment = false;
221     Change.StartOfBlockComment = nullptr;
222     Change.IndentationOffset = 0;
223     if (Change.Tok->is(tok::comment)) {
224       if (Change.Tok->is(TT_LineComment) || !Change.IsInsideToken)
225         LastBlockComment = &Change;
226       else {
227         if ((Change.StartOfBlockComment = LastBlockComment))
228           Change.IndentationOffset =
229               Change.StartOfTokenColumn -
230               Change.StartOfBlockComment->StartOfTokenColumn;
231       }
232     } else {
233       LastBlockComment = nullptr;
234     }
235   }
236 
237   // Compute conditional nesting level
238   // Level is increased for each conditional, unless this conditional continues
239   // a chain of conditional, i.e. starts immediately after the colon of another
240   // conditional.
241   SmallVector<bool, 16> ScopeStack;
242   int ConditionalsLevel = 0;
243   for (auto &Change : Changes) {
244     for (unsigned i = 0, e = Change.Tok->FakeLParens.size(); i != e; ++i) {
245       bool isNestedConditional =
246           Change.Tok->FakeLParens[e - 1 - i] == prec::Conditional &&
247           !(i == 0 && Change.Tok->Previous &&
248             Change.Tok->Previous->is(TT_ConditionalExpr) &&
249             Change.Tok->Previous->is(tok::colon));
250       if (isNestedConditional)
251         ++ConditionalsLevel;
252       ScopeStack.push_back(isNestedConditional);
253     }
254 
255     Change.ConditionalsLevel = ConditionalsLevel;
256 
257     for (unsigned i = Change.Tok->FakeRParens; i > 0 && ScopeStack.size();
258          --i) {
259       if (ScopeStack.pop_back_val())
260         --ConditionalsLevel;
261     }
262   }
263 }
264 
265 // Align a single sequence of tokens, see AlignTokens below.
266 template <typename F>
267 static void
268 AlignTokenSequence(const FormatStyle &Style, unsigned Start, unsigned End,
269                    unsigned Column, F &&Matches,
270                    SmallVector<WhitespaceManager::Change, 16> &Changes) {
271   bool FoundMatchOnLine = false;
272   int Shift = 0;
273 
274   // ScopeStack keeps track of the current scope depth. It contains indices of
275   // the first token on each scope.
276   // We only run the "Matches" function on tokens from the outer-most scope.
277   // However, we do need to pay special attention to one class of tokens
278   // that are not in the outer-most scope, and that is function parameters
279   // which are split across multiple lines, as illustrated by this example:
280   //   double a(int x);
281   //   int    b(int  y,
282   //          double z);
283   // In the above example, we need to take special care to ensure that
284   // 'double z' is indented along with it's owning function 'b'.
285   // The same holds for calling a function:
286   //   double a = foo(x);
287   //   int    b = bar(foo(y),
288   //            foor(z));
289   // Similar for broken string literals:
290   //   double x = 3.14;
291   //   auto s   = "Hello"
292   //          "World";
293   // Special handling is required for 'nested' ternary operators.
294   SmallVector<unsigned, 16> ScopeStack;
295 
296   for (unsigned i = Start; i != End; ++i) {
297     if (ScopeStack.size() != 0 &&
298         Changes[i].indentAndNestingLevel() <
299             Changes[ScopeStack.back()].indentAndNestingLevel())
300       ScopeStack.pop_back();
301 
302     // Compare current token to previous non-comment token to ensure whether
303     // it is in a deeper scope or not.
304     unsigned PreviousNonComment = i - 1;
305     while (PreviousNonComment > Start &&
306            Changes[PreviousNonComment].Tok->is(tok::comment))
307       PreviousNonComment--;
308     if (i != Start && Changes[i].indentAndNestingLevel() >
309                           Changes[PreviousNonComment].indentAndNestingLevel())
310       ScopeStack.push_back(i);
311 
312     bool InsideNestedScope = ScopeStack.size() != 0;
313     bool ContinuedStringLiteral = i > Start &&
314                                   Changes[i].Tok->is(tok::string_literal) &&
315                                   Changes[i - 1].Tok->is(tok::string_literal);
316     bool SkipMatchCheck = InsideNestedScope || ContinuedStringLiteral;
317 
318     if (Changes[i].NewlinesBefore > 0 && !SkipMatchCheck) {
319       Shift = 0;
320       FoundMatchOnLine = false;
321     }
322 
323     // If this is the first matching token to be aligned, remember by how many
324     // spaces it has to be shifted, so the rest of the changes on the line are
325     // shifted by the same amount
326     if (!FoundMatchOnLine && !SkipMatchCheck && Matches(Changes[i])) {
327       FoundMatchOnLine = true;
328       Shift = Column - Changes[i].StartOfTokenColumn;
329       Changes[i].Spaces += Shift;
330     }
331 
332     // This is for function parameters that are split across multiple lines,
333     // as mentioned in the ScopeStack comment.
334     if (InsideNestedScope && Changes[i].NewlinesBefore > 0) {
335       unsigned ScopeStart = ScopeStack.back();
336       auto ShouldShiftBeAdded = [&] {
337         // Function declaration
338         if (Changes[ScopeStart - 1].Tok->is(TT_FunctionDeclarationName))
339           return true;
340 
341         // Continued function declaration
342         if (ScopeStart > Start + 1 &&
343             Changes[ScopeStart - 2].Tok->is(TT_FunctionDeclarationName))
344           return true;
345 
346         // Continued function call
347         if (ScopeStart > Start + 1 &&
348             Changes[ScopeStart - 2].Tok->is(tok::identifier) &&
349             Changes[ScopeStart - 1].Tok->is(tok::l_paren))
350           return true;
351 
352         // Ternary operator
353         if (Changes[i].Tok->is(TT_ConditionalExpr))
354           return true;
355 
356         // Continued ternary operator
357         if (Changes[i].Tok->Previous &&
358             Changes[i].Tok->Previous->is(TT_ConditionalExpr))
359           return true;
360 
361         return false;
362       };
363 
364       if (ShouldShiftBeAdded())
365         Changes[i].Spaces += Shift;
366     }
367 
368     if (ContinuedStringLiteral)
369       Changes[i].Spaces += Shift;
370 
371     assert(Shift >= 0);
372 
373     Changes[i].StartOfTokenColumn += Shift;
374     if (i + 1 != Changes.size())
375       Changes[i + 1].PreviousEndOfTokenColumn += Shift;
376 
377     // If PointerAlignment is PAS_Right, keep *s or &s next to the token
378     if (Style.PointerAlignment == FormatStyle::PAS_Right &&
379         Changes[i].Spaces != 0) {
380       for (int Previous = i - 1;
381            Previous >= 0 &&
382            Changes[Previous].Tok->getType() == TT_PointerOrReference;
383            --Previous) {
384         Changes[Previous + 1].Spaces -= Shift;
385         Changes[Previous].Spaces += Shift;
386       }
387     }
388   }
389 }
390 
391 // Walk through a subset of the changes, starting at StartAt, and find
392 // sequences of matching tokens to align. To do so, keep track of the lines and
393 // whether or not a matching token was found on a line. If a matching token is
394 // found, extend the current sequence. If the current line cannot be part of a
395 // sequence, e.g. because there is an empty line before it or it contains only
396 // non-matching tokens, finalize the previous sequence.
397 // The value returned is the token on which we stopped, either because we
398 // exhausted all items inside Changes, or because we hit a scope level higher
399 // than our initial scope.
400 // This function is recursive. Each invocation processes only the scope level
401 // equal to the initial level, which is the level of Changes[StartAt].
402 // If we encounter a scope level greater than the initial level, then we call
403 // ourselves recursively, thereby avoiding the pollution of the current state
404 // with the alignment requirements of the nested sub-level. This recursive
405 // behavior is necessary for aligning function prototypes that have one or more
406 // arguments.
407 // If this function encounters a scope level less than the initial level,
408 // it returns the current position.
409 // There is a non-obvious subtlety in the recursive behavior: Even though we
410 // defer processing of nested levels to recursive invocations of this
411 // function, when it comes time to align a sequence of tokens, we run the
412 // alignment on the entire sequence, including the nested levels.
413 // When doing so, most of the nested tokens are skipped, because their
414 // alignment was already handled by the recursive invocations of this function.
415 // However, the special exception is that we do NOT skip function parameters
416 // that are split across multiple lines. See the test case in FormatTest.cpp
417 // that mentions "split function parameter alignment" for an example of this.
418 template <typename F>
419 static unsigned AlignTokens(
420     const FormatStyle &Style, F &&Matches,
421     SmallVector<WhitespaceManager::Change, 16> &Changes, unsigned StartAt,
422     const FormatStyle::AlignConsecutiveStyle &ACS = FormatStyle::ACS_None) {
423   unsigned MinColumn = 0;
424   unsigned MaxColumn = UINT_MAX;
425 
426   // Line number of the start and the end of the current token sequence.
427   unsigned StartOfSequence = 0;
428   unsigned EndOfSequence = 0;
429 
430   // Measure the scope level (i.e. depth of (), [], {}) of the first token, and
431   // abort when we hit any token in a higher scope than the starting one.
432   auto IndentAndNestingLevel = StartAt < Changes.size()
433                                    ? Changes[StartAt].indentAndNestingLevel()
434                                    : std::tuple<unsigned, unsigned, unsigned>();
435 
436   // Keep track of the number of commas before the matching tokens, we will only
437   // align a sequence of matching tokens if they are preceded by the same number
438   // of commas.
439   unsigned CommasBeforeLastMatch = 0;
440   unsigned CommasBeforeMatch = 0;
441 
442   // Whether a matching token has been found on the current line.
443   bool FoundMatchOnLine = false;
444 
445   // Whether the current line consists purely of comments.
446   bool LineIsComment = true;
447 
448   // Aligns a sequence of matching tokens, on the MinColumn column.
449   //
450   // Sequences start from the first matching token to align, and end at the
451   // first token of the first line that doesn't need to be aligned.
452   //
453   // We need to adjust the StartOfTokenColumn of each Change that is on a line
454   // containing any matching token to be aligned and located after such token.
455   auto AlignCurrentSequence = [&] {
456     if (StartOfSequence > 0 && StartOfSequence < EndOfSequence)
457       AlignTokenSequence(Style, StartOfSequence, EndOfSequence, MinColumn,
458                          Matches, Changes);
459     MinColumn = 0;
460     MaxColumn = UINT_MAX;
461     StartOfSequence = 0;
462     EndOfSequence = 0;
463   };
464 
465   unsigned i = StartAt;
466   for (unsigned e = Changes.size(); i != e; ++i) {
467     if (Changes[i].indentAndNestingLevel() < IndentAndNestingLevel)
468       break;
469 
470     if (Changes[i].NewlinesBefore != 0) {
471       CommasBeforeMatch = 0;
472       EndOfSequence = i;
473 
474       // Whether to break the alignment sequence because of an empty line.
475       bool EmptyLineBreak =
476           (Changes[i].NewlinesBefore > 1) &&
477           (ACS != FormatStyle::ACS_AcrossEmptyLines) &&
478           (ACS != FormatStyle::ACS_AcrossEmptyLinesAndComments);
479 
480       // Whether to break the alignment sequence because of a line without a
481       // match.
482       bool NoMatchBreak =
483           !FoundMatchOnLine &&
484           !(LineIsComment &&
485             ((ACS == FormatStyle::ACS_AcrossComments) ||
486              (ACS == FormatStyle::ACS_AcrossEmptyLinesAndComments)));
487 
488       if (EmptyLineBreak || NoMatchBreak)
489         AlignCurrentSequence();
490 
491       // A new line starts, re-initialize line status tracking bools.
492       // Keep the match state if a string literal is continued on this line.
493       if (i == 0 || !Changes[i].Tok->is(tok::string_literal) ||
494           !Changes[i - 1].Tok->is(tok::string_literal))
495         FoundMatchOnLine = false;
496       LineIsComment = true;
497     }
498 
499     if (!Changes[i].Tok->is(tok::comment)) {
500       LineIsComment = false;
501     }
502 
503     if (Changes[i].Tok->is(tok::comma)) {
504       ++CommasBeforeMatch;
505     } else if (Changes[i].indentAndNestingLevel() > IndentAndNestingLevel) {
506       // Call AlignTokens recursively, skipping over this scope block.
507       unsigned StoppedAt = AlignTokens(Style, Matches, Changes, i, ACS);
508       i = StoppedAt - 1;
509       continue;
510     }
511 
512     if (!Matches(Changes[i]))
513       continue;
514 
515     // If there is more than one matching token per line, or if the number of
516     // preceding commas, do not match anymore, end the sequence.
517     if (FoundMatchOnLine || CommasBeforeMatch != CommasBeforeLastMatch)
518       AlignCurrentSequence();
519 
520     CommasBeforeLastMatch = CommasBeforeMatch;
521     FoundMatchOnLine = true;
522 
523     if (StartOfSequence == 0)
524       StartOfSequence = i;
525 
526     unsigned ChangeMinColumn = Changes[i].StartOfTokenColumn;
527     int LineLengthAfter = Changes[i].TokenLength;
528     for (unsigned j = i + 1; j != e && Changes[j].NewlinesBefore == 0; ++j) {
529       LineLengthAfter += Changes[j].Spaces;
530       // Changes are generally 1:1 with the tokens, but a change could also be
531       // inside of a token, in which case it's counted more than once: once for
532       // the whitespace surrounding the token (!IsInsideToken) and once for
533       // each whitespace change within it (IsInsideToken).
534       // Therefore, changes inside of a token should only count the space.
535       if (!Changes[j].IsInsideToken)
536         LineLengthAfter += Changes[j].TokenLength;
537     }
538     unsigned ChangeMaxColumn = Style.ColumnLimit - LineLengthAfter;
539 
540     // If we are restricted by the maximum column width, end the sequence.
541     if (ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn ||
542         CommasBeforeLastMatch != CommasBeforeMatch) {
543       AlignCurrentSequence();
544       StartOfSequence = i;
545     }
546 
547     MinColumn = std::max(MinColumn, ChangeMinColumn);
548     MaxColumn = std::min(MaxColumn, ChangeMaxColumn);
549   }
550 
551   EndOfSequence = i;
552   AlignCurrentSequence();
553   return i;
554 }
555 
556 // Aligns a sequence of matching tokens, on the MinColumn column.
557 //
558 // Sequences start from the first matching token to align, and end at the
559 // first token of the first line that doesn't need to be aligned.
560 //
561 // We need to adjust the StartOfTokenColumn of each Change that is on a line
562 // containing any matching token to be aligned and located after such token.
563 static void AlignMacroSequence(
564     unsigned &StartOfSequence, unsigned &EndOfSequence, unsigned &MinColumn,
565     unsigned &MaxColumn, bool &FoundMatchOnLine,
566     std::function<bool(const WhitespaceManager::Change &C)> AlignMacrosMatches,
567     SmallVector<WhitespaceManager::Change, 16> &Changes) {
568   if (StartOfSequence > 0 && StartOfSequence < EndOfSequence) {
569 
570     FoundMatchOnLine = false;
571     int Shift = 0;
572 
573     for (unsigned I = StartOfSequence; I != EndOfSequence; ++I) {
574       if (Changes[I].NewlinesBefore > 0) {
575         Shift = 0;
576         FoundMatchOnLine = false;
577       }
578 
579       // If this is the first matching token to be aligned, remember by how many
580       // spaces it has to be shifted, so the rest of the changes on the line are
581       // shifted by the same amount
582       if (!FoundMatchOnLine && AlignMacrosMatches(Changes[I])) {
583         FoundMatchOnLine = true;
584         Shift = MinColumn - Changes[I].StartOfTokenColumn;
585         Changes[I].Spaces += Shift;
586       }
587 
588       assert(Shift >= 0);
589       Changes[I].StartOfTokenColumn += Shift;
590       if (I + 1 != Changes.size())
591         Changes[I + 1].PreviousEndOfTokenColumn += Shift;
592     }
593   }
594 
595   MinColumn = 0;
596   MaxColumn = UINT_MAX;
597   StartOfSequence = 0;
598   EndOfSequence = 0;
599 }
600 
601 void WhitespaceManager::alignConsecutiveMacros() {
602   if (Style.AlignConsecutiveMacros == FormatStyle::ACS_None)
603     return;
604 
605   auto AlignMacrosMatches = [](const Change &C) {
606     const FormatToken *Current = C.Tok;
607     unsigned SpacesRequiredBefore = 1;
608 
609     if (Current->SpacesRequiredBefore == 0 || !Current->Previous)
610       return false;
611 
612     Current = Current->Previous;
613 
614     // If token is a ")", skip over the parameter list, to the
615     // token that precedes the "("
616     if (Current->is(tok::r_paren) && Current->MatchingParen) {
617       Current = Current->MatchingParen->Previous;
618       SpacesRequiredBefore = 0;
619     }
620 
621     if (!Current || !Current->is(tok::identifier))
622       return false;
623 
624     if (!Current->Previous || !Current->Previous->is(tok::pp_define))
625       return false;
626 
627     // For a macro function, 0 spaces are required between the
628     // identifier and the lparen that opens the parameter list.
629     // For a simple macro, 1 space is required between the
630     // identifier and the first token of the defined value.
631     return Current->Next->SpacesRequiredBefore == SpacesRequiredBefore;
632   };
633 
634   unsigned MinColumn = 0;
635   unsigned MaxColumn = UINT_MAX;
636 
637   // Start and end of the token sequence we're processing.
638   unsigned StartOfSequence = 0;
639   unsigned EndOfSequence = 0;
640 
641   // Whether a matching token has been found on the current line.
642   bool FoundMatchOnLine = false;
643 
644   // Whether the current line consists only of comments
645   bool LineIsComment = true;
646 
647   unsigned I = 0;
648   for (unsigned E = Changes.size(); I != E; ++I) {
649     if (Changes[I].NewlinesBefore != 0) {
650       EndOfSequence = I;
651 
652       // Whether to break the alignment sequence because of an empty line.
653       bool EmptyLineBreak =
654           (Changes[I].NewlinesBefore > 1) &&
655           (Style.AlignConsecutiveMacros != FormatStyle::ACS_AcrossEmptyLines) &&
656           (Style.AlignConsecutiveMacros !=
657            FormatStyle::ACS_AcrossEmptyLinesAndComments);
658 
659       // Whether to break the alignment sequence because of a line without a
660       // match.
661       bool NoMatchBreak =
662           !FoundMatchOnLine &&
663           !(LineIsComment && ((Style.AlignConsecutiveMacros ==
664                                FormatStyle::ACS_AcrossComments) ||
665                               (Style.AlignConsecutiveMacros ==
666                                FormatStyle::ACS_AcrossEmptyLinesAndComments)));
667 
668       if (EmptyLineBreak || NoMatchBreak)
669         AlignMacroSequence(StartOfSequence, EndOfSequence, MinColumn, MaxColumn,
670                            FoundMatchOnLine, AlignMacrosMatches, Changes);
671 
672       // A new line starts, re-initialize line status tracking bools.
673       FoundMatchOnLine = false;
674       LineIsComment = true;
675     }
676 
677     if (!Changes[I].Tok->is(tok::comment)) {
678       LineIsComment = false;
679     }
680 
681     if (!AlignMacrosMatches(Changes[I]))
682       continue;
683 
684     FoundMatchOnLine = true;
685 
686     if (StartOfSequence == 0)
687       StartOfSequence = I;
688 
689     unsigned ChangeMinColumn = Changes[I].StartOfTokenColumn;
690     int LineLengthAfter = -Changes[I].Spaces;
691     for (unsigned j = I; j != E && Changes[j].NewlinesBefore == 0; ++j)
692       LineLengthAfter += Changes[j].Spaces + Changes[j].TokenLength;
693     unsigned ChangeMaxColumn = Style.ColumnLimit - LineLengthAfter;
694 
695     MinColumn = std::max(MinColumn, ChangeMinColumn);
696     MaxColumn = std::min(MaxColumn, ChangeMaxColumn);
697   }
698 
699   EndOfSequence = I;
700   AlignMacroSequence(StartOfSequence, EndOfSequence, MinColumn, MaxColumn,
701                      FoundMatchOnLine, AlignMacrosMatches, Changes);
702 }
703 
704 void WhitespaceManager::alignConsecutiveAssignments() {
705   if (Style.AlignConsecutiveAssignments == FormatStyle::ACS_None)
706     return;
707 
708   AlignTokens(
709       Style,
710       [&](const Change &C) {
711         // Do not align on equal signs that are first on a line.
712         if (C.NewlinesBefore > 0)
713           return false;
714 
715         // Do not align on equal signs that are last on a line.
716         if (&C != &Changes.back() && (&C + 1)->NewlinesBefore > 0)
717           return false;
718 
719         return C.Tok->is(tok::equal);
720       },
721       Changes, /*StartAt=*/0, Style.AlignConsecutiveAssignments);
722 }
723 
724 void WhitespaceManager::alignConsecutiveBitFields() {
725   if (Style.AlignConsecutiveBitFields == FormatStyle::ACS_None)
726     return;
727 
728   AlignTokens(
729       Style,
730       [&](Change const &C) {
731         // Do not align on ':' that is first on a line.
732         if (C.NewlinesBefore > 0)
733           return false;
734 
735         // Do not align on ':' that is last on a line.
736         if (&C != &Changes.back() && (&C + 1)->NewlinesBefore > 0)
737           return false;
738 
739         return C.Tok->is(TT_BitFieldColon);
740       },
741       Changes, /*StartAt=*/0, Style.AlignConsecutiveBitFields);
742 }
743 
744 void WhitespaceManager::alignConsecutiveDeclarations() {
745   if (Style.AlignConsecutiveDeclarations == FormatStyle::ACS_None)
746     return;
747 
748   AlignTokens(
749       Style,
750       [](Change const &C) {
751         // tok::kw_operator is necessary for aligning operator overload
752         // definitions.
753         if (C.Tok->isOneOf(TT_FunctionDeclarationName, tok::kw_operator))
754           return true;
755         if (C.Tok->isNot(TT_StartOfName))
756           return false;
757         if (C.Tok->Previous &&
758             C.Tok->Previous->is(TT_StatementAttributeLikeMacro))
759           return false;
760         // Check if there is a subsequent name that starts the same declaration.
761         for (FormatToken *Next = C.Tok->Next; Next; Next = Next->Next) {
762           if (Next->is(tok::comment))
763             continue;
764           if (Next->is(TT_PointerOrReference))
765             return false;
766           if (!Next->Tok.getIdentifierInfo())
767             break;
768           if (Next->isOneOf(TT_StartOfName, TT_FunctionDeclarationName,
769                             tok::kw_operator))
770             return false;
771         }
772         return true;
773       },
774       Changes, /*StartAt=*/0, Style.AlignConsecutiveDeclarations);
775 }
776 
777 void WhitespaceManager::alignChainedConditionals() {
778   if (Style.BreakBeforeTernaryOperators) {
779     AlignTokens(
780         Style,
781         [](Change const &C) {
782           // Align question operators and last colon
783           return C.Tok->is(TT_ConditionalExpr) &&
784                  ((C.Tok->is(tok::question) && !C.NewlinesBefore) ||
785                   (C.Tok->is(tok::colon) && C.Tok->Next &&
786                    (C.Tok->Next->FakeLParens.size() == 0 ||
787                     C.Tok->Next->FakeLParens.back() != prec::Conditional)));
788         },
789         Changes, /*StartAt=*/0);
790   } else {
791     static auto AlignWrappedOperand = [](Change const &C) {
792       FormatToken *Previous = C.Tok->getPreviousNonComment();
793       return C.NewlinesBefore && Previous && Previous->is(TT_ConditionalExpr) &&
794              (Previous->is(tok::colon) &&
795               (C.Tok->FakeLParens.size() == 0 ||
796                C.Tok->FakeLParens.back() != prec::Conditional));
797     };
798     // Ensure we keep alignment of wrapped operands with non-wrapped operands
799     // Since we actually align the operators, the wrapped operands need the
800     // extra offset to be properly aligned.
801     for (Change &C : Changes) {
802       if (AlignWrappedOperand(C))
803         C.StartOfTokenColumn -= 2;
804     }
805     AlignTokens(
806         Style,
807         [this](Change const &C) {
808           // Align question operators if next operand is not wrapped, as
809           // well as wrapped operands after question operator or last
810           // colon in conditional sequence
811           return (C.Tok->is(TT_ConditionalExpr) && C.Tok->is(tok::question) &&
812                   &C != &Changes.back() && (&C + 1)->NewlinesBefore == 0 &&
813                   !(&C + 1)->IsTrailingComment) ||
814                  AlignWrappedOperand(C);
815         },
816         Changes, /*StartAt=*/0);
817   }
818 }
819 
820 void WhitespaceManager::alignTrailingComments() {
821   unsigned MinColumn = 0;
822   unsigned MaxColumn = UINT_MAX;
823   unsigned StartOfSequence = 0;
824   bool BreakBeforeNext = false;
825   unsigned Newlines = 0;
826   for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
827     if (Changes[i].StartOfBlockComment)
828       continue;
829     Newlines += Changes[i].NewlinesBefore;
830     if (!Changes[i].IsTrailingComment)
831       continue;
832 
833     unsigned ChangeMinColumn = Changes[i].StartOfTokenColumn;
834     unsigned ChangeMaxColumn;
835 
836     if (Style.ColumnLimit == 0)
837       ChangeMaxColumn = UINT_MAX;
838     else if (Style.ColumnLimit >= Changes[i].TokenLength)
839       ChangeMaxColumn = Style.ColumnLimit - Changes[i].TokenLength;
840     else
841       ChangeMaxColumn = ChangeMinColumn;
842 
843     // If we don't create a replacement for this change, we have to consider
844     // it to be immovable.
845     if (!Changes[i].CreateReplacement)
846       ChangeMaxColumn = ChangeMinColumn;
847 
848     if (i + 1 != e && Changes[i + 1].ContinuesPPDirective)
849       ChangeMaxColumn -= 2;
850     // If this comment follows an } in column 0, it probably documents the
851     // closing of a namespace and we don't want to align it.
852     bool FollowsRBraceInColumn0 = i > 0 && Changes[i].NewlinesBefore == 0 &&
853                                   Changes[i - 1].Tok->is(tok::r_brace) &&
854                                   Changes[i - 1].StartOfTokenColumn == 0;
855     bool WasAlignedWithStartOfNextLine = false;
856     if (Changes[i].NewlinesBefore == 1) { // A comment on its own line.
857       unsigned CommentColumn = SourceMgr.getSpellingColumnNumber(
858           Changes[i].OriginalWhitespaceRange.getEnd());
859       for (unsigned j = i + 1; j != e; ++j) {
860         if (Changes[j].Tok->is(tok::comment))
861           continue;
862 
863         unsigned NextColumn = SourceMgr.getSpellingColumnNumber(
864             Changes[j].OriginalWhitespaceRange.getEnd());
865         // The start of the next token was previously aligned with the
866         // start of this comment.
867         WasAlignedWithStartOfNextLine =
868             CommentColumn == NextColumn ||
869             CommentColumn == NextColumn + Style.IndentWidth;
870         break;
871       }
872     }
873     if (!Style.AlignTrailingComments || FollowsRBraceInColumn0) {
874       alignTrailingComments(StartOfSequence, i, MinColumn);
875       MinColumn = ChangeMinColumn;
876       MaxColumn = ChangeMinColumn;
877       StartOfSequence = i;
878     } else if (BreakBeforeNext || Newlines > 1 ||
879                (ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn) ||
880                // Break the comment sequence if the previous line did not end
881                // in a trailing comment.
882                (Changes[i].NewlinesBefore == 1 && i > 0 &&
883                 !Changes[i - 1].IsTrailingComment) ||
884                WasAlignedWithStartOfNextLine) {
885       alignTrailingComments(StartOfSequence, i, MinColumn);
886       MinColumn = ChangeMinColumn;
887       MaxColumn = ChangeMaxColumn;
888       StartOfSequence = i;
889     } else {
890       MinColumn = std::max(MinColumn, ChangeMinColumn);
891       MaxColumn = std::min(MaxColumn, ChangeMaxColumn);
892     }
893     BreakBeforeNext = (i == 0) || (Changes[i].NewlinesBefore > 1) ||
894                       // Never start a sequence with a comment at the beginning
895                       // of the line.
896                       (Changes[i].NewlinesBefore == 1 && StartOfSequence == i);
897     Newlines = 0;
898   }
899   alignTrailingComments(StartOfSequence, Changes.size(), MinColumn);
900 }
901 
902 void WhitespaceManager::alignTrailingComments(unsigned Start, unsigned End,
903                                               unsigned Column) {
904   for (unsigned i = Start; i != End; ++i) {
905     int Shift = 0;
906     if (Changes[i].IsTrailingComment) {
907       Shift = Column - Changes[i].StartOfTokenColumn;
908     }
909     if (Changes[i].StartOfBlockComment) {
910       Shift = Changes[i].IndentationOffset +
911               Changes[i].StartOfBlockComment->StartOfTokenColumn -
912               Changes[i].StartOfTokenColumn;
913     }
914     assert(Shift >= 0);
915     Changes[i].Spaces += Shift;
916     if (i + 1 != Changes.size())
917       Changes[i + 1].PreviousEndOfTokenColumn += Shift;
918     Changes[i].StartOfTokenColumn += Shift;
919   }
920 }
921 
922 void WhitespaceManager::alignEscapedNewlines() {
923   if (Style.AlignEscapedNewlines == FormatStyle::ENAS_DontAlign)
924     return;
925 
926   bool AlignLeft = Style.AlignEscapedNewlines == FormatStyle::ENAS_Left;
927   unsigned MaxEndOfLine = AlignLeft ? 0 : Style.ColumnLimit;
928   unsigned StartOfMacro = 0;
929   for (unsigned i = 1, e = Changes.size(); i < e; ++i) {
930     Change &C = Changes[i];
931     if (C.NewlinesBefore > 0) {
932       if (C.ContinuesPPDirective) {
933         MaxEndOfLine = std::max(C.PreviousEndOfTokenColumn + 2, MaxEndOfLine);
934       } else {
935         alignEscapedNewlines(StartOfMacro + 1, i, MaxEndOfLine);
936         MaxEndOfLine = AlignLeft ? 0 : Style.ColumnLimit;
937         StartOfMacro = i;
938       }
939     }
940   }
941   alignEscapedNewlines(StartOfMacro + 1, Changes.size(), MaxEndOfLine);
942 }
943 
944 void WhitespaceManager::alignEscapedNewlines(unsigned Start, unsigned End,
945                                              unsigned Column) {
946   for (unsigned i = Start; i < End; ++i) {
947     Change &C = Changes[i];
948     if (C.NewlinesBefore > 0) {
949       assert(C.ContinuesPPDirective);
950       if (C.PreviousEndOfTokenColumn + 1 > Column)
951         C.EscapedNewlineColumn = 0;
952       else
953         C.EscapedNewlineColumn = Column;
954     }
955   }
956 }
957 
958 void WhitespaceManager::alignArrayInitializers() {
959   if (Style.AlignArrayOfStructures == FormatStyle::AIAS_None)
960     return;
961 
962   for (unsigned ChangeIndex = 1U, ChangeEnd = Changes.size();
963        ChangeIndex < ChangeEnd; ++ChangeIndex) {
964     auto &C = Changes[ChangeIndex];
965     if (C.Tok->IsArrayInitializer) {
966       bool FoundComplete = false;
967       for (unsigned InsideIndex = ChangeIndex + 1; InsideIndex < ChangeEnd;
968            ++InsideIndex) {
969         if (Changes[InsideIndex].Tok == C.Tok->MatchingParen) {
970           alignArrayInitializers(ChangeIndex, InsideIndex + 1);
971           ChangeIndex = InsideIndex + 1;
972           FoundComplete = true;
973           break;
974         }
975       }
976       if (!FoundComplete)
977         ChangeIndex = ChangeEnd;
978     }
979   }
980 }
981 
982 void WhitespaceManager::alignArrayInitializers(unsigned Start, unsigned End) {
983 
984   if (Style.AlignArrayOfStructures == FormatStyle::AIAS_Right)
985     alignArrayInitializersRightJustified(getCells(Start, End));
986   else if (Style.AlignArrayOfStructures == FormatStyle::AIAS_Left)
987     alignArrayInitializersLeftJustified(getCells(Start, End));
988 }
989 
990 void WhitespaceManager::alignArrayInitializersRightJustified(
991     CellDescriptions &&CellDescs) {
992   auto &Cells = CellDescs.Cells;
993 
994   // Now go through and fixup the spaces.
995   auto *CellIter = Cells.begin();
996   for (auto i = 0U; i < CellDescs.CellCount; i++, ++CellIter) {
997     unsigned NetWidth = 0U;
998     if (isSplitCell(*CellIter))
999       NetWidth = getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces);
1000     auto CellWidth = getMaximumCellWidth(CellIter, NetWidth);
1001 
1002     if (Changes[CellIter->Index].Tok->is(tok::r_brace)) {
1003       // So in here we want to see if there is a brace that falls
1004       // on a line that was split. If so on that line we make sure that
1005       // the spaces in front of the brace are enough.
1006       Changes[CellIter->Index].NewlinesBefore = 0;
1007       Changes[CellIter->Index].Spaces = 0;
1008       for (const auto *Next = CellIter->NextColumnElement; Next != nullptr;
1009            Next = Next->NextColumnElement) {
1010         Changes[Next->Index].Spaces = 0;
1011         Changes[Next->Index].NewlinesBefore = 0;
1012       }
1013       // Unless the array is empty, we need the position of all the
1014       // immediately adjacent cells
1015       if (CellIter != Cells.begin()) {
1016         auto ThisNetWidth =
1017             getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces);
1018         auto MaxNetWidth =
1019             getMaximumNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces,
1020                                CellDescs.CellCount);
1021         if (ThisNetWidth < MaxNetWidth)
1022           Changes[CellIter->Index].Spaces = (MaxNetWidth - ThisNetWidth);
1023         auto RowCount = 1U;
1024         auto Offset = std::distance(Cells.begin(), CellIter);
1025         for (const auto *Next = CellIter->NextColumnElement; Next != nullptr;
1026              Next = Next->NextColumnElement) {
1027           auto *Start = (Cells.begin() + RowCount * CellDescs.CellCount);
1028           auto *End = Start + Offset;
1029           ThisNetWidth = getNetWidth(Start, End, CellDescs.InitialSpaces);
1030           if (ThisNetWidth < MaxNetWidth)
1031             Changes[Next->Index].Spaces = (MaxNetWidth - ThisNetWidth);
1032           ++RowCount;
1033         }
1034       }
1035     } else {
1036       auto ThisWidth =
1037           calculateCellWidth(CellIter->Index, CellIter->EndIndex, true) +
1038           NetWidth;
1039       if (Changes[CellIter->Index].NewlinesBefore == 0) {
1040         Changes[CellIter->Index].Spaces = (CellWidth - (ThisWidth + NetWidth));
1041         Changes[CellIter->Index].Spaces += (i > 0) ? 1 : 0;
1042       }
1043       alignToStartOfCell(CellIter->Index, CellIter->EndIndex);
1044       for (const auto *Next = CellIter->NextColumnElement; Next != nullptr;
1045            Next = Next->NextColumnElement) {
1046         ThisWidth =
1047             calculateCellWidth(Next->Index, Next->EndIndex, true) + NetWidth;
1048         if (Changes[Next->Index].NewlinesBefore == 0) {
1049           Changes[Next->Index].Spaces = (CellWidth - ThisWidth);
1050           Changes[Next->Index].Spaces += (i > 0) ? 1 : 0;
1051         }
1052         alignToStartOfCell(Next->Index, Next->EndIndex);
1053       }
1054     }
1055   }
1056 }
1057 
1058 void WhitespaceManager::alignArrayInitializersLeftJustified(
1059     CellDescriptions &&CellDescs) {
1060   auto &Cells = CellDescs.Cells;
1061 
1062   // Now go through and fixup the spaces.
1063   auto *CellIter = Cells.begin();
1064   // The first cell needs to be against the left brace.
1065   if (Changes[CellIter->Index].NewlinesBefore == 0)
1066     Changes[CellIter->Index].Spaces = 0;
1067   else
1068     Changes[CellIter->Index].Spaces = CellDescs.InitialSpaces;
1069   ++CellIter;
1070   for (auto i = 1U; i < CellDescs.CellCount; i++, ++CellIter) {
1071     auto MaxNetWidth = getMaximumNetWidth(
1072         Cells.begin(), CellIter, CellDescs.InitialSpaces, CellDescs.CellCount);
1073     auto ThisNetWidth =
1074         getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces);
1075     if (Changes[CellIter->Index].NewlinesBefore == 0) {
1076       Changes[CellIter->Index].Spaces =
1077           MaxNetWidth - ThisNetWidth +
1078           (Changes[CellIter->Index].Tok->isNot(tok::r_brace) ? 1 : 0);
1079     }
1080     auto RowCount = 1U;
1081     auto Offset = std::distance(Cells.begin(), CellIter);
1082     for (const auto *Next = CellIter->NextColumnElement; Next != nullptr;
1083          Next = Next->NextColumnElement) {
1084       auto *Start = (Cells.begin() + RowCount * CellDescs.CellCount);
1085       auto *End = Start + Offset;
1086       auto ThisNetWidth = getNetWidth(Start, End, CellDescs.InitialSpaces);
1087       if (Changes[Next->Index].NewlinesBefore == 0) {
1088         Changes[Next->Index].Spaces =
1089             MaxNetWidth - ThisNetWidth +
1090             (Changes[Next->Index].Tok->isNot(tok::r_brace) ? 1 : 0);
1091       }
1092       ++RowCount;
1093     }
1094   }
1095 }
1096 
1097 bool WhitespaceManager::isSplitCell(const CellDescription &Cell) {
1098   if (Cell.HasSplit)
1099     return true;
1100   for (const auto *Next = Cell.NextColumnElement; Next != nullptr;
1101        Next = Next->NextColumnElement) {
1102     if (Next->HasSplit)
1103       return true;
1104   }
1105   return false;
1106 }
1107 
1108 WhitespaceManager::CellDescriptions WhitespaceManager::getCells(unsigned Start,
1109                                                                 unsigned End) {
1110 
1111   unsigned Depth = 0;
1112   unsigned Cell = 0;
1113   unsigned CellCount = 0;
1114   unsigned InitialSpaces = 0;
1115   unsigned InitialTokenLength = 0;
1116   unsigned EndSpaces = 0;
1117   SmallVector<CellDescription> Cells;
1118   const FormatToken *MatchingParen = nullptr;
1119   for (unsigned i = Start; i < End; ++i) {
1120     auto &C = Changes[i];
1121     if (C.Tok->is(tok::l_brace))
1122       ++Depth;
1123     else if (C.Tok->is(tok::r_brace))
1124       --Depth;
1125     if (Depth == 2) {
1126       if (C.Tok->is(tok::l_brace)) {
1127         Cell = 0;
1128         MatchingParen = C.Tok->MatchingParen;
1129         if (InitialSpaces == 0) {
1130           InitialSpaces = C.Spaces + C.TokenLength;
1131           InitialTokenLength = C.TokenLength;
1132           auto j = i - 1;
1133           for (; Changes[j].NewlinesBefore == 0 && j > Start; --j) {
1134             InitialSpaces += Changes[j].Spaces + Changes[j].TokenLength;
1135             InitialTokenLength += Changes[j].TokenLength;
1136           }
1137           if (C.NewlinesBefore == 0) {
1138             InitialSpaces += Changes[j].Spaces + Changes[j].TokenLength;
1139             InitialTokenLength += Changes[j].TokenLength;
1140           }
1141         }
1142       } else if (C.Tok->is(tok::comma)) {
1143         if (!Cells.empty())
1144           Cells.back().EndIndex = i;
1145         Cell++;
1146       }
1147     } else if (Depth == 1) {
1148       if (C.Tok == MatchingParen) {
1149         if (!Cells.empty())
1150           Cells.back().EndIndex = i;
1151         Cells.push_back(CellDescription{i, ++Cell, i + 1, false, nullptr});
1152         CellCount = Cell + 1;
1153         // Go to the next non-comment and ensure there is a break in front
1154         const auto *NextNonComment = C.Tok->getNextNonComment();
1155         while (NextNonComment->is(tok::comma))
1156           NextNonComment = NextNonComment->getNextNonComment();
1157         auto j = i;
1158         while (Changes[j].Tok != NextNonComment && j < End)
1159           j++;
1160         if (j < End && Changes[j].NewlinesBefore == 0 &&
1161             Changes[j].Tok->isNot(tok::r_brace)) {
1162           Changes[j].NewlinesBefore = 1;
1163           // Account for the added token lengths
1164           Changes[j].Spaces = InitialSpaces - InitialTokenLength;
1165         }
1166       } else if (C.Tok->is(tok::comment)) {
1167         // Trailing comments stay at a space past the last token
1168         C.Spaces = Changes[i - 1].Tok->is(tok::comma) ? 1 : 2;
1169       } else if (C.Tok->is(tok::l_brace)) {
1170         // We need to make sure that the ending braces is aligned to the
1171         // start of our initializer
1172         auto j = i - 1;
1173         for (; j > 0 && !Changes[j].Tok->ArrayInitializerLineStart; --j)
1174           ; // Nothing the loop does the work
1175         EndSpaces = Changes[j].Spaces;
1176       }
1177     } else if (Depth == 0 && C.Tok->is(tok::r_brace)) {
1178       C.NewlinesBefore = 1;
1179       C.Spaces = EndSpaces;
1180     }
1181     if (C.Tok->StartsColumn) {
1182       // This gets us past tokens that have been split over multiple
1183       // lines
1184       bool HasSplit = false;
1185       if (Changes[i].NewlinesBefore > 0) {
1186         // So if we split a line previously and the tail line + this token is
1187         // less then the column limit we remove the split here and just put
1188         // the column start at a space past the comma
1189         auto j = i - 1;
1190         if ((j - 1) > Start && Changes[j].Tok->is(tok::comma) &&
1191             Changes[j - 1].NewlinesBefore > 0) {
1192           --j;
1193           auto LineLimit = Changes[j].Spaces + Changes[j].TokenLength;
1194           if (LineLimit < Style.ColumnLimit) {
1195             Changes[i].NewlinesBefore = 0;
1196             Changes[i].Spaces = 1;
1197           }
1198         }
1199       }
1200       while (Changes[i].NewlinesBefore > 0 && Changes[i].Tok == C.Tok) {
1201         Changes[i].Spaces = InitialSpaces;
1202         ++i;
1203         HasSplit = true;
1204       }
1205       if (Changes[i].Tok != C.Tok)
1206         --i;
1207       Cells.push_back(CellDescription{i, Cell, i, HasSplit, nullptr});
1208     }
1209   }
1210 
1211   return linkCells({Cells, CellCount, InitialSpaces});
1212 }
1213 
1214 unsigned WhitespaceManager::calculateCellWidth(unsigned Start, unsigned End,
1215                                                bool WithSpaces) const {
1216   unsigned CellWidth = 0;
1217   for (auto i = Start; i < End; i++) {
1218     if (Changes[i].NewlinesBefore > 0)
1219       CellWidth = 0;
1220     CellWidth += Changes[i].TokenLength;
1221     CellWidth += (WithSpaces ? Changes[i].Spaces : 0);
1222   }
1223   return CellWidth;
1224 }
1225 
1226 void WhitespaceManager::alignToStartOfCell(unsigned Start, unsigned End) {
1227   if ((End - Start) <= 1)
1228     return;
1229   // If the line is broken anywhere in there make sure everything
1230   // is aligned to the parent
1231   for (auto i = Start + 1; i < End; i++) {
1232     if (Changes[i].NewlinesBefore > 0)
1233       Changes[i].Spaces = Changes[Start].Spaces;
1234   }
1235 }
1236 
1237 WhitespaceManager::CellDescriptions
1238 WhitespaceManager::linkCells(CellDescriptions &&CellDesc) {
1239   auto &Cells = CellDesc.Cells;
1240   for (auto *CellIter = Cells.begin(); CellIter != Cells.end(); ++CellIter) {
1241     if (CellIter->NextColumnElement == nullptr &&
1242         ((CellIter + 1) != Cells.end())) {
1243       for (auto *NextIter = CellIter + 1; NextIter != Cells.end(); ++NextIter) {
1244         if (NextIter->Cell == CellIter->Cell) {
1245           CellIter->NextColumnElement = &(*NextIter);
1246           break;
1247         }
1248       }
1249     }
1250   }
1251   return std::move(CellDesc);
1252 }
1253 
1254 void WhitespaceManager::generateChanges() {
1255   for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
1256     const Change &C = Changes[i];
1257     if (i > 0) {
1258       assert(Changes[i - 1].OriginalWhitespaceRange.getBegin() !=
1259                  C.OriginalWhitespaceRange.getBegin() &&
1260              "Generating two replacements for the same location");
1261     }
1262     if (C.CreateReplacement) {
1263       std::string ReplacementText = C.PreviousLinePostfix;
1264       if (C.ContinuesPPDirective)
1265         appendEscapedNewlineText(ReplacementText, C.NewlinesBefore,
1266                                  C.PreviousEndOfTokenColumn,
1267                                  C.EscapedNewlineColumn);
1268       else
1269         appendNewlineText(ReplacementText, C.NewlinesBefore);
1270       appendIndentText(
1271           ReplacementText, C.Tok->IndentLevel, std::max(0, C.Spaces),
1272           C.StartOfTokenColumn - std::max(0, C.Spaces), C.IsAligned);
1273       ReplacementText.append(C.CurrentLinePrefix);
1274       storeReplacement(C.OriginalWhitespaceRange, ReplacementText);
1275     }
1276   }
1277 }
1278 
1279 void WhitespaceManager::storeReplacement(SourceRange Range, StringRef Text) {
1280   unsigned WhitespaceLength = SourceMgr.getFileOffset(Range.getEnd()) -
1281                               SourceMgr.getFileOffset(Range.getBegin());
1282   // Don't create a replacement, if it does not change anything.
1283   if (StringRef(SourceMgr.getCharacterData(Range.getBegin()),
1284                 WhitespaceLength) == Text)
1285     return;
1286   auto Err = Replaces.add(tooling::Replacement(
1287       SourceMgr, CharSourceRange::getCharRange(Range), Text));
1288   // FIXME: better error handling. For now, just print an error message in the
1289   // release version.
1290   if (Err) {
1291     llvm::errs() << llvm::toString(std::move(Err)) << "\n";
1292     assert(false);
1293   }
1294 }
1295 
1296 void WhitespaceManager::appendNewlineText(std::string &Text,
1297                                           unsigned Newlines) {
1298   for (unsigned i = 0; i < Newlines; ++i)
1299     Text.append(UseCRLF ? "\r\n" : "\n");
1300 }
1301 
1302 void WhitespaceManager::appendEscapedNewlineText(
1303     std::string &Text, unsigned Newlines, unsigned PreviousEndOfTokenColumn,
1304     unsigned EscapedNewlineColumn) {
1305   if (Newlines > 0) {
1306     unsigned Spaces =
1307         std::max<int>(1, EscapedNewlineColumn - PreviousEndOfTokenColumn - 1);
1308     for (unsigned i = 0; i < Newlines; ++i) {
1309       Text.append(Spaces, ' ');
1310       Text.append(UseCRLF ? "\\\r\n" : "\\\n");
1311       Spaces = std::max<int>(0, EscapedNewlineColumn - 1);
1312     }
1313   }
1314 }
1315 
1316 void WhitespaceManager::appendIndentText(std::string &Text,
1317                                          unsigned IndentLevel, unsigned Spaces,
1318                                          unsigned WhitespaceStartColumn,
1319                                          bool IsAligned) {
1320   switch (Style.UseTab) {
1321   case FormatStyle::UT_Never:
1322     Text.append(Spaces, ' ');
1323     break;
1324   case FormatStyle::UT_Always: {
1325     if (Style.TabWidth) {
1326       unsigned FirstTabWidth =
1327           Style.TabWidth - WhitespaceStartColumn % Style.TabWidth;
1328 
1329       // Insert only spaces when we want to end up before the next tab.
1330       if (Spaces < FirstTabWidth || Spaces == 1) {
1331         Text.append(Spaces, ' ');
1332         break;
1333       }
1334       // Align to the next tab.
1335       Spaces -= FirstTabWidth;
1336       Text.append("\t");
1337 
1338       Text.append(Spaces / Style.TabWidth, '\t');
1339       Text.append(Spaces % Style.TabWidth, ' ');
1340     } else if (Spaces == 1) {
1341       Text.append(Spaces, ' ');
1342     }
1343     break;
1344   }
1345   case FormatStyle::UT_ForIndentation:
1346     if (WhitespaceStartColumn == 0) {
1347       unsigned Indentation = IndentLevel * Style.IndentWidth;
1348       Spaces = appendTabIndent(Text, Spaces, Indentation);
1349     }
1350     Text.append(Spaces, ' ');
1351     break;
1352   case FormatStyle::UT_ForContinuationAndIndentation:
1353     if (WhitespaceStartColumn == 0)
1354       Spaces = appendTabIndent(Text, Spaces, Spaces);
1355     Text.append(Spaces, ' ');
1356     break;
1357   case FormatStyle::UT_AlignWithSpaces:
1358     if (WhitespaceStartColumn == 0) {
1359       unsigned Indentation =
1360           IsAligned ? IndentLevel * Style.IndentWidth : Spaces;
1361       Spaces = appendTabIndent(Text, Spaces, Indentation);
1362     }
1363     Text.append(Spaces, ' ');
1364     break;
1365   }
1366 }
1367 
1368 unsigned WhitespaceManager::appendTabIndent(std::string &Text, unsigned Spaces,
1369                                             unsigned Indentation) {
1370   // This happens, e.g. when a line in a block comment is indented less than the
1371   // first one.
1372   if (Indentation > Spaces)
1373     Indentation = Spaces;
1374   if (Style.TabWidth) {
1375     unsigned Tabs = Indentation / Style.TabWidth;
1376     Text.append(Tabs, '\t');
1377     Spaces -= Tabs * Style.TabWidth;
1378   }
1379   return Spaces;
1380 }
1381 
1382 } // namespace format
1383 } // namespace clang
1384