blob: 4896ad70b01a0db10ddfd11114ab266cb7cf9bf7 [file] [log] [blame]
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001//===--- 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
18namespace clang {
19namespace format {
20
Daniel Jasperb05a81d2014-05-09 13:11:16 +000021bool WhitespaceManager::Change::IsBeforeInFile::
22operator()(const Change &C1, const Change &C2) const {
Manuel Klimek4fe43002013-05-22 12:51:29 +000023 return SourceMgr.isBeforeInTranslationUnit(
24 C1.OriginalWhitespaceRange.getBegin(),
25 C2.OriginalWhitespaceRange.getBegin());
26}
Daniel Jasper6fe2f002013-04-25 08:56:26 +000027
Manuel Klimek4fe43002013-05-22 12:51:29 +000028WhitespaceManager::Change::Change(
29 bool CreateReplacement, const SourceRange &OriginalWhitespaceRange,
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +000030 unsigned IndentLevel, int Spaces, unsigned StartOfTokenColumn,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +000031 unsigned NewlinesBefore, StringRef PreviousLinePostfix,
32 StringRef CurrentLinePrefix, tok::TokenKind Kind, bool ContinuesPPDirective)
Manuel Klimek4fe43002013-05-22 12:51:29 +000033 : CreateReplacement(CreateReplacement),
34 OriginalWhitespaceRange(OriginalWhitespaceRange),
35 StartOfTokenColumn(StartOfTokenColumn), NewlinesBefore(NewlinesBefore),
36 PreviousLinePostfix(PreviousLinePostfix),
37 CurrentLinePrefix(CurrentLinePrefix), Kind(Kind),
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +000038 ContinuesPPDirective(ContinuesPPDirective), IndentLevel(IndentLevel),
Manuel Klimek2d293402015-03-03 14:21:48 +000039 Spaces(Spaces), IsTrailingComment(false), TokenLength(0),
40 PreviousEndOfTokenColumn(0), EscapedNewlineColumn(0),
41 StartOfBlockComment(nullptr), IndentationOffset(0) {}
Manuel Klimek4fe43002013-05-22 12:51:29 +000042
Manuel Klimek71814b42013-10-11 21:25:45 +000043void WhitespaceManager::reset() {
44 Changes.clear();
45 Replaces.clear();
46}
47
48void WhitespaceManager::replaceWhitespace(FormatToken &Tok, unsigned Newlines,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +000049 unsigned IndentLevel, unsigned Spaces,
Manuel Klimek4fe43002013-05-22 12:51:29 +000050 unsigned StartOfTokenColumn,
51 bool InPPDirective) {
Manuel Klimek71814b42013-10-11 21:25:45 +000052 if (Tok.Finalized)
53 return;
54 Tok.Decision = (Newlines > 0) ? FD_Break : FD_Continue;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +000055 Changes.push_back(Change(true, Tok.WhitespaceRange, IndentLevel, Spaces,
Daniel Jasper3ac9b9e2013-07-08 14:34:09 +000056 StartOfTokenColumn, Newlines, "", "",
57 Tok.Tok.getKind(), InPPDirective && !Tok.IsFirst));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000058}
59
Manuel Klimek4fe43002013-05-22 12:51:29 +000060void WhitespaceManager::addUntouchableToken(const FormatToken &Tok,
61 bool InPPDirective) {
Manuel Klimek71814b42013-10-11 21:25:45 +000062 if (Tok.Finalized)
63 return;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +000064 Changes.push_back(Change(false, Tok.WhitespaceRange, /*IndentLevel=*/0,
65 /*Spaces=*/0, Tok.OriginalColumn, Tok.NewlinesBefore,
66 "", "", Tok.Tok.getKind(),
67 InPPDirective && !Tok.IsFirst));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000068}
69
Alexander Kornienko555efc32013-06-11 16:01:49 +000070void WhitespaceManager::replaceWhitespaceInToken(
71 const FormatToken &Tok, unsigned Offset, unsigned ReplaceChars,
72 StringRef PreviousPostfix, StringRef CurrentPrefix, bool InPPDirective,
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +000073 unsigned Newlines, unsigned IndentLevel, int Spaces) {
Manuel Klimek71814b42013-10-11 21:25:45 +000074 if (Tok.Finalized)
75 return;
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +000076 SourceLocation Start = Tok.getStartOfNonWhitespace().getLocWithOffset(Offset);
Manuel Klimek4fe43002013-05-22 12:51:29 +000077 Changes.push_back(Change(
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +000078 true, SourceRange(Start, Start.getLocWithOffset(ReplaceChars)),
79 IndentLevel, Spaces, std::max(0, Spaces), Newlines, PreviousPostfix,
80 CurrentPrefix,
Alexander Kornienko4d26b6e2013-06-17 12:59:44 +000081 // If we don't add a newline this change doesn't start a comment. Thus,
82 // when we align line comments, we don't need to treat this change as one.
83 // FIXME: We still need to take this change in account to properly
84 // calculate the new length of the comment and to calculate the changes
85 // for which to do the alignment when aligning comments.
Daniel Jaspera98b7b02014-11-25 10:05:17 +000086 Tok.is(TT_LineComment) && Newlines > 0 ? tok::comment : tok::unknown,
Alexander Kornienko4d26b6e2013-06-17 12:59:44 +000087 InPPDirective && !Tok.IsFirst));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000088}
89
Manuel Klimek4fe43002013-05-22 12:51:29 +000090const tooling::Replacements &WhitespaceManager::generateReplacements() {
91 if (Changes.empty())
92 return Replaces;
93
94 std::sort(Changes.begin(), Changes.end(), Change::IsBeforeInFile(SourceMgr));
95 calculateLineBreakInformation();
96 alignTrailingComments();
97 alignEscapedNewlines();
98 generateChanges();
99
100 return Replaces;
101}
102
103void WhitespaceManager::calculateLineBreakInformation() {
104 Changes[0].PreviousEndOfTokenColumn = 0;
105 for (unsigned i = 1, e = Changes.size(); i != e; ++i) {
106 unsigned OriginalWhitespaceStart =
107 SourceMgr.getFileOffset(Changes[i].OriginalWhitespaceRange.getBegin());
108 unsigned PreviousOriginalWhitespaceEnd = SourceMgr.getFileOffset(
109 Changes[i - 1].OriginalWhitespaceRange.getEnd());
Daniel Jasper3ac9b9e2013-07-08 14:34:09 +0000110 Changes[i - 1].TokenLength = OriginalWhitespaceStart -
111 PreviousOriginalWhitespaceEnd +
112 Changes[i].PreviousLinePostfix.size() +
113 Changes[i - 1].CurrentLinePrefix.size();
Manuel Klimek4fe43002013-05-22 12:51:29 +0000114
115 Changes[i].PreviousEndOfTokenColumn =
116 Changes[i - 1].StartOfTokenColumn + Changes[i - 1].TokenLength;
117
118 Changes[i - 1].IsTrailingComment =
119 (Changes[i].NewlinesBefore > 0 || Changes[i].Kind == tok::eof) &&
120 Changes[i - 1].Kind == tok::comment;
121 }
Manuel Klimek05c67892013-05-22 14:01:08 +0000122 // FIXME: The last token is currently not always an eof token; in those
123 // cases, setting TokenLength of the last token to 0 is wrong.
124 Changes.back().TokenLength = 0;
Manuel Klimek4fe43002013-05-22 12:51:29 +0000125 Changes.back().IsTrailingComment = Changes.back().Kind == tok::comment;
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000126
127 const WhitespaceManager::Change *LastBlockComment = nullptr;
128 for (auto &Change : Changes) {
129 Change.StartOfBlockComment = nullptr;
130 Change.IndentationOffset = 0;
131 if (Change.Kind == tok::comment) {
132 LastBlockComment = &Change;
133 } else if (Change.Kind == tok::unknown) {
134 if ((Change.StartOfBlockComment = LastBlockComment))
135 Change.IndentationOffset =
136 Change.StartOfTokenColumn -
137 Change.StartOfBlockComment->StartOfTokenColumn;
138 } else {
139 LastBlockComment = nullptr;
140 }
141 }
Manuel Klimek4fe43002013-05-22 12:51:29 +0000142}
143
144void WhitespaceManager::alignTrailingComments() {
145 unsigned MinColumn = 0;
146 unsigned MaxColumn = UINT_MAX;
147 unsigned StartOfSequence = 0;
148 bool BreakBeforeNext = false;
149 unsigned Newlines = 0;
150 for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000151 if (Changes[i].StartOfBlockComment)
152 continue;
153 Newlines += Changes[i].NewlinesBefore;
154 if (!Changes[i].IsTrailingComment)
155 continue;
156
Manuel Klimek4fe43002013-05-22 12:51:29 +0000157 unsigned ChangeMinColumn = Changes[i].StartOfTokenColumn;
Manuel Klimek4fe43002013-05-22 12:51:29 +0000158 unsigned ChangeMaxColumn = Style.ColumnLimit - Changes[i].TokenLength;
Daniel Jasper66935022014-04-27 10:03:19 +0000159 if (i + 1 != e && Changes[i + 1].ContinuesPPDirective)
160 ChangeMaxColumn -= 2;
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000161 // If this comment follows an } in column 0, it probably documents the
162 // closing of a namespace and we don't want to align it.
163 bool FollowsRBraceInColumn0 = i > 0 && Changes[i].NewlinesBefore == 0 &&
164 Changes[i - 1].Kind == tok::r_brace &&
165 Changes[i - 1].StartOfTokenColumn == 0;
166 bool WasAlignedWithStartOfNextLine = false;
167 if (Changes[i].NewlinesBefore == 1) { // A comment on its own line.
Daniel Jasper49532102015-01-07 14:00:11 +0000168 unsigned CommentColumn = SourceMgr.getSpellingColumnNumber(
169 Changes[i].OriginalWhitespaceRange.getEnd());
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000170 for (unsigned j = i + 1; j != e; ++j) {
171 if (Changes[j].Kind != tok::comment) { // Skip over comments.
Daniel Jasper49532102015-01-07 14:00:11 +0000172 unsigned NextColumn = SourceMgr.getSpellingColumnNumber(
173 Changes[j].OriginalWhitespaceRange.getEnd());
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000174 // The start of the next token was previously aligned with the
175 // start of this comment.
176 WasAlignedWithStartOfNextLine =
Daniel Jasper49532102015-01-07 14:00:11 +0000177 CommentColumn == NextColumn ||
178 CommentColumn == NextColumn + Style.IndentWidth;
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000179 break;
Daniel Jasper0e93cdb2013-11-08 23:31:14 +0000180 }
181 }
Manuel Klimek4fe43002013-05-22 12:51:29 +0000182 }
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000183 if (!Style.AlignTrailingComments || FollowsRBraceInColumn0) {
184 alignTrailingComments(StartOfSequence, i, MinColumn);
185 MinColumn = ChangeMinColumn;
186 MaxColumn = ChangeMinColumn;
187 StartOfSequence = i;
188 } else if (BreakBeforeNext || Newlines > 1 ||
189 (ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn) ||
190 // Break the comment sequence if the previous line did not end
191 // in a trailing comment.
192 (Changes[i].NewlinesBefore == 1 && i > 0 &&
193 !Changes[i - 1].IsTrailingComment) ||
194 WasAlignedWithStartOfNextLine) {
195 alignTrailingComments(StartOfSequence, i, MinColumn);
196 MinColumn = ChangeMinColumn;
197 MaxColumn = ChangeMaxColumn;
198 StartOfSequence = i;
199 } else {
200 MinColumn = std::max(MinColumn, ChangeMinColumn);
201 MaxColumn = std::min(MaxColumn, ChangeMaxColumn);
202 }
203 BreakBeforeNext =
204 (i == 0) || (Changes[i].NewlinesBefore > 1) ||
205 // Never start a sequence with a comment at the beginning of
206 // the line.
207 (Changes[i].NewlinesBefore == 1 && StartOfSequence == i);
208 Newlines = 0;
Manuel Klimek4fe43002013-05-22 12:51:29 +0000209 }
210 alignTrailingComments(StartOfSequence, Changes.size(), MinColumn);
211}
212
213void WhitespaceManager::alignTrailingComments(unsigned Start, unsigned End,
214 unsigned Column) {
215 for (unsigned i = Start; i != End; ++i) {
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000216 int Shift = 0;
Manuel Klimek4fe43002013-05-22 12:51:29 +0000217 if (Changes[i].IsTrailingComment) {
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000218 Shift = Column - Changes[i].StartOfTokenColumn;
Manuel Klimek4fe43002013-05-22 12:51:29 +0000219 }
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000220 if (Changes[i].StartOfBlockComment) {
221 Shift = Changes[i].IndentationOffset +
222 Changes[i].StartOfBlockComment->StartOfTokenColumn -
223 Changes[i].StartOfTokenColumn;
224 }
225 assert(Shift >= 0);
226 Changes[i].Spaces += Shift;
227 if (i + 1 != End)
228 Changes[i + 1].PreviousEndOfTokenColumn += Shift;
229 Changes[i].StartOfTokenColumn += Shift;
Manuel Klimek4fe43002013-05-22 12:51:29 +0000230 }
231}
232
233void WhitespaceManager::alignEscapedNewlines() {
Daniel Jaspera49393f2013-08-28 09:07:32 +0000234 unsigned MaxEndOfLine =
235 Style.AlignEscapedNewlinesLeft ? 0 : Style.ColumnLimit;
Manuel Klimek4fe43002013-05-22 12:51:29 +0000236 unsigned StartOfMacro = 0;
237 for (unsigned i = 1, e = Changes.size(); i < e; ++i) {
238 Change &C = Changes[i];
239 if (C.NewlinesBefore > 0) {
240 if (C.ContinuesPPDirective) {
Daniel Jaspera49393f2013-08-28 09:07:32 +0000241 MaxEndOfLine = std::max(C.PreviousEndOfTokenColumn + 2, MaxEndOfLine);
Manuel Klimek4fe43002013-05-22 12:51:29 +0000242 } else {
243 alignEscapedNewlines(StartOfMacro + 1, i, MaxEndOfLine);
Daniel Jaspera49393f2013-08-28 09:07:32 +0000244 MaxEndOfLine = Style.AlignEscapedNewlinesLeft ? 0 : Style.ColumnLimit;
Manuel Klimek4fe43002013-05-22 12:51:29 +0000245 StartOfMacro = i;
246 }
247 }
248 }
249 alignEscapedNewlines(StartOfMacro + 1, Changes.size(), MaxEndOfLine);
250}
251
252void WhitespaceManager::alignEscapedNewlines(unsigned Start, unsigned End,
253 unsigned Column) {
254 for (unsigned i = Start; i < End; ++i) {
255 Change &C = Changes[i];
256 if (C.NewlinesBefore > 0) {
257 assert(C.ContinuesPPDirective);
258 if (C.PreviousEndOfTokenColumn + 1 > Column)
259 C.EscapedNewlineColumn = 0;
260 else
261 C.EscapedNewlineColumn = Column;
262 }
263 }
264}
265
266void WhitespaceManager::generateChanges() {
267 for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
268 const Change &C = Changes[i];
Daniel Jasper47b35ae2015-01-29 10:47:14 +0000269 if (i > 0) {
270 assert(Changes[i - 1].OriginalWhitespaceRange.getBegin() !=
271 C.OriginalWhitespaceRange.getBegin() &&
272 "Generating two replacements for the same location");
273 }
Manuel Klimek4fe43002013-05-22 12:51:29 +0000274 if (C.CreateReplacement) {
Alexander Kornienko9e649af2013-09-11 12:25:57 +0000275 std::string ReplacementText = C.PreviousLinePostfix;
276 if (C.ContinuesPPDirective)
277 appendNewlineText(ReplacementText, C.NewlinesBefore,
278 C.PreviousEndOfTokenColumn, C.EscapedNewlineColumn);
279 else
280 appendNewlineText(ReplacementText, C.NewlinesBefore);
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000281 appendIndentText(ReplacementText, C.IndentLevel, std::max(0, C.Spaces),
282 C.StartOfTokenColumn - std::max(0, C.Spaces));
Alexander Kornienko9e649af2013-09-11 12:25:57 +0000283 ReplacementText.append(C.CurrentLinePrefix);
Manuel Klimek4fe43002013-05-22 12:51:29 +0000284 storeReplacement(C.OriginalWhitespaceRange, ReplacementText);
285 }
286 }
287}
288
289void WhitespaceManager::storeReplacement(const SourceRange &Range,
290 StringRef Text) {
291 unsigned WhitespaceLength = SourceMgr.getFileOffset(Range.getEnd()) -
292 SourceMgr.getFileOffset(Range.getBegin());
293 // Don't create a replacement, if it does not change anything.
294 if (StringRef(SourceMgr.getCharacterData(Range.getBegin()),
Daniel Jasper3ac9b9e2013-07-08 14:34:09 +0000295 WhitespaceLength) == Text)
Manuel Klimek4fe43002013-05-22 12:51:29 +0000296 return;
297 Replaces.insert(tooling::Replacement(
298 SourceMgr, CharSourceRange::getCharRange(Range), Text));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000299}
300
Alexander Kornienko9e649af2013-09-11 12:25:57 +0000301void WhitespaceManager::appendNewlineText(std::string &Text,
302 unsigned Newlines) {
303 for (unsigned i = 0; i < Newlines; ++i)
304 Text.append(UseCRLF ? "\r\n" : "\n");
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000305}
306
Alexander Kornienko9e649af2013-09-11 12:25:57 +0000307void WhitespaceManager::appendNewlineText(std::string &Text, unsigned Newlines,
308 unsigned PreviousEndOfTokenColumn,
309 unsigned EscapedNewlineColumn) {
Alexander Kornienko555efc32013-06-11 16:01:49 +0000310 if (Newlines > 0) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000311 unsigned Offset =
Manuel Klimek4fe43002013-05-22 12:51:29 +0000312 std::min<int>(EscapedNewlineColumn - 1, PreviousEndOfTokenColumn);
Alexander Kornienko555efc32013-06-11 16:01:49 +0000313 for (unsigned i = 0; i < Newlines; ++i) {
Alexander Kornienko9e649af2013-09-11 12:25:57 +0000314 Text.append(std::string(EscapedNewlineColumn - Offset - 1, ' '));
315 Text.append(UseCRLF ? "\\\r\n" : "\\\n");
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000316 Offset = 0;
317 }
318 }
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000319}
320
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000321void WhitespaceManager::appendIndentText(std::string &Text,
322 unsigned IndentLevel, unsigned Spaces,
Alexander Kornienkodb4c21f2013-09-27 09:45:40 +0000323 unsigned WhitespaceStartColumn) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000324 switch (Style.UseTab) {
325 case FormatStyle::UT_Never:
Alexander Kornienko9e649af2013-09-11 12:25:57 +0000326 Text.append(std::string(Spaces, ' '));
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000327 break;
328 case FormatStyle::UT_Always: {
Alexander Kornienkodb4c21f2013-09-27 09:45:40 +0000329 unsigned FirstTabWidth =
330 Style.TabWidth - WhitespaceStartColumn % Style.TabWidth;
331 // Indent with tabs only when there's at least one full tab.
332 if (FirstTabWidth + Style.TabWidth <= Spaces) {
333 Spaces -= FirstTabWidth;
334 Text.append("\t");
335 }
Alexander Kornienko9e649af2013-09-11 12:25:57 +0000336 Text.append(std::string(Spaces / Style.TabWidth, '\t'));
337 Text.append(std::string(Spaces % Style.TabWidth, ' '));
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000338 break;
339 }
340 case FormatStyle::UT_ForIndentation:
341 if (WhitespaceStartColumn == 0) {
342 unsigned Indentation = IndentLevel * Style.IndentWidth;
Alexander Kornienko45dc1b22013-09-27 16:40:11 +0000343 // This happens, e.g. when a line in a block comment is indented less than
344 // the first one.
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000345 if (Indentation > Spaces)
346 Indentation = Spaces;
347 unsigned Tabs = Indentation / Style.TabWidth;
348 Text.append(std::string(Tabs, '\t'));
349 Spaces -= Tabs * Style.TabWidth;
350 }
351 Text.append(std::string(Spaces, ' '));
352 break;
Alexander Kornienko9e649af2013-09-11 12:25:57 +0000353 }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000354}
355
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000356} // namespace format
357} // namespace clang