blob: 93a2e490c660404cd1eb5a772cb785138089586f [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
Daniel Jasper7d42f3f2017-01-31 11:25:01 +000028WhitespaceManager::Change::Change(const FormatToken &Tok,
29 bool CreateReplacement,
30 SourceRange OriginalWhitespaceRange,
31 int Spaces, unsigned StartOfTokenColumn,
32 unsigned NewlinesBefore,
33 StringRef PreviousLinePostfix,
34 StringRef CurrentLinePrefix,
35 bool ContinuesPPDirective, bool IsInsideToken)
36 : Tok(&Tok), CreateReplacement(CreateReplacement),
Manuel Klimek4fe43002013-05-22 12:51:29 +000037 OriginalWhitespaceRange(OriginalWhitespaceRange),
38 StartOfTokenColumn(StartOfTokenColumn), NewlinesBefore(NewlinesBefore),
39 PreviousLinePostfix(PreviousLinePostfix),
Daniel Jasper7d42f3f2017-01-31 11:25:01 +000040 CurrentLinePrefix(CurrentLinePrefix),
41 ContinuesPPDirective(ContinuesPPDirective), Spaces(Spaces),
42 IsInsideToken(IsInsideToken), IsTrailingComment(false), TokenLength(0),
43 PreviousEndOfTokenColumn(0), EscapedNewlineColumn(0),
Manuel Klimek2d293402015-03-03 14:21:48 +000044 StartOfBlockComment(nullptr), IndentationOffset(0) {}
Manuel Klimek4fe43002013-05-22 12:51:29 +000045
Manuel Klimek71814b42013-10-11 21:25:45 +000046void WhitespaceManager::replaceWhitespace(FormatToken &Tok, unsigned Newlines,
Daniel Jasper7d42f3f2017-01-31 11:25:01 +000047 unsigned Spaces,
Manuel Klimek4fe43002013-05-22 12:51:29 +000048 unsigned StartOfTokenColumn,
49 bool InPPDirective) {
Manuel Klimek71814b42013-10-11 21:25:45 +000050 if (Tok.Finalized)
51 return;
52 Tok.Decision = (Newlines > 0) ? FD_Break : FD_Continue;
Daniel Jasper7d42f3f2017-01-31 11:25:01 +000053 Changes.push_back(Change(Tok, /*CreateReplacement=*/true,
54 Tok.WhitespaceRange, Spaces, StartOfTokenColumn,
55 Newlines, "", "", InPPDirective && !Tok.IsFirst,
56 /*IsInsideToken=*/false));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000057}
58
Manuel Klimek4fe43002013-05-22 12:51:29 +000059void WhitespaceManager::addUntouchableToken(const FormatToken &Tok,
60 bool InPPDirective) {
Manuel Klimek71814b42013-10-11 21:25:45 +000061 if (Tok.Finalized)
62 return;
Daniel Jasper7d42f3f2017-01-31 11:25:01 +000063 Changes.push_back(Change(Tok, /*CreateReplacement=*/false,
64 Tok.WhitespaceRange, /*Spaces=*/0,
65 Tok.OriginalColumn, Tok.NewlinesBefore, "", "",
66 InPPDirective && !Tok.IsFirst,
67 /*IsInsideToken=*/false));
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,
Daniel Jasper7d42f3f2017-01-31 11:25:01 +000073 unsigned Newlines, 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);
Daniel Jasper7d42f3f2017-01-31 11:25:01 +000077 Changes.push_back(
78 Change(Tok, /*CreateReplacement=*/true,
79 SourceRange(Start, Start.getLocWithOffset(ReplaceChars)), Spaces,
80 std::max(0, Spaces), Newlines, PreviousPostfix, CurrentPrefix,
81 InPPDirective && !Tok.IsFirst, /*IsInsideToken=*/true));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000082}
83
Manuel Klimek4fe43002013-05-22 12:51:29 +000084const tooling::Replacements &WhitespaceManager::generateReplacements() {
85 if (Changes.empty())
86 return Replaces;
87
88 std::sort(Changes.begin(), Changes.end(), Change::IsBeforeInFile(SourceMgr));
89 calculateLineBreakInformation();
Daniel Jaspere12597c2015-10-01 10:06:54 +000090 alignConsecutiveDeclarations();
Daniel Jaspera44991332015-04-29 13:06:49 +000091 alignConsecutiveAssignments();
Manuel Klimek4fe43002013-05-22 12:51:29 +000092 alignTrailingComments();
93 alignEscapedNewlines();
94 generateChanges();
95
96 return Replaces;
97}
98
99void WhitespaceManager::calculateLineBreakInformation() {
100 Changes[0].PreviousEndOfTokenColumn = 0;
Benjamin Kramerdab50462016-01-11 16:27:16 +0000101 Change *LastOutsideTokenChange = &Changes[0];
Manuel Klimek4fe43002013-05-22 12:51:29 +0000102 for (unsigned i = 1, e = Changes.size(); i != e; ++i) {
103 unsigned OriginalWhitespaceStart =
104 SourceMgr.getFileOffset(Changes[i].OriginalWhitespaceRange.getBegin());
105 unsigned PreviousOriginalWhitespaceEnd = SourceMgr.getFileOffset(
106 Changes[i - 1].OriginalWhitespaceRange.getEnd());
Daniel Jasper3ac9b9e2013-07-08 14:34:09 +0000107 Changes[i - 1].TokenLength = OriginalWhitespaceStart -
108 PreviousOriginalWhitespaceEnd +
109 Changes[i].PreviousLinePostfix.size() +
110 Changes[i - 1].CurrentLinePrefix.size();
Manuel Klimek4fe43002013-05-22 12:51:29 +0000111
Benjamin Kramerdab50462016-01-11 16:27:16 +0000112 // If there are multiple changes in this token, sum up all the changes until
113 // the end of the line.
114 if (Changes[i - 1].IsInsideToken)
115 LastOutsideTokenChange->TokenLength +=
116 Changes[i - 1].TokenLength + Changes[i - 1].Spaces;
117 else
118 LastOutsideTokenChange = &Changes[i - 1];
119
Manuel Klimek4fe43002013-05-22 12:51:29 +0000120 Changes[i].PreviousEndOfTokenColumn =
121 Changes[i - 1].StartOfTokenColumn + Changes[i - 1].TokenLength;
122
123 Changes[i - 1].IsTrailingComment =
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000124 (Changes[i].NewlinesBefore > 0 || Changes[i].Tok->is(tok::eof) ||
125 (Changes[i].IsInsideToken && Changes[i].Tok->is(tok::comment))) &&
126 Changes[i - 1].Tok->is(tok::comment) &&
Krasimir Georgiev91834222017-01-25 13:58:58 +0000127 // FIXME: This is a dirty hack. The problem is that
128 // BreakableLineCommentSection does comment reflow changes and here is
129 // the aligning of trailing comments. Consider the case where we reflow
130 // the second line up in this example:
131 //
132 // // line 1
133 // // line 2
134 //
135 // That amounts to 2 changes by BreakableLineCommentSection:
136 // - the first, delimited by (), for the whitespace between the tokens,
137 // - and second, delimited by [], for the whitespace at the beginning
138 // of the second token:
139 //
140 // // line 1(
141 // )[// ]line 2
142 //
143 // So in the end we have two changes like this:
144 //
145 // // line1()[ ]line 2
146 //
147 // Note that the OriginalWhitespaceStart of the second change is the
148 // same as the PreviousOriginalWhitespaceEnd of the first change.
149 // In this case, the below check ensures that the second change doesn't
150 // get treated as a trailing comment change here, since this might
151 // trigger additional whitespace to be wrongly inserted before "line 2"
152 // by the comment aligner here.
153 //
154 // For a proper solution we need a mechanism to say to WhitespaceManager
155 // that a particular change breaks the current sequence of trailing
156 // comments.
157 OriginalWhitespaceStart != PreviousOriginalWhitespaceEnd;
Manuel Klimek4fe43002013-05-22 12:51:29 +0000158 }
Manuel Klimek05c67892013-05-22 14:01:08 +0000159 // FIXME: The last token is currently not always an eof token; in those
160 // cases, setting TokenLength of the last token to 0 is wrong.
161 Changes.back().TokenLength = 0;
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000162 Changes.back().IsTrailingComment = Changes.back().Tok->is(tok::comment);
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000163
164 const WhitespaceManager::Change *LastBlockComment = nullptr;
165 for (auto &Change : Changes) {
Benjamin Kramerdab50462016-01-11 16:27:16 +0000166 // Reset the IsTrailingComment flag for changes inside of trailing comments
Krasimir Georgievd105b722017-02-03 10:18:25 +0000167 // so they don't get realigned later. Comment line breaks however still need
168 // to be aligned.
169 if (Change.IsInsideToken && Change.NewlinesBefore == 0)
Benjamin Kramerdab50462016-01-11 16:27:16 +0000170 Change.IsTrailingComment = false;
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000171 Change.StartOfBlockComment = nullptr;
172 Change.IndentationOffset = 0;
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000173 if (Change.Tok->is(tok::comment)) {
174 if (Change.Tok->is(TT_LineComment) || !Change.IsInsideToken)
175 LastBlockComment = &Change;
176 else {
177 if ((Change.StartOfBlockComment = LastBlockComment))
178 Change.IndentationOffset =
179 Change.StartOfTokenColumn -
180 Change.StartOfBlockComment->StartOfTokenColumn;
181 }
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000182 } else {
183 LastBlockComment = nullptr;
184 }
185 }
Manuel Klimek4fe43002013-05-22 12:51:29 +0000186}
187
Daniel Jasperec90e512015-12-01 12:00:43 +0000188// Align a single sequence of tokens, see AlignTokens below.
189template <typename F>
190static void
191AlignTokenSequence(unsigned Start, unsigned End, unsigned Column, F &&Matches,
192 SmallVector<WhitespaceManager::Change, 16> &Changes) {
193 bool FoundMatchOnLine = false;
194 int Shift = 0;
195 for (unsigned i = Start; i != End; ++i) {
196 if (Changes[i].NewlinesBefore > 0) {
197 FoundMatchOnLine = false;
198 Shift = 0;
199 }
200
201 // If this is the first matching token to be aligned, remember by how many
202 // spaces it has to be shifted, so the rest of the changes on the line are
203 // shifted by the same amount
204 if (!FoundMatchOnLine && Matches(Changes[i])) {
205 FoundMatchOnLine = true;
206 Shift = Column - Changes[i].StartOfTokenColumn;
207 Changes[i].Spaces += Shift;
208 }
209
210 assert(Shift >= 0);
211 Changes[i].StartOfTokenColumn += Shift;
212 if (i + 1 != Changes.size())
213 Changes[i + 1].PreviousEndOfTokenColumn += Shift;
214 }
215}
216
217// Walk through all of the changes and find sequences of matching tokens to
218// align. To do so, keep track of the lines and whether or not a matching token
219// was found on a line. If a matching token is found, extend the current
220// sequence. If the current line cannot be part of a sequence, e.g. because
221// there is an empty line before it or it contains only non-matching tokens,
222// finalize the previous sequence.
223template <typename F>
224static void AlignTokens(const FormatStyle &Style, F &&Matches,
225 SmallVector<WhitespaceManager::Change, 16> &Changes) {
226 unsigned MinColumn = 0;
227 unsigned MaxColumn = UINT_MAX;
228
229 // Line number of the start and the end of the current token sequence.
230 unsigned StartOfSequence = 0;
231 unsigned EndOfSequence = 0;
232
233 // Keep track of the nesting level of matching tokens, i.e. the number of
234 // surrounding (), [], or {}. We will only align a sequence of matching
235 // token that share the same scope depth.
236 //
237 // FIXME: This could use FormatToken::NestingLevel information, but there is
238 // an outstanding issue wrt the brace scopes.
239 unsigned NestingLevelOfLastMatch = 0;
240 unsigned NestingLevel = 0;
241
242 // Keep track of the number of commas before the matching tokens, we will only
243 // align a sequence of matching tokens if they are preceded by the same number
244 // of commas.
245 unsigned CommasBeforeLastMatch = 0;
246 unsigned CommasBeforeMatch = 0;
247
248 // Whether a matching token has been found on the current line.
249 bool FoundMatchOnLine = false;
250
251 // Aligns a sequence of matching tokens, on the MinColumn column.
252 //
253 // Sequences start from the first matching token to align, and end at the
254 // first token of the first line that doesn't need to be aligned.
255 //
256 // We need to adjust the StartOfTokenColumn of each Change that is on a line
257 // containing any matching token to be aligned and located after such token.
258 auto AlignCurrentSequence = [&] {
259 if (StartOfSequence > 0 && StartOfSequence < EndOfSequence)
260 AlignTokenSequence(StartOfSequence, EndOfSequence, MinColumn, Matches,
261 Changes);
262 MinColumn = 0;
263 MaxColumn = UINT_MAX;
264 StartOfSequence = 0;
265 EndOfSequence = 0;
266 };
267
268 for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
269 if (Changes[i].NewlinesBefore != 0) {
270 CommasBeforeMatch = 0;
271 EndOfSequence = i;
272 // If there is a blank line, or if the last line didn't contain any
273 // matching token, the sequence ends here.
274 if (Changes[i].NewlinesBefore > 1 || !FoundMatchOnLine)
275 AlignCurrentSequence();
276
277 FoundMatchOnLine = false;
278 }
279
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000280 if (Changes[i].Tok->is(tok::comma)) {
Daniel Jasperec90e512015-12-01 12:00:43 +0000281 ++CommasBeforeMatch;
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000282 } else if (Changes[i].Tok->isOneOf(tok::r_brace, tok::r_paren,
283 tok::r_square)) {
Daniel Jasperec90e512015-12-01 12:00:43 +0000284 --NestingLevel;
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000285 } else if (Changes[i].Tok->isOneOf(tok::l_brace, tok::l_paren,
286 tok::l_square)) {
Daniel Jasperec90e512015-12-01 12:00:43 +0000287 // We want sequences to skip over child scopes if possible, but not the
288 // other way around.
289 NestingLevelOfLastMatch = std::min(NestingLevelOfLastMatch, NestingLevel);
290 ++NestingLevel;
291 }
292
293 if (!Matches(Changes[i]))
294 continue;
295
296 // If there is more than one matching token per line, or if the number of
297 // preceding commas, or the scope depth, do not match anymore, end the
298 // sequence.
299 if (FoundMatchOnLine || CommasBeforeMatch != CommasBeforeLastMatch ||
300 NestingLevel != NestingLevelOfLastMatch)
301 AlignCurrentSequence();
302
303 CommasBeforeLastMatch = CommasBeforeMatch;
304 NestingLevelOfLastMatch = NestingLevel;
305 FoundMatchOnLine = true;
306
307 if (StartOfSequence == 0)
308 StartOfSequence = i;
309
310 unsigned ChangeMinColumn = Changes[i].StartOfTokenColumn;
311 int LineLengthAfter = -Changes[i].Spaces;
312 for (unsigned j = i; j != e && Changes[j].NewlinesBefore == 0; ++j)
313 LineLengthAfter += Changes[j].Spaces + Changes[j].TokenLength;
314 unsigned ChangeMaxColumn = Style.ColumnLimit - LineLengthAfter;
315
316 // If we are restricted by the maximum column width, end the sequence.
317 if (ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn ||
318 CommasBeforeLastMatch != CommasBeforeMatch) {
319 AlignCurrentSequence();
320 StartOfSequence = i;
321 }
322
323 MinColumn = std::max(MinColumn, ChangeMinColumn);
324 MaxColumn = std::min(MaxColumn, ChangeMaxColumn);
325 }
326
327 EndOfSequence = Changes.size();
328 AlignCurrentSequence();
329}
330
Daniel Jaspera44991332015-04-29 13:06:49 +0000331void WhitespaceManager::alignConsecutiveAssignments() {
332 if (!Style.AlignConsecutiveAssignments)
333 return;
334
Daniel Jasperec90e512015-12-01 12:00:43 +0000335 AlignTokens(Style,
336 [&](const Change &C) {
337 // Do not align on equal signs that are first on a line.
338 if (C.NewlinesBefore > 0)
339 return false;
Daniel Jaspera44991332015-04-29 13:06:49 +0000340
Daniel Jasperec90e512015-12-01 12:00:43 +0000341 // Do not align on equal signs that are last on a line.
342 if (&C != &Changes.back() && (&C + 1)->NewlinesBefore > 0)
343 return false;
Daniel Jaspera44991332015-04-29 13:06:49 +0000344
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000345 return C.Tok->is(tok::equal);
Daniel Jasperec90e512015-12-01 12:00:43 +0000346 },
347 Changes);
Daniel Jaspera44991332015-04-29 13:06:49 +0000348}
349
Daniel Jaspere12597c2015-10-01 10:06:54 +0000350void WhitespaceManager::alignConsecutiveDeclarations() {
351 if (!Style.AlignConsecutiveDeclarations)
352 return;
353
Daniel Jasperec90e512015-12-01 12:00:43 +0000354 // FIXME: Currently we don't handle properly the PointerAlignment: Right
355 // The * and & are not aligned and are left dangling. Something has to be done
356 // about it, but it raises the question of alignment of code like:
357 // const char* const* v1;
358 // float const* v2;
359 // SomeVeryLongType const& v3;
Daniel Jaspere12597c2015-10-01 10:06:54 +0000360
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000361 AlignTokens(Style,
362 [](Change const &C) {
363 return C.Tok->isOneOf(TT_StartOfName,
364 TT_FunctionDeclarationName);
365 },
Daniel Jasperec90e512015-12-01 12:00:43 +0000366 Changes);
Daniel Jaspere12597c2015-10-01 10:06:54 +0000367}
368
Manuel Klimek4fe43002013-05-22 12:51:29 +0000369void WhitespaceManager::alignTrailingComments() {
370 unsigned MinColumn = 0;
371 unsigned MaxColumn = UINT_MAX;
372 unsigned StartOfSequence = 0;
373 bool BreakBeforeNext = false;
374 unsigned Newlines = 0;
375 for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000376 if (Changes[i].StartOfBlockComment)
377 continue;
378 Newlines += Changes[i].NewlinesBefore;
379 if (!Changes[i].IsTrailingComment)
380 continue;
381
Manuel Klimek4fe43002013-05-22 12:51:29 +0000382 unsigned ChangeMinColumn = Changes[i].StartOfTokenColumn;
Manuel Klimek4fe43002013-05-22 12:51:29 +0000383 unsigned ChangeMaxColumn = Style.ColumnLimit - Changes[i].TokenLength;
Daniel Jasper417fc812016-01-09 15:56:53 +0000384
385 // If we don't create a replacement for this change, we have to consider
386 // it to be immovable.
387 if (!Changes[i].CreateReplacement)
388 ChangeMaxColumn = ChangeMinColumn;
389
Daniel Jasper66935022014-04-27 10:03:19 +0000390 if (i + 1 != e && Changes[i + 1].ContinuesPPDirective)
391 ChangeMaxColumn -= 2;
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000392 // If this comment follows an } in column 0, it probably documents the
393 // closing of a namespace and we don't want to align it.
394 bool FollowsRBraceInColumn0 = i > 0 && Changes[i].NewlinesBefore == 0 &&
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000395 Changes[i - 1].Tok->is(tok::r_brace) &&
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000396 Changes[i - 1].StartOfTokenColumn == 0;
397 bool WasAlignedWithStartOfNextLine = false;
398 if (Changes[i].NewlinesBefore == 1) { // A comment on its own line.
Daniel Jasper49532102015-01-07 14:00:11 +0000399 unsigned CommentColumn = SourceMgr.getSpellingColumnNumber(
400 Changes[i].OriginalWhitespaceRange.getEnd());
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000401 for (unsigned j = i + 1; j != e; ++j) {
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000402 if (Changes[j].Tok->is(tok::comment))
Daniel Jasperbb37a2f2016-02-01 11:20:55 +0000403 continue;
404
405 unsigned NextColumn = SourceMgr.getSpellingColumnNumber(
406 Changes[j].OriginalWhitespaceRange.getEnd());
407 // The start of the next token was previously aligned with the
408 // start of this comment.
409 WasAlignedWithStartOfNextLine =
410 CommentColumn == NextColumn ||
411 CommentColumn == NextColumn + Style.IndentWidth;
412 break;
Daniel Jasper0e93cdb2013-11-08 23:31:14 +0000413 }
Manuel Klimek4fe43002013-05-22 12:51:29 +0000414 }
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000415 if (!Style.AlignTrailingComments || FollowsRBraceInColumn0) {
416 alignTrailingComments(StartOfSequence, i, MinColumn);
417 MinColumn = ChangeMinColumn;
418 MaxColumn = ChangeMinColumn;
419 StartOfSequence = i;
420 } else if (BreakBeforeNext || Newlines > 1 ||
421 (ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn) ||
422 // Break the comment sequence if the previous line did not end
423 // in a trailing comment.
424 (Changes[i].NewlinesBefore == 1 && i > 0 &&
425 !Changes[i - 1].IsTrailingComment) ||
426 WasAlignedWithStartOfNextLine) {
427 alignTrailingComments(StartOfSequence, i, MinColumn);
428 MinColumn = ChangeMinColumn;
429 MaxColumn = ChangeMaxColumn;
430 StartOfSequence = i;
431 } else {
432 MinColumn = std::max(MinColumn, ChangeMinColumn);
433 MaxColumn = std::min(MaxColumn, ChangeMaxColumn);
434 }
435 BreakBeforeNext =
436 (i == 0) || (Changes[i].NewlinesBefore > 1) ||
437 // Never start a sequence with a comment at the beginning of
438 // the line.
439 (Changes[i].NewlinesBefore == 1 && StartOfSequence == i);
440 Newlines = 0;
Manuel Klimek4fe43002013-05-22 12:51:29 +0000441 }
442 alignTrailingComments(StartOfSequence, Changes.size(), MinColumn);
443}
444
445void WhitespaceManager::alignTrailingComments(unsigned Start, unsigned End,
446 unsigned Column) {
447 for (unsigned i = Start; i != End; ++i) {
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000448 int Shift = 0;
Manuel Klimek4fe43002013-05-22 12:51:29 +0000449 if (Changes[i].IsTrailingComment) {
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000450 Shift = Column - Changes[i].StartOfTokenColumn;
Manuel Klimek4fe43002013-05-22 12:51:29 +0000451 }
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000452 if (Changes[i].StartOfBlockComment) {
453 Shift = Changes[i].IndentationOffset +
454 Changes[i].StartOfBlockComment->StartOfTokenColumn -
455 Changes[i].StartOfTokenColumn;
456 }
457 assert(Shift >= 0);
458 Changes[i].Spaces += Shift;
Andi-Bogdan Postelnicua9a8fde2016-10-26 07:44:51 +0000459 if (i + 1 != Changes.size())
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000460 Changes[i + 1].PreviousEndOfTokenColumn += Shift;
461 Changes[i].StartOfTokenColumn += Shift;
Manuel Klimek4fe43002013-05-22 12:51:29 +0000462 }
463}
464
465void WhitespaceManager::alignEscapedNewlines() {
Daniel Jaspera49393f2013-08-28 09:07:32 +0000466 unsigned MaxEndOfLine =
467 Style.AlignEscapedNewlinesLeft ? 0 : Style.ColumnLimit;
Manuel Klimek4fe43002013-05-22 12:51:29 +0000468 unsigned StartOfMacro = 0;
469 for (unsigned i = 1, e = Changes.size(); i < e; ++i) {
470 Change &C = Changes[i];
471 if (C.NewlinesBefore > 0) {
472 if (C.ContinuesPPDirective) {
Daniel Jaspera49393f2013-08-28 09:07:32 +0000473 MaxEndOfLine = std::max(C.PreviousEndOfTokenColumn + 2, MaxEndOfLine);
Manuel Klimek4fe43002013-05-22 12:51:29 +0000474 } else {
475 alignEscapedNewlines(StartOfMacro + 1, i, MaxEndOfLine);
Daniel Jaspera49393f2013-08-28 09:07:32 +0000476 MaxEndOfLine = Style.AlignEscapedNewlinesLeft ? 0 : Style.ColumnLimit;
Manuel Klimek4fe43002013-05-22 12:51:29 +0000477 StartOfMacro = i;
478 }
479 }
480 }
481 alignEscapedNewlines(StartOfMacro + 1, Changes.size(), MaxEndOfLine);
482}
483
484void WhitespaceManager::alignEscapedNewlines(unsigned Start, unsigned End,
485 unsigned Column) {
486 for (unsigned i = Start; i < End; ++i) {
487 Change &C = Changes[i];
488 if (C.NewlinesBefore > 0) {
489 assert(C.ContinuesPPDirective);
490 if (C.PreviousEndOfTokenColumn + 1 > Column)
491 C.EscapedNewlineColumn = 0;
492 else
493 C.EscapedNewlineColumn = Column;
494 }
495 }
496}
497
498void WhitespaceManager::generateChanges() {
499 for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
500 const Change &C = Changes[i];
Daniel Jasper47b35ae2015-01-29 10:47:14 +0000501 if (i > 0) {
502 assert(Changes[i - 1].OriginalWhitespaceRange.getBegin() !=
503 C.OriginalWhitespaceRange.getBegin() &&
504 "Generating two replacements for the same location");
505 }
Manuel Klimek4fe43002013-05-22 12:51:29 +0000506 if (C.CreateReplacement) {
Alexander Kornienko9e649af2013-09-11 12:25:57 +0000507 std::string ReplacementText = C.PreviousLinePostfix;
508 if (C.ContinuesPPDirective)
509 appendNewlineText(ReplacementText, C.NewlinesBefore,
510 C.PreviousEndOfTokenColumn, C.EscapedNewlineColumn);
511 else
512 appendNewlineText(ReplacementText, C.NewlinesBefore);
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000513 appendIndentText(ReplacementText, C.Tok->IndentLevel,
514 std::max(0, C.Spaces),
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000515 C.StartOfTokenColumn - std::max(0, C.Spaces));
Alexander Kornienko9e649af2013-09-11 12:25:57 +0000516 ReplacementText.append(C.CurrentLinePrefix);
Manuel Klimek4fe43002013-05-22 12:51:29 +0000517 storeReplacement(C.OriginalWhitespaceRange, ReplacementText);
518 }
519 }
520}
521
Craig Toppere335f252015-10-04 04:53:55 +0000522void WhitespaceManager::storeReplacement(SourceRange Range,
Manuel Klimek4fe43002013-05-22 12:51:29 +0000523 StringRef Text) {
524 unsigned WhitespaceLength = SourceMgr.getFileOffset(Range.getEnd()) -
525 SourceMgr.getFileOffset(Range.getBegin());
526 // Don't create a replacement, if it does not change anything.
527 if (StringRef(SourceMgr.getCharacterData(Range.getBegin()),
Daniel Jasper3ac9b9e2013-07-08 14:34:09 +0000528 WhitespaceLength) == Text)
Manuel Klimek4fe43002013-05-22 12:51:29 +0000529 return;
Eric Liu40ef2fb2016-08-01 10:16:37 +0000530 auto Err = Replaces.add(tooling::Replacement(
Manuel Klimek4fe43002013-05-22 12:51:29 +0000531 SourceMgr, CharSourceRange::getCharRange(Range), Text));
Eric Liu40ef2fb2016-08-01 10:16:37 +0000532 // FIXME: better error handling. For now, just print an error message in the
533 // release version.
Piotr Padlewski1ec383c2016-12-23 11:40:44 +0000534 if (Err) {
Eric Liu40ef2fb2016-08-01 10:16:37 +0000535 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Piotr Padlewski1ec383c2016-12-23 11:40:44 +0000536 assert(false);
537 }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000538}
539
Alexander Kornienko9e649af2013-09-11 12:25:57 +0000540void WhitespaceManager::appendNewlineText(std::string &Text,
541 unsigned Newlines) {
542 for (unsigned i = 0; i < Newlines; ++i)
543 Text.append(UseCRLF ? "\r\n" : "\n");
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000544}
545
Alexander Kornienko9e649af2013-09-11 12:25:57 +0000546void WhitespaceManager::appendNewlineText(std::string &Text, unsigned Newlines,
547 unsigned PreviousEndOfTokenColumn,
548 unsigned EscapedNewlineColumn) {
Alexander Kornienko555efc32013-06-11 16:01:49 +0000549 if (Newlines > 0) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000550 unsigned Offset =
Manuel Klimek4fe43002013-05-22 12:51:29 +0000551 std::min<int>(EscapedNewlineColumn - 1, PreviousEndOfTokenColumn);
Alexander Kornienko555efc32013-06-11 16:01:49 +0000552 for (unsigned i = 0; i < Newlines; ++i) {
Benjamin Kramerddf1cda2015-05-28 19:55:49 +0000553 Text.append(EscapedNewlineColumn - Offset - 1, ' ');
Alexander Kornienko9e649af2013-09-11 12:25:57 +0000554 Text.append(UseCRLF ? "\\\r\n" : "\\\n");
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000555 Offset = 0;
556 }
557 }
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000558}
559
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000560void WhitespaceManager::appendIndentText(std::string &Text,
561 unsigned IndentLevel, unsigned Spaces,
Alexander Kornienkodb4c21f2013-09-27 09:45:40 +0000562 unsigned WhitespaceStartColumn) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000563 switch (Style.UseTab) {
564 case FormatStyle::UT_Never:
Benjamin Kramerddf1cda2015-05-28 19:55:49 +0000565 Text.append(Spaces, ' ');
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000566 break;
567 case FormatStyle::UT_Always: {
Alexander Kornienkodb4c21f2013-09-27 09:45:40 +0000568 unsigned FirstTabWidth =
569 Style.TabWidth - WhitespaceStartColumn % Style.TabWidth;
570 // Indent with tabs only when there's at least one full tab.
571 if (FirstTabWidth + Style.TabWidth <= Spaces) {
572 Spaces -= FirstTabWidth;
573 Text.append("\t");
574 }
Benjamin Kramerddf1cda2015-05-28 19:55:49 +0000575 Text.append(Spaces / Style.TabWidth, '\t');
576 Text.append(Spaces % Style.TabWidth, ' ');
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000577 break;
578 }
579 case FormatStyle::UT_ForIndentation:
580 if (WhitespaceStartColumn == 0) {
581 unsigned Indentation = IndentLevel * Style.IndentWidth;
Alexander Kornienko45dc1b22013-09-27 16:40:11 +0000582 // This happens, e.g. when a line in a block comment is indented less than
583 // the first one.
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000584 if (Indentation > Spaces)
585 Indentation = Spaces;
586 unsigned Tabs = Indentation / Style.TabWidth;
Benjamin Kramerddf1cda2015-05-28 19:55:49 +0000587 Text.append(Tabs, '\t');
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000588 Spaces -= Tabs * Style.TabWidth;
589 }
Benjamin Kramerddf1cda2015-05-28 19:55:49 +0000590 Text.append(Spaces, ' ');
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000591 break;
Marianne Mailhot-Sarrasin51fe2792016-04-14 14:52:26 +0000592 case FormatStyle::UT_ForContinuationAndIndentation:
593 if (WhitespaceStartColumn == 0) {
594 unsigned Tabs = Spaces / Style.TabWidth;
595 Text.append(Tabs, '\t');
596 Spaces -= Tabs * Style.TabWidth;
597 }
598 Text.append(Spaces, ' ');
599 break;
Alexander Kornienko9e649af2013-09-11 12:25:57 +0000600 }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000601}
602
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000603} // namespace format
604} // namespace clang