blob: 18d73b553e6f06db636cab5937fbe342bf821743 [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,
Daniel Jaspere12597c2015-10-01 10:06:54 +000032 StringRef CurrentLinePrefix, tok::TokenKind Kind, bool ContinuesPPDirective,
33 bool IsStartOfDeclName)
Manuel Klimek4fe43002013-05-22 12:51:29 +000034 : CreateReplacement(CreateReplacement),
35 OriginalWhitespaceRange(OriginalWhitespaceRange),
36 StartOfTokenColumn(StartOfTokenColumn), NewlinesBefore(NewlinesBefore),
37 PreviousLinePostfix(PreviousLinePostfix),
38 CurrentLinePrefix(CurrentLinePrefix), Kind(Kind),
Daniel Jaspere12597c2015-10-01 10:06:54 +000039 ContinuesPPDirective(ContinuesPPDirective),
40 IsStartOfDeclName(IsStartOfDeclName), IndentLevel(IndentLevel),
Manuel Klimek2d293402015-03-03 14:21:48 +000041 Spaces(Spaces), IsTrailingComment(false), TokenLength(0),
42 PreviousEndOfTokenColumn(0), EscapedNewlineColumn(0),
43 StartOfBlockComment(nullptr), IndentationOffset(0) {}
Manuel Klimek4fe43002013-05-22 12:51:29 +000044
Manuel Klimek71814b42013-10-11 21:25:45 +000045void WhitespaceManager::reset() {
46 Changes.clear();
47 Replaces.clear();
48}
49
50void WhitespaceManager::replaceWhitespace(FormatToken &Tok, unsigned Newlines,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +000051 unsigned IndentLevel, unsigned Spaces,
Manuel Klimek4fe43002013-05-22 12:51:29 +000052 unsigned StartOfTokenColumn,
53 bool InPPDirective) {
Manuel Klimek71814b42013-10-11 21:25:45 +000054 if (Tok.Finalized)
55 return;
56 Tok.Decision = (Newlines > 0) ? FD_Break : FD_Continue;
Daniel Jaspere12597c2015-10-01 10:06:54 +000057 Changes.push_back(
58 Change(true, Tok.WhitespaceRange, IndentLevel, Spaces, StartOfTokenColumn,
59 Newlines, "", "", Tok.Tok.getKind(), InPPDirective && !Tok.IsFirst,
60 Tok.is(TT_StartOfName) || Tok.is(TT_FunctionDeclarationName)));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000061}
62
Manuel Klimek4fe43002013-05-22 12:51:29 +000063void WhitespaceManager::addUntouchableToken(const FormatToken &Tok,
64 bool InPPDirective) {
Manuel Klimek71814b42013-10-11 21:25:45 +000065 if (Tok.Finalized)
66 return;
Daniel Jaspere12597c2015-10-01 10:06:54 +000067 Changes.push_back(
68 Change(false, Tok.WhitespaceRange, /*IndentLevel=*/0,
69 /*Spaces=*/0, Tok.OriginalColumn, Tok.NewlinesBefore, "", "",
70 Tok.Tok.getKind(), InPPDirective && !Tok.IsFirst,
71 Tok.is(TT_StartOfName) || Tok.is(TT_FunctionDeclarationName)));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000072}
73
Alexander Kornienko555efc32013-06-11 16:01:49 +000074void WhitespaceManager::replaceWhitespaceInToken(
75 const FormatToken &Tok, unsigned Offset, unsigned ReplaceChars,
76 StringRef PreviousPostfix, StringRef CurrentPrefix, bool InPPDirective,
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +000077 unsigned Newlines, unsigned IndentLevel, int Spaces) {
Manuel Klimek71814b42013-10-11 21:25:45 +000078 if (Tok.Finalized)
79 return;
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +000080 SourceLocation Start = Tok.getStartOfNonWhitespace().getLocWithOffset(Offset);
Manuel Klimek4fe43002013-05-22 12:51:29 +000081 Changes.push_back(Change(
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +000082 true, SourceRange(Start, Start.getLocWithOffset(ReplaceChars)),
83 IndentLevel, Spaces, std::max(0, Spaces), Newlines, PreviousPostfix,
84 CurrentPrefix,
Alexander Kornienko4d26b6e2013-06-17 12:59:44 +000085 // If we don't add a newline this change doesn't start a comment. Thus,
86 // when we align line comments, we don't need to treat this change as one.
87 // FIXME: We still need to take this change in account to properly
88 // calculate the new length of the comment and to calculate the changes
89 // for which to do the alignment when aligning comments.
Daniel Jaspera98b7b02014-11-25 10:05:17 +000090 Tok.is(TT_LineComment) && Newlines > 0 ? tok::comment : tok::unknown,
Daniel Jaspere12597c2015-10-01 10:06:54 +000091 InPPDirective && !Tok.IsFirst,
92 Tok.is(TT_StartOfName) || Tok.is(TT_FunctionDeclarationName)));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000093}
94
Manuel Klimek4fe43002013-05-22 12:51:29 +000095const tooling::Replacements &WhitespaceManager::generateReplacements() {
96 if (Changes.empty())
97 return Replaces;
98
99 std::sort(Changes.begin(), Changes.end(), Change::IsBeforeInFile(SourceMgr));
100 calculateLineBreakInformation();
Daniel Jaspere12597c2015-10-01 10:06:54 +0000101 alignConsecutiveDeclarations();
Daniel Jaspera44991332015-04-29 13:06:49 +0000102 alignConsecutiveAssignments();
Manuel Klimek4fe43002013-05-22 12:51:29 +0000103 alignTrailingComments();
104 alignEscapedNewlines();
105 generateChanges();
106
107 return Replaces;
108}
109
110void WhitespaceManager::calculateLineBreakInformation() {
111 Changes[0].PreviousEndOfTokenColumn = 0;
112 for (unsigned i = 1, e = Changes.size(); i != e; ++i) {
113 unsigned OriginalWhitespaceStart =
114 SourceMgr.getFileOffset(Changes[i].OriginalWhitespaceRange.getBegin());
115 unsigned PreviousOriginalWhitespaceEnd = SourceMgr.getFileOffset(
116 Changes[i - 1].OriginalWhitespaceRange.getEnd());
Daniel Jasper3ac9b9e2013-07-08 14:34:09 +0000117 Changes[i - 1].TokenLength = OriginalWhitespaceStart -
118 PreviousOriginalWhitespaceEnd +
119 Changes[i].PreviousLinePostfix.size() +
120 Changes[i - 1].CurrentLinePrefix.size();
Manuel Klimek4fe43002013-05-22 12:51:29 +0000121
122 Changes[i].PreviousEndOfTokenColumn =
123 Changes[i - 1].StartOfTokenColumn + Changes[i - 1].TokenLength;
124
125 Changes[i - 1].IsTrailingComment =
126 (Changes[i].NewlinesBefore > 0 || Changes[i].Kind == tok::eof) &&
127 Changes[i - 1].Kind == tok::comment;
128 }
Manuel Klimek05c67892013-05-22 14:01:08 +0000129 // FIXME: The last token is currently not always an eof token; in those
130 // cases, setting TokenLength of the last token to 0 is wrong.
131 Changes.back().TokenLength = 0;
Manuel Klimek4fe43002013-05-22 12:51:29 +0000132 Changes.back().IsTrailingComment = Changes.back().Kind == tok::comment;
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000133
134 const WhitespaceManager::Change *LastBlockComment = nullptr;
135 for (auto &Change : Changes) {
136 Change.StartOfBlockComment = nullptr;
137 Change.IndentationOffset = 0;
138 if (Change.Kind == tok::comment) {
139 LastBlockComment = &Change;
140 } else if (Change.Kind == tok::unknown) {
141 if ((Change.StartOfBlockComment = LastBlockComment))
142 Change.IndentationOffset =
143 Change.StartOfTokenColumn -
144 Change.StartOfBlockComment->StartOfTokenColumn;
145 } else {
146 LastBlockComment = nullptr;
147 }
148 }
Manuel Klimek4fe43002013-05-22 12:51:29 +0000149}
150
Daniel Jaspera44991332015-04-29 13:06:49 +0000151// Walk through all of the changes and find sequences of "=" to align. To do
152// so, keep track of the lines and whether or not an "=" was found on align. If
153// a "=" is found on a line, extend the current sequence. If the current line
154// cannot be part of a sequence, e.g. because there is an empty line before it
155// or it contains non-assignments, finalize the previous sequence.
156void WhitespaceManager::alignConsecutiveAssignments() {
157 if (!Style.AlignConsecutiveAssignments)
158 return;
159
160 unsigned MinColumn = 0;
Daniel Jaspere12597c2015-10-01 10:06:54 +0000161 unsigned MaxColumn = UINT_MAX;
Daniel Jaspera44991332015-04-29 13:06:49 +0000162 unsigned StartOfSequence = 0;
163 unsigned EndOfSequence = 0;
164 bool FoundAssignmentOnLine = false;
165 bool FoundLeftParenOnLine = false;
Daniel Jaspera44991332015-04-29 13:06:49 +0000166
Daniel Jasperbbfd20d2015-09-22 09:32:00 +0000167 // Aligns a sequence of assignment tokens, on the MinColumn column.
168 //
169 // Sequences start from the first assignment token to align, and end at the
170 // first token of the first line that doesn't need to be aligned.
171 //
172 // We need to adjust the StartOfTokenColumn of each Change that is on a line
173 // containing any assignment to be aligned and located after such assignment
Daniel Jaspera44991332015-04-29 13:06:49 +0000174 auto AlignSequence = [&] {
Daniel Jasperbbfd20d2015-09-22 09:32:00 +0000175 if (StartOfSequence > 0 && StartOfSequence < EndOfSequence)
176 alignConsecutiveAssignments(StartOfSequence, EndOfSequence, MinColumn);
Daniel Jaspera44991332015-04-29 13:06:49 +0000177 MinColumn = 0;
Daniel Jaspere12597c2015-10-01 10:06:54 +0000178 MaxColumn = UINT_MAX;
Daniel Jaspera44991332015-04-29 13:06:49 +0000179 StartOfSequence = 0;
180 EndOfSequence = 0;
181 };
182
183 for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
Daniel Jasperbbfd20d2015-09-22 09:32:00 +0000184 if (Changes[i].NewlinesBefore > 0) {
185 EndOfSequence = i;
186 // If there is a blank line or if the last line didn't contain any
187 // assignment, the sequence ends here.
188 if (Changes[i].NewlinesBefore > 1 || !FoundAssignmentOnLine) {
189 // NB: In the latter case, the sequence should end at the beggining of
190 // the previous line, but it doesn't really matter as there is no
191 // assignment on it
Daniel Jaspera44991332015-04-29 13:06:49 +0000192 AlignSequence();
193 }
Daniel Jasperbbfd20d2015-09-22 09:32:00 +0000194
Daniel Jaspera44991332015-04-29 13:06:49 +0000195 FoundAssignmentOnLine = false;
196 FoundLeftParenOnLine = false;
197 }
198
Daniel Jasperbbfd20d2015-09-22 09:32:00 +0000199 // If there is more than one "=" per line, or if the "=" appears first on
200 // the line of if it appears last, end the sequence
201 if (Changes[i].Kind == tok::equal &&
202 (FoundAssignmentOnLine || Changes[i].NewlinesBefore > 0 ||
203 Changes[i + 1].NewlinesBefore > 0)) {
204 AlignSequence();
205 } else if (!FoundLeftParenOnLine && Changes[i].Kind == tok::r_paren) {
206 AlignSequence();
Daniel Jaspera44991332015-04-29 13:06:49 +0000207 } else if (Changes[i].Kind == tok::l_paren) {
208 FoundLeftParenOnLine = true;
Daniel Jasperbbfd20d2015-09-22 09:32:00 +0000209 if (!FoundAssignmentOnLine)
Daniel Jaspera44991332015-04-29 13:06:49 +0000210 AlignSequence();
211 } else if (!FoundAssignmentOnLine && !FoundLeftParenOnLine &&
212 Changes[i].Kind == tok::equal) {
213 FoundAssignmentOnLine = true;
Daniel Jaspera44991332015-04-29 13:06:49 +0000214 if (StartOfSequence == 0)
215 StartOfSequence = i;
216
217 unsigned ChangeMinColumn = Changes[i].StartOfTokenColumn;
Daniel Jaspere12597c2015-10-01 10:06:54 +0000218 int LineLengthAfter = -Changes[i].Spaces;
219 for (unsigned j = i; j != e && Changes[j].NewlinesBefore == 0; ++j)
220 LineLengthAfter += Changes[j].Spaces + Changes[j].TokenLength;
221 unsigned ChangeMaxColumn = Style.ColumnLimit - LineLengthAfter;
222
223 if (ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn) {
224 AlignSequence();
225 StartOfSequence = i;
226 }
227
Daniel Jaspera44991332015-04-29 13:06:49 +0000228 MinColumn = std::max(MinColumn, ChangeMinColumn);
Daniel Jaspere12597c2015-10-01 10:06:54 +0000229 MaxColumn = std::min(MaxColumn, ChangeMaxColumn);
Daniel Jaspera44991332015-04-29 13:06:49 +0000230 }
231 }
232
Daniel Jasperbbfd20d2015-09-22 09:32:00 +0000233 EndOfSequence = Changes.size();
234 AlignSequence();
Daniel Jaspera44991332015-04-29 13:06:49 +0000235}
236
237void WhitespaceManager::alignConsecutiveAssignments(unsigned Start,
238 unsigned End,
239 unsigned Column) {
Daniel Jasperbbfd20d2015-09-22 09:32:00 +0000240 bool FoundAssignmentOnLine = false;
241 int Shift = 0;
Daniel Jaspera44991332015-04-29 13:06:49 +0000242 for (unsigned i = Start; i != End; ++i) {
Daniel Jasperbbfd20d2015-09-22 09:32:00 +0000243 if (Changes[i].NewlinesBefore > 0) {
244 FoundAssignmentOnLine = false;
245 Shift = 0;
Daniel Jaspera44991332015-04-29 13:06:49 +0000246 }
Daniel Jasperbbfd20d2015-09-22 09:32:00 +0000247
248 // If this is the first assignment to be aligned, remember by how many
249 // spaces it has to be shifted, so the rest of the changes on the line are
250 // shifted by the same amount
251 if (!FoundAssignmentOnLine && Changes[i].Kind == tok::equal) {
252 FoundAssignmentOnLine = true;
253 Shift = Column - Changes[i].StartOfTokenColumn;
254 Changes[i].Spaces += Shift;
255 }
256
Daniel Jaspera44991332015-04-29 13:06:49 +0000257 assert(Shift >= 0);
Daniel Jasperbbfd20d2015-09-22 09:32:00 +0000258 Changes[i].StartOfTokenColumn += Shift;
Daniel Jaspera44991332015-04-29 13:06:49 +0000259 if (i + 1 != Changes.size())
260 Changes[i + 1].PreviousEndOfTokenColumn += Shift;
Daniel Jaspera44991332015-04-29 13:06:49 +0000261 }
262}
263
Daniel Jaspere12597c2015-10-01 10:06:54 +0000264// Walk through all of the changes and find sequences of declaration names to
265// align. To do so, keep track of the lines and whether or not a name was found
266// on align. If a name is found on a line, extend the current sequence. If the
267// current line cannot be part of a sequence, e.g. because there is an empty
268// line before it or it contains non-declarations, finalize the previous
269// sequence.
270void WhitespaceManager::alignConsecutiveDeclarations() {
271 if (!Style.AlignConsecutiveDeclarations)
272 return;
273
274 unsigned MinColumn = 0;
275 unsigned MaxColumn = UINT_MAX;
276 unsigned StartOfSequence = 0;
277 unsigned EndOfSequence = 0;
278 bool FoundDeclarationOnLine = false;
279 bool FoundLeftBraceOnLine = false;
280 bool FoundLeftParenOnLine = false;
281
282 auto AlignSequence = [&] {
283 if (StartOfSequence > 0 && StartOfSequence < EndOfSequence)
284 alignConsecutiveDeclarations(StartOfSequence, EndOfSequence, MinColumn);
285 MinColumn = 0;
286 MaxColumn = UINT_MAX;
287 StartOfSequence = 0;
288 EndOfSequence = 0;
289 };
290
291 for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
292 if (Changes[i].NewlinesBefore != 0) {
293 EndOfSequence = i;
294 if (Changes[i].NewlinesBefore > 1 || !FoundDeclarationOnLine ||
295 FoundLeftBraceOnLine || FoundLeftParenOnLine)
296 AlignSequence();
297 FoundDeclarationOnLine = false;
298 FoundLeftBraceOnLine = false;
299 FoundLeftParenOnLine = false;
300 }
301
302 if (Changes[i].Kind == tok::r_brace) {
303 if (!FoundLeftBraceOnLine)
304 AlignSequence();
305 FoundLeftBraceOnLine = false;
306 } else if (Changes[i].Kind == tok::l_brace) {
307 FoundLeftBraceOnLine = true;
308 if (!FoundDeclarationOnLine)
309 AlignSequence();
310 } else if (Changes[i].Kind == tok::r_paren) {
311 if (!FoundLeftParenOnLine)
312 AlignSequence();
313 FoundLeftParenOnLine = false;
314 } else if (Changes[i].Kind == tok::l_paren) {
315 FoundLeftParenOnLine = true;
316 if (!FoundDeclarationOnLine)
317 AlignSequence();
318 } else if (!FoundDeclarationOnLine && !FoundLeftBraceOnLine &&
319 !FoundLeftParenOnLine && Changes[i].IsStartOfDeclName) {
320 FoundDeclarationOnLine = true;
321 if (StartOfSequence == 0)
322 StartOfSequence = i;
323
324 unsigned ChangeMinColumn = Changes[i].StartOfTokenColumn;
325 int LineLengthAfter = -Changes[i].Spaces;
326 for (unsigned j = i; j != e && Changes[j].NewlinesBefore == 0; ++j)
327 LineLengthAfter += Changes[j].Spaces + Changes[j].TokenLength;
328 unsigned ChangeMaxColumn = Style.ColumnLimit - LineLengthAfter;
329
330 if (ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn) {
331 AlignSequence();
332 StartOfSequence = i;
333 }
334
335 MinColumn = std::max(MinColumn, ChangeMinColumn);
336 MaxColumn = std::min(MaxColumn, ChangeMaxColumn);
337 }
338 }
339
340 EndOfSequence = Changes.size();
341 AlignSequence();
342}
343
344void WhitespaceManager::alignConsecutiveDeclarations(unsigned Start,
345 unsigned End,
346 unsigned Column) {
347 bool FoundDeclarationOnLine = false;
348 int Shift = 0;
349 for (unsigned i = Start; i != End; ++i) {
350 if (Changes[i].NewlinesBefore != 0) {
351 FoundDeclarationOnLine = false;
352 Shift = 0;
353 }
354
355 if (!FoundDeclarationOnLine && Changes[i].IsStartOfDeclName) {
356 FoundDeclarationOnLine = true;
357 Shift = Column - Changes[i].StartOfTokenColumn;
358 Changes[i].Spaces += Shift;
359 }
360
361 assert(Shift >= 0);
362 Changes[i].StartOfTokenColumn += Shift;
363 if (i + 1 != Changes.size())
364 Changes[i + 1].PreviousEndOfTokenColumn += Shift;
365 }
366}
367
Manuel Klimek4fe43002013-05-22 12:51:29 +0000368void WhitespaceManager::alignTrailingComments() {
369 unsigned MinColumn = 0;
370 unsigned MaxColumn = UINT_MAX;
371 unsigned StartOfSequence = 0;
372 bool BreakBeforeNext = false;
373 unsigned Newlines = 0;
374 for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000375 if (Changes[i].StartOfBlockComment)
376 continue;
377 Newlines += Changes[i].NewlinesBefore;
378 if (!Changes[i].IsTrailingComment)
379 continue;
380
Manuel Klimek4fe43002013-05-22 12:51:29 +0000381 unsigned ChangeMinColumn = Changes[i].StartOfTokenColumn;
Manuel Klimek4fe43002013-05-22 12:51:29 +0000382 unsigned ChangeMaxColumn = Style.ColumnLimit - Changes[i].TokenLength;
Daniel Jasper66935022014-04-27 10:03:19 +0000383 if (i + 1 != e && Changes[i + 1].ContinuesPPDirective)
384 ChangeMaxColumn -= 2;
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000385 // If this comment follows an } in column 0, it probably documents the
386 // closing of a namespace and we don't want to align it.
387 bool FollowsRBraceInColumn0 = i > 0 && Changes[i].NewlinesBefore == 0 &&
388 Changes[i - 1].Kind == tok::r_brace &&
389 Changes[i - 1].StartOfTokenColumn == 0;
390 bool WasAlignedWithStartOfNextLine = false;
391 if (Changes[i].NewlinesBefore == 1) { // A comment on its own line.
Daniel Jasper49532102015-01-07 14:00:11 +0000392 unsigned CommentColumn = SourceMgr.getSpellingColumnNumber(
393 Changes[i].OriginalWhitespaceRange.getEnd());
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000394 for (unsigned j = i + 1; j != e; ++j) {
395 if (Changes[j].Kind != tok::comment) { // Skip over comments.
Daniel Jasper49532102015-01-07 14:00:11 +0000396 unsigned NextColumn = SourceMgr.getSpellingColumnNumber(
397 Changes[j].OriginalWhitespaceRange.getEnd());
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000398 // The start of the next token was previously aligned with the
399 // start of this comment.
400 WasAlignedWithStartOfNextLine =
Daniel Jasper49532102015-01-07 14:00:11 +0000401 CommentColumn == NextColumn ||
402 CommentColumn == NextColumn + Style.IndentWidth;
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000403 break;
Daniel Jasper0e93cdb2013-11-08 23:31:14 +0000404 }
405 }
Manuel Klimek4fe43002013-05-22 12:51:29 +0000406 }
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000407 if (!Style.AlignTrailingComments || FollowsRBraceInColumn0) {
408 alignTrailingComments(StartOfSequence, i, MinColumn);
409 MinColumn = ChangeMinColumn;
410 MaxColumn = ChangeMinColumn;
411 StartOfSequence = i;
412 } else if (BreakBeforeNext || Newlines > 1 ||
413 (ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn) ||
414 // Break the comment sequence if the previous line did not end
415 // in a trailing comment.
416 (Changes[i].NewlinesBefore == 1 && i > 0 &&
417 !Changes[i - 1].IsTrailingComment) ||
418 WasAlignedWithStartOfNextLine) {
419 alignTrailingComments(StartOfSequence, i, MinColumn);
420 MinColumn = ChangeMinColumn;
421 MaxColumn = ChangeMaxColumn;
422 StartOfSequence = i;
423 } else {
424 MinColumn = std::max(MinColumn, ChangeMinColumn);
425 MaxColumn = std::min(MaxColumn, ChangeMaxColumn);
426 }
427 BreakBeforeNext =
428 (i == 0) || (Changes[i].NewlinesBefore > 1) ||
429 // Never start a sequence with a comment at the beginning of
430 // the line.
431 (Changes[i].NewlinesBefore == 1 && StartOfSequence == i);
432 Newlines = 0;
Manuel Klimek4fe43002013-05-22 12:51:29 +0000433 }
434 alignTrailingComments(StartOfSequence, Changes.size(), MinColumn);
435}
436
437void WhitespaceManager::alignTrailingComments(unsigned Start, unsigned End,
438 unsigned Column) {
439 for (unsigned i = Start; i != End; ++i) {
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000440 int Shift = 0;
Manuel Klimek4fe43002013-05-22 12:51:29 +0000441 if (Changes[i].IsTrailingComment) {
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000442 Shift = Column - Changes[i].StartOfTokenColumn;
Manuel Klimek4fe43002013-05-22 12:51:29 +0000443 }
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000444 if (Changes[i].StartOfBlockComment) {
445 Shift = Changes[i].IndentationOffset +
446 Changes[i].StartOfBlockComment->StartOfTokenColumn -
447 Changes[i].StartOfTokenColumn;
448 }
449 assert(Shift >= 0);
450 Changes[i].Spaces += Shift;
451 if (i + 1 != End)
452 Changes[i + 1].PreviousEndOfTokenColumn += Shift;
453 Changes[i].StartOfTokenColumn += Shift;
Manuel Klimek4fe43002013-05-22 12:51:29 +0000454 }
455}
456
457void WhitespaceManager::alignEscapedNewlines() {
Daniel Jaspera49393f2013-08-28 09:07:32 +0000458 unsigned MaxEndOfLine =
459 Style.AlignEscapedNewlinesLeft ? 0 : Style.ColumnLimit;
Manuel Klimek4fe43002013-05-22 12:51:29 +0000460 unsigned StartOfMacro = 0;
461 for (unsigned i = 1, e = Changes.size(); i < e; ++i) {
462 Change &C = Changes[i];
463 if (C.NewlinesBefore > 0) {
464 if (C.ContinuesPPDirective) {
Daniel Jaspera49393f2013-08-28 09:07:32 +0000465 MaxEndOfLine = std::max(C.PreviousEndOfTokenColumn + 2, MaxEndOfLine);
Manuel Klimek4fe43002013-05-22 12:51:29 +0000466 } else {
467 alignEscapedNewlines(StartOfMacro + 1, i, MaxEndOfLine);
Daniel Jaspera49393f2013-08-28 09:07:32 +0000468 MaxEndOfLine = Style.AlignEscapedNewlinesLeft ? 0 : Style.ColumnLimit;
Manuel Klimek4fe43002013-05-22 12:51:29 +0000469 StartOfMacro = i;
470 }
471 }
472 }
473 alignEscapedNewlines(StartOfMacro + 1, Changes.size(), MaxEndOfLine);
474}
475
476void WhitespaceManager::alignEscapedNewlines(unsigned Start, unsigned End,
477 unsigned Column) {
478 for (unsigned i = Start; i < End; ++i) {
479 Change &C = Changes[i];
480 if (C.NewlinesBefore > 0) {
481 assert(C.ContinuesPPDirective);
482 if (C.PreviousEndOfTokenColumn + 1 > Column)
483 C.EscapedNewlineColumn = 0;
484 else
485 C.EscapedNewlineColumn = Column;
486 }
487 }
488}
489
490void WhitespaceManager::generateChanges() {
491 for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
492 const Change &C = Changes[i];
Daniel Jasper47b35ae2015-01-29 10:47:14 +0000493 if (i > 0) {
494 assert(Changes[i - 1].OriginalWhitespaceRange.getBegin() !=
495 C.OriginalWhitespaceRange.getBegin() &&
496 "Generating two replacements for the same location");
497 }
Manuel Klimek4fe43002013-05-22 12:51:29 +0000498 if (C.CreateReplacement) {
Alexander Kornienko9e649af2013-09-11 12:25:57 +0000499 std::string ReplacementText = C.PreviousLinePostfix;
500 if (C.ContinuesPPDirective)
501 appendNewlineText(ReplacementText, C.NewlinesBefore,
502 C.PreviousEndOfTokenColumn, C.EscapedNewlineColumn);
503 else
504 appendNewlineText(ReplacementText, C.NewlinesBefore);
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000505 appendIndentText(ReplacementText, C.IndentLevel, std::max(0, C.Spaces),
506 C.StartOfTokenColumn - std::max(0, C.Spaces));
Alexander Kornienko9e649af2013-09-11 12:25:57 +0000507 ReplacementText.append(C.CurrentLinePrefix);
Manuel Klimek4fe43002013-05-22 12:51:29 +0000508 storeReplacement(C.OriginalWhitespaceRange, ReplacementText);
509 }
510 }
511}
512
513void WhitespaceManager::storeReplacement(const SourceRange &Range,
514 StringRef Text) {
515 unsigned WhitespaceLength = SourceMgr.getFileOffset(Range.getEnd()) -
516 SourceMgr.getFileOffset(Range.getBegin());
517 // Don't create a replacement, if it does not change anything.
518 if (StringRef(SourceMgr.getCharacterData(Range.getBegin()),
Daniel Jasper3ac9b9e2013-07-08 14:34:09 +0000519 WhitespaceLength) == Text)
Manuel Klimek4fe43002013-05-22 12:51:29 +0000520 return;
521 Replaces.insert(tooling::Replacement(
522 SourceMgr, CharSourceRange::getCharRange(Range), Text));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000523}
524
Alexander Kornienko9e649af2013-09-11 12:25:57 +0000525void WhitespaceManager::appendNewlineText(std::string &Text,
526 unsigned Newlines) {
527 for (unsigned i = 0; i < Newlines; ++i)
528 Text.append(UseCRLF ? "\r\n" : "\n");
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000529}
530
Alexander Kornienko9e649af2013-09-11 12:25:57 +0000531void WhitespaceManager::appendNewlineText(std::string &Text, unsigned Newlines,
532 unsigned PreviousEndOfTokenColumn,
533 unsigned EscapedNewlineColumn) {
Alexander Kornienko555efc32013-06-11 16:01:49 +0000534 if (Newlines > 0) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000535 unsigned Offset =
Manuel Klimek4fe43002013-05-22 12:51:29 +0000536 std::min<int>(EscapedNewlineColumn - 1, PreviousEndOfTokenColumn);
Alexander Kornienko555efc32013-06-11 16:01:49 +0000537 for (unsigned i = 0; i < Newlines; ++i) {
Benjamin Kramerddf1cda2015-05-28 19:55:49 +0000538 Text.append(EscapedNewlineColumn - Offset - 1, ' ');
Alexander Kornienko9e649af2013-09-11 12:25:57 +0000539 Text.append(UseCRLF ? "\\\r\n" : "\\\n");
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000540 Offset = 0;
541 }
542 }
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000543}
544
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000545void WhitespaceManager::appendIndentText(std::string &Text,
546 unsigned IndentLevel, unsigned Spaces,
Alexander Kornienkodb4c21f2013-09-27 09:45:40 +0000547 unsigned WhitespaceStartColumn) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000548 switch (Style.UseTab) {
549 case FormatStyle::UT_Never:
Benjamin Kramerddf1cda2015-05-28 19:55:49 +0000550 Text.append(Spaces, ' ');
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000551 break;
552 case FormatStyle::UT_Always: {
Alexander Kornienkodb4c21f2013-09-27 09:45:40 +0000553 unsigned FirstTabWidth =
554 Style.TabWidth - WhitespaceStartColumn % Style.TabWidth;
555 // Indent with tabs only when there's at least one full tab.
556 if (FirstTabWidth + Style.TabWidth <= Spaces) {
557 Spaces -= FirstTabWidth;
558 Text.append("\t");
559 }
Benjamin Kramerddf1cda2015-05-28 19:55:49 +0000560 Text.append(Spaces / Style.TabWidth, '\t');
561 Text.append(Spaces % Style.TabWidth, ' ');
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000562 break;
563 }
564 case FormatStyle::UT_ForIndentation:
565 if (WhitespaceStartColumn == 0) {
566 unsigned Indentation = IndentLevel * Style.IndentWidth;
Alexander Kornienko45dc1b22013-09-27 16:40:11 +0000567 // This happens, e.g. when a line in a block comment is indented less than
568 // the first one.
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000569 if (Indentation > Spaces)
570 Indentation = Spaces;
571 unsigned Tabs = Indentation / Style.TabWidth;
Benjamin Kramerddf1cda2015-05-28 19:55:49 +0000572 Text.append(Tabs, '\t');
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000573 Spaces -= Tabs * Style.TabWidth;
574 }
Benjamin Kramerddf1cda2015-05-28 19:55:49 +0000575 Text.append(Spaces, ' ');
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000576 break;
Alexander Kornienko9e649af2013-09-11 12:25:57 +0000577 }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000578}
579
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000580} // namespace format
581} // namespace clang