blob: c3b40fc7e2aea8bdf5eacd233d86424d2a5f9376 [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(
Craig Toppere335f252015-10-04 04:53:55 +000029 bool CreateReplacement, 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(
Daniel Jasper417fc812016-01-09 15:56:53 +000058 Change(/*CreateReplacement=*/true, Tok.WhitespaceRange, IndentLevel,
59 Spaces, StartOfTokenColumn, Newlines, "", "", Tok.Tok.getKind(),
60 InPPDirective && !Tok.IsFirst,
Daniel Jaspere12597c2015-10-01 10:06:54 +000061 Tok.is(TT_StartOfName) || Tok.is(TT_FunctionDeclarationName)));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000062}
63
Manuel Klimek4fe43002013-05-22 12:51:29 +000064void WhitespaceManager::addUntouchableToken(const FormatToken &Tok,
65 bool InPPDirective) {
Manuel Klimek71814b42013-10-11 21:25:45 +000066 if (Tok.Finalized)
67 return;
Daniel Jasper417fc812016-01-09 15:56:53 +000068 Changes.push_back(Change(
69 /*CreateReplacement=*/false, Tok.WhitespaceRange, /*IndentLevel=*/0,
70 /*Spaces=*/0, Tok.OriginalColumn, Tok.NewlinesBefore, "", "",
71 Tok.Tok.getKind(), InPPDirective && !Tok.IsFirst,
72 Tok.is(TT_StartOfName) || Tok.is(TT_FunctionDeclarationName)));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000073}
74
Alexander Kornienko555efc32013-06-11 16:01:49 +000075void WhitespaceManager::replaceWhitespaceInToken(
76 const FormatToken &Tok, unsigned Offset, unsigned ReplaceChars,
77 StringRef PreviousPostfix, StringRef CurrentPrefix, bool InPPDirective,
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +000078 unsigned Newlines, unsigned IndentLevel, int Spaces) {
Manuel Klimek71814b42013-10-11 21:25:45 +000079 if (Tok.Finalized)
80 return;
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +000081 SourceLocation Start = Tok.getStartOfNonWhitespace().getLocWithOffset(Offset);
Manuel Klimek4fe43002013-05-22 12:51:29 +000082 Changes.push_back(Change(
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +000083 true, SourceRange(Start, Start.getLocWithOffset(ReplaceChars)),
84 IndentLevel, Spaces, std::max(0, Spaces), Newlines, PreviousPostfix,
85 CurrentPrefix,
Alexander Kornienko4d26b6e2013-06-17 12:59:44 +000086 // If we don't add a newline this change doesn't start a comment. Thus,
87 // when we align line comments, we don't need to treat this change as one.
88 // FIXME: We still need to take this change in account to properly
89 // calculate the new length of the comment and to calculate the changes
90 // for which to do the alignment when aligning comments.
Daniel Jaspera98b7b02014-11-25 10:05:17 +000091 Tok.is(TT_LineComment) && Newlines > 0 ? tok::comment : tok::unknown,
Daniel Jaspere12597c2015-10-01 10:06:54 +000092 InPPDirective && !Tok.IsFirst,
93 Tok.is(TT_StartOfName) || Tok.is(TT_FunctionDeclarationName)));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000094}
95
Manuel Klimek4fe43002013-05-22 12:51:29 +000096const tooling::Replacements &WhitespaceManager::generateReplacements() {
97 if (Changes.empty())
98 return Replaces;
99
100 std::sort(Changes.begin(), Changes.end(), Change::IsBeforeInFile(SourceMgr));
101 calculateLineBreakInformation();
Daniel Jaspere12597c2015-10-01 10:06:54 +0000102 alignConsecutiveDeclarations();
Daniel Jaspera44991332015-04-29 13:06:49 +0000103 alignConsecutiveAssignments();
Manuel Klimek4fe43002013-05-22 12:51:29 +0000104 alignTrailingComments();
105 alignEscapedNewlines();
106 generateChanges();
107
108 return Replaces;
109}
110
111void WhitespaceManager::calculateLineBreakInformation() {
112 Changes[0].PreviousEndOfTokenColumn = 0;
113 for (unsigned i = 1, e = Changes.size(); i != e; ++i) {
114 unsigned OriginalWhitespaceStart =
115 SourceMgr.getFileOffset(Changes[i].OriginalWhitespaceRange.getBegin());
116 unsigned PreviousOriginalWhitespaceEnd = SourceMgr.getFileOffset(
117 Changes[i - 1].OriginalWhitespaceRange.getEnd());
Daniel Jasper3ac9b9e2013-07-08 14:34:09 +0000118 Changes[i - 1].TokenLength = OriginalWhitespaceStart -
119 PreviousOriginalWhitespaceEnd +
120 Changes[i].PreviousLinePostfix.size() +
121 Changes[i - 1].CurrentLinePrefix.size();
Manuel Klimek4fe43002013-05-22 12:51:29 +0000122
123 Changes[i].PreviousEndOfTokenColumn =
124 Changes[i - 1].StartOfTokenColumn + Changes[i - 1].TokenLength;
125
126 Changes[i - 1].IsTrailingComment =
127 (Changes[i].NewlinesBefore > 0 || Changes[i].Kind == tok::eof) &&
128 Changes[i - 1].Kind == tok::comment;
129 }
Manuel Klimek05c67892013-05-22 14:01:08 +0000130 // FIXME: The last token is currently not always an eof token; in those
131 // cases, setting TokenLength of the last token to 0 is wrong.
132 Changes.back().TokenLength = 0;
Manuel Klimek4fe43002013-05-22 12:51:29 +0000133 Changes.back().IsTrailingComment = Changes.back().Kind == tok::comment;
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000134
135 const WhitespaceManager::Change *LastBlockComment = nullptr;
136 for (auto &Change : Changes) {
137 Change.StartOfBlockComment = nullptr;
138 Change.IndentationOffset = 0;
139 if (Change.Kind == tok::comment) {
140 LastBlockComment = &Change;
141 } else if (Change.Kind == tok::unknown) {
142 if ((Change.StartOfBlockComment = LastBlockComment))
143 Change.IndentationOffset =
144 Change.StartOfTokenColumn -
145 Change.StartOfBlockComment->StartOfTokenColumn;
146 } else {
147 LastBlockComment = nullptr;
148 }
149 }
Manuel Klimek4fe43002013-05-22 12:51:29 +0000150}
151
Daniel Jasperec90e512015-12-01 12:00:43 +0000152// Align a single sequence of tokens, see AlignTokens below.
153template <typename F>
154static void
155AlignTokenSequence(unsigned Start, unsigned End, unsigned Column, F &&Matches,
156 SmallVector<WhitespaceManager::Change, 16> &Changes) {
157 bool FoundMatchOnLine = false;
158 int Shift = 0;
159 for (unsigned i = Start; i != End; ++i) {
160 if (Changes[i].NewlinesBefore > 0) {
161 FoundMatchOnLine = false;
162 Shift = 0;
163 }
164
165 // If this is the first matching token to be aligned, remember by how many
166 // spaces it has to be shifted, so the rest of the changes on the line are
167 // shifted by the same amount
168 if (!FoundMatchOnLine && Matches(Changes[i])) {
169 FoundMatchOnLine = true;
170 Shift = Column - Changes[i].StartOfTokenColumn;
171 Changes[i].Spaces += Shift;
172 }
173
174 assert(Shift >= 0);
175 Changes[i].StartOfTokenColumn += Shift;
176 if (i + 1 != Changes.size())
177 Changes[i + 1].PreviousEndOfTokenColumn += Shift;
178 }
179}
180
181// Walk through all of the changes and find sequences of matching tokens to
182// align. To do so, keep track of the lines and whether or not a matching token
183// was found on a line. If a matching token is found, extend the current
184// sequence. If the current line cannot be part of a sequence, e.g. because
185// there is an empty line before it or it contains only non-matching tokens,
186// finalize the previous sequence.
187template <typename F>
188static void AlignTokens(const FormatStyle &Style, F &&Matches,
189 SmallVector<WhitespaceManager::Change, 16> &Changes) {
190 unsigned MinColumn = 0;
191 unsigned MaxColumn = UINT_MAX;
192
193 // Line number of the start and the end of the current token sequence.
194 unsigned StartOfSequence = 0;
195 unsigned EndOfSequence = 0;
196
197 // Keep track of the nesting level of matching tokens, i.e. the number of
198 // surrounding (), [], or {}. We will only align a sequence of matching
199 // token that share the same scope depth.
200 //
201 // FIXME: This could use FormatToken::NestingLevel information, but there is
202 // an outstanding issue wrt the brace scopes.
203 unsigned NestingLevelOfLastMatch = 0;
204 unsigned NestingLevel = 0;
205
206 // Keep track of the number of commas before the matching tokens, we will only
207 // align a sequence of matching tokens if they are preceded by the same number
208 // of commas.
209 unsigned CommasBeforeLastMatch = 0;
210 unsigned CommasBeforeMatch = 0;
211
212 // Whether a matching token has been found on the current line.
213 bool FoundMatchOnLine = false;
214
215 // Aligns a sequence of matching tokens, on the MinColumn column.
216 //
217 // Sequences start from the first matching token to align, and end at the
218 // first token of the first line that doesn't need to be aligned.
219 //
220 // We need to adjust the StartOfTokenColumn of each Change that is on a line
221 // containing any matching token to be aligned and located after such token.
222 auto AlignCurrentSequence = [&] {
223 if (StartOfSequence > 0 && StartOfSequence < EndOfSequence)
224 AlignTokenSequence(StartOfSequence, EndOfSequence, MinColumn, Matches,
225 Changes);
226 MinColumn = 0;
227 MaxColumn = UINT_MAX;
228 StartOfSequence = 0;
229 EndOfSequence = 0;
230 };
231
232 for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
233 if (Changes[i].NewlinesBefore != 0) {
234 CommasBeforeMatch = 0;
235 EndOfSequence = i;
236 // If there is a blank line, or if the last line didn't contain any
237 // matching token, the sequence ends here.
238 if (Changes[i].NewlinesBefore > 1 || !FoundMatchOnLine)
239 AlignCurrentSequence();
240
241 FoundMatchOnLine = false;
242 }
243
244 if (Changes[i].Kind == tok::comma) {
245 ++CommasBeforeMatch;
246 } else if (Changes[i].Kind == tok::r_brace ||
247 Changes[i].Kind == tok::r_paren ||
248 Changes[i].Kind == tok::r_square) {
249 --NestingLevel;
250 } else if (Changes[i].Kind == tok::l_brace ||
251 Changes[i].Kind == tok::l_paren ||
252 Changes[i].Kind == tok::l_square) {
253 // We want sequences to skip over child scopes if possible, but not the
254 // other way around.
255 NestingLevelOfLastMatch = std::min(NestingLevelOfLastMatch, NestingLevel);
256 ++NestingLevel;
257 }
258
259 if (!Matches(Changes[i]))
260 continue;
261
262 // If there is more than one matching token per line, or if the number of
263 // preceding commas, or the scope depth, do not match anymore, end the
264 // sequence.
265 if (FoundMatchOnLine || CommasBeforeMatch != CommasBeforeLastMatch ||
266 NestingLevel != NestingLevelOfLastMatch)
267 AlignCurrentSequence();
268
269 CommasBeforeLastMatch = CommasBeforeMatch;
270 NestingLevelOfLastMatch = NestingLevel;
271 FoundMatchOnLine = true;
272
273 if (StartOfSequence == 0)
274 StartOfSequence = i;
275
276 unsigned ChangeMinColumn = Changes[i].StartOfTokenColumn;
277 int LineLengthAfter = -Changes[i].Spaces;
278 for (unsigned j = i; j != e && Changes[j].NewlinesBefore == 0; ++j)
279 LineLengthAfter += Changes[j].Spaces + Changes[j].TokenLength;
280 unsigned ChangeMaxColumn = Style.ColumnLimit - LineLengthAfter;
281
282 // If we are restricted by the maximum column width, end the sequence.
283 if (ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn ||
284 CommasBeforeLastMatch != CommasBeforeMatch) {
285 AlignCurrentSequence();
286 StartOfSequence = i;
287 }
288
289 MinColumn = std::max(MinColumn, ChangeMinColumn);
290 MaxColumn = std::min(MaxColumn, ChangeMaxColumn);
291 }
292
293 EndOfSequence = Changes.size();
294 AlignCurrentSequence();
295}
296
Daniel Jaspera44991332015-04-29 13:06:49 +0000297void WhitespaceManager::alignConsecutiveAssignments() {
298 if (!Style.AlignConsecutiveAssignments)
299 return;
300
Daniel Jasperec90e512015-12-01 12:00:43 +0000301 AlignTokens(Style,
302 [&](const Change &C) {
303 // Do not align on equal signs that are first on a line.
304 if (C.NewlinesBefore > 0)
305 return false;
Daniel Jaspera44991332015-04-29 13:06:49 +0000306
Daniel Jasperec90e512015-12-01 12:00:43 +0000307 // Do not align on equal signs that are last on a line.
308 if (&C != &Changes.back() && (&C + 1)->NewlinesBefore > 0)
309 return false;
Daniel Jaspera44991332015-04-29 13:06:49 +0000310
Daniel Jasperec90e512015-12-01 12:00:43 +0000311 return C.Kind == tok::equal;
312 },
313 Changes);
Daniel Jaspera44991332015-04-29 13:06:49 +0000314}
315
Daniel Jaspere12597c2015-10-01 10:06:54 +0000316void WhitespaceManager::alignConsecutiveDeclarations() {
317 if (!Style.AlignConsecutiveDeclarations)
318 return;
319
Daniel Jasperec90e512015-12-01 12:00:43 +0000320 // FIXME: Currently we don't handle properly the PointerAlignment: Right
321 // The * and & are not aligned and are left dangling. Something has to be done
322 // about it, but it raises the question of alignment of code like:
323 // const char* const* v1;
324 // float const* v2;
325 // SomeVeryLongType const& v3;
Daniel Jaspere12597c2015-10-01 10:06:54 +0000326
Daniel Jasperec90e512015-12-01 12:00:43 +0000327 AlignTokens(Style, [](Change const &C) { return C.IsStartOfDeclName; },
328 Changes);
Daniel Jaspere12597c2015-10-01 10:06:54 +0000329}
330
Manuel Klimek4fe43002013-05-22 12:51:29 +0000331void WhitespaceManager::alignTrailingComments() {
332 unsigned MinColumn = 0;
333 unsigned MaxColumn = UINT_MAX;
334 unsigned StartOfSequence = 0;
335 bool BreakBeforeNext = false;
336 unsigned Newlines = 0;
337 for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000338 if (Changes[i].StartOfBlockComment)
339 continue;
340 Newlines += Changes[i].NewlinesBefore;
341 if (!Changes[i].IsTrailingComment)
342 continue;
343
Manuel Klimek4fe43002013-05-22 12:51:29 +0000344 unsigned ChangeMinColumn = Changes[i].StartOfTokenColumn;
Manuel Klimek4fe43002013-05-22 12:51:29 +0000345 unsigned ChangeMaxColumn = Style.ColumnLimit - Changes[i].TokenLength;
Daniel Jasper417fc812016-01-09 15:56:53 +0000346
347 // If we don't create a replacement for this change, we have to consider
348 // it to be immovable.
349 if (!Changes[i].CreateReplacement)
350 ChangeMaxColumn = ChangeMinColumn;
351
Daniel Jasper66935022014-04-27 10:03:19 +0000352 if (i + 1 != e && Changes[i + 1].ContinuesPPDirective)
353 ChangeMaxColumn -= 2;
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000354 // If this comment follows an } in column 0, it probably documents the
355 // closing of a namespace and we don't want to align it.
356 bool FollowsRBraceInColumn0 = i > 0 && Changes[i].NewlinesBefore == 0 &&
357 Changes[i - 1].Kind == tok::r_brace &&
358 Changes[i - 1].StartOfTokenColumn == 0;
359 bool WasAlignedWithStartOfNextLine = false;
360 if (Changes[i].NewlinesBefore == 1) { // A comment on its own line.
Daniel Jasper49532102015-01-07 14:00:11 +0000361 unsigned CommentColumn = SourceMgr.getSpellingColumnNumber(
362 Changes[i].OriginalWhitespaceRange.getEnd());
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000363 for (unsigned j = i + 1; j != e; ++j) {
364 if (Changes[j].Kind != tok::comment) { // Skip over comments.
Daniel Jasper49532102015-01-07 14:00:11 +0000365 unsigned NextColumn = SourceMgr.getSpellingColumnNumber(
366 Changes[j].OriginalWhitespaceRange.getEnd());
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000367 // The start of the next token was previously aligned with the
368 // start of this comment.
369 WasAlignedWithStartOfNextLine =
Daniel Jasper49532102015-01-07 14:00:11 +0000370 CommentColumn == NextColumn ||
371 CommentColumn == NextColumn + Style.IndentWidth;
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000372 break;
Daniel Jasper0e93cdb2013-11-08 23:31:14 +0000373 }
374 }
Manuel Klimek4fe43002013-05-22 12:51:29 +0000375 }
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000376 if (!Style.AlignTrailingComments || FollowsRBraceInColumn0) {
377 alignTrailingComments(StartOfSequence, i, MinColumn);
378 MinColumn = ChangeMinColumn;
379 MaxColumn = ChangeMinColumn;
380 StartOfSequence = i;
381 } else if (BreakBeforeNext || Newlines > 1 ||
382 (ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn) ||
383 // Break the comment sequence if the previous line did not end
384 // in a trailing comment.
385 (Changes[i].NewlinesBefore == 1 && i > 0 &&
386 !Changes[i - 1].IsTrailingComment) ||
387 WasAlignedWithStartOfNextLine) {
388 alignTrailingComments(StartOfSequence, i, MinColumn);
389 MinColumn = ChangeMinColumn;
390 MaxColumn = ChangeMaxColumn;
391 StartOfSequence = i;
392 } else {
393 MinColumn = std::max(MinColumn, ChangeMinColumn);
394 MaxColumn = std::min(MaxColumn, ChangeMaxColumn);
395 }
396 BreakBeforeNext =
397 (i == 0) || (Changes[i].NewlinesBefore > 1) ||
398 // Never start a sequence with a comment at the beginning of
399 // the line.
400 (Changes[i].NewlinesBefore == 1 && StartOfSequence == i);
401 Newlines = 0;
Manuel Klimek4fe43002013-05-22 12:51:29 +0000402 }
403 alignTrailingComments(StartOfSequence, Changes.size(), MinColumn);
404}
405
406void WhitespaceManager::alignTrailingComments(unsigned Start, unsigned End,
407 unsigned Column) {
408 for (unsigned i = Start; i != End; ++i) {
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000409 int Shift = 0;
Manuel Klimek4fe43002013-05-22 12:51:29 +0000410 if (Changes[i].IsTrailingComment) {
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000411 Shift = Column - Changes[i].StartOfTokenColumn;
Manuel Klimek4fe43002013-05-22 12:51:29 +0000412 }
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000413 if (Changes[i].StartOfBlockComment) {
414 Shift = Changes[i].IndentationOffset +
415 Changes[i].StartOfBlockComment->StartOfTokenColumn -
416 Changes[i].StartOfTokenColumn;
417 }
418 assert(Shift >= 0);
419 Changes[i].Spaces += Shift;
420 if (i + 1 != End)
421 Changes[i + 1].PreviousEndOfTokenColumn += Shift;
422 Changes[i].StartOfTokenColumn += Shift;
Manuel Klimek4fe43002013-05-22 12:51:29 +0000423 }
424}
425
426void WhitespaceManager::alignEscapedNewlines() {
Daniel Jaspera49393f2013-08-28 09:07:32 +0000427 unsigned MaxEndOfLine =
428 Style.AlignEscapedNewlinesLeft ? 0 : Style.ColumnLimit;
Manuel Klimek4fe43002013-05-22 12:51:29 +0000429 unsigned StartOfMacro = 0;
430 for (unsigned i = 1, e = Changes.size(); i < e; ++i) {
431 Change &C = Changes[i];
432 if (C.NewlinesBefore > 0) {
433 if (C.ContinuesPPDirective) {
Daniel Jaspera49393f2013-08-28 09:07:32 +0000434 MaxEndOfLine = std::max(C.PreviousEndOfTokenColumn + 2, MaxEndOfLine);
Manuel Klimek4fe43002013-05-22 12:51:29 +0000435 } else {
436 alignEscapedNewlines(StartOfMacro + 1, i, MaxEndOfLine);
Daniel Jaspera49393f2013-08-28 09:07:32 +0000437 MaxEndOfLine = Style.AlignEscapedNewlinesLeft ? 0 : Style.ColumnLimit;
Manuel Klimek4fe43002013-05-22 12:51:29 +0000438 StartOfMacro = i;
439 }
440 }
441 }
442 alignEscapedNewlines(StartOfMacro + 1, Changes.size(), MaxEndOfLine);
443}
444
445void WhitespaceManager::alignEscapedNewlines(unsigned Start, unsigned End,
446 unsigned Column) {
447 for (unsigned i = Start; i < End; ++i) {
448 Change &C = Changes[i];
449 if (C.NewlinesBefore > 0) {
450 assert(C.ContinuesPPDirective);
451 if (C.PreviousEndOfTokenColumn + 1 > Column)
452 C.EscapedNewlineColumn = 0;
453 else
454 C.EscapedNewlineColumn = Column;
455 }
456 }
457}
458
459void WhitespaceManager::generateChanges() {
460 for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
461 const Change &C = Changes[i];
Daniel Jasper47b35ae2015-01-29 10:47:14 +0000462 if (i > 0) {
463 assert(Changes[i - 1].OriginalWhitespaceRange.getBegin() !=
464 C.OriginalWhitespaceRange.getBegin() &&
465 "Generating two replacements for the same location");
466 }
Manuel Klimek4fe43002013-05-22 12:51:29 +0000467 if (C.CreateReplacement) {
Alexander Kornienko9e649af2013-09-11 12:25:57 +0000468 std::string ReplacementText = C.PreviousLinePostfix;
469 if (C.ContinuesPPDirective)
470 appendNewlineText(ReplacementText, C.NewlinesBefore,
471 C.PreviousEndOfTokenColumn, C.EscapedNewlineColumn);
472 else
473 appendNewlineText(ReplacementText, C.NewlinesBefore);
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000474 appendIndentText(ReplacementText, C.IndentLevel, std::max(0, C.Spaces),
475 C.StartOfTokenColumn - std::max(0, C.Spaces));
Alexander Kornienko9e649af2013-09-11 12:25:57 +0000476 ReplacementText.append(C.CurrentLinePrefix);
Manuel Klimek4fe43002013-05-22 12:51:29 +0000477 storeReplacement(C.OriginalWhitespaceRange, ReplacementText);
478 }
479 }
480}
481
Craig Toppere335f252015-10-04 04:53:55 +0000482void WhitespaceManager::storeReplacement(SourceRange Range,
Manuel Klimek4fe43002013-05-22 12:51:29 +0000483 StringRef Text) {
484 unsigned WhitespaceLength = SourceMgr.getFileOffset(Range.getEnd()) -
485 SourceMgr.getFileOffset(Range.getBegin());
486 // Don't create a replacement, if it does not change anything.
487 if (StringRef(SourceMgr.getCharacterData(Range.getBegin()),
Daniel Jasper3ac9b9e2013-07-08 14:34:09 +0000488 WhitespaceLength) == Text)
Manuel Klimek4fe43002013-05-22 12:51:29 +0000489 return;
490 Replaces.insert(tooling::Replacement(
491 SourceMgr, CharSourceRange::getCharRange(Range), Text));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000492}
493
Alexander Kornienko9e649af2013-09-11 12:25:57 +0000494void WhitespaceManager::appendNewlineText(std::string &Text,
495 unsigned Newlines) {
496 for (unsigned i = 0; i < Newlines; ++i)
497 Text.append(UseCRLF ? "\r\n" : "\n");
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000498}
499
Alexander Kornienko9e649af2013-09-11 12:25:57 +0000500void WhitespaceManager::appendNewlineText(std::string &Text, unsigned Newlines,
501 unsigned PreviousEndOfTokenColumn,
502 unsigned EscapedNewlineColumn) {
Alexander Kornienko555efc32013-06-11 16:01:49 +0000503 if (Newlines > 0) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000504 unsigned Offset =
Manuel Klimek4fe43002013-05-22 12:51:29 +0000505 std::min<int>(EscapedNewlineColumn - 1, PreviousEndOfTokenColumn);
Alexander Kornienko555efc32013-06-11 16:01:49 +0000506 for (unsigned i = 0; i < Newlines; ++i) {
Benjamin Kramerddf1cda2015-05-28 19:55:49 +0000507 Text.append(EscapedNewlineColumn - Offset - 1, ' ');
Alexander Kornienko9e649af2013-09-11 12:25:57 +0000508 Text.append(UseCRLF ? "\\\r\n" : "\\\n");
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000509 Offset = 0;
510 }
511 }
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000512}
513
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000514void WhitespaceManager::appendIndentText(std::string &Text,
515 unsigned IndentLevel, unsigned Spaces,
Alexander Kornienkodb4c21f2013-09-27 09:45:40 +0000516 unsigned WhitespaceStartColumn) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000517 switch (Style.UseTab) {
518 case FormatStyle::UT_Never:
Benjamin Kramerddf1cda2015-05-28 19:55:49 +0000519 Text.append(Spaces, ' ');
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000520 break;
521 case FormatStyle::UT_Always: {
Alexander Kornienkodb4c21f2013-09-27 09:45:40 +0000522 unsigned FirstTabWidth =
523 Style.TabWidth - WhitespaceStartColumn % Style.TabWidth;
524 // Indent with tabs only when there's at least one full tab.
525 if (FirstTabWidth + Style.TabWidth <= Spaces) {
526 Spaces -= FirstTabWidth;
527 Text.append("\t");
528 }
Benjamin Kramerddf1cda2015-05-28 19:55:49 +0000529 Text.append(Spaces / Style.TabWidth, '\t');
530 Text.append(Spaces % Style.TabWidth, ' ');
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000531 break;
532 }
533 case FormatStyle::UT_ForIndentation:
534 if (WhitespaceStartColumn == 0) {
535 unsigned Indentation = IndentLevel * Style.IndentWidth;
Alexander Kornienko45dc1b22013-09-27 16:40:11 +0000536 // This happens, e.g. when a line in a block comment is indented less than
537 // the first one.
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000538 if (Indentation > Spaces)
539 Indentation = Spaces;
540 unsigned Tabs = Indentation / Style.TabWidth;
Benjamin Kramerddf1cda2015-05-28 19:55:49 +0000541 Text.append(Tabs, '\t');
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000542 Spaces -= Tabs * Style.TabWidth;
543 }
Benjamin Kramerddf1cda2015-05-28 19:55:49 +0000544 Text.append(Spaces, ' ');
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000545 break;
Alexander Kornienko9e649af2013-09-11 12:25:57 +0000546 }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000547}
548
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000549} // namespace format
550} // namespace clang