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 
17 namespace clang {
18 namespace format {
19 
20 bool WhitespaceManager::Change::IsBeforeInFile::operator()(
21     const Change &C1, const Change &C2) const {
22   return SourceMgr.isBeforeInTranslationUnit(
23       C1.OriginalWhitespaceRange.getBegin(),
24       C2.OriginalWhitespaceRange.getBegin());
25 }
26 
27 WhitespaceManager::Change::Change(const FormatToken &Tok,
28                                   bool CreateReplacement,
29                                   SourceRange OriginalWhitespaceRange,
30                                   int Spaces, unsigned StartOfTokenColumn,
31                                   unsigned NewlinesBefore,
32                                   StringRef PreviousLinePostfix,
33                                   StringRef CurrentLinePrefix, bool IsAligned,
34                                   bool ContinuesPPDirective, bool IsInsideToken)
35     : Tok(&Tok), CreateReplacement(CreateReplacement),
36       OriginalWhitespaceRange(OriginalWhitespaceRange),
37       StartOfTokenColumn(StartOfTokenColumn), NewlinesBefore(NewlinesBefore),
38       PreviousLinePostfix(PreviousLinePostfix),
39       CurrentLinePrefix(CurrentLinePrefix), IsAligned(IsAligned),
40       ContinuesPPDirective(ContinuesPPDirective), Spaces(Spaces),
41       IsInsideToken(IsInsideToken), IsTrailingComment(false), TokenLength(0),
42       PreviousEndOfTokenColumn(0), EscapedNewlineColumn(0),
43       StartOfBlockComment(nullptr), IndentationOffset(0) {}
44 
45 void WhitespaceManager::replaceWhitespace(FormatToken &Tok, unsigned Newlines,
46                                           unsigned Spaces,
47                                           unsigned StartOfTokenColumn,
48                                           bool IsAligned, bool InPPDirective) {
49   if (Tok.Finalized)
50     return;
51   Tok.Decision = (Newlines > 0) ? FD_Break : FD_Continue;
52   Changes.push_back(Change(Tok, /*CreateReplacement=*/true, Tok.WhitespaceRange,
53                            Spaces, StartOfTokenColumn, Newlines, "", "",
54                            IsAligned, InPPDirective && !Tok.IsFirst,
55                            /*IsInsideToken=*/false));
56 }
57 
58 void WhitespaceManager::addUntouchableToken(const FormatToken &Tok,
59                                             bool InPPDirective) {
60   if (Tok.Finalized)
61     return;
62   Changes.push_back(Change(Tok, /*CreateReplacement=*/false,
63                            Tok.WhitespaceRange, /*Spaces=*/0,
64                            Tok.OriginalColumn, Tok.NewlinesBefore, "", "",
65                            /*IsAligned=*/false, InPPDirective && !Tok.IsFirst,
66                            /*IsInsideToken=*/false));
67 }
68 
69 llvm::Error
70 WhitespaceManager::addReplacement(const tooling::Replacement &Replacement) {
71   return Replaces.add(Replacement);
72 }
73 
74 void WhitespaceManager::replaceWhitespaceInToken(
75     const FormatToken &Tok, unsigned Offset, unsigned ReplaceChars,
76     StringRef PreviousPostfix, StringRef CurrentPrefix, bool InPPDirective,
77     unsigned Newlines, int Spaces) {
78   if (Tok.Finalized)
79     return;
80   SourceLocation Start = Tok.getStartOfNonWhitespace().getLocWithOffset(Offset);
81   Changes.push_back(
82       Change(Tok, /*CreateReplacement=*/true,
83              SourceRange(Start, Start.getLocWithOffset(ReplaceChars)), Spaces,
84              std::max(0, Spaces), Newlines, PreviousPostfix, CurrentPrefix,
85              /*IsAligned=*/true, InPPDirective && !Tok.IsFirst,
86              /*IsInsideToken=*/true));
87 }
88 
89 const tooling::Replacements &WhitespaceManager::generateReplacements() {
90   if (Changes.empty())
91     return Replaces;
92 
93   llvm::sort(Changes, Change::IsBeforeInFile(SourceMgr));
94   calculateLineBreakInformation();
95   alignConsecutiveMacros();
96   alignConsecutiveDeclarations();
97   alignConsecutiveAssignments();
98   alignTrailingComments();
99   alignEscapedNewlines();
100   generateChanges();
101 
102   return Replaces;
103 }
104 
105 void WhitespaceManager::calculateLineBreakInformation() {
106   Changes[0].PreviousEndOfTokenColumn = 0;
107   Change *LastOutsideTokenChange = &Changes[0];
108   for (unsigned i = 1, e = Changes.size(); i != e; ++i) {
109     SourceLocation OriginalWhitespaceStart =
110         Changes[i].OriginalWhitespaceRange.getBegin();
111     SourceLocation PreviousOriginalWhitespaceEnd =
112         Changes[i - 1].OriginalWhitespaceRange.getEnd();
113     unsigned OriginalWhitespaceStartOffset =
114         SourceMgr.getFileOffset(OriginalWhitespaceStart);
115     unsigned PreviousOriginalWhitespaceEndOffset =
116         SourceMgr.getFileOffset(PreviousOriginalWhitespaceEnd);
117     assert(PreviousOriginalWhitespaceEndOffset <=
118            OriginalWhitespaceStartOffset);
119     const char *const PreviousOriginalWhitespaceEndData =
120         SourceMgr.getCharacterData(PreviousOriginalWhitespaceEnd);
121     StringRef Text(PreviousOriginalWhitespaceEndData,
122                    SourceMgr.getCharacterData(OriginalWhitespaceStart) -
123                        PreviousOriginalWhitespaceEndData);
124     // Usually consecutive changes would occur in consecutive tokens. This is
125     // not the case however when analyzing some preprocessor runs of the
126     // annotated lines. For example, in this code:
127     //
128     // #if A // line 1
129     // int i = 1;
130     // #else B // line 2
131     // int i = 2;
132     // #endif // line 3
133     //
134     // one of the runs will produce the sequence of lines marked with line 1, 2
135     // and 3. So the two consecutive whitespace changes just before '// line 2'
136     // and before '#endif // line 3' span multiple lines and tokens:
137     //
138     // #else B{change X}[// line 2
139     // int i = 2;
140     // ]{change Y}#endif // line 3
141     //
142     // For this reason, if the text between consecutive changes spans multiple
143     // newlines, the token length must be adjusted to the end of the original
144     // line of the token.
145     auto NewlinePos = Text.find_first_of('\n');
146     if (NewlinePos == StringRef::npos) {
147       Changes[i - 1].TokenLength = OriginalWhitespaceStartOffset -
148                                    PreviousOriginalWhitespaceEndOffset +
149                                    Changes[i].PreviousLinePostfix.size() +
150                                    Changes[i - 1].CurrentLinePrefix.size();
151     } else {
152       Changes[i - 1].TokenLength =
153           NewlinePos + Changes[i - 1].CurrentLinePrefix.size();
154     }
155 
156     // If there are multiple changes in this token, sum up all the changes until
157     // the end of the line.
158     if (Changes[i - 1].IsInsideToken && Changes[i - 1].NewlinesBefore == 0)
159       LastOutsideTokenChange->TokenLength +=
160           Changes[i - 1].TokenLength + Changes[i - 1].Spaces;
161     else
162       LastOutsideTokenChange = &Changes[i - 1];
163 
164     Changes[i].PreviousEndOfTokenColumn =
165         Changes[i - 1].StartOfTokenColumn + Changes[i - 1].TokenLength;
166 
167     Changes[i - 1].IsTrailingComment =
168         (Changes[i].NewlinesBefore > 0 || Changes[i].Tok->is(tok::eof) ||
169          (Changes[i].IsInsideToken && Changes[i].Tok->is(tok::comment))) &&
170         Changes[i - 1].Tok->is(tok::comment) &&
171         // FIXME: This is a dirty hack. The problem is that
172         // BreakableLineCommentSection does comment reflow changes and here is
173         // the aligning of trailing comments. Consider the case where we reflow
174         // the second line up in this example:
175         //
176         // // line 1
177         // // line 2
178         //
179         // That amounts to 2 changes by BreakableLineCommentSection:
180         //  - the first, delimited by (), for the whitespace between the tokens,
181         //  - and second, delimited by [], for the whitespace at the beginning
182         //  of the second token:
183         //
184         // // line 1(
185         // )[// ]line 2
186         //
187         // So in the end we have two changes like this:
188         //
189         // // line1()[ ]line 2
190         //
191         // Note that the OriginalWhitespaceStart of the second change is the
192         // same as the PreviousOriginalWhitespaceEnd of the first change.
193         // In this case, the below check ensures that the second change doesn't
194         // get treated as a trailing comment change here, since this might
195         // trigger additional whitespace to be wrongly inserted before "line 2"
196         // by the comment aligner here.
197         //
198         // For a proper solution we need a mechanism to say to WhitespaceManager
199         // that a particular change breaks the current sequence of trailing
200         // comments.
201         OriginalWhitespaceStart != PreviousOriginalWhitespaceEnd;
202   }
203   // FIXME: The last token is currently not always an eof token; in those
204   // cases, setting TokenLength of the last token to 0 is wrong.
205   Changes.back().TokenLength = 0;
206   Changes.back().IsTrailingComment = Changes.back().Tok->is(tok::comment);
207 
208   const WhitespaceManager::Change *LastBlockComment = nullptr;
209   for (auto &Change : Changes) {
210     // Reset the IsTrailingComment flag for changes inside of trailing comments
211     // so they don't get realigned later. Comment line breaks however still need
212     // to be aligned.
213     if (Change.IsInsideToken && Change.NewlinesBefore == 0)
214       Change.IsTrailingComment = false;
215     Change.StartOfBlockComment = nullptr;
216     Change.IndentationOffset = 0;
217     if (Change.Tok->is(tok::comment)) {
218       if (Change.Tok->is(TT_LineComment) || !Change.IsInsideToken)
219         LastBlockComment = &Change;
220       else {
221         if ((Change.StartOfBlockComment = LastBlockComment))
222           Change.IndentationOffset =
223               Change.StartOfTokenColumn -
224               Change.StartOfBlockComment->StartOfTokenColumn;
225       }
226     } else {
227       LastBlockComment = nullptr;
228     }
229   }
230 }
231 
232 // Align a single sequence of tokens, see AlignTokens below.
233 template <typename F>
234 static void
235 AlignTokenSequence(unsigned Start, unsigned End, unsigned Column, F &&Matches,
236                    SmallVector<WhitespaceManager::Change, 16> &Changes) {
237   bool FoundMatchOnLine = false;
238   int Shift = 0;
239 
240   // ScopeStack keeps track of the current scope depth. It contains indices of
241   // the first token on each scope.
242   // We only run the "Matches" function on tokens from the outer-most scope.
243   // However, we do need to pay special attention to one class of tokens
244   // that are not in the outer-most scope, and that is function parameters
245   // which are split across multiple lines, as illustrated by this example:
246   //   double a(int x);
247   //   int    b(int  y,
248   //          double z);
249   // In the above example, we need to take special care to ensure that
250   // 'double z' is indented along with it's owning function 'b'.
251   SmallVector<unsigned, 16> ScopeStack;
252 
253   for (unsigned i = Start; i != End; ++i) {
254     if (ScopeStack.size() != 0 &&
255         Changes[i].indentAndNestingLevel() <
256             Changes[ScopeStack.back()].indentAndNestingLevel())
257       ScopeStack.pop_back();
258 
259     // Compare current token to previous non-comment token to ensure whether
260     // it is in a deeper scope or not.
261     unsigned PreviousNonComment = i - 1;
262     while (PreviousNonComment > Start &&
263            Changes[PreviousNonComment].Tok->is(tok::comment))
264       PreviousNonComment--;
265     if (i != Start && Changes[i].indentAndNestingLevel() >
266                           Changes[PreviousNonComment].indentAndNestingLevel())
267       ScopeStack.push_back(i);
268 
269     bool InsideNestedScope = ScopeStack.size() != 0;
270 
271     if (Changes[i].NewlinesBefore > 0 && !InsideNestedScope) {
272       Shift = 0;
273       FoundMatchOnLine = false;
274     }
275 
276     // If this is the first matching token to be aligned, remember by how many
277     // spaces it has to be shifted, so the rest of the changes on the line are
278     // shifted by the same amount
279     if (!FoundMatchOnLine && !InsideNestedScope && Matches(Changes[i])) {
280       FoundMatchOnLine = true;
281       Shift = Column - Changes[i].StartOfTokenColumn;
282       Changes[i].Spaces += Shift;
283     }
284 
285     // This is for function parameters that are split across multiple lines,
286     // as mentioned in the ScopeStack comment.
287     if (InsideNestedScope && Changes[i].NewlinesBefore > 0) {
288       unsigned ScopeStart = ScopeStack.back();
289       if (Changes[ScopeStart - 1].Tok->is(TT_FunctionDeclarationName) ||
290           (ScopeStart > Start + 1 &&
291            Changes[ScopeStart - 2].Tok->is(TT_FunctionDeclarationName)))
292         Changes[i].Spaces += Shift;
293     }
294 
295     assert(Shift >= 0);
296     Changes[i].StartOfTokenColumn += Shift;
297     if (i + 1 != Changes.size())
298       Changes[i + 1].PreviousEndOfTokenColumn += Shift;
299   }
300 }
301 
302 // Walk through a subset of the changes, starting at StartAt, and find
303 // sequences of matching tokens to align. To do so, keep track of the lines and
304 // whether or not a matching token was found on a line. If a matching token is
305 // found, extend the current sequence. If the current line cannot be part of a
306 // sequence, e.g. because there is an empty line before it or it contains only
307 // non-matching tokens, finalize the previous sequence.
308 // The value returned is the token on which we stopped, either because we
309 // exhausted all items inside Changes, or because we hit a scope level higher
310 // than our initial scope.
311 // This function is recursive. Each invocation processes only the scope level
312 // equal to the initial level, which is the level of Changes[StartAt].
313 // If we encounter a scope level greater than the initial level, then we call
314 // ourselves recursively, thereby avoiding the pollution of the current state
315 // with the alignment requirements of the nested sub-level. This recursive
316 // behavior is necessary for aligning function prototypes that have one or more
317 // arguments.
318 // If this function encounters a scope level less than the initial level,
319 // it returns the current position.
320 // There is a non-obvious subtlety in the recursive behavior: Even though we
321 // defer processing of nested levels to recursive invocations of this
322 // function, when it comes time to align a sequence of tokens, we run the
323 // alignment on the entire sequence, including the nested levels.
324 // When doing so, most of the nested tokens are skipped, because their
325 // alignment was already handled by the recursive invocations of this function.
326 // However, the special exception is that we do NOT skip function parameters
327 // that are split across multiple lines. See the test case in FormatTest.cpp
328 // that mentions "split function parameter alignment" for an example of this.
329 template <typename F>
330 static unsigned AlignTokens(const FormatStyle &Style, F &&Matches,
331                             SmallVector<WhitespaceManager::Change, 16> &Changes,
332                             unsigned StartAt) {
333   unsigned MinColumn = 0;
334   unsigned MaxColumn = UINT_MAX;
335 
336   // Line number of the start and the end of the current token sequence.
337   unsigned StartOfSequence = 0;
338   unsigned EndOfSequence = 0;
339 
340   // Measure the scope level (i.e. depth of (), [], {}) of the first token, and
341   // abort when we hit any token in a higher scope than the starting one.
342   auto IndentAndNestingLevel = StartAt < Changes.size()
343                                    ? Changes[StartAt].indentAndNestingLevel()
344                                    : std::pair<unsigned, unsigned>(0, 0);
345 
346   // Keep track of the number of commas before the matching tokens, we will only
347   // align a sequence of matching tokens if they are preceded by the same number
348   // of commas.
349   unsigned CommasBeforeLastMatch = 0;
350   unsigned CommasBeforeMatch = 0;
351 
352   // Whether a matching token has been found on the current line.
353   bool FoundMatchOnLine = false;
354 
355   // Aligns a sequence of matching tokens, on the MinColumn column.
356   //
357   // Sequences start from the first matching token to align, and end at the
358   // first token of the first line that doesn't need to be aligned.
359   //
360   // We need to adjust the StartOfTokenColumn of each Change that is on a line
361   // containing any matching token to be aligned and located after such token.
362   auto AlignCurrentSequence = [&] {
363     if (StartOfSequence > 0 && StartOfSequence < EndOfSequence)
364       AlignTokenSequence(StartOfSequence, EndOfSequence, MinColumn, Matches,
365                          Changes);
366     MinColumn = 0;
367     MaxColumn = UINT_MAX;
368     StartOfSequence = 0;
369     EndOfSequence = 0;
370   };
371 
372   unsigned i = StartAt;
373   for (unsigned e = Changes.size(); i != e; ++i) {
374     if (Changes[i].indentAndNestingLevel() < IndentAndNestingLevel)
375       break;
376 
377     if (Changes[i].NewlinesBefore != 0) {
378       CommasBeforeMatch = 0;
379       EndOfSequence = i;
380       // If there is a blank line, or if the last line didn't contain any
381       // matching token, the sequence ends here.
382       if (Changes[i].NewlinesBefore > 1 || !FoundMatchOnLine)
383         AlignCurrentSequence();
384 
385       FoundMatchOnLine = false;
386     }
387 
388     if (Changes[i].Tok->is(tok::comma)) {
389       ++CommasBeforeMatch;
390     } else if (Changes[i].indentAndNestingLevel() > IndentAndNestingLevel) {
391       // Call AlignTokens recursively, skipping over this scope block.
392       unsigned StoppedAt = AlignTokens(Style, Matches, Changes, i);
393       i = StoppedAt - 1;
394       continue;
395     }
396 
397     if (!Matches(Changes[i]))
398       continue;
399 
400     // If there is more than one matching token per line, or if the number of
401     // preceding commas, do not match anymore, end the sequence.
402     if (FoundMatchOnLine || CommasBeforeMatch != CommasBeforeLastMatch)
403       AlignCurrentSequence();
404 
405     CommasBeforeLastMatch = CommasBeforeMatch;
406     FoundMatchOnLine = true;
407 
408     if (StartOfSequence == 0)
409       StartOfSequence = i;
410 
411     unsigned ChangeMinColumn = Changes[i].StartOfTokenColumn;
412     int LineLengthAfter = -Changes[i].Spaces;
413     for (unsigned j = i; j != e && Changes[j].NewlinesBefore == 0; ++j)
414       LineLengthAfter += Changes[j].Spaces + Changes[j].TokenLength;
415     unsigned ChangeMaxColumn = Style.ColumnLimit - LineLengthAfter;
416 
417     // If we are restricted by the maximum column width, end the sequence.
418     if (ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn ||
419         CommasBeforeLastMatch != CommasBeforeMatch) {
420       AlignCurrentSequence();
421       StartOfSequence = i;
422     }
423 
424     MinColumn = std::max(MinColumn, ChangeMinColumn);
425     MaxColumn = std::min(MaxColumn, ChangeMaxColumn);
426   }
427 
428   EndOfSequence = i;
429   AlignCurrentSequence();
430   return i;
431 }
432 
433 // Aligns a sequence of matching tokens, on the MinColumn column.
434 //
435 // Sequences start from the first matching token to align, and end at the
436 // first token of the first line that doesn't need to be aligned.
437 //
438 // We need to adjust the StartOfTokenColumn of each Change that is on a line
439 // containing any matching token to be aligned and located after such token.
440 static void AlignMacroSequence(
441     unsigned &StartOfSequence, unsigned &EndOfSequence, unsigned &MinColumn,
442     unsigned &MaxColumn, bool &FoundMatchOnLine,
443     std::function<bool(const WhitespaceManager::Change &C)> AlignMacrosMatches,
444     SmallVector<WhitespaceManager::Change, 16> &Changes) {
445   if (StartOfSequence > 0 && StartOfSequence < EndOfSequence) {
446 
447     FoundMatchOnLine = false;
448     int Shift = 0;
449 
450     for (unsigned I = StartOfSequence; I != EndOfSequence; ++I) {
451       if (Changes[I].NewlinesBefore > 0) {
452         Shift = 0;
453         FoundMatchOnLine = false;
454       }
455 
456       // If this is the first matching token to be aligned, remember by how many
457       // spaces it has to be shifted, so the rest of the changes on the line are
458       // shifted by the same amount
459       if (!FoundMatchOnLine && AlignMacrosMatches(Changes[I])) {
460         FoundMatchOnLine = true;
461         Shift = MinColumn - Changes[I].StartOfTokenColumn;
462         Changes[I].Spaces += Shift;
463       }
464 
465       assert(Shift >= 0);
466       Changes[I].StartOfTokenColumn += Shift;
467       if (I + 1 != Changes.size())
468         Changes[I + 1].PreviousEndOfTokenColumn += Shift;
469     }
470   }
471 
472   MinColumn = 0;
473   MaxColumn = UINT_MAX;
474   StartOfSequence = 0;
475   EndOfSequence = 0;
476 }
477 
478 void WhitespaceManager::alignConsecutiveMacros() {
479   if (!Style.AlignConsecutiveMacros)
480     return;
481 
482   auto AlignMacrosMatches = [](const Change &C) {
483     const FormatToken *Current = C.Tok;
484     unsigned SpacesRequiredBefore = 1;
485 
486     if (Current->SpacesRequiredBefore == 0 || !Current->Previous)
487       return false;
488 
489     Current = Current->Previous;
490 
491     // If token is a ")", skip over the parameter list, to the
492     // token that precedes the "("
493     if (Current->is(tok::r_paren) && Current->MatchingParen) {
494       Current = Current->MatchingParen->Previous;
495       SpacesRequiredBefore = 0;
496     }
497 
498     if (!Current || !Current->is(tok::identifier))
499       return false;
500 
501     if (!Current->Previous || !Current->Previous->is(tok::pp_define))
502       return false;
503 
504     // For a macro function, 0 spaces are required between the
505     // identifier and the lparen that opens the parameter list.
506     // For a simple macro, 1 space is required between the
507     // identifier and the first token of the defined value.
508     return Current->Next->SpacesRequiredBefore == SpacesRequiredBefore;
509   };
510 
511   unsigned MinColumn = 0;
512   unsigned MaxColumn = UINT_MAX;
513 
514   // Start and end of the token sequence we're processing.
515   unsigned StartOfSequence = 0;
516   unsigned EndOfSequence = 0;
517 
518   // Whether a matching token has been found on the current line.
519   bool FoundMatchOnLine = false;
520 
521   unsigned I = 0;
522   for (unsigned E = Changes.size(); I != E; ++I) {
523     if (Changes[I].NewlinesBefore != 0) {
524       EndOfSequence = I;
525       // If there is a blank line, or if the last line didn't contain any
526       // matching token, the sequence ends here.
527       if (Changes[I].NewlinesBefore > 1 || !FoundMatchOnLine)
528         AlignMacroSequence(StartOfSequence, EndOfSequence, MinColumn, MaxColumn,
529                            FoundMatchOnLine, AlignMacrosMatches, Changes);
530 
531       FoundMatchOnLine = false;
532     }
533 
534     if (!AlignMacrosMatches(Changes[I]))
535       continue;
536 
537     FoundMatchOnLine = true;
538 
539     if (StartOfSequence == 0)
540       StartOfSequence = I;
541 
542     unsigned ChangeMinColumn = Changes[I].StartOfTokenColumn;
543     int LineLengthAfter = -Changes[I].Spaces;
544     for (unsigned j = I; j != E && Changes[j].NewlinesBefore == 0; ++j)
545       LineLengthAfter += Changes[j].Spaces + Changes[j].TokenLength;
546     unsigned ChangeMaxColumn = Style.ColumnLimit - LineLengthAfter;
547 
548     MinColumn = std::max(MinColumn, ChangeMinColumn);
549     MaxColumn = std::min(MaxColumn, ChangeMaxColumn);
550   }
551 
552   EndOfSequence = I;
553   AlignMacroSequence(StartOfSequence, EndOfSequence, MinColumn, MaxColumn,
554                      FoundMatchOnLine, AlignMacrosMatches, Changes);
555 }
556 
557 void WhitespaceManager::alignConsecutiveAssignments() {
558   if (!Style.AlignConsecutiveAssignments)
559     return;
560 
561   AlignTokens(
562       Style,
563       [&](const Change &C) {
564         // Do not align on equal signs that are first on a line.
565         if (C.NewlinesBefore > 0)
566           return false;
567 
568         // Do not align on equal signs that are last on a line.
569         if (&C != &Changes.back() && (&C + 1)->NewlinesBefore > 0)
570           return false;
571 
572         return C.Tok->is(tok::equal);
573       },
574       Changes, /*StartAt=*/0);
575 }
576 
577 void WhitespaceManager::alignConsecutiveDeclarations() {
578   if (!Style.AlignConsecutiveDeclarations)
579     return;
580 
581   // FIXME: Currently we don't handle properly the PointerAlignment: Right
582   // The * and & are not aligned and are left dangling. Something has to be done
583   // about it, but it raises the question of alignment of code like:
584   //   const char* const* v1;
585   //   float const* v2;
586   //   SomeVeryLongType const& v3;
587   AlignTokens(
588       Style,
589       [](Change const &C) {
590         // tok::kw_operator is necessary for aligning operator overload
591         // definitions.
592         if (C.Tok->isOneOf(TT_FunctionDeclarationName, tok::kw_operator))
593           return true;
594         if (C.Tok->isNot(TT_StartOfName))
595           return false;
596         // Check if there is a subsequent name that starts the same declaration.
597         for (FormatToken *Next = C.Tok->Next; Next; Next = Next->Next) {
598           if (Next->is(tok::comment))
599             continue;
600           if (!Next->Tok.getIdentifierInfo())
601             break;
602           if (Next->isOneOf(TT_StartOfName, TT_FunctionDeclarationName,
603                             tok::kw_operator))
604             return false;
605         }
606         return true;
607       },
608       Changes, /*StartAt=*/0);
609 }
610 
611 void WhitespaceManager::alignTrailingComments() {
612   unsigned MinColumn = 0;
613   unsigned MaxColumn = UINT_MAX;
614   unsigned StartOfSequence = 0;
615   bool BreakBeforeNext = false;
616   unsigned Newlines = 0;
617   for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
618     if (Changes[i].StartOfBlockComment)
619       continue;
620     Newlines += Changes[i].NewlinesBefore;
621     if (!Changes[i].IsTrailingComment)
622       continue;
623 
624     unsigned ChangeMinColumn = Changes[i].StartOfTokenColumn;
625     unsigned ChangeMaxColumn;
626 
627     if (Style.ColumnLimit == 0)
628       ChangeMaxColumn = UINT_MAX;
629     else if (Style.ColumnLimit >= Changes[i].TokenLength)
630       ChangeMaxColumn = Style.ColumnLimit - Changes[i].TokenLength;
631     else
632       ChangeMaxColumn = ChangeMinColumn;
633 
634     // If we don't create a replacement for this change, we have to consider
635     // it to be immovable.
636     if (!Changes[i].CreateReplacement)
637       ChangeMaxColumn = ChangeMinColumn;
638 
639     if (i + 1 != e && Changes[i + 1].ContinuesPPDirective)
640       ChangeMaxColumn -= 2;
641     // If this comment follows an } in column 0, it probably documents the
642     // closing of a namespace and we don't want to align it.
643     bool FollowsRBraceInColumn0 = i > 0 && Changes[i].NewlinesBefore == 0 &&
644                                   Changes[i - 1].Tok->is(tok::r_brace) &&
645                                   Changes[i - 1].StartOfTokenColumn == 0;
646     bool WasAlignedWithStartOfNextLine = false;
647     if (Changes[i].NewlinesBefore == 1) { // A comment on its own line.
648       unsigned CommentColumn = SourceMgr.getSpellingColumnNumber(
649           Changes[i].OriginalWhitespaceRange.getEnd());
650       for (unsigned j = i + 1; j != e; ++j) {
651         if (Changes[j].Tok->is(tok::comment))
652           continue;
653 
654         unsigned NextColumn = SourceMgr.getSpellingColumnNumber(
655             Changes[j].OriginalWhitespaceRange.getEnd());
656         // The start of the next token was previously aligned with the
657         // start of this comment.
658         WasAlignedWithStartOfNextLine =
659             CommentColumn == NextColumn ||
660             CommentColumn == NextColumn + Style.IndentWidth;
661         break;
662       }
663     }
664     if (!Style.AlignTrailingComments || FollowsRBraceInColumn0) {
665       alignTrailingComments(StartOfSequence, i, MinColumn);
666       MinColumn = ChangeMinColumn;
667       MaxColumn = ChangeMinColumn;
668       StartOfSequence = i;
669     } else if (BreakBeforeNext || Newlines > 1 ||
670                (ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn) ||
671                // Break the comment sequence if the previous line did not end
672                // in a trailing comment.
673                (Changes[i].NewlinesBefore == 1 && i > 0 &&
674                 !Changes[i - 1].IsTrailingComment) ||
675                WasAlignedWithStartOfNextLine) {
676       alignTrailingComments(StartOfSequence, i, MinColumn);
677       MinColumn = ChangeMinColumn;
678       MaxColumn = ChangeMaxColumn;
679       StartOfSequence = i;
680     } else {
681       MinColumn = std::max(MinColumn, ChangeMinColumn);
682       MaxColumn = std::min(MaxColumn, ChangeMaxColumn);
683     }
684     BreakBeforeNext = (i == 0) || (Changes[i].NewlinesBefore > 1) ||
685                       // Never start a sequence with a comment at the beginning
686                       // of the line.
687                       (Changes[i].NewlinesBefore == 1 && StartOfSequence == i);
688     Newlines = 0;
689   }
690   alignTrailingComments(StartOfSequence, Changes.size(), MinColumn);
691 }
692 
693 void WhitespaceManager::alignTrailingComments(unsigned Start, unsigned End,
694                                               unsigned Column) {
695   for (unsigned i = Start; i != End; ++i) {
696     int Shift = 0;
697     if (Changes[i].IsTrailingComment) {
698       Shift = Column - Changes[i].StartOfTokenColumn;
699     }
700     if (Changes[i].StartOfBlockComment) {
701       Shift = Changes[i].IndentationOffset +
702               Changes[i].StartOfBlockComment->StartOfTokenColumn -
703               Changes[i].StartOfTokenColumn;
704     }
705     assert(Shift >= 0);
706     Changes[i].Spaces += Shift;
707     if (i + 1 != Changes.size())
708       Changes[i + 1].PreviousEndOfTokenColumn += Shift;
709     Changes[i].StartOfTokenColumn += Shift;
710   }
711 }
712 
713 void WhitespaceManager::alignEscapedNewlines() {
714   if (Style.AlignEscapedNewlines == FormatStyle::ENAS_DontAlign)
715     return;
716 
717   bool AlignLeft = Style.AlignEscapedNewlines == FormatStyle::ENAS_Left;
718   unsigned MaxEndOfLine = AlignLeft ? 0 : Style.ColumnLimit;
719   unsigned StartOfMacro = 0;
720   for (unsigned i = 1, e = Changes.size(); i < e; ++i) {
721     Change &C = Changes[i];
722     if (C.NewlinesBefore > 0) {
723       if (C.ContinuesPPDirective) {
724         MaxEndOfLine = std::max(C.PreviousEndOfTokenColumn + 2, MaxEndOfLine);
725       } else {
726         alignEscapedNewlines(StartOfMacro + 1, i, MaxEndOfLine);
727         MaxEndOfLine = AlignLeft ? 0 : Style.ColumnLimit;
728         StartOfMacro = i;
729       }
730     }
731   }
732   alignEscapedNewlines(StartOfMacro + 1, Changes.size(), MaxEndOfLine);
733 }
734 
735 void WhitespaceManager::alignEscapedNewlines(unsigned Start, unsigned End,
736                                              unsigned Column) {
737   for (unsigned i = Start; i < End; ++i) {
738     Change &C = Changes[i];
739     if (C.NewlinesBefore > 0) {
740       assert(C.ContinuesPPDirective);
741       if (C.PreviousEndOfTokenColumn + 1 > Column)
742         C.EscapedNewlineColumn = 0;
743       else
744         C.EscapedNewlineColumn = Column;
745     }
746   }
747 }
748 
749 void WhitespaceManager::generateChanges() {
750   for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
751     const Change &C = Changes[i];
752     if (i > 0) {
753       assert(Changes[i - 1].OriginalWhitespaceRange.getBegin() !=
754                  C.OriginalWhitespaceRange.getBegin() &&
755              "Generating two replacements for the same location");
756     }
757     if (C.CreateReplacement) {
758       std::string ReplacementText = C.PreviousLinePostfix;
759       if (C.ContinuesPPDirective)
760         appendEscapedNewlineText(ReplacementText, C.NewlinesBefore,
761                                  C.PreviousEndOfTokenColumn,
762                                  C.EscapedNewlineColumn);
763       else
764         appendNewlineText(ReplacementText, C.NewlinesBefore);
765       appendIndentText(
766           ReplacementText, C.Tok->IndentLevel, std::max(0, C.Spaces),
767           C.StartOfTokenColumn - std::max(0, C.Spaces), C.IsAligned);
768       ReplacementText.append(C.CurrentLinePrefix);
769       storeReplacement(C.OriginalWhitespaceRange, ReplacementText);
770     }
771   }
772 }
773 
774 void WhitespaceManager::storeReplacement(SourceRange Range, StringRef Text) {
775   unsigned WhitespaceLength = SourceMgr.getFileOffset(Range.getEnd()) -
776                               SourceMgr.getFileOffset(Range.getBegin());
777   // Don't create a replacement, if it does not change anything.
778   if (StringRef(SourceMgr.getCharacterData(Range.getBegin()),
779                 WhitespaceLength) == Text)
780     return;
781   auto Err = Replaces.add(tooling::Replacement(
782       SourceMgr, CharSourceRange::getCharRange(Range), Text));
783   // FIXME: better error handling. For now, just print an error message in the
784   // release version.
785   if (Err) {
786     llvm::errs() << llvm::toString(std::move(Err)) << "\n";
787     assert(false);
788   }
789 }
790 
791 void WhitespaceManager::appendNewlineText(std::string &Text,
792                                           unsigned Newlines) {
793   for (unsigned i = 0; i < Newlines; ++i)
794     Text.append(UseCRLF ? "\r\n" : "\n");
795 }
796 
797 void WhitespaceManager::appendEscapedNewlineText(
798     std::string &Text, unsigned Newlines, unsigned PreviousEndOfTokenColumn,
799     unsigned EscapedNewlineColumn) {
800   if (Newlines > 0) {
801     unsigned Spaces =
802         std::max<int>(1, EscapedNewlineColumn - PreviousEndOfTokenColumn - 1);
803     for (unsigned i = 0; i < Newlines; ++i) {
804       Text.append(Spaces, ' ');
805       Text.append(UseCRLF ? "\\\r\n" : "\\\n");
806       Spaces = std::max<int>(0, EscapedNewlineColumn - 1);
807     }
808   }
809 }
810 
811 void WhitespaceManager::appendIndentText(std::string &Text,
812                                          unsigned IndentLevel, unsigned Spaces,
813                                          unsigned WhitespaceStartColumn,
814                                          bool IsAligned) {
815   switch (Style.UseTab) {
816   case FormatStyle::UT_Never:
817     Text.append(Spaces, ' ');
818     break;
819   case FormatStyle::UT_Always: {
820     if (Style.TabWidth) {
821       unsigned FirstTabWidth =
822           Style.TabWidth - WhitespaceStartColumn % Style.TabWidth;
823 
824       // Insert only spaces when we want to end up before the next tab.
825       if (Spaces < FirstTabWidth || Spaces == 1) {
826         Text.append(Spaces, ' ');
827         break;
828       }
829       // Align to the next tab.
830       Spaces -= FirstTabWidth;
831       Text.append("\t");
832 
833       Text.append(Spaces / Style.TabWidth, '\t');
834       Text.append(Spaces % Style.TabWidth, ' ');
835     } else if (Spaces == 1) {
836       Text.append(Spaces, ' ');
837     }
838     break;
839   }
840   case FormatStyle::UT_ForIndentation:
841     if (WhitespaceStartColumn == 0) {
842       unsigned Indentation = IndentLevel * Style.IndentWidth;
843       Spaces = appendTabIndent(Text, Spaces, Indentation);
844     }
845     Text.append(Spaces, ' ');
846     break;
847   case FormatStyle::UT_ForContinuationAndIndentation:
848     if (WhitespaceStartColumn == 0)
849       Spaces = appendTabIndent(Text, Spaces, Spaces);
850     Text.append(Spaces, ' ');
851     break;
852   case FormatStyle::UT_AlignWithSpaces:
853     if (WhitespaceStartColumn == 0) {
854       unsigned Indentation =
855           IsAligned ? IndentLevel * Style.IndentWidth : Spaces;
856       Spaces = appendTabIndent(Text, Spaces, Indentation);
857     }
858     Text.append(Spaces, ' ');
859     break;
860   }
861 }
862 
863 unsigned WhitespaceManager::appendTabIndent(std::string &Text, unsigned Spaces,
864                                             unsigned Indentation) {
865   // This happens, e.g. when a line in a block comment is indented less than the
866   // first one.
867   if (Indentation > Spaces)
868     Indentation = Spaces;
869   if (Style.TabWidth) {
870     unsigned Tabs = Indentation / Style.TabWidth;
871     Text.append(Tabs, '\t');
872     Spaces -= Tabs * Style.TabWidth;
873   }
874   return Spaces;
875 }
876 
877 } // namespace format
878 } // namespace clang
879