blob: c97486e4e4a7970d3c28d21cea67e3b315ad7cef [file] [log] [blame]
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001//===--- BreakableToken.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 Contains implementation of BreakableToken class and classes derived
12/// from it.
13///
14//===----------------------------------------------------------------------===//
15
16#include "BreakableToken.h"
Krasimir Georgiev91834222017-01-25 13:58:58 +000017#include "ContinuationIndenter.h"
Alexander Kornienko555efc32013-06-11 16:01:49 +000018#include "clang/Basic/CharInfo.h"
Manuel Klimek9043c742013-05-27 15:23:34 +000019#include "clang/Format/Format.h"
Alexander Kornienko9e90b622013-04-17 17:34:05 +000020#include "llvm/ADT/STLExtras.h"
Manuel Klimek9043c742013-05-27 15:23:34 +000021#include "llvm/Support/Debug.h"
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000022#include <algorithm>
23
Chandler Carruth10346662014-04-22 03:17:02 +000024#define DEBUG_TYPE "format-token-breaker"
25
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000026namespace clang {
27namespace format {
28
Daniel Jasper580da272013-10-30 07:36:40 +000029static const char *const Blanks = " \t\v\f\r";
Alexander Kornienkob93062e2013-06-20 13:58:37 +000030static bool IsBlank(char C) {
31 switch (C) {
Daniel Jasper3ac9b9e2013-07-08 14:34:09 +000032 case ' ':
33 case '\t':
34 case '\v':
35 case '\f':
Daniel Jasper580da272013-10-30 07:36:40 +000036 case '\r':
Daniel Jasper3ac9b9e2013-07-08 14:34:09 +000037 return true;
38 default:
39 return false;
Alexander Kornienkob93062e2013-06-20 13:58:37 +000040 }
41}
42
Krasimir Georgiev91834222017-01-25 13:58:58 +000043static StringRef getLineCommentIndentPrefix(StringRef Comment) {
44 static const char *const KnownPrefixes[] = {"///", "//", "//!"};
45 StringRef LongestPrefix;
46 for (StringRef KnownPrefix : KnownPrefixes) {
47 if (Comment.startswith(KnownPrefix)) {
48 size_t PrefixLength = KnownPrefix.size();
49 while (PrefixLength < Comment.size() && Comment[PrefixLength] == ' ')
50 ++PrefixLength;
51 if (PrefixLength > LongestPrefix.size())
52 LongestPrefix = Comment.substr(0, PrefixLength);
53 }
54 }
55 return LongestPrefix;
56}
57
Craig Topperbfb5c402013-07-01 03:38:29 +000058static BreakableToken::Split getCommentSplit(StringRef Text,
59 unsigned ContentStartColumn,
60 unsigned ColumnLimit,
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +000061 unsigned TabWidth,
Craig Topperbfb5c402013-07-01 03:38:29 +000062 encoding::Encoding Encoding) {
Alexander Kornienko9e90b622013-04-17 17:34:05 +000063 if (ColumnLimit <= ContentStartColumn + 1)
Manuel Klimek9043c742013-05-27 15:23:34 +000064 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienko9e90b622013-04-17 17:34:05 +000065
66 unsigned MaxSplit = ColumnLimit - ContentStartColumn + 1;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +000067 unsigned MaxSplitBytes = 0;
68
69 for (unsigned NumChars = 0;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +000070 NumChars < MaxSplit && MaxSplitBytes < Text.size();) {
71 unsigned BytesInChar =
Alexander Kornienkoffcc0102013-06-05 14:09:10 +000072 encoding::getCodePointNumBytes(Text[MaxSplitBytes], Encoding);
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +000073 NumChars +=
74 encoding::columnWidthWithTabs(Text.substr(MaxSplitBytes, BytesInChar),
75 ContentStartColumn, TabWidth, Encoding);
76 MaxSplitBytes += BytesInChar;
77 }
Alexander Kornienkoffcc0102013-06-05 14:09:10 +000078
Alexander Kornienkob93062e2013-06-20 13:58:37 +000079 StringRef::size_type SpaceOffset = Text.find_last_of(Blanks, MaxSplitBytes);
Alexander Kornienko9e90b622013-04-17 17:34:05 +000080 if (SpaceOffset == StringRef::npos ||
Manuel Klimek9043c742013-05-27 15:23:34 +000081 // Don't break at leading whitespace.
Alexander Kornienkob93062e2013-06-20 13:58:37 +000082 Text.find_last_not_of(Blanks, SpaceOffset) == StringRef::npos) {
Manuel Klimekae1fbfb2013-05-29 22:06:18 +000083 // Make sure that we don't break at leading whitespace that
84 // reaches past MaxSplit.
Alexander Kornienkob93062e2013-06-20 13:58:37 +000085 StringRef::size_type FirstNonWhitespace = Text.find_first_not_of(Blanks);
Manuel Klimekae1fbfb2013-05-29 22:06:18 +000086 if (FirstNonWhitespace == StringRef::npos)
87 // If the comment is only whitespace, we cannot split.
88 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienkob93062e2013-06-20 13:58:37 +000089 SpaceOffset = Text.find_first_of(
90 Blanks, std::max<unsigned>(MaxSplitBytes, FirstNonWhitespace));
Manuel Klimekae1fbfb2013-05-29 22:06:18 +000091 }
Alexander Kornienko9e90b622013-04-17 17:34:05 +000092 if (SpaceOffset != StringRef::npos && SpaceOffset != 0) {
Alexander Kornienkob93062e2013-06-20 13:58:37 +000093 StringRef BeforeCut = Text.substr(0, SpaceOffset).rtrim(Blanks);
94 StringRef AfterCut = Text.substr(SpaceOffset).ltrim(Blanks);
Alexander Kornienko9e90b622013-04-17 17:34:05 +000095 return BreakableToken::Split(BeforeCut.size(),
96 AfterCut.begin() - BeforeCut.end());
97 }
98 return BreakableToken::Split(StringRef::npos, 0);
99}
100
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000101static BreakableToken::Split
102getStringSplit(StringRef Text, unsigned UsedColumns, unsigned ColumnLimit,
103 unsigned TabWidth, encoding::Encoding Encoding) {
Manuel Klimek9043c742013-05-27 15:23:34 +0000104 // FIXME: Reduce unit test case.
105 if (Text.empty())
106 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienko81e32942013-09-16 20:20:49 +0000107 if (ColumnLimit <= UsedColumns)
Manuel Klimek9043c742013-05-27 15:23:34 +0000108 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienko71d95d62013-11-26 10:38:53 +0000109 unsigned MaxSplit = ColumnLimit - UsedColumns;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000110 StringRef::size_type SpaceOffset = 0;
111 StringRef::size_type SlashOffset = 0;
Alexander Kornienko72852072013-06-19 14:22:47 +0000112 StringRef::size_type WordStartOffset = 0;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000113 StringRef::size_type SplitPoint = 0;
114 for (unsigned Chars = 0;;) {
115 unsigned Advance;
116 if (Text[0] == '\\') {
117 Advance = encoding::getEscapeSequenceLength(Text);
118 Chars += Advance;
119 } else {
120 Advance = encoding::getCodePointNumBytes(Text[0], Encoding);
Alexander Kornienko81e32942013-09-16 20:20:49 +0000121 Chars += encoding::columnWidthWithTabs(
122 Text.substr(0, Advance), UsedColumns + Chars, TabWidth, Encoding);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000123 }
124
Daniel Jaspere4b48c62015-01-21 19:50:35 +0000125 if (Chars > MaxSplit || Text.size() <= Advance)
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000126 break;
127
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000128 if (IsBlank(Text[0]))
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000129 SpaceOffset = SplitPoint;
130 if (Text[0] == '/')
131 SlashOffset = SplitPoint;
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000132 if (Advance == 1 && !isAlphanumeric(Text[0]))
Alexander Kornienko72852072013-06-19 14:22:47 +0000133 WordStartOffset = SplitPoint;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000134
135 SplitPoint += Advance;
136 Text = Text.substr(Advance);
137 }
138
139 if (SpaceOffset != 0)
140 return BreakableToken::Split(SpaceOffset + 1, 0);
141 if (SlashOffset != 0)
142 return BreakableToken::Split(SlashOffset + 1, 0);
Alexander Kornienko72852072013-06-19 14:22:47 +0000143 if (WordStartOffset != 0)
144 return BreakableToken::Split(WordStartOffset + 1, 0);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000145 if (SplitPoint != 0)
146 return BreakableToken::Split(SplitPoint, 0);
147 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000148}
149
Krasimir Georgiev91834222017-01-25 13:58:58 +0000150bool switchesFormatting(const FormatToken &Token) {
151 assert((Token.is(TT_BlockComment) || Token.is(TT_LineComment)) &&
152 "formatting regions are switched by comment tokens");
153 StringRef Content = Token.TokenText.substr(2).ltrim();
154 return Content.startswith("clang-format on") ||
155 Content.startswith("clang-format off");
156}
157
158unsigned
159BreakableToken::getLineLengthAfterCompression(unsigned RemainingTokenColumns,
160 Split Split) const {
161 // Example: consider the content
162 // lala lala
163 // - RemainingTokenColumns is the original number of columns, 10;
164 // - Split is (4, 2), denoting the two spaces between the two words;
165 //
166 // We compute the number of columns when the split is compressed into a single
167 // space, like:
168 // lala lala
169 return RemainingTokenColumns + 1 - Split.second;
170}
171
Manuel Klimek9043c742013-05-27 15:23:34 +0000172unsigned BreakableSingleLineToken::getLineCount() const { return 1; }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000173
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000174unsigned BreakableSingleLineToken::getLineLengthAfterSplit(
Krasimir Georgiev91834222017-01-25 13:58:58 +0000175 unsigned LineIndex, unsigned TailOffset,
176 StringRef::size_type Length) const {
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000177 return StartColumn + Prefix.size() + Postfix.size() +
Krasimir Georgiev91834222017-01-25 13:58:58 +0000178 encoding::columnWidthWithTabs(Line.substr(TailOffset, Length),
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000179 StartColumn + Prefix.size(),
180 Style.TabWidth, Encoding);
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000181}
182
Alexander Kornienkobe633902013-06-14 11:46:10 +0000183BreakableSingleLineToken::BreakableSingleLineToken(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000184 const FormatToken &Tok, unsigned StartColumn, StringRef Prefix,
185 StringRef Postfix, bool InPPDirective, encoding::Encoding Encoding,
186 const FormatStyle &Style)
187 : BreakableToken(Tok, InPPDirective, Encoding, Style),
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000188 StartColumn(StartColumn), Prefix(Prefix), Postfix(Postfix) {
Alexander Kornienkod4fa2e62017-04-11 09:55:00 +0000189 assert(Tok.TokenText.startswith(Prefix) && Tok.TokenText.endswith(Postfix));
Manuel Klimek9043c742013-05-27 15:23:34 +0000190 Line = Tok.TokenText.substr(
191 Prefix.size(), Tok.TokenText.size() - Prefix.size() - Postfix.size());
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000192}
193
Alexander Kornienko81e32942013-09-16 20:20:49 +0000194BreakableStringLiteral::BreakableStringLiteral(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000195 const FormatToken &Tok, unsigned StartColumn, StringRef Prefix,
196 StringRef Postfix, bool InPPDirective, encoding::Encoding Encoding,
197 const FormatStyle &Style)
198 : BreakableSingleLineToken(Tok, StartColumn, Prefix, Postfix, InPPDirective,
199 Encoding, Style) {}
Manuel Klimek9043c742013-05-27 15:23:34 +0000200
201BreakableToken::Split
202BreakableStringLiteral::getSplit(unsigned LineIndex, unsigned TailOffset,
Krasimir Georgiev17725d82017-03-08 08:55:12 +0000203 unsigned ColumnLimit,
204 llvm::Regex &CommentPragmasRegex) const {
Alexander Kornienko81e32942013-09-16 20:20:49 +0000205 return getStringSplit(Line.substr(TailOffset),
206 StartColumn + Prefix.size() + Postfix.size(),
207 ColumnLimit, Style.TabWidth, Encoding);
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000208}
209
Alexander Kornienko555efc32013-06-11 16:01:49 +0000210void BreakableStringLiteral::insertBreak(unsigned LineIndex,
211 unsigned TailOffset, Split Split,
Alexander Kornienko555efc32013-06-11 16:01:49 +0000212 WhitespaceManager &Whitespaces) {
213 Whitespaces.replaceWhitespaceInToken(
214 Tok, Prefix.size() + TailOffset + Split.first, Split.second, Postfix,
Alexander Kornienkod4fa2e62017-04-11 09:55:00 +0000215 Prefix, InPPDirective, 1, StartColumn);
Alexander Kornienko555efc32013-06-11 16:01:49 +0000216}
217
Krasimir Georgiev91834222017-01-25 13:58:58 +0000218BreakableComment::BreakableComment(const FormatToken &Token,
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000219 unsigned StartColumn,
Krasimir Georgiev4b159222017-02-21 10:54:50 +0000220 bool InPPDirective,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000221 encoding::Encoding Encoding,
222 const FormatStyle &Style)
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000223 : BreakableToken(Token, InPPDirective, Encoding, Style),
Krasimir Georgiev4b159222017-02-21 10:54:50 +0000224 StartColumn(StartColumn) {}
Manuel Klimek9043c742013-05-27 15:23:34 +0000225
Krasimir Georgiev91834222017-01-25 13:58:58 +0000226unsigned BreakableComment::getLineCount() const { return Lines.size(); }
227
Krasimir Georgiev17725d82017-03-08 08:55:12 +0000228BreakableToken::Split
229BreakableComment::getSplit(unsigned LineIndex, unsigned TailOffset,
230 unsigned ColumnLimit,
231 llvm::Regex &CommentPragmasRegex) const {
232 // Don't break lines matching the comment pragmas regex.
233 if (CommentPragmasRegex.match(Content[LineIndex]))
234 return Split(StringRef::npos, 0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000235 return getCommentSplit(Content[LineIndex].substr(TailOffset),
236 getContentStartColumn(LineIndex, TailOffset),
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000237 ColumnLimit, Style.TabWidth, Encoding);
Manuel Klimek9043c742013-05-27 15:23:34 +0000238}
239
Krasimir Georgiev91834222017-01-25 13:58:58 +0000240void BreakableComment::compressWhitespace(unsigned LineIndex,
241 unsigned TailOffset, Split Split,
242 WhitespaceManager &Whitespaces) {
243 StringRef Text = Content[LineIndex].substr(TailOffset);
244 // Text is relative to the content line, but Whitespaces operates relative to
245 // the start of the corresponding token, so compute the start of the Split
246 // that needs to be compressed into a single space relative to the start of
247 // its token.
248 unsigned BreakOffsetInToken =
249 Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
250 unsigned CharsToRemove = Split.second;
Alexander Kornienko555efc32013-06-11 16:01:49 +0000251 Whitespaces.replaceWhitespaceInToken(
Krasimir Georgiev91834222017-01-25 13:58:58 +0000252 tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", "",
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000253 /*InPPDirective=*/false, /*Newlines=*/0, /*Spaces=*/1);
Alexander Kornienko875395f2013-11-12 17:50:13 +0000254}
255
Krasimir Georgiev91834222017-01-25 13:58:58 +0000256BreakableToken::Split
257BreakableComment::getReflowSplit(StringRef Text, StringRef ReflowPrefix,
258 unsigned PreviousEndColumn,
259 unsigned ColumnLimit) const {
260 unsigned ReflowStartColumn = PreviousEndColumn + ReflowPrefix.size();
261 StringRef TrimmedText = Text.rtrim(Blanks);
262 // This is the width of the resulting line in case the full line of Text gets
263 // reflown up starting at ReflowStartColumn.
264 unsigned FullWidth = ReflowStartColumn + encoding::columnWidthWithTabs(
265 TrimmedText, ReflowStartColumn,
266 Style.TabWidth, Encoding);
267 // If the full line fits up, we return a reflow split after it,
268 // otherwise we compute the largest piece of text that fits after
269 // ReflowStartColumn.
270 Split ReflowSplit =
271 FullWidth <= ColumnLimit
272 ? Split(TrimmedText.size(), Text.size() - TrimmedText.size())
273 : getCommentSplit(Text, ReflowStartColumn, ColumnLimit,
274 Style.TabWidth, Encoding);
Alexander Kornienko555efc32013-06-11 16:01:49 +0000275
Krasimir Georgiev91834222017-01-25 13:58:58 +0000276 // We need to be extra careful here, because while it's OK to keep a long line
277 // if it can't be broken into smaller pieces (like when the first word of a
278 // long line is longer than the column limit), it's not OK to reflow that long
279 // word up. So we recompute the size of the previous line after reflowing and
280 // only return the reflow split if that's under the line limit.
281 if (ReflowSplit.first != StringRef::npos &&
282 // Check if the width of the newly reflown line is under the limit.
283 PreviousEndColumn + ReflowPrefix.size() +
284 encoding::columnWidthWithTabs(Text.substr(0, ReflowSplit.first),
285 PreviousEndColumn +
286 ReflowPrefix.size(),
287 Style.TabWidth, Encoding) <=
288 ColumnLimit) {
289 return ReflowSplit;
Alexander Kornienko555efc32013-06-11 16:01:49 +0000290 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000291 return Split(StringRef::npos, 0);
292}
293
294const FormatToken &BreakableComment::tokenAt(unsigned LineIndex) const {
295 return Tokens[LineIndex] ? *Tokens[LineIndex] : Tok;
296}
297
298static bool mayReflowContent(StringRef Content) {
299 Content = Content.trim(Blanks);
Krasimir Georgiev28912c02017-02-02 10:52:08 +0000300 // Lines starting with '@' commonly have special meaning.
301 static const SmallVector<StringRef, 4> kSpecialMeaningPrefixes = {
302 "@", "TODO", "FIXME", "XXX"};
303 bool hasSpecialMeaningPrefix = false;
304 for (StringRef Prefix : kSpecialMeaningPrefixes) {
305 if (Content.startswith(Prefix)) {
306 hasSpecialMeaningPrefix = true;
307 break;
308 }
309 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000310 // Simple heuristic for what to reflow: content should contain at least two
311 // characters and either the first or second character must be
312 // non-punctuation.
Krasimir Georgiev28912c02017-02-02 10:52:08 +0000313 return Content.size() >= 2 && !hasSpecialMeaningPrefix &&
314 !Content.endswith("\\") &&
Krasimir Georgiev91834222017-01-25 13:58:58 +0000315 // Note that this is UTF-8 safe, since if isPunctuation(Content[0]) is
316 // true, then the first code point must be 1 byte long.
317 (!isPunctuation(Content[0]) || !isPunctuation(Content[1]));
318}
319
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000320BreakableBlockComment::BreakableBlockComment(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000321 const FormatToken &Token, unsigned StartColumn,
Alexander Kornienkobe633902013-06-14 11:46:10 +0000322 unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective,
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000323 encoding::Encoding Encoding, const FormatStyle &Style)
Krasimir Georgiev4b159222017-02-21 10:54:50 +0000324 : BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000325 assert(Tok.is(TT_BlockComment) &&
326 "block comment section must start with a block comment");
327
328 StringRef TokenText(Tok.TokenText);
Manuel Klimek9043c742013-05-27 15:23:34 +0000329 assert(TokenText.startswith("/*") && TokenText.endswith("*/"));
330 TokenText.substr(2, TokenText.size() - 4).split(Lines, "\n");
331
332 int IndentDelta = StartColumn - OriginalStartColumn;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000333 Content.resize(Lines.size());
334 Content[0] = Lines[0];
335 ContentColumn.resize(Lines.size());
336 // Account for the initial '/*'.
337 ContentColumn[0] = StartColumn + 2;
338 Tokens.resize(Lines.size());
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000339 for (size_t i = 1; i < Lines.size(); ++i)
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000340 adjustWhitespace(i, IndentDelta);
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000341
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000342 // Align decorations with the column of the star on the first line,
343 // that is one column after the start "/*".
344 DecorationColumn = StartColumn + 1;
345
346 // Account for comment decoration patterns like this:
347 //
348 // /*
349 // ** blah blah blah
350 // */
351 if (Lines.size() >= 2 && Content[1].startswith("**") &&
352 static_cast<unsigned>(ContentColumn[1]) == StartColumn) {
353 DecorationColumn = StartColumn;
354 }
355
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000356 Decoration = "* ";
Manuel Klimek9043c742013-05-27 15:23:34 +0000357 if (Lines.size() == 1 && !FirstInLine) {
358 // Comments for which FirstInLine is false can start on arbitrary column,
359 // and available horizontal space can be too small to align consecutive
360 // lines with the first one.
361 // FIXME: We could, probably, align them to current indentation level, but
362 // now we just wrap them without stars.
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000363 Decoration = "";
Manuel Klimek9043c742013-05-27 15:23:34 +0000364 }
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000365 for (size_t i = 1, e = Lines.size(); i < e && !Decoration.empty(); ++i) {
366 // If the last line is empty, the closing "*/" will have a star.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000367 if (i + 1 == e && Content[i].empty())
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000368 break;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000369 if (!Content[i].empty() && i + 1 != e &&
370 Decoration.startswith(Content[i]))
Daniel Jasper6d9b88d2015-05-06 07:17:22 +0000371 continue;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000372 while (!Content[i].startswith(Decoration))
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000373 Decoration = Decoration.substr(0, Decoration.size() - 1);
Manuel Klimek9043c742013-05-27 15:23:34 +0000374 }
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000375
376 LastLineNeedsDecoration = true;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000377 IndentAtLineBreak = ContentColumn[0] + 1;
378 for (size_t i = 1, e = Lines.size(); i < e; ++i) {
379 if (Content[i].empty()) {
380 if (i + 1 == e) {
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000381 // Empty last line means that we already have a star as a part of the
382 // trailing */. We also need to preserve whitespace, so that */ is
383 // correctly indented.
384 LastLineNeedsDecoration = false;
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000385 // Align the star in the last '*/' with the stars on the previous lines.
386 if (e >= 2 && !Decoration.empty()) {
387 ContentColumn[i] = DecorationColumn;
388 }
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000389 } else if (Decoration.empty()) {
390 // For all other lines, set the start column to 0 if they're empty, so
391 // we do not insert trailing whitespace anywhere.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000392 ContentColumn[i] = 0;
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000393 }
Manuel Klimek9043c742013-05-27 15:23:34 +0000394 continue;
395 }
Daniel Jasper6d9b88d2015-05-06 07:17:22 +0000396
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000397 // The first line already excludes the star.
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000398 // The last line excludes the star if LastLineNeedsDecoration is false.
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000399 // For all other lines, adjust the line to exclude the star and
400 // (optionally) the first whitespace.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000401 unsigned DecorationSize = Decoration.startswith(Content[i])
402 ? Content[i].size()
403 : Decoration.size();
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000404 if (DecorationSize) {
405 ContentColumn[i] = DecorationColumn + DecorationSize;
406 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000407 Content[i] = Content[i].substr(DecorationSize);
408 if (!Decoration.startswith(Content[i]))
Daniel Jasper6d9b88d2015-05-06 07:17:22 +0000409 IndentAtLineBreak =
Krasimir Georgiev91834222017-01-25 13:58:58 +0000410 std::min<int>(IndentAtLineBreak, std::max(0, ContentColumn[i]));
Manuel Klimek9043c742013-05-27 15:23:34 +0000411 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000412 IndentAtLineBreak =
413 std::max<unsigned>(IndentAtLineBreak, Decoration.size());
414
Manuel Klimek9043c742013-05-27 15:23:34 +0000415 DEBUG({
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000416 llvm::dbgs() << "IndentAtLineBreak " << IndentAtLineBreak << "\n";
Manuel Klimek9043c742013-05-27 15:23:34 +0000417 for (size_t i = 0; i < Lines.size(); ++i) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000418 llvm::dbgs() << i << " |" << Content[i] << "| "
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000419 << "CC=" << ContentColumn[i] << "| "
420 << "IN=" << (Content[i].data() - Lines[i].data()) << "\n";
Manuel Klimek9043c742013-05-27 15:23:34 +0000421 }
422 });
423}
424
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000425void BreakableBlockComment::adjustWhitespace(unsigned LineIndex,
Manuel Klimek9043c742013-05-27 15:23:34 +0000426 int IndentDelta) {
Alexander Kornienkobe633902013-06-14 11:46:10 +0000427 // When in a preprocessor directive, the trailing backslash in a block comment
428 // is not needed, but can serve a purpose of uniformity with necessary escaped
429 // newlines outside the comment. In this case we remove it here before
430 // trimming the trailing whitespace. The backslash will be re-added later when
431 // inserting a line break.
432 size_t EndOfPreviousLine = Lines[LineIndex - 1].size();
433 if (InPPDirective && Lines[LineIndex - 1].endswith("\\"))
434 --EndOfPreviousLine;
435
Manuel Klimek9043c742013-05-27 15:23:34 +0000436 // Calculate the end of the non-whitespace text in the previous line.
Alexander Kornienkobe633902013-06-14 11:46:10 +0000437 EndOfPreviousLine =
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000438 Lines[LineIndex - 1].find_last_not_of(Blanks, EndOfPreviousLine);
Manuel Klimek9043c742013-05-27 15:23:34 +0000439 if (EndOfPreviousLine == StringRef::npos)
440 EndOfPreviousLine = 0;
441 else
442 ++EndOfPreviousLine;
443 // Calculate the start of the non-whitespace text in the current line.
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000444 size_t StartOfLine = Lines[LineIndex].find_first_not_of(Blanks);
Manuel Klimek9043c742013-05-27 15:23:34 +0000445 if (StartOfLine == StringRef::npos)
Daniel Jasperd6e61882015-06-17 12:23:15 +0000446 StartOfLine = Lines[LineIndex].rtrim("\r\n").size();
Manuel Klimek9043c742013-05-27 15:23:34 +0000447
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000448 StringRef Whitespace = Lines[LineIndex].substr(0, StartOfLine);
Manuel Klimek9043c742013-05-27 15:23:34 +0000449 // Adjust Lines to only contain relevant text.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000450 size_t PreviousContentOffset =
451 Content[LineIndex - 1].data() - Lines[LineIndex - 1].data();
452 Content[LineIndex - 1] = Lines[LineIndex - 1].substr(
453 PreviousContentOffset, EndOfPreviousLine - PreviousContentOffset);
454 Content[LineIndex] = Lines[LineIndex].substr(StartOfLine);
Manuel Klimek34d15152013-05-28 10:01:59 +0000455
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000456 // Adjust the start column uniformly across all lines.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000457 ContentColumn[LineIndex] =
Alexander Kornienko39856b72013-09-10 09:38:25 +0000458 encoding::columnWidthWithTabs(Whitespace, 0, Style.TabWidth, Encoding) +
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000459 IndentDelta;
Manuel Klimek9043c742013-05-27 15:23:34 +0000460}
461
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000462unsigned BreakableBlockComment::getLineLengthAfterSplit(
Krasimir Georgiev91834222017-01-25 13:58:58 +0000463 unsigned LineIndex, unsigned TailOffset,
464 StringRef::size_type Length) const {
465 unsigned ContentStartColumn = getContentStartColumn(LineIndex, TailOffset);
466 unsigned LineLength =
467 ContentStartColumn + encoding::columnWidthWithTabs(
468 Content[LineIndex].substr(TailOffset, Length),
469 ContentStartColumn, Style.TabWidth, Encoding);
470 // The last line gets a "*/" postfix.
471 if (LineIndex + 1 == Lines.size()) {
472 LineLength += 2;
473 // We never need a decoration when breaking just the trailing "*/" postfix.
474 // Note that checking that Length == 0 is not enough, since Length could
475 // also be StringRef::npos.
476 if (Content[LineIndex].substr(TailOffset, Length).empty()) {
477 LineLength -= Decoration.size();
478 }
479 }
480 return LineLength;
Manuel Klimek9043c742013-05-27 15:23:34 +0000481}
482
483void BreakableBlockComment::insertBreak(unsigned LineIndex, unsigned TailOffset,
Alexander Kornienkobe633902013-06-14 11:46:10 +0000484 Split Split,
Manuel Klimek9043c742013-05-27 15:23:34 +0000485 WhitespaceManager &Whitespaces) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000486 StringRef Text = Content[LineIndex].substr(TailOffset);
Manuel Klimek9043c742013-05-27 15:23:34 +0000487 StringRef Prefix = Decoration;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000488 // We need this to account for the case when we have a decoration "* " for all
489 // the lines except for the last one, where the star in "*/" acts as a
490 // decoration.
491 unsigned LocalIndentAtLineBreak = IndentAtLineBreak;
Manuel Klimek9043c742013-05-27 15:23:34 +0000492 if (LineIndex + 1 == Lines.size() &&
493 Text.size() == Split.first + Split.second) {
494 // For the last line we need to break before "*/", but not to add "* ".
495 Prefix = "";
Krasimir Georgiev91834222017-01-25 13:58:58 +0000496 if (LocalIndentAtLineBreak >= 2)
497 LocalIndentAtLineBreak -= 2;
498 }
499 // The split offset is from the beginning of the line. Convert it to an offset
500 // from the beginning of the token text.
501 unsigned BreakOffsetInToken =
502 Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
503 unsigned CharsToRemove = Split.second;
504 assert(LocalIndentAtLineBreak >= Prefix.size());
505 Whitespaces.replaceWhitespaceInToken(
506 tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", Prefix,
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000507 InPPDirective, /*Newlines=*/1,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000508 /*Spaces=*/LocalIndentAtLineBreak - Prefix.size());
509}
510
511BreakableToken::Split BreakableBlockComment::getSplitBefore(
512 unsigned LineIndex,
513 unsigned PreviousEndColumn,
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000514 unsigned ColumnLimit,
515 llvm::Regex &CommentPragmasRegex) const {
516 if (!mayReflow(LineIndex, CommentPragmasRegex))
Krasimir Georgiev91834222017-01-25 13:58:58 +0000517 return Split(StringRef::npos, 0);
518 StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
519 return getReflowSplit(TrimmedContent, ReflowPrefix, PreviousEndColumn,
520 ColumnLimit);
521}
522
523unsigned BreakableBlockComment::getReflownColumn(
524 StringRef Content,
525 unsigned LineIndex,
526 unsigned PreviousEndColumn) const {
527 unsigned StartColumn = PreviousEndColumn + ReflowPrefix.size();
528 // If this is the last line, it will carry around its '*/' postfix.
529 unsigned PostfixLength = (LineIndex + 1 == Lines.size() ? 2 : 0);
530 // The line is composed of previous text, reflow prefix, reflown text and
531 // postfix.
532 unsigned ReflownColumn =
533 StartColumn + encoding::columnWidthWithTabs(Content, StartColumn,
534 Style.TabWidth, Encoding) +
535 PostfixLength;
536 return ReflownColumn;
537}
538
539unsigned BreakableBlockComment::getLineLengthAfterSplitBefore(
540 unsigned LineIndex, unsigned TailOffset,
541 unsigned PreviousEndColumn,
542 unsigned ColumnLimit,
543 Split SplitBefore) const {
Krasimir Georgievaf1b9622017-01-31 14:31:44 +0000544 if (SplitBefore.first == StringRef::npos ||
545 // Block comment line contents contain the trailing whitespace after the
546 // decoration, so the need of left trim. Note that this behavior is
547 // consistent with the breaking of block comments where the indentation of
548 // a broken line is uniform across all the lines of the block comment.
549 SplitBefore.first + SplitBefore.second <
550 Content[LineIndex].ltrim().size()) {
551 // A piece of line, not the whole, gets reflown.
552 return getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000553 } else {
554 // The whole line gets reflown, need to check if we need to insert a break
555 // for the postfix or not.
556 StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
557 unsigned ReflownColumn =
558 getReflownColumn(TrimmedContent, LineIndex, PreviousEndColumn);
559 if (ReflownColumn <= ColumnLimit) {
560 return ReflownColumn;
561 }
562 return getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
563 }
564}
565void BreakableBlockComment::replaceWhitespaceBefore(
566 unsigned LineIndex, unsigned PreviousEndColumn, unsigned ColumnLimit,
567 Split SplitBefore, WhitespaceManager &Whitespaces) {
568 if (LineIndex == 0) return;
569 StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
570 if (SplitBefore.first != StringRef::npos) {
571 // Here we need to reflow.
572 assert(Tokens[LineIndex - 1] == Tokens[LineIndex] &&
573 "Reflowing whitespace within a token");
574 // This is the offset of the end of the last line relative to the start of
575 // the token text in the token.
576 unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
577 Content[LineIndex - 1].size() -
578 tokenAt(LineIndex).TokenText.data();
579 unsigned WhitespaceLength = TrimmedContent.data() -
580 tokenAt(LineIndex).TokenText.data() -
581 WhitespaceOffsetInToken;
582 Whitespaces.replaceWhitespaceInToken(
583 tokenAt(LineIndex), WhitespaceOffsetInToken,
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000584 /*ReplaceChars=*/WhitespaceLength, /*PreviousPostfix=*/"",
585 /*CurrentPrefix=*/ReflowPrefix, InPPDirective, /*Newlines=*/0,
586 /*Spaces=*/0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000587 // Check if we need to also insert a break at the whitespace range.
588 // For this we first adapt the reflow split relative to the beginning of the
589 // content.
590 // Note that we don't need a penalty for this break, since it doesn't change
591 // the total number of lines.
592 Split BreakSplit = SplitBefore;
593 BreakSplit.first += TrimmedContent.data() - Content[LineIndex].data();
594 unsigned ReflownColumn =
595 getReflownColumn(TrimmedContent, LineIndex, PreviousEndColumn);
596 if (ReflownColumn > ColumnLimit) {
597 insertBreak(LineIndex, 0, BreakSplit, Whitespaces);
598 }
599 return;
Manuel Klimek9043c742013-05-27 15:23:34 +0000600 }
601
Krasimir Georgiev91834222017-01-25 13:58:58 +0000602 // Here no reflow with the previous line will happen.
603 // Fix the decoration of the line at LineIndex.
Manuel Klimek9043c742013-05-27 15:23:34 +0000604 StringRef Prefix = Decoration;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000605 if (Content[LineIndex].empty()) {
Manuel Klimek281dcbe2013-05-28 08:55:01 +0000606 if (LineIndex + 1 == Lines.size()) {
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000607 if (!LastLineNeedsDecoration) {
608 // If the last line was empty, we don't need a prefix, as the */ will
609 // line up with the decoration (if it exists).
610 Prefix = "";
611 }
Manuel Klimek281dcbe2013-05-28 08:55:01 +0000612 } else if (!Decoration.empty()) {
613 // For other empty lines, if we do have a decoration, adapt it to not
614 // contain a trailing whitespace.
615 Prefix = Prefix.substr(0, 1);
616 }
Daniel Jasper51fb2b22013-05-30 06:40:07 +0000617 } else {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000618 if (ContentColumn[LineIndex] == 1) {
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000619 // This line starts immediately after the decorating *.
Daniel Jasper51fb2b22013-05-30 06:40:07 +0000620 Prefix = Prefix.substr(0, 1);
621 }
Manuel Klimek281dcbe2013-05-28 08:55:01 +0000622 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000623 // This is the offset of the end of the last line relative to the start of the
624 // token text in the token.
625 unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
626 Content[LineIndex - 1].size() -
627 tokenAt(LineIndex).TokenText.data();
628 unsigned WhitespaceLength = Content[LineIndex].data() -
629 tokenAt(LineIndex).TokenText.data() -
630 WhitespaceOffsetInToken;
Alexander Kornienko555efc32013-06-11 16:01:49 +0000631 Whitespaces.replaceWhitespaceInToken(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000632 tokenAt(LineIndex), WhitespaceOffsetInToken, WhitespaceLength, "", Prefix,
633 InPPDirective, /*Newlines=*/1, ContentColumn[LineIndex] - Prefix.size());
Manuel Klimek9043c742013-05-27 15:23:34 +0000634}
635
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000636bool BreakableBlockComment::mayReflow(unsigned LineIndex,
637 llvm::Regex &CommentPragmasRegex) const {
638 // Content[LineIndex] may exclude the indent after the '*' decoration. In that
639 // case, we compute the start of the comment pragma manually.
640 StringRef IndentContent = Content[LineIndex];
641 if (Lines[LineIndex].ltrim(Blanks).startswith("*")) {
642 IndentContent = Lines[LineIndex].ltrim(Blanks).substr(1);
643 }
644 return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
645 mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
646 !switchesFormatting(tokenAt(LineIndex));
647}
648
Manuel Klimek9043c742013-05-27 15:23:34 +0000649unsigned
650BreakableBlockComment::getContentStartColumn(unsigned LineIndex,
651 unsigned TailOffset) const {
652 // If we break, we always break at the predefined indent.
653 if (TailOffset != 0)
654 return IndentAtLineBreak;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000655 return std::max(0, ContentColumn[LineIndex]);
656}
657
658BreakableLineCommentSection::BreakableLineCommentSection(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000659 const FormatToken &Token, unsigned StartColumn,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000660 unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective,
661 encoding::Encoding Encoding, const FormatStyle &Style)
Krasimir Georgiev4b159222017-02-21 10:54:50 +0000662 : BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000663 assert(Tok.is(TT_LineComment) &&
664 "line comment section must start with a line comment");
665 FormatToken *LineTok = nullptr;
666 for (const FormatToken *CurrentTok = &Tok;
667 CurrentTok && CurrentTok->is(TT_LineComment);
668 CurrentTok = CurrentTok->Next) {
669 LastLineTok = LineTok;
670 StringRef TokenText(CurrentTok->TokenText);
671 assert(TokenText.startswith("//"));
672 size_t FirstLineIndex = Lines.size();
673 TokenText.split(Lines, "\n");
674 Content.resize(Lines.size());
675 ContentColumn.resize(Lines.size());
676 OriginalContentColumn.resize(Lines.size());
677 Tokens.resize(Lines.size());
678 Prefix.resize(Lines.size());
679 OriginalPrefix.resize(Lines.size());
680 for (size_t i = FirstLineIndex, e = Lines.size(); i < e; ++i) {
Krasimir Georgieve518e0b2017-01-30 21:00:01 +0000681 // We need to trim the blanks in case this is not the first line in a
682 // multiline comment. Then the indent is included in Lines[i].
683 StringRef IndentPrefix =
684 getLineCommentIndentPrefix(Lines[i].ltrim(Blanks));
685 assert(IndentPrefix.startswith("//"));
Krasimir Georgiev91834222017-01-25 13:58:58 +0000686 OriginalPrefix[i] = Prefix[i] = IndentPrefix;
687 if (Lines[i].size() > Prefix[i].size() &&
688 isAlphanumeric(Lines[i][Prefix[i].size()])) {
689 if (Prefix[i] == "//")
690 Prefix[i] = "// ";
691 else if (Prefix[i] == "///")
692 Prefix[i] = "/// ";
693 else if (Prefix[i] == "//!")
694 Prefix[i] = "//! ";
695 }
696
697 Tokens[i] = LineTok;
698 Content[i] = Lines[i].substr(IndentPrefix.size());
699 OriginalContentColumn[i] =
700 StartColumn +
701 encoding::columnWidthWithTabs(OriginalPrefix[i],
702 StartColumn,
703 Style.TabWidth,
704 Encoding);
705 ContentColumn[i] =
706 StartColumn +
707 encoding::columnWidthWithTabs(Prefix[i],
708 StartColumn,
709 Style.TabWidth,
710 Encoding);
711
712 // Calculate the end of the non-whitespace text in this line.
713 size_t EndOfLine = Content[i].find_last_not_of(Blanks);
714 if (EndOfLine == StringRef::npos)
715 EndOfLine = Content[i].size();
716 else
717 ++EndOfLine;
718 Content[i] = Content[i].substr(0, EndOfLine);
719 }
720 LineTok = CurrentTok->Next;
Krasimir Georgievb6ccd382017-02-02 14:36:50 +0000721 if (CurrentTok->Next && !CurrentTok->Next->ContinuesLineCommentSection) {
Krasimir Georgiev753625b2017-01-31 13:32:38 +0000722 // A line comment section needs to broken by a line comment that is
723 // preceded by at least two newlines. Note that we put this break here
724 // instead of breaking at a previous stage during parsing, since that
725 // would split the contents of the enum into two unwrapped lines in this
726 // example, which is undesirable:
727 // enum A {
728 // a, // comment about a
729 //
730 // // comment about b
731 // b
732 // };
733 //
734 // FIXME: Consider putting separate line comment sections as children to
735 // the unwrapped line instead.
736 break;
737 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000738 }
739}
740
741unsigned BreakableLineCommentSection::getLineLengthAfterSplit(
742 unsigned LineIndex, unsigned TailOffset,
743 StringRef::size_type Length) const {
744 unsigned ContentStartColumn =
745 (TailOffset == 0 ? ContentColumn[LineIndex]
746 : OriginalContentColumn[LineIndex]);
747 return ContentStartColumn + encoding::columnWidthWithTabs(
748 Content[LineIndex].substr(TailOffset, Length),
749 ContentStartColumn, Style.TabWidth, Encoding);
750}
751
752void BreakableLineCommentSection::insertBreak(unsigned LineIndex,
753 unsigned TailOffset, Split Split,
754 WhitespaceManager &Whitespaces) {
755 StringRef Text = Content[LineIndex].substr(TailOffset);
756 // Compute the offset of the split relative to the beginning of the token
757 // text.
758 unsigned BreakOffsetInToken =
759 Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
760 unsigned CharsToRemove = Split.second;
761 // Compute the size of the new indent, including the size of the new prefix of
762 // the newly broken line.
763 unsigned IndentAtLineBreak = OriginalContentColumn[LineIndex] +
764 Prefix[LineIndex].size() -
765 OriginalPrefix[LineIndex].size();
766 assert(IndentAtLineBreak >= Prefix[LineIndex].size());
767 Whitespaces.replaceWhitespaceInToken(
768 tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "",
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000769 Prefix[LineIndex], InPPDirective, /*Newlines=*/1,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000770 /*Spaces=*/IndentAtLineBreak - Prefix[LineIndex].size());
771}
772
773BreakableComment::Split BreakableLineCommentSection::getSplitBefore(
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000774 unsigned LineIndex, unsigned PreviousEndColumn, unsigned ColumnLimit,
775 llvm::Regex &CommentPragmasRegex) const {
776 if (!mayReflow(LineIndex, CommentPragmasRegex))
777 return Split(StringRef::npos, 0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000778 return getReflowSplit(Content[LineIndex], ReflowPrefix, PreviousEndColumn,
779 ColumnLimit);
780}
781
782unsigned BreakableLineCommentSection::getLineLengthAfterSplitBefore(
783 unsigned LineIndex, unsigned TailOffset,
784 unsigned PreviousEndColumn,
785 unsigned ColumnLimit,
786 Split SplitBefore) const {
787 if (SplitBefore.first == StringRef::npos ||
788 SplitBefore.first + SplitBefore.second < Content[LineIndex].size()) {
789 // A piece of line, not the whole line, gets reflown.
790 return getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
791 } else {
792 // The whole line gets reflown.
793 unsigned StartColumn = PreviousEndColumn + ReflowPrefix.size();
794 return StartColumn + encoding::columnWidthWithTabs(Content[LineIndex],
795 StartColumn,
796 Style.TabWidth,
797 Encoding);
798 }
799}
800
801void BreakableLineCommentSection::replaceWhitespaceBefore(
802 unsigned LineIndex, unsigned PreviousEndColumn, unsigned ColumnLimit,
803 Split SplitBefore, WhitespaceManager &Whitespaces) {
804 // If this is the first line of a token, we need to inform Whitespace Manager
805 // about it: either adapt the whitespace range preceding it, or mark it as an
806 // untouchable token.
807 // This happens for instance here:
808 // // line 1 \
809 // // line 2
810 if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) {
811 if (SplitBefore.first != StringRef::npos) {
812 // Reflow happens between tokens. Replace the whitespace between the
813 // tokens by the empty string.
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000814 Whitespaces.replaceWhitespace(
815 *Tokens[LineIndex], /*Newlines=*/0, /*Spaces=*/0,
816 /*StartOfTokenColumn=*/StartColumn, /*InPPDirective=*/false);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000817 // Replace the indent and prefix of the token with the reflow prefix.
818 unsigned WhitespaceLength =
819 Content[LineIndex].data() - tokenAt(LineIndex).TokenText.data();
820 Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex],
821 /*Offset=*/0,
822 /*ReplaceChars=*/WhitespaceLength,
823 /*PreviousPostfix=*/"",
824 /*CurrentPrefix=*/ReflowPrefix,
825 /*InPPDirective=*/false,
826 /*Newlines=*/0,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000827 /*Spaces=*/0);
828 } else {
829 // This is the first line for the current token, but no reflow with the
830 // previous token is necessary. However, we still may need to adjust the
Krasimir Georgievb796ceb2017-01-31 15:40:15 +0000831 // start column. Note that ContentColumn[LineIndex] is the expected
832 // content column after a possible update to the prefix, hence the prefix
833 // length change is included.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000834 unsigned LineColumn =
835 ContentColumn[LineIndex] -
Krasimir Georgievb796ceb2017-01-31 15:40:15 +0000836 (Content[LineIndex].data() - Lines[LineIndex].data()) +
837 (OriginalPrefix[LineIndex].size() - Prefix[LineIndex].size());
Krasimir Georgiev13dbaa02017-02-01 10:10:04 +0000838
839 // We always want to create a replacement instead of adding an untouchable
840 // token, even if LineColumn is the same as the original column of the
841 // token. This is because WhitespaceManager doesn't align trailing
842 // comments if they are untouchable.
843 Whitespaces.replaceWhitespace(*Tokens[LineIndex],
844 /*Newlines=*/1,
845 /*Spaces=*/LineColumn,
846 /*StartOfTokenColumn=*/LineColumn,
847 /*InPPDirective=*/false);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000848 }
Krasimir Georgievb796ceb2017-01-31 15:40:15 +0000849 }
850 if (OriginalPrefix[LineIndex] != Prefix[LineIndex]) {
851 // Adjust the prefix if necessary.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000852
853 // Take care of the space possibly introduced after a decoration.
854 assert(Prefix[LineIndex] == (OriginalPrefix[LineIndex] + " ").str() &&
Krasimir Georgievb796ceb2017-01-31 15:40:15 +0000855 "Expecting a line comment prefix to differ from original by at most "
856 "a space");
Krasimir Georgiev91834222017-01-25 13:58:58 +0000857 Whitespaces.replaceWhitespaceInToken(
858 tokenAt(LineIndex), OriginalPrefix[LineIndex].size(), 0, "", "",
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000859 /*InPPDirective=*/false, /*Newlines=*/0, /*Spaces=*/1);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000860 }
861 // Add a break after a reflow split has been introduced, if necessary.
862 // Note that this break doesn't need to be penalized, since it doesn't change
863 // the number of lines.
864 if (SplitBefore.first != StringRef::npos &&
865 SplitBefore.first + SplitBefore.second < Content[LineIndex].size()) {
866 insertBreak(LineIndex, 0, SplitBefore, Whitespaces);
867 }
868}
869
870void BreakableLineCommentSection::updateNextToken(LineState& State) const {
871 if (LastLineTok) {
872 State.NextToken = LastLineTok->Next;
873 }
874}
875
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000876bool BreakableLineCommentSection::mayReflow(
877 unsigned LineIndex, llvm::Regex &CommentPragmasRegex) const {
878 // Line comments have the indent as part of the prefix, so we need to
879 // recompute the start of the line.
880 StringRef IndentContent = Content[LineIndex];
881 if (Lines[LineIndex].startswith("//")) {
882 IndentContent = Lines[LineIndex].substr(2);
883 }
884 return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
885 mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
886 !switchesFormatting(tokenAt(LineIndex)) &&
887 OriginalPrefix[LineIndex] == OriginalPrefix[LineIndex - 1];
888}
889
Krasimir Georgiev91834222017-01-25 13:58:58 +0000890unsigned
891BreakableLineCommentSection::getContentStartColumn(unsigned LineIndex,
892 unsigned TailOffset) const {
893 if (TailOffset != 0) {
894 return OriginalContentColumn[LineIndex];
895 }
896 return ContentColumn[LineIndex];
Manuel Klimek9043c742013-05-27 15:23:34 +0000897}
898
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000899} // namespace format
900} // namespace clang