blob: 42e6a2140af15bd3092b487ffca55b4d0eaa4d83 [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) {
Daniel Jasper174b0122014-01-09 14:18:12 +0000189 assert(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,
203 unsigned ColumnLimit) const {
Alexander Kornienko81e32942013-09-16 20:20:49 +0000204 return getStringSplit(Line.substr(TailOffset),
205 StartColumn + Prefix.size() + Postfix.size(),
206 ColumnLimit, Style.TabWidth, Encoding);
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000207}
208
Alexander Kornienko555efc32013-06-11 16:01:49 +0000209void BreakableStringLiteral::insertBreak(unsigned LineIndex,
210 unsigned TailOffset, Split Split,
Alexander Kornienko555efc32013-06-11 16:01:49 +0000211 WhitespaceManager &Whitespaces) {
Daniel Jasperd07c2ee2014-01-14 09:53:07 +0000212 unsigned LeadingSpaces = StartColumn;
213 // The '@' of an ObjC string literal (@"Test") does not become part of the
214 // string token.
215 // FIXME: It might be a cleaner solution to merge the tokens as a
216 // precomputation step.
217 if (Prefix.startswith("@"))
218 --LeadingSpaces;
Alexander Kornienko555efc32013-06-11 16:01:49 +0000219 Whitespaces.replaceWhitespaceInToken(
220 Tok, Prefix.size() + TailOffset + Split.first, Split.second, Postfix,
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000221 Prefix, InPPDirective, 1, LeadingSpaces);
Alexander Kornienko555efc32013-06-11 16:01:49 +0000222}
223
Krasimir Georgiev91834222017-01-25 13:58:58 +0000224BreakableComment::BreakableComment(const FormatToken &Token,
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000225 unsigned StartColumn,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000226 unsigned OriginalStartColumn,
227 bool FirstInLine, bool InPPDirective,
228 encoding::Encoding Encoding,
229 const FormatStyle &Style)
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000230 : BreakableToken(Token, InPPDirective, Encoding, Style),
Krasimir Georgiev91834222017-01-25 13:58:58 +0000231 StartColumn(StartColumn), OriginalStartColumn(OriginalStartColumn),
232 FirstInLine(FirstInLine) {}
Manuel Klimek9043c742013-05-27 15:23:34 +0000233
Krasimir Georgiev91834222017-01-25 13:58:58 +0000234unsigned BreakableComment::getLineCount() const { return Lines.size(); }
235
236BreakableToken::Split BreakableComment::getSplit(unsigned LineIndex,
237 unsigned TailOffset,
238 unsigned ColumnLimit) const {
239 return getCommentSplit(Content[LineIndex].substr(TailOffset),
240 getContentStartColumn(LineIndex, TailOffset),
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000241 ColumnLimit, Style.TabWidth, Encoding);
Manuel Klimek9043c742013-05-27 15:23:34 +0000242}
243
Krasimir Georgiev91834222017-01-25 13:58:58 +0000244void BreakableComment::compressWhitespace(unsigned LineIndex,
245 unsigned TailOffset, Split Split,
246 WhitespaceManager &Whitespaces) {
247 StringRef Text = Content[LineIndex].substr(TailOffset);
248 // Text is relative to the content line, but Whitespaces operates relative to
249 // the start of the corresponding token, so compute the start of the Split
250 // that needs to be compressed into a single space relative to the start of
251 // its token.
252 unsigned BreakOffsetInToken =
253 Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
254 unsigned CharsToRemove = Split.second;
Alexander Kornienko555efc32013-06-11 16:01:49 +0000255 Whitespaces.replaceWhitespaceInToken(
Krasimir Georgiev91834222017-01-25 13:58:58 +0000256 tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", "",
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000257 /*InPPDirective=*/false, /*Newlines=*/0, /*Spaces=*/1);
Alexander Kornienko875395f2013-11-12 17:50:13 +0000258}
259
Krasimir Georgiev91834222017-01-25 13:58:58 +0000260BreakableToken::Split
261BreakableComment::getReflowSplit(StringRef Text, StringRef ReflowPrefix,
262 unsigned PreviousEndColumn,
263 unsigned ColumnLimit) const {
264 unsigned ReflowStartColumn = PreviousEndColumn + ReflowPrefix.size();
265 StringRef TrimmedText = Text.rtrim(Blanks);
266 // This is the width of the resulting line in case the full line of Text gets
267 // reflown up starting at ReflowStartColumn.
268 unsigned FullWidth = ReflowStartColumn + encoding::columnWidthWithTabs(
269 TrimmedText, ReflowStartColumn,
270 Style.TabWidth, Encoding);
271 // If the full line fits up, we return a reflow split after it,
272 // otherwise we compute the largest piece of text that fits after
273 // ReflowStartColumn.
274 Split ReflowSplit =
275 FullWidth <= ColumnLimit
276 ? Split(TrimmedText.size(), Text.size() - TrimmedText.size())
277 : getCommentSplit(Text, ReflowStartColumn, ColumnLimit,
278 Style.TabWidth, Encoding);
Alexander Kornienko555efc32013-06-11 16:01:49 +0000279
Krasimir Georgiev91834222017-01-25 13:58:58 +0000280 // We need to be extra careful here, because while it's OK to keep a long line
281 // if it can't be broken into smaller pieces (like when the first word of a
282 // long line is longer than the column limit), it's not OK to reflow that long
283 // word up. So we recompute the size of the previous line after reflowing and
284 // only return the reflow split if that's under the line limit.
285 if (ReflowSplit.first != StringRef::npos &&
286 // Check if the width of the newly reflown line is under the limit.
287 PreviousEndColumn + ReflowPrefix.size() +
288 encoding::columnWidthWithTabs(Text.substr(0, ReflowSplit.first),
289 PreviousEndColumn +
290 ReflowPrefix.size(),
291 Style.TabWidth, Encoding) <=
292 ColumnLimit) {
293 return ReflowSplit;
Alexander Kornienko555efc32013-06-11 16:01:49 +0000294 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000295 return Split(StringRef::npos, 0);
296}
297
298const FormatToken &BreakableComment::tokenAt(unsigned LineIndex) const {
299 return Tokens[LineIndex] ? *Tokens[LineIndex] : Tok;
300}
301
302static bool mayReflowContent(StringRef Content) {
303 Content = Content.trim(Blanks);
Krasimir Georgiev28912c02017-02-02 10:52:08 +0000304 // Lines starting with '@' commonly have special meaning.
305 static const SmallVector<StringRef, 4> kSpecialMeaningPrefixes = {
306 "@", "TODO", "FIXME", "XXX"};
307 bool hasSpecialMeaningPrefix = false;
308 for (StringRef Prefix : kSpecialMeaningPrefixes) {
309 if (Content.startswith(Prefix)) {
310 hasSpecialMeaningPrefix = true;
311 break;
312 }
313 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000314 // Simple heuristic for what to reflow: content should contain at least two
315 // characters and either the first or second character must be
316 // non-punctuation.
Krasimir Georgiev28912c02017-02-02 10:52:08 +0000317 return Content.size() >= 2 && !hasSpecialMeaningPrefix &&
318 !Content.endswith("\\") &&
Krasimir Georgiev91834222017-01-25 13:58:58 +0000319 // Note that this is UTF-8 safe, since if isPunctuation(Content[0]) is
320 // true, then the first code point must be 1 byte long.
321 (!isPunctuation(Content[0]) || !isPunctuation(Content[1]));
322}
323
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000324BreakableBlockComment::BreakableBlockComment(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000325 const FormatToken &Token, unsigned StartColumn,
Alexander Kornienkobe633902013-06-14 11:46:10 +0000326 unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective,
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000327 encoding::Encoding Encoding, const FormatStyle &Style)
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000328 : BreakableComment(Token, StartColumn, OriginalStartColumn, FirstInLine,
329 InPPDirective, Encoding, Style) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000330 assert(Tok.is(TT_BlockComment) &&
331 "block comment section must start with a block comment");
332
333 StringRef TokenText(Tok.TokenText);
Manuel Klimek9043c742013-05-27 15:23:34 +0000334 assert(TokenText.startswith("/*") && TokenText.endswith("*/"));
335 TokenText.substr(2, TokenText.size() - 4).split(Lines, "\n");
336
337 int IndentDelta = StartColumn - OriginalStartColumn;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000338 Content.resize(Lines.size());
339 Content[0] = Lines[0];
340 ContentColumn.resize(Lines.size());
341 // Account for the initial '/*'.
342 ContentColumn[0] = StartColumn + 2;
343 Tokens.resize(Lines.size());
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000344 for (size_t i = 1; i < Lines.size(); ++i)
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000345 adjustWhitespace(i, IndentDelta);
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000346
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000347 // Align decorations with the column of the star on the first line,
348 // that is one column after the start "/*".
349 DecorationColumn = StartColumn + 1;
350
351 // Account for comment decoration patterns like this:
352 //
353 // /*
354 // ** blah blah blah
355 // */
356 if (Lines.size() >= 2 && Content[1].startswith("**") &&
357 static_cast<unsigned>(ContentColumn[1]) == StartColumn) {
358 DecorationColumn = StartColumn;
359 }
360
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000361 Decoration = "* ";
Manuel Klimek9043c742013-05-27 15:23:34 +0000362 if (Lines.size() == 1 && !FirstInLine) {
363 // Comments for which FirstInLine is false can start on arbitrary column,
364 // and available horizontal space can be too small to align consecutive
365 // lines with the first one.
366 // FIXME: We could, probably, align them to current indentation level, but
367 // now we just wrap them without stars.
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000368 Decoration = "";
Manuel Klimek9043c742013-05-27 15:23:34 +0000369 }
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000370 for (size_t i = 1, e = Lines.size(); i < e && !Decoration.empty(); ++i) {
371 // If the last line is empty, the closing "*/" will have a star.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000372 if (i + 1 == e && Content[i].empty())
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000373 break;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000374 if (!Content[i].empty() && i + 1 != e &&
375 Decoration.startswith(Content[i]))
Daniel Jasper6d9b88d2015-05-06 07:17:22 +0000376 continue;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000377 while (!Content[i].startswith(Decoration))
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000378 Decoration = Decoration.substr(0, Decoration.size() - 1);
Manuel Klimek9043c742013-05-27 15:23:34 +0000379 }
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000380
381 LastLineNeedsDecoration = true;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000382 IndentAtLineBreak = ContentColumn[0] + 1;
383 for (size_t i = 1, e = Lines.size(); i < e; ++i) {
384 if (Content[i].empty()) {
385 if (i + 1 == e) {
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000386 // Empty last line means that we already have a star as a part of the
387 // trailing */. We also need to preserve whitespace, so that */ is
388 // correctly indented.
389 LastLineNeedsDecoration = false;
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000390 // Align the star in the last '*/' with the stars on the previous lines.
391 if (e >= 2 && !Decoration.empty()) {
392 ContentColumn[i] = DecorationColumn;
393 }
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000394 } else if (Decoration.empty()) {
395 // For all other lines, set the start column to 0 if they're empty, so
396 // we do not insert trailing whitespace anywhere.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000397 ContentColumn[i] = 0;
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000398 }
Manuel Klimek9043c742013-05-27 15:23:34 +0000399 continue;
400 }
Daniel Jasper6d9b88d2015-05-06 07:17:22 +0000401
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000402 // The first line already excludes the star.
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000403 // The last line excludes the star if LastLineNeedsDecoration is false.
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000404 // For all other lines, adjust the line to exclude the star and
405 // (optionally) the first whitespace.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000406 unsigned DecorationSize = Decoration.startswith(Content[i])
407 ? Content[i].size()
408 : Decoration.size();
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000409 if (DecorationSize) {
410 ContentColumn[i] = DecorationColumn + DecorationSize;
411 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000412 Content[i] = Content[i].substr(DecorationSize);
413 if (!Decoration.startswith(Content[i]))
Daniel Jasper6d9b88d2015-05-06 07:17:22 +0000414 IndentAtLineBreak =
Krasimir Georgiev91834222017-01-25 13:58:58 +0000415 std::min<int>(IndentAtLineBreak, std::max(0, ContentColumn[i]));
Manuel Klimek9043c742013-05-27 15:23:34 +0000416 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000417 IndentAtLineBreak =
418 std::max<unsigned>(IndentAtLineBreak, Decoration.size());
419
Manuel Klimek9043c742013-05-27 15:23:34 +0000420 DEBUG({
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000421 llvm::dbgs() << "IndentAtLineBreak " << IndentAtLineBreak << "\n";
Manuel Klimek9043c742013-05-27 15:23:34 +0000422 for (size_t i = 0; i < Lines.size(); ++i) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000423 llvm::dbgs() << i << " |" << Content[i] << "| "
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000424 << "CC=" << ContentColumn[i] << "| "
425 << "IN=" << (Content[i].data() - Lines[i].data()) << "\n";
Manuel Klimek9043c742013-05-27 15:23:34 +0000426 }
427 });
428}
429
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000430void BreakableBlockComment::adjustWhitespace(unsigned LineIndex,
Manuel Klimek9043c742013-05-27 15:23:34 +0000431 int IndentDelta) {
Alexander Kornienkobe633902013-06-14 11:46:10 +0000432 // When in a preprocessor directive, the trailing backslash in a block comment
433 // is not needed, but can serve a purpose of uniformity with necessary escaped
434 // newlines outside the comment. In this case we remove it here before
435 // trimming the trailing whitespace. The backslash will be re-added later when
436 // inserting a line break.
437 size_t EndOfPreviousLine = Lines[LineIndex - 1].size();
438 if (InPPDirective && Lines[LineIndex - 1].endswith("\\"))
439 --EndOfPreviousLine;
440
Manuel Klimek9043c742013-05-27 15:23:34 +0000441 // Calculate the end of the non-whitespace text in the previous line.
Alexander Kornienkobe633902013-06-14 11:46:10 +0000442 EndOfPreviousLine =
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000443 Lines[LineIndex - 1].find_last_not_of(Blanks, EndOfPreviousLine);
Manuel Klimek9043c742013-05-27 15:23:34 +0000444 if (EndOfPreviousLine == StringRef::npos)
445 EndOfPreviousLine = 0;
446 else
447 ++EndOfPreviousLine;
448 // Calculate the start of the non-whitespace text in the current line.
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000449 size_t StartOfLine = Lines[LineIndex].find_first_not_of(Blanks);
Manuel Klimek9043c742013-05-27 15:23:34 +0000450 if (StartOfLine == StringRef::npos)
Daniel Jasperd6e61882015-06-17 12:23:15 +0000451 StartOfLine = Lines[LineIndex].rtrim("\r\n").size();
Manuel Klimek9043c742013-05-27 15:23:34 +0000452
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000453 StringRef Whitespace = Lines[LineIndex].substr(0, StartOfLine);
Manuel Klimek9043c742013-05-27 15:23:34 +0000454 // Adjust Lines to only contain relevant text.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000455 size_t PreviousContentOffset =
456 Content[LineIndex - 1].data() - Lines[LineIndex - 1].data();
457 Content[LineIndex - 1] = Lines[LineIndex - 1].substr(
458 PreviousContentOffset, EndOfPreviousLine - PreviousContentOffset);
459 Content[LineIndex] = Lines[LineIndex].substr(StartOfLine);
Manuel Klimek34d15152013-05-28 10:01:59 +0000460
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000461 // Adjust the start column uniformly across all lines.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000462 ContentColumn[LineIndex] =
Alexander Kornienko39856b72013-09-10 09:38:25 +0000463 encoding::columnWidthWithTabs(Whitespace, 0, Style.TabWidth, Encoding) +
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000464 IndentDelta;
Manuel Klimek9043c742013-05-27 15:23:34 +0000465}
466
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000467unsigned BreakableBlockComment::getLineLengthAfterSplit(
Krasimir Georgiev91834222017-01-25 13:58:58 +0000468 unsigned LineIndex, unsigned TailOffset,
469 StringRef::size_type Length) const {
470 unsigned ContentStartColumn = getContentStartColumn(LineIndex, TailOffset);
471 unsigned LineLength =
472 ContentStartColumn + encoding::columnWidthWithTabs(
473 Content[LineIndex].substr(TailOffset, Length),
474 ContentStartColumn, Style.TabWidth, Encoding);
475 // The last line gets a "*/" postfix.
476 if (LineIndex + 1 == Lines.size()) {
477 LineLength += 2;
478 // We never need a decoration when breaking just the trailing "*/" postfix.
479 // Note that checking that Length == 0 is not enough, since Length could
480 // also be StringRef::npos.
481 if (Content[LineIndex].substr(TailOffset, Length).empty()) {
482 LineLength -= Decoration.size();
483 }
484 }
485 return LineLength;
Manuel Klimek9043c742013-05-27 15:23:34 +0000486}
487
488void BreakableBlockComment::insertBreak(unsigned LineIndex, unsigned TailOffset,
Alexander Kornienkobe633902013-06-14 11:46:10 +0000489 Split Split,
Manuel Klimek9043c742013-05-27 15:23:34 +0000490 WhitespaceManager &Whitespaces) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000491 StringRef Text = Content[LineIndex].substr(TailOffset);
Manuel Klimek9043c742013-05-27 15:23:34 +0000492 StringRef Prefix = Decoration;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000493 // We need this to account for the case when we have a decoration "* " for all
494 // the lines except for the last one, where the star in "*/" acts as a
495 // decoration.
496 unsigned LocalIndentAtLineBreak = IndentAtLineBreak;
Manuel Klimek9043c742013-05-27 15:23:34 +0000497 if (LineIndex + 1 == Lines.size() &&
498 Text.size() == Split.first + Split.second) {
499 // For the last line we need to break before "*/", but not to add "* ".
500 Prefix = "";
Krasimir Georgiev91834222017-01-25 13:58:58 +0000501 if (LocalIndentAtLineBreak >= 2)
502 LocalIndentAtLineBreak -= 2;
503 }
504 // The split offset is from the beginning of the line. Convert it to an offset
505 // from the beginning of the token text.
506 unsigned BreakOffsetInToken =
507 Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
508 unsigned CharsToRemove = Split.second;
509 assert(LocalIndentAtLineBreak >= Prefix.size());
510 Whitespaces.replaceWhitespaceInToken(
511 tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", Prefix,
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000512 InPPDirective, /*Newlines=*/1,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000513 /*Spaces=*/LocalIndentAtLineBreak - Prefix.size());
514}
515
516BreakableToken::Split BreakableBlockComment::getSplitBefore(
517 unsigned LineIndex,
518 unsigned PreviousEndColumn,
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000519 unsigned ColumnLimit,
520 llvm::Regex &CommentPragmasRegex) const {
521 if (!mayReflow(LineIndex, CommentPragmasRegex))
Krasimir Georgiev91834222017-01-25 13:58:58 +0000522 return Split(StringRef::npos, 0);
523 StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
524 return getReflowSplit(TrimmedContent, ReflowPrefix, PreviousEndColumn,
525 ColumnLimit);
526}
527
528unsigned BreakableBlockComment::getReflownColumn(
529 StringRef Content,
530 unsigned LineIndex,
531 unsigned PreviousEndColumn) const {
532 unsigned StartColumn = PreviousEndColumn + ReflowPrefix.size();
533 // If this is the last line, it will carry around its '*/' postfix.
534 unsigned PostfixLength = (LineIndex + 1 == Lines.size() ? 2 : 0);
535 // The line is composed of previous text, reflow prefix, reflown text and
536 // postfix.
537 unsigned ReflownColumn =
538 StartColumn + encoding::columnWidthWithTabs(Content, StartColumn,
539 Style.TabWidth, Encoding) +
540 PostfixLength;
541 return ReflownColumn;
542}
543
544unsigned BreakableBlockComment::getLineLengthAfterSplitBefore(
545 unsigned LineIndex, unsigned TailOffset,
546 unsigned PreviousEndColumn,
547 unsigned ColumnLimit,
548 Split SplitBefore) const {
Krasimir Georgievaf1b9622017-01-31 14:31:44 +0000549 if (SplitBefore.first == StringRef::npos ||
550 // Block comment line contents contain the trailing whitespace after the
551 // decoration, so the need of left trim. Note that this behavior is
552 // consistent with the breaking of block comments where the indentation of
553 // a broken line is uniform across all the lines of the block comment.
554 SplitBefore.first + SplitBefore.second <
555 Content[LineIndex].ltrim().size()) {
556 // A piece of line, not the whole, gets reflown.
557 return getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000558 } else {
559 // The whole line gets reflown, need to check if we need to insert a break
560 // for the postfix or not.
561 StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
562 unsigned ReflownColumn =
563 getReflownColumn(TrimmedContent, LineIndex, PreviousEndColumn);
564 if (ReflownColumn <= ColumnLimit) {
565 return ReflownColumn;
566 }
567 return getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
568 }
569}
570void BreakableBlockComment::replaceWhitespaceBefore(
571 unsigned LineIndex, unsigned PreviousEndColumn, unsigned ColumnLimit,
572 Split SplitBefore, WhitespaceManager &Whitespaces) {
573 if (LineIndex == 0) return;
574 StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
575 if (SplitBefore.first != StringRef::npos) {
576 // Here we need to reflow.
577 assert(Tokens[LineIndex - 1] == Tokens[LineIndex] &&
578 "Reflowing whitespace within a token");
579 // This is the offset of the end of the last line relative to the start of
580 // the token text in the token.
581 unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
582 Content[LineIndex - 1].size() -
583 tokenAt(LineIndex).TokenText.data();
584 unsigned WhitespaceLength = TrimmedContent.data() -
585 tokenAt(LineIndex).TokenText.data() -
586 WhitespaceOffsetInToken;
587 Whitespaces.replaceWhitespaceInToken(
588 tokenAt(LineIndex), WhitespaceOffsetInToken,
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000589 /*ReplaceChars=*/WhitespaceLength, /*PreviousPostfix=*/"",
590 /*CurrentPrefix=*/ReflowPrefix, InPPDirective, /*Newlines=*/0,
591 /*Spaces=*/0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000592 // Check if we need to also insert a break at the whitespace range.
593 // For this we first adapt the reflow split relative to the beginning of the
594 // content.
595 // Note that we don't need a penalty for this break, since it doesn't change
596 // the total number of lines.
597 Split BreakSplit = SplitBefore;
598 BreakSplit.first += TrimmedContent.data() - Content[LineIndex].data();
599 unsigned ReflownColumn =
600 getReflownColumn(TrimmedContent, LineIndex, PreviousEndColumn);
601 if (ReflownColumn > ColumnLimit) {
602 insertBreak(LineIndex, 0, BreakSplit, Whitespaces);
603 }
604 return;
Manuel Klimek9043c742013-05-27 15:23:34 +0000605 }
606
Krasimir Georgiev91834222017-01-25 13:58:58 +0000607 // Here no reflow with the previous line will happen.
608 // Fix the decoration of the line at LineIndex.
Manuel Klimek9043c742013-05-27 15:23:34 +0000609 StringRef Prefix = Decoration;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000610 if (Content[LineIndex].empty()) {
Manuel Klimek281dcbe2013-05-28 08:55:01 +0000611 if (LineIndex + 1 == Lines.size()) {
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000612 if (!LastLineNeedsDecoration) {
613 // If the last line was empty, we don't need a prefix, as the */ will
614 // line up with the decoration (if it exists).
615 Prefix = "";
616 }
Manuel Klimek281dcbe2013-05-28 08:55:01 +0000617 } else if (!Decoration.empty()) {
618 // For other empty lines, if we do have a decoration, adapt it to not
619 // contain a trailing whitespace.
620 Prefix = Prefix.substr(0, 1);
621 }
Daniel Jasper51fb2b22013-05-30 06:40:07 +0000622 } else {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000623 if (ContentColumn[LineIndex] == 1) {
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000624 // This line starts immediately after the decorating *.
Daniel Jasper51fb2b22013-05-30 06:40:07 +0000625 Prefix = Prefix.substr(0, 1);
626 }
Manuel Klimek281dcbe2013-05-28 08:55:01 +0000627 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000628 // This is the offset of the end of the last line relative to the start of the
629 // token text in the token.
630 unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
631 Content[LineIndex - 1].size() -
632 tokenAt(LineIndex).TokenText.data();
633 unsigned WhitespaceLength = Content[LineIndex].data() -
634 tokenAt(LineIndex).TokenText.data() -
635 WhitespaceOffsetInToken;
Alexander Kornienko555efc32013-06-11 16:01:49 +0000636 Whitespaces.replaceWhitespaceInToken(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000637 tokenAt(LineIndex), WhitespaceOffsetInToken, WhitespaceLength, "", Prefix,
638 InPPDirective, /*Newlines=*/1, ContentColumn[LineIndex] - Prefix.size());
Manuel Klimek9043c742013-05-27 15:23:34 +0000639}
640
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000641bool BreakableBlockComment::mayReflow(unsigned LineIndex,
642 llvm::Regex &CommentPragmasRegex) const {
643 // Content[LineIndex] may exclude the indent after the '*' decoration. In that
644 // case, we compute the start of the comment pragma manually.
645 StringRef IndentContent = Content[LineIndex];
646 if (Lines[LineIndex].ltrim(Blanks).startswith("*")) {
647 IndentContent = Lines[LineIndex].ltrim(Blanks).substr(1);
648 }
649 return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
650 mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
651 !switchesFormatting(tokenAt(LineIndex));
652}
653
Manuel Klimek9043c742013-05-27 15:23:34 +0000654unsigned
655BreakableBlockComment::getContentStartColumn(unsigned LineIndex,
656 unsigned TailOffset) const {
657 // If we break, we always break at the predefined indent.
658 if (TailOffset != 0)
659 return IndentAtLineBreak;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000660 return std::max(0, ContentColumn[LineIndex]);
661}
662
663BreakableLineCommentSection::BreakableLineCommentSection(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000664 const FormatToken &Token, unsigned StartColumn,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000665 unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective,
666 encoding::Encoding Encoding, const FormatStyle &Style)
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000667 : BreakableComment(Token, StartColumn, OriginalStartColumn, FirstInLine,
668 InPPDirective, Encoding, Style) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000669 assert(Tok.is(TT_LineComment) &&
670 "line comment section must start with a line comment");
671 FormatToken *LineTok = nullptr;
672 for (const FormatToken *CurrentTok = &Tok;
673 CurrentTok && CurrentTok->is(TT_LineComment);
674 CurrentTok = CurrentTok->Next) {
675 LastLineTok = LineTok;
676 StringRef TokenText(CurrentTok->TokenText);
677 assert(TokenText.startswith("//"));
678 size_t FirstLineIndex = Lines.size();
679 TokenText.split(Lines, "\n");
680 Content.resize(Lines.size());
681 ContentColumn.resize(Lines.size());
682 OriginalContentColumn.resize(Lines.size());
683 Tokens.resize(Lines.size());
684 Prefix.resize(Lines.size());
685 OriginalPrefix.resize(Lines.size());
686 for (size_t i = FirstLineIndex, e = Lines.size(); i < e; ++i) {
Krasimir Georgieve518e0b2017-01-30 21:00:01 +0000687 // We need to trim the blanks in case this is not the first line in a
688 // multiline comment. Then the indent is included in Lines[i].
689 StringRef IndentPrefix =
690 getLineCommentIndentPrefix(Lines[i].ltrim(Blanks));
691 assert(IndentPrefix.startswith("//"));
Krasimir Georgiev91834222017-01-25 13:58:58 +0000692 OriginalPrefix[i] = Prefix[i] = IndentPrefix;
693 if (Lines[i].size() > Prefix[i].size() &&
694 isAlphanumeric(Lines[i][Prefix[i].size()])) {
695 if (Prefix[i] == "//")
696 Prefix[i] = "// ";
697 else if (Prefix[i] == "///")
698 Prefix[i] = "/// ";
699 else if (Prefix[i] == "//!")
700 Prefix[i] = "//! ";
701 }
702
703 Tokens[i] = LineTok;
704 Content[i] = Lines[i].substr(IndentPrefix.size());
705 OriginalContentColumn[i] =
706 StartColumn +
707 encoding::columnWidthWithTabs(OriginalPrefix[i],
708 StartColumn,
709 Style.TabWidth,
710 Encoding);
711 ContentColumn[i] =
712 StartColumn +
713 encoding::columnWidthWithTabs(Prefix[i],
714 StartColumn,
715 Style.TabWidth,
716 Encoding);
717
718 // Calculate the end of the non-whitespace text in this line.
719 size_t EndOfLine = Content[i].find_last_not_of(Blanks);
720 if (EndOfLine == StringRef::npos)
721 EndOfLine = Content[i].size();
722 else
723 ++EndOfLine;
724 Content[i] = Content[i].substr(0, EndOfLine);
725 }
726 LineTok = CurrentTok->Next;
Krasimir Georgievb6ccd382017-02-02 14:36:50 +0000727 if (CurrentTok->Next && !CurrentTok->Next->ContinuesLineCommentSection) {
Krasimir Georgiev753625b2017-01-31 13:32:38 +0000728 // A line comment section needs to broken by a line comment that is
729 // preceded by at least two newlines. Note that we put this break here
730 // instead of breaking at a previous stage during parsing, since that
731 // would split the contents of the enum into two unwrapped lines in this
732 // example, which is undesirable:
733 // enum A {
734 // a, // comment about a
735 //
736 // // comment about b
737 // b
738 // };
739 //
740 // FIXME: Consider putting separate line comment sections as children to
741 // the unwrapped line instead.
742 break;
743 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000744 }
745}
746
747unsigned BreakableLineCommentSection::getLineLengthAfterSplit(
748 unsigned LineIndex, unsigned TailOffset,
749 StringRef::size_type Length) const {
750 unsigned ContentStartColumn =
751 (TailOffset == 0 ? ContentColumn[LineIndex]
752 : OriginalContentColumn[LineIndex]);
753 return ContentStartColumn + encoding::columnWidthWithTabs(
754 Content[LineIndex].substr(TailOffset, Length),
755 ContentStartColumn, Style.TabWidth, Encoding);
756}
757
758void BreakableLineCommentSection::insertBreak(unsigned LineIndex,
759 unsigned TailOffset, Split Split,
760 WhitespaceManager &Whitespaces) {
761 StringRef Text = Content[LineIndex].substr(TailOffset);
762 // Compute the offset of the split relative to the beginning of the token
763 // text.
764 unsigned BreakOffsetInToken =
765 Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
766 unsigned CharsToRemove = Split.second;
767 // Compute the size of the new indent, including the size of the new prefix of
768 // the newly broken line.
769 unsigned IndentAtLineBreak = OriginalContentColumn[LineIndex] +
770 Prefix[LineIndex].size() -
771 OriginalPrefix[LineIndex].size();
772 assert(IndentAtLineBreak >= Prefix[LineIndex].size());
773 Whitespaces.replaceWhitespaceInToken(
774 tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "",
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000775 Prefix[LineIndex], InPPDirective, /*Newlines=*/1,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000776 /*Spaces=*/IndentAtLineBreak - Prefix[LineIndex].size());
777}
778
779BreakableComment::Split BreakableLineCommentSection::getSplitBefore(
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000780 unsigned LineIndex, unsigned PreviousEndColumn, unsigned ColumnLimit,
781 llvm::Regex &CommentPragmasRegex) const {
782 if (!mayReflow(LineIndex, CommentPragmasRegex))
783 return Split(StringRef::npos, 0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000784 return getReflowSplit(Content[LineIndex], ReflowPrefix, PreviousEndColumn,
785 ColumnLimit);
786}
787
788unsigned BreakableLineCommentSection::getLineLengthAfterSplitBefore(
789 unsigned LineIndex, unsigned TailOffset,
790 unsigned PreviousEndColumn,
791 unsigned ColumnLimit,
792 Split SplitBefore) const {
793 if (SplitBefore.first == StringRef::npos ||
794 SplitBefore.first + SplitBefore.second < Content[LineIndex].size()) {
795 // A piece of line, not the whole line, gets reflown.
796 return getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
797 } else {
798 // The whole line gets reflown.
799 unsigned StartColumn = PreviousEndColumn + ReflowPrefix.size();
800 return StartColumn + encoding::columnWidthWithTabs(Content[LineIndex],
801 StartColumn,
802 Style.TabWidth,
803 Encoding);
804 }
805}
806
807void BreakableLineCommentSection::replaceWhitespaceBefore(
808 unsigned LineIndex, unsigned PreviousEndColumn, unsigned ColumnLimit,
809 Split SplitBefore, WhitespaceManager &Whitespaces) {
810 // If this is the first line of a token, we need to inform Whitespace Manager
811 // about it: either adapt the whitespace range preceding it, or mark it as an
812 // untouchable token.
813 // This happens for instance here:
814 // // line 1 \
815 // // line 2
816 if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) {
817 if (SplitBefore.first != StringRef::npos) {
818 // Reflow happens between tokens. Replace the whitespace between the
819 // tokens by the empty string.
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000820 Whitespaces.replaceWhitespace(
821 *Tokens[LineIndex], /*Newlines=*/0, /*Spaces=*/0,
822 /*StartOfTokenColumn=*/StartColumn, /*InPPDirective=*/false);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000823 // Replace the indent and prefix of the token with the reflow prefix.
824 unsigned WhitespaceLength =
825 Content[LineIndex].data() - tokenAt(LineIndex).TokenText.data();
826 Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex],
827 /*Offset=*/0,
828 /*ReplaceChars=*/WhitespaceLength,
829 /*PreviousPostfix=*/"",
830 /*CurrentPrefix=*/ReflowPrefix,
831 /*InPPDirective=*/false,
832 /*Newlines=*/0,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000833 /*Spaces=*/0);
834 } else {
835 // This is the first line for the current token, but no reflow with the
836 // previous token is necessary. However, we still may need to adjust the
Krasimir Georgievb796ceb2017-01-31 15:40:15 +0000837 // start column. Note that ContentColumn[LineIndex] is the expected
838 // content column after a possible update to the prefix, hence the prefix
839 // length change is included.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000840 unsigned LineColumn =
841 ContentColumn[LineIndex] -
Krasimir Georgievb796ceb2017-01-31 15:40:15 +0000842 (Content[LineIndex].data() - Lines[LineIndex].data()) +
843 (OriginalPrefix[LineIndex].size() - Prefix[LineIndex].size());
Krasimir Georgiev13dbaa02017-02-01 10:10:04 +0000844
845 // We always want to create a replacement instead of adding an untouchable
846 // token, even if LineColumn is the same as the original column of the
847 // token. This is because WhitespaceManager doesn't align trailing
848 // comments if they are untouchable.
849 Whitespaces.replaceWhitespace(*Tokens[LineIndex],
850 /*Newlines=*/1,
851 /*Spaces=*/LineColumn,
852 /*StartOfTokenColumn=*/LineColumn,
853 /*InPPDirective=*/false);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000854 }
Krasimir Georgievb796ceb2017-01-31 15:40:15 +0000855 }
856 if (OriginalPrefix[LineIndex] != Prefix[LineIndex]) {
857 // Adjust the prefix if necessary.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000858
859 // Take care of the space possibly introduced after a decoration.
860 assert(Prefix[LineIndex] == (OriginalPrefix[LineIndex] + " ").str() &&
Krasimir Georgievb796ceb2017-01-31 15:40:15 +0000861 "Expecting a line comment prefix to differ from original by at most "
862 "a space");
Krasimir Georgiev91834222017-01-25 13:58:58 +0000863 Whitespaces.replaceWhitespaceInToken(
864 tokenAt(LineIndex), OriginalPrefix[LineIndex].size(), 0, "", "",
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000865 /*InPPDirective=*/false, /*Newlines=*/0, /*Spaces=*/1);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000866 }
867 // Add a break after a reflow split has been introduced, if necessary.
868 // Note that this break doesn't need to be penalized, since it doesn't change
869 // the number of lines.
870 if (SplitBefore.first != StringRef::npos &&
871 SplitBefore.first + SplitBefore.second < Content[LineIndex].size()) {
872 insertBreak(LineIndex, 0, SplitBefore, Whitespaces);
873 }
874}
875
876void BreakableLineCommentSection::updateNextToken(LineState& State) const {
877 if (LastLineTok) {
878 State.NextToken = LastLineTok->Next;
879 }
880}
881
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000882bool BreakableLineCommentSection::mayReflow(
883 unsigned LineIndex, llvm::Regex &CommentPragmasRegex) const {
884 // Line comments have the indent as part of the prefix, so we need to
885 // recompute the start of the line.
886 StringRef IndentContent = Content[LineIndex];
887 if (Lines[LineIndex].startswith("//")) {
888 IndentContent = Lines[LineIndex].substr(2);
889 }
890 return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
891 mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
892 !switchesFormatting(tokenAt(LineIndex)) &&
893 OriginalPrefix[LineIndex] == OriginalPrefix[LineIndex - 1];
894}
895
Krasimir Georgiev91834222017-01-25 13:58:58 +0000896unsigned
897BreakableLineCommentSection::getContentStartColumn(unsigned LineIndex,
898 unsigned TailOffset) const {
899 if (TailOffset != 0) {
900 return OriginalContentColumn[LineIndex];
901 }
902 return ContentColumn[LineIndex];
Manuel Klimek9043c742013-05-27 15:23:34 +0000903}
904
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000905} // namespace format
906} // namespace clang