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