1 //===--- WhitespaceManager.cpp - Format C++ code --------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// \brief This file implements WhitespaceManager class.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "WhitespaceManager.h"
16 #include "llvm/ADT/STLExtras.h"
17 
18 namespace clang {
19 namespace format {
20 
21 bool
22 WhitespaceManager::Change::IsBeforeInFile::operator()(const Change &C1,
23                                                       const Change &C2) const {
24   return SourceMgr.isBeforeInTranslationUnit(
25       C1.OriginalWhitespaceRange.getBegin(),
26       C2.OriginalWhitespaceRange.getBegin());
27 }
28 
29 WhitespaceManager::Change::Change(
30     bool CreateReplacement, const SourceRange &OriginalWhitespaceRange,
31     unsigned Spaces, unsigned StartOfTokenColumn, unsigned NewlinesBefore,
32     StringRef PreviousLinePostfix, StringRef CurrentLinePrefix,
33     tok::TokenKind Kind, bool ContinuesPPDirective)
34     : CreateReplacement(CreateReplacement),
35       OriginalWhitespaceRange(OriginalWhitespaceRange),
36       StartOfTokenColumn(StartOfTokenColumn), NewlinesBefore(NewlinesBefore),
37       PreviousLinePostfix(PreviousLinePostfix),
38       CurrentLinePrefix(CurrentLinePrefix), Kind(Kind),
39       ContinuesPPDirective(ContinuesPPDirective), Spaces(Spaces) {}
40 
41 void WhitespaceManager::replaceWhitespace(const FormatToken &Tok,
42                                           unsigned Newlines, unsigned Spaces,
43                                           unsigned StartOfTokenColumn,
44                                           bool InPPDirective) {
45   Changes.push_back(Change(true, Tok.WhitespaceRange, Spaces,
46                            StartOfTokenColumn, Newlines, "", "",
47                            Tok.Tok.getKind(), InPPDirective && !Tok.IsFirst));
48 }
49 
50 void WhitespaceManager::addUntouchableToken(const FormatToken &Tok,
51                                             bool InPPDirective) {
52   Changes.push_back(Change(false, Tok.WhitespaceRange, /*Spaces=*/0,
53                            Tok.OriginalColumn, Tok.NewlinesBefore, "", "",
54                            Tok.Tok.getKind(), InPPDirective && !Tok.IsFirst));
55 }
56 
57 void WhitespaceManager::replaceWhitespaceInToken(
58     const FormatToken &Tok, unsigned Offset, unsigned ReplaceChars,
59     StringRef PreviousPostfix, StringRef CurrentPrefix, bool InPPDirective,
60     unsigned Newlines, unsigned Spaces) {
61   Changes.push_back(Change(
62       true, SourceRange(Tok.getStartOfNonWhitespace().getLocWithOffset(Offset),
63                         Tok.getStartOfNonWhitespace().getLocWithOffset(
64                             Offset + ReplaceChars)),
65       Spaces, Spaces, Newlines, PreviousPostfix, CurrentPrefix,
66       // If we don't add a newline this change doesn't start a comment. Thus,
67       // when we align line comments, we don't need to treat this change as one.
68       // FIXME: We still need to take this change in account to properly
69       // calculate the new length of the comment and to calculate the changes
70       // for which to do the alignment when aligning comments.
71       Tok.Type == TT_LineComment && Newlines > 0 ? tok::comment : tok::unknown,
72       InPPDirective && !Tok.IsFirst));
73 }
74 
75 const tooling::Replacements &WhitespaceManager::generateReplacements() {
76   if (Changes.empty())
77     return Replaces;
78 
79   std::sort(Changes.begin(), Changes.end(), Change::IsBeforeInFile(SourceMgr));
80   calculateLineBreakInformation();
81   alignTrailingComments();
82   alignEscapedNewlines();
83   generateChanges();
84 
85   return Replaces;
86 }
87 
88 void WhitespaceManager::calculateLineBreakInformation() {
89   Changes[0].PreviousEndOfTokenColumn = 0;
90   for (unsigned i = 1, e = Changes.size(); i != e; ++i) {
91     unsigned OriginalWhitespaceStart =
92         SourceMgr.getFileOffset(Changes[i].OriginalWhitespaceRange.getBegin());
93     unsigned PreviousOriginalWhitespaceEnd = SourceMgr.getFileOffset(
94         Changes[i - 1].OriginalWhitespaceRange.getEnd());
95     Changes[i - 1].TokenLength = OriginalWhitespaceStart -
96                                  PreviousOriginalWhitespaceEnd +
97                                  Changes[i].PreviousLinePostfix.size() +
98                                  Changes[i - 1].CurrentLinePrefix.size();
99 
100     Changes[i].PreviousEndOfTokenColumn =
101         Changes[i - 1].StartOfTokenColumn + Changes[i - 1].TokenLength;
102 
103     Changes[i - 1].IsTrailingComment =
104         (Changes[i].NewlinesBefore > 0 || Changes[i].Kind == tok::eof) &&
105         Changes[i - 1].Kind == tok::comment;
106   }
107   // FIXME: The last token is currently not always an eof token; in those
108   // cases, setting TokenLength of the last token to 0 is wrong.
109   Changes.back().TokenLength = 0;
110   Changes.back().IsTrailingComment = Changes.back().Kind == tok::comment;
111 }
112 
113 void WhitespaceManager::alignTrailingComments() {
114   unsigned MinColumn = 0;
115   unsigned MaxColumn = UINT_MAX;
116   unsigned StartOfSequence = 0;
117   bool BreakBeforeNext = false;
118   unsigned Newlines = 0;
119   for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
120     unsigned ChangeMinColumn = Changes[i].StartOfTokenColumn;
121     // FIXME: Correctly handle ChangeMaxColumn in PP directives.
122     unsigned ChangeMaxColumn = Style.ColumnLimit - Changes[i].TokenLength;
123     Newlines += Changes[i].NewlinesBefore;
124     if (Changes[i].IsTrailingComment) {
125       // If this comment follows an } in column 0, it probably documents the
126       // closing of a namespace and we don't want to align it.
127       bool FollowsRBraceInColumn0 = i > 0 && Changes[i].NewlinesBefore == 0 &&
128                                     Changes[i - 1].Kind == tok::r_brace &&
129                                     Changes[i - 1].StartOfTokenColumn == 0;
130       bool WasAlignedWithStartOfNextLine =
131           // A comment on its own line.
132           Changes[i].NewlinesBefore == 1 &&
133           // Not the last line.
134           i + 1 != e &&
135           // The start of the next token was previously aligned with
136           // the start of this comment.
137           (SourceMgr.getSpellingColumnNumber(
138                Changes[i].OriginalWhitespaceRange.getEnd()) ==
139            SourceMgr.getSpellingColumnNumber(
140                Changes[i + 1].OriginalWhitespaceRange.getEnd())) &&
141           // Which is not a comment itself.
142           Changes[i + 1].Kind != tok::comment;
143       if (!Style.AlignTrailingComments || FollowsRBraceInColumn0) {
144         alignTrailingComments(StartOfSequence, i, MinColumn);
145         MinColumn = ChangeMinColumn;
146         MaxColumn = ChangeMinColumn;
147         StartOfSequence = i;
148       } else if (BreakBeforeNext || Newlines > 1 ||
149                  (ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn) ||
150                  // Break the comment sequence if the previous line did not end
151                  // in a trailing comment.
152                  (Changes[i].NewlinesBefore == 1 && i > 0 &&
153                   !Changes[i - 1].IsTrailingComment) ||
154                  WasAlignedWithStartOfNextLine) {
155         alignTrailingComments(StartOfSequence, i, MinColumn);
156         MinColumn = ChangeMinColumn;
157         MaxColumn = ChangeMaxColumn;
158         StartOfSequence = i;
159       } else {
160         MinColumn = std::max(MinColumn, ChangeMinColumn);
161         MaxColumn = std::min(MaxColumn, ChangeMaxColumn);
162       }
163       BreakBeforeNext =
164           (i == 0) || (Changes[i].NewlinesBefore > 1) ||
165           // Never start a sequence with a comment at the beginning of
166           // the line.
167           (Changes[i].NewlinesBefore == 1 && StartOfSequence == i);
168       Newlines = 0;
169     }
170   }
171   alignTrailingComments(StartOfSequence, Changes.size(), MinColumn);
172 }
173 
174 void WhitespaceManager::alignTrailingComments(unsigned Start, unsigned End,
175                                               unsigned Column) {
176   for (unsigned i = Start; i != End; ++i) {
177     if (Changes[i].IsTrailingComment) {
178       assert(Column >= Changes[i].StartOfTokenColumn);
179       Changes[i].Spaces += Column - Changes[i].StartOfTokenColumn;
180       Changes[i].StartOfTokenColumn = Column;
181     }
182   }
183 }
184 
185 void WhitespaceManager::alignEscapedNewlines() {
186   unsigned MaxEndOfLine =
187       Style.AlignEscapedNewlinesLeft ? 0 : Style.ColumnLimit;
188   unsigned StartOfMacro = 0;
189   for (unsigned i = 1, e = Changes.size(); i < e; ++i) {
190     Change &C = Changes[i];
191     if (C.NewlinesBefore > 0) {
192       if (C.ContinuesPPDirective) {
193         MaxEndOfLine = std::max(C.PreviousEndOfTokenColumn + 2, MaxEndOfLine);
194       } else {
195         alignEscapedNewlines(StartOfMacro + 1, i, MaxEndOfLine);
196         MaxEndOfLine = Style.AlignEscapedNewlinesLeft ? 0 : Style.ColumnLimit;
197         StartOfMacro = i;
198       }
199     }
200   }
201   alignEscapedNewlines(StartOfMacro + 1, Changes.size(), MaxEndOfLine);
202 }
203 
204 void WhitespaceManager::alignEscapedNewlines(unsigned Start, unsigned End,
205                                              unsigned Column) {
206   for (unsigned i = Start; i < End; ++i) {
207     Change &C = Changes[i];
208     if (C.NewlinesBefore > 0) {
209       assert(C.ContinuesPPDirective);
210       if (C.PreviousEndOfTokenColumn + 1 > Column)
211         C.EscapedNewlineColumn = 0;
212       else
213         C.EscapedNewlineColumn = Column;
214     }
215   }
216 }
217 
218 void WhitespaceManager::generateChanges() {
219   for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
220     const Change &C = Changes[i];
221     if (C.CreateReplacement) {
222       std::string ReplacementText = C.PreviousLinePostfix;
223       if (C.ContinuesPPDirective)
224         appendNewlineText(ReplacementText, C.NewlinesBefore,
225                           C.PreviousEndOfTokenColumn, C.EscapedNewlineColumn);
226       else
227         appendNewlineText(ReplacementText, C.NewlinesBefore);
228       appendIndentText(ReplacementText, C.Spaces);
229       ReplacementText.append(C.CurrentLinePrefix);
230       storeReplacement(C.OriginalWhitespaceRange, ReplacementText);
231     }
232   }
233 }
234 
235 void WhitespaceManager::storeReplacement(const SourceRange &Range,
236                                          StringRef Text) {
237   unsigned WhitespaceLength = SourceMgr.getFileOffset(Range.getEnd()) -
238                               SourceMgr.getFileOffset(Range.getBegin());
239   // Don't create a replacement, if it does not change anything.
240   if (StringRef(SourceMgr.getCharacterData(Range.getBegin()),
241                 WhitespaceLength) == Text)
242     return;
243   Replaces.insert(tooling::Replacement(
244       SourceMgr, CharSourceRange::getCharRange(Range), Text));
245 }
246 
247 void WhitespaceManager::appendNewlineText(std::string &Text,
248                                           unsigned Newlines) {
249   for (unsigned i = 0; i < Newlines; ++i)
250     Text.append(UseCRLF ? "\r\n" : "\n");
251 }
252 
253 void WhitespaceManager::appendNewlineText(std::string &Text, unsigned Newlines,
254                                           unsigned PreviousEndOfTokenColumn,
255                                           unsigned EscapedNewlineColumn) {
256   if (Newlines > 0) {
257     unsigned Offset =
258         std::min<int>(EscapedNewlineColumn - 1, PreviousEndOfTokenColumn);
259     for (unsigned i = 0; i < Newlines; ++i) {
260       Text.append(std::string(EscapedNewlineColumn - Offset - 1, ' '));
261       Text.append(UseCRLF ? "\\\r\n" : "\\\n");
262       Offset = 0;
263     }
264   }
265 }
266 
267 void WhitespaceManager::appendIndentText(std::string &Text, unsigned Spaces) {
268   if (!Style.UseTab) {
269     Text.append(std::string(Spaces, ' '));
270   } else {
271     Text.append(std::string(Spaces / Style.TabWidth, '\t'));
272     Text.append(std::string(Spaces % Style.TabWidth, ' '));
273   }
274 }
275 
276 } // namespace format
277 } // namespace clang
278