blob: b42e4aee5057e7e83853d353c837ba55b7578f65 [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,
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) {
Daniel Jasperd07c2ee2014-01-14 09:53:07 +0000213 unsigned LeadingSpaces = StartColumn;
214 // The '@' of an ObjC string literal (@"Test") does not become part of the
215 // string token.
216 // FIXME: It might be a cleaner solution to merge the tokens as a
217 // precomputation step.
218 if (Prefix.startswith("@"))
219 --LeadingSpaces;
Alexander Kornienko555efc32013-06-11 16:01:49 +0000220 Whitespaces.replaceWhitespaceInToken(
221 Tok, Prefix.size() + TailOffset + Split.first, Split.second, Postfix,
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000222 Prefix, InPPDirective, 1, LeadingSpaces);
Alexander Kornienko555efc32013-06-11 16:01:49 +0000223}
224
Krasimir Georgiev91834222017-01-25 13:58:58 +0000225BreakableComment::BreakableComment(const FormatToken &Token,
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000226 unsigned StartColumn,
Krasimir Georgiev4b159222017-02-21 10:54:50 +0000227 bool InPPDirective,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000228 encoding::Encoding Encoding,
229 const FormatStyle &Style)
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000230 : BreakableToken(Token, InPPDirective, Encoding, Style),
Krasimir Georgiev4b159222017-02-21 10:54:50 +0000231 StartColumn(StartColumn) {}
Manuel Klimek9043c742013-05-27 15:23:34 +0000232
Krasimir Georgiev91834222017-01-25 13:58:58 +0000233unsigned BreakableComment::getLineCount() const { return Lines.size(); }
234
Krasimir Georgiev17725d82017-03-08 08:55:12 +0000235BreakableToken::Split
236BreakableComment::getSplit(unsigned LineIndex, unsigned TailOffset,
237 unsigned ColumnLimit,
238 llvm::Regex &CommentPragmasRegex) const {
239 // Don't break lines matching the comment pragmas regex.
240 if (CommentPragmasRegex.match(Content[LineIndex]))
241 return Split(StringRef::npos, 0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000242 return getCommentSplit(Content[LineIndex].substr(TailOffset),
243 getContentStartColumn(LineIndex, TailOffset),
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000244 ColumnLimit, Style.TabWidth, Encoding);
Manuel Klimek9043c742013-05-27 15:23:34 +0000245}
246
Krasimir Georgiev91834222017-01-25 13:58:58 +0000247void BreakableComment::compressWhitespace(unsigned LineIndex,
248 unsigned TailOffset, Split Split,
249 WhitespaceManager &Whitespaces) {
250 StringRef Text = Content[LineIndex].substr(TailOffset);
251 // Text is relative to the content line, but Whitespaces operates relative to
252 // the start of the corresponding token, so compute the start of the Split
253 // that needs to be compressed into a single space relative to the start of
254 // its token.
255 unsigned BreakOffsetInToken =
256 Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
257 unsigned CharsToRemove = Split.second;
Alexander Kornienko555efc32013-06-11 16:01:49 +0000258 Whitespaces.replaceWhitespaceInToken(
Krasimir Georgiev91834222017-01-25 13:58:58 +0000259 tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", "",
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000260 /*InPPDirective=*/false, /*Newlines=*/0, /*Spaces=*/1);
Alexander Kornienko875395f2013-11-12 17:50:13 +0000261}
262
Krasimir Georgiev91834222017-01-25 13:58:58 +0000263BreakableToken::Split
264BreakableComment::getReflowSplit(StringRef Text, StringRef ReflowPrefix,
265 unsigned PreviousEndColumn,
266 unsigned ColumnLimit) const {
267 unsigned ReflowStartColumn = PreviousEndColumn + ReflowPrefix.size();
268 StringRef TrimmedText = Text.rtrim(Blanks);
269 // This is the width of the resulting line in case the full line of Text gets
270 // reflown up starting at ReflowStartColumn.
271 unsigned FullWidth = ReflowStartColumn + encoding::columnWidthWithTabs(
272 TrimmedText, ReflowStartColumn,
273 Style.TabWidth, Encoding);
274 // If the full line fits up, we return a reflow split after it,
275 // otherwise we compute the largest piece of text that fits after
276 // ReflowStartColumn.
277 Split ReflowSplit =
278 FullWidth <= ColumnLimit
279 ? Split(TrimmedText.size(), Text.size() - TrimmedText.size())
280 : getCommentSplit(Text, ReflowStartColumn, ColumnLimit,
281 Style.TabWidth, Encoding);
Alexander Kornienko555efc32013-06-11 16:01:49 +0000282
Krasimir Georgiev91834222017-01-25 13:58:58 +0000283 // We need to be extra careful here, because while it's OK to keep a long line
284 // if it can't be broken into smaller pieces (like when the first word of a
285 // long line is longer than the column limit), it's not OK to reflow that long
286 // word up. So we recompute the size of the previous line after reflowing and
287 // only return the reflow split if that's under the line limit.
288 if (ReflowSplit.first != StringRef::npos &&
289 // Check if the width of the newly reflown line is under the limit.
290 PreviousEndColumn + ReflowPrefix.size() +
291 encoding::columnWidthWithTabs(Text.substr(0, ReflowSplit.first),
292 PreviousEndColumn +
293 ReflowPrefix.size(),
294 Style.TabWidth, Encoding) <=
295 ColumnLimit) {
296 return ReflowSplit;
Alexander Kornienko555efc32013-06-11 16:01:49 +0000297 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000298 return Split(StringRef::npos, 0);
299}
300
301const FormatToken &BreakableComment::tokenAt(unsigned LineIndex) const {
302 return Tokens[LineIndex] ? *Tokens[LineIndex] : Tok;
303}
304
305static bool mayReflowContent(StringRef Content) {
306 Content = Content.trim(Blanks);
Krasimir Georgiev28912c02017-02-02 10:52:08 +0000307 // Lines starting with '@' commonly have special meaning.
308 static const SmallVector<StringRef, 4> kSpecialMeaningPrefixes = {
309 "@", "TODO", "FIXME", "XXX"};
310 bool hasSpecialMeaningPrefix = false;
311 for (StringRef Prefix : kSpecialMeaningPrefixes) {
312 if (Content.startswith(Prefix)) {
313 hasSpecialMeaningPrefix = true;
314 break;
315 }
316 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000317 // Simple heuristic for what to reflow: content should contain at least two
318 // characters and either the first or second character must be
319 // non-punctuation.
Krasimir Georgiev28912c02017-02-02 10:52:08 +0000320 return Content.size() >= 2 && !hasSpecialMeaningPrefix &&
321 !Content.endswith("\\") &&
Krasimir Georgiev91834222017-01-25 13:58:58 +0000322 // Note that this is UTF-8 safe, since if isPunctuation(Content[0]) is
323 // true, then the first code point must be 1 byte long.
324 (!isPunctuation(Content[0]) || !isPunctuation(Content[1]));
325}
326
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000327BreakableBlockComment::BreakableBlockComment(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000328 const FormatToken &Token, unsigned StartColumn,
Alexander Kornienkobe633902013-06-14 11:46:10 +0000329 unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective,
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000330 encoding::Encoding Encoding, const FormatStyle &Style)
Krasimir Georgiev4b159222017-02-21 10:54:50 +0000331 : BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000332 assert(Tok.is(TT_BlockComment) &&
333 "block comment section must start with a block comment");
334
335 StringRef TokenText(Tok.TokenText);
Manuel Klimek9043c742013-05-27 15:23:34 +0000336 assert(TokenText.startswith("/*") && TokenText.endswith("*/"));
337 TokenText.substr(2, TokenText.size() - 4).split(Lines, "\n");
338
339 int IndentDelta = StartColumn - OriginalStartColumn;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000340 Content.resize(Lines.size());
341 Content[0] = Lines[0];
342 ContentColumn.resize(Lines.size());
343 // Account for the initial '/*'.
344 ContentColumn[0] = StartColumn + 2;
345 Tokens.resize(Lines.size());
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000346 for (size_t i = 1; i < Lines.size(); ++i)
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000347 adjustWhitespace(i, IndentDelta);
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000348
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000349 // Align decorations with the column of the star on the first line,
350 // that is one column after the start "/*".
351 DecorationColumn = StartColumn + 1;
352
353 // Account for comment decoration patterns like this:
354 //
355 // /*
356 // ** blah blah blah
357 // */
358 if (Lines.size() >= 2 && Content[1].startswith("**") &&
359 static_cast<unsigned>(ContentColumn[1]) == StartColumn) {
360 DecorationColumn = StartColumn;
361 }
362
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000363 Decoration = "* ";
Manuel Klimek9043c742013-05-27 15:23:34 +0000364 if (Lines.size() == 1 && !FirstInLine) {
365 // Comments for which FirstInLine is false can start on arbitrary column,
366 // and available horizontal space can be too small to align consecutive
367 // lines with the first one.
368 // FIXME: We could, probably, align them to current indentation level, but
369 // now we just wrap them without stars.
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000370 Decoration = "";
Manuel Klimek9043c742013-05-27 15:23:34 +0000371 }
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000372 for (size_t i = 1, e = Lines.size(); i < e && !Decoration.empty(); ++i) {
373 // If the last line is empty, the closing "*/" will have a star.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000374 if (i + 1 == e && Content[i].empty())
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000375 break;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000376 if (!Content[i].empty() && i + 1 != e &&
377 Decoration.startswith(Content[i]))
Daniel Jasper6d9b88d2015-05-06 07:17:22 +0000378 continue;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000379 while (!Content[i].startswith(Decoration))
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000380 Decoration = Decoration.substr(0, Decoration.size() - 1);
Manuel Klimek9043c742013-05-27 15:23:34 +0000381 }
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000382
383 LastLineNeedsDecoration = true;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000384 IndentAtLineBreak = ContentColumn[0] + 1;
385 for (size_t i = 1, e = Lines.size(); i < e; ++i) {
386 if (Content[i].empty()) {
387 if (i + 1 == e) {
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000388 // Empty last line means that we already have a star as a part of the
389 // trailing */. We also need to preserve whitespace, so that */ is
390 // correctly indented.
391 LastLineNeedsDecoration = false;
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000392 // Align the star in the last '*/' with the stars on the previous lines.
393 if (e >= 2 && !Decoration.empty()) {
394 ContentColumn[i] = DecorationColumn;
395 }
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000396 } else if (Decoration.empty()) {
397 // For all other lines, set the start column to 0 if they're empty, so
398 // we do not insert trailing whitespace anywhere.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000399 ContentColumn[i] = 0;
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000400 }
Manuel Klimek9043c742013-05-27 15:23:34 +0000401 continue;
402 }
Daniel Jasper6d9b88d2015-05-06 07:17:22 +0000403
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000404 // The first line already excludes the star.
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000405 // The last line excludes the star if LastLineNeedsDecoration is false.
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000406 // For all other lines, adjust the line to exclude the star and
407 // (optionally) the first whitespace.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000408 unsigned DecorationSize = Decoration.startswith(Content[i])
409 ? Content[i].size()
410 : Decoration.size();
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000411 if (DecorationSize) {
412 ContentColumn[i] = DecorationColumn + DecorationSize;
413 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000414 Content[i] = Content[i].substr(DecorationSize);
415 if (!Decoration.startswith(Content[i]))
Daniel Jasper6d9b88d2015-05-06 07:17:22 +0000416 IndentAtLineBreak =
Krasimir Georgiev91834222017-01-25 13:58:58 +0000417 std::min<int>(IndentAtLineBreak, std::max(0, ContentColumn[i]));
Manuel Klimek9043c742013-05-27 15:23:34 +0000418 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000419 IndentAtLineBreak =
420 std::max<unsigned>(IndentAtLineBreak, Decoration.size());
421
Manuel Klimek9043c742013-05-27 15:23:34 +0000422 DEBUG({
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000423 llvm::dbgs() << "IndentAtLineBreak " << IndentAtLineBreak << "\n";
Manuel Klimek9043c742013-05-27 15:23:34 +0000424 for (size_t i = 0; i < Lines.size(); ++i) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000425 llvm::dbgs() << i << " |" << Content[i] << "| "
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000426 << "CC=" << ContentColumn[i] << "| "
427 << "IN=" << (Content[i].data() - Lines[i].data()) << "\n";
Manuel Klimek9043c742013-05-27 15:23:34 +0000428 }
429 });
430}
431
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000432void BreakableBlockComment::adjustWhitespace(unsigned LineIndex,
Manuel Klimek9043c742013-05-27 15:23:34 +0000433 int IndentDelta) {
Alexander Kornienkobe633902013-06-14 11:46:10 +0000434 // When in a preprocessor directive, the trailing backslash in a block comment
435 // is not needed, but can serve a purpose of uniformity with necessary escaped
436 // newlines outside the comment. In this case we remove it here before
437 // trimming the trailing whitespace. The backslash will be re-added later when
438 // inserting a line break.
439 size_t EndOfPreviousLine = Lines[LineIndex - 1].size();
440 if (InPPDirective && Lines[LineIndex - 1].endswith("\\"))
441 --EndOfPreviousLine;
442
Manuel Klimek9043c742013-05-27 15:23:34 +0000443 // Calculate the end of the non-whitespace text in the previous line.
Alexander Kornienkobe633902013-06-14 11:46:10 +0000444 EndOfPreviousLine =
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000445 Lines[LineIndex - 1].find_last_not_of(Blanks, EndOfPreviousLine);
Manuel Klimek9043c742013-05-27 15:23:34 +0000446 if (EndOfPreviousLine == StringRef::npos)
447 EndOfPreviousLine = 0;
448 else
449 ++EndOfPreviousLine;
450 // Calculate the start of the non-whitespace text in the current line.
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000451 size_t StartOfLine = Lines[LineIndex].find_first_not_of(Blanks);
Manuel Klimek9043c742013-05-27 15:23:34 +0000452 if (StartOfLine == StringRef::npos)
Daniel Jasperd6e61882015-06-17 12:23:15 +0000453 StartOfLine = Lines[LineIndex].rtrim("\r\n").size();
Manuel Klimek9043c742013-05-27 15:23:34 +0000454
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000455 StringRef Whitespace = Lines[LineIndex].substr(0, StartOfLine);
Manuel Klimek9043c742013-05-27 15:23:34 +0000456 // Adjust Lines to only contain relevant text.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000457 size_t PreviousContentOffset =
458 Content[LineIndex - 1].data() - Lines[LineIndex - 1].data();
459 Content[LineIndex - 1] = Lines[LineIndex - 1].substr(
460 PreviousContentOffset, EndOfPreviousLine - PreviousContentOffset);
461 Content[LineIndex] = Lines[LineIndex].substr(StartOfLine);
Manuel Klimek34d15152013-05-28 10:01:59 +0000462
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000463 // Adjust the start column uniformly across all lines.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000464 ContentColumn[LineIndex] =
Alexander Kornienko39856b72013-09-10 09:38:25 +0000465 encoding::columnWidthWithTabs(Whitespace, 0, Style.TabWidth, Encoding) +
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000466 IndentDelta;
Manuel Klimek9043c742013-05-27 15:23:34 +0000467}
468
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000469unsigned BreakableBlockComment::getLineLengthAfterSplit(
Krasimir Georgiev91834222017-01-25 13:58:58 +0000470 unsigned LineIndex, unsigned TailOffset,
471 StringRef::size_type Length) const {
472 unsigned ContentStartColumn = getContentStartColumn(LineIndex, TailOffset);
473 unsigned LineLength =
474 ContentStartColumn + encoding::columnWidthWithTabs(
475 Content[LineIndex].substr(TailOffset, Length),
476 ContentStartColumn, Style.TabWidth, Encoding);
477 // The last line gets a "*/" postfix.
478 if (LineIndex + 1 == Lines.size()) {
479 LineLength += 2;
480 // We never need a decoration when breaking just the trailing "*/" postfix.
481 // Note that checking that Length == 0 is not enough, since Length could
482 // also be StringRef::npos.
483 if (Content[LineIndex].substr(TailOffset, Length).empty()) {
484 LineLength -= Decoration.size();
485 }
486 }
487 return LineLength;
Manuel Klimek9043c742013-05-27 15:23:34 +0000488}
489
490void BreakableBlockComment::insertBreak(unsigned LineIndex, unsigned TailOffset,
Alexander Kornienkobe633902013-06-14 11:46:10 +0000491 Split Split,
Manuel Klimek9043c742013-05-27 15:23:34 +0000492 WhitespaceManager &Whitespaces) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000493 StringRef Text = Content[LineIndex].substr(TailOffset);
Manuel Klimek9043c742013-05-27 15:23:34 +0000494 StringRef Prefix = Decoration;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000495 // We need this to account for the case when we have a decoration "* " for all
496 // the lines except for the last one, where the star in "*/" acts as a
497 // decoration.
498 unsigned LocalIndentAtLineBreak = IndentAtLineBreak;
Manuel Klimek9043c742013-05-27 15:23:34 +0000499 if (LineIndex + 1 == Lines.size() &&
500 Text.size() == Split.first + Split.second) {
501 // For the last line we need to break before "*/", but not to add "* ".
502 Prefix = "";
Krasimir Georgiev91834222017-01-25 13:58:58 +0000503 if (LocalIndentAtLineBreak >= 2)
504 LocalIndentAtLineBreak -= 2;
505 }
506 // The split offset is from the beginning of the line. Convert it to an offset
507 // from the beginning of the token text.
508 unsigned BreakOffsetInToken =
509 Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
510 unsigned CharsToRemove = Split.second;
511 assert(LocalIndentAtLineBreak >= Prefix.size());
512 Whitespaces.replaceWhitespaceInToken(
513 tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", Prefix,
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000514 InPPDirective, /*Newlines=*/1,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000515 /*Spaces=*/LocalIndentAtLineBreak - Prefix.size());
516}
517
518BreakableToken::Split BreakableBlockComment::getSplitBefore(
519 unsigned LineIndex,
520 unsigned PreviousEndColumn,
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000521 unsigned ColumnLimit,
522 llvm::Regex &CommentPragmasRegex) const {
523 if (!mayReflow(LineIndex, CommentPragmasRegex))
Krasimir Georgiev91834222017-01-25 13:58:58 +0000524 return Split(StringRef::npos, 0);
525 StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
526 return getReflowSplit(TrimmedContent, ReflowPrefix, PreviousEndColumn,
527 ColumnLimit);
528}
529
530unsigned BreakableBlockComment::getReflownColumn(
531 StringRef Content,
532 unsigned LineIndex,
533 unsigned PreviousEndColumn) const {
534 unsigned StartColumn = PreviousEndColumn + ReflowPrefix.size();
535 // If this is the last line, it will carry around its '*/' postfix.
536 unsigned PostfixLength = (LineIndex + 1 == Lines.size() ? 2 : 0);
537 // The line is composed of previous text, reflow prefix, reflown text and
538 // postfix.
539 unsigned ReflownColumn =
540 StartColumn + encoding::columnWidthWithTabs(Content, StartColumn,
541 Style.TabWidth, Encoding) +
542 PostfixLength;
543 return ReflownColumn;
544}
545
546unsigned BreakableBlockComment::getLineLengthAfterSplitBefore(
547 unsigned LineIndex, unsigned TailOffset,
548 unsigned PreviousEndColumn,
549 unsigned ColumnLimit,
550 Split SplitBefore) const {
Krasimir Georgievaf1b9622017-01-31 14:31:44 +0000551 if (SplitBefore.first == StringRef::npos ||
552 // Block comment line contents contain the trailing whitespace after the
553 // decoration, so the need of left trim. Note that this behavior is
554 // consistent with the breaking of block comments where the indentation of
555 // a broken line is uniform across all the lines of the block comment.
556 SplitBefore.first + SplitBefore.second <
557 Content[LineIndex].ltrim().size()) {
558 // A piece of line, not the whole, gets reflown.
559 return getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000560 } else {
561 // The whole line gets reflown, need to check if we need to insert a break
562 // for the postfix or not.
563 StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
564 unsigned ReflownColumn =
565 getReflownColumn(TrimmedContent, LineIndex, PreviousEndColumn);
566 if (ReflownColumn <= ColumnLimit) {
567 return ReflownColumn;
568 }
569 return getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
570 }
571}
572void BreakableBlockComment::replaceWhitespaceBefore(
573 unsigned LineIndex, unsigned PreviousEndColumn, unsigned ColumnLimit,
574 Split SplitBefore, WhitespaceManager &Whitespaces) {
575 if (LineIndex == 0) return;
576 StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
577 if (SplitBefore.first != StringRef::npos) {
578 // Here we need to reflow.
579 assert(Tokens[LineIndex - 1] == Tokens[LineIndex] &&
580 "Reflowing whitespace within a token");
581 // This is the offset of the end of the last line relative to the start of
582 // the token text in the token.
583 unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
584 Content[LineIndex - 1].size() -
585 tokenAt(LineIndex).TokenText.data();
586 unsigned WhitespaceLength = TrimmedContent.data() -
587 tokenAt(LineIndex).TokenText.data() -
588 WhitespaceOffsetInToken;
589 Whitespaces.replaceWhitespaceInToken(
590 tokenAt(LineIndex), WhitespaceOffsetInToken,
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000591 /*ReplaceChars=*/WhitespaceLength, /*PreviousPostfix=*/"",
592 /*CurrentPrefix=*/ReflowPrefix, InPPDirective, /*Newlines=*/0,
593 /*Spaces=*/0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000594 // Check if we need to also insert a break at the whitespace range.
595 // For this we first adapt the reflow split relative to the beginning of the
596 // content.
597 // Note that we don't need a penalty for this break, since it doesn't change
598 // the total number of lines.
599 Split BreakSplit = SplitBefore;
600 BreakSplit.first += TrimmedContent.data() - Content[LineIndex].data();
601 unsigned ReflownColumn =
602 getReflownColumn(TrimmedContent, LineIndex, PreviousEndColumn);
603 if (ReflownColumn > ColumnLimit) {
604 insertBreak(LineIndex, 0, BreakSplit, Whitespaces);
605 }
606 return;
Manuel Klimek9043c742013-05-27 15:23:34 +0000607 }
608
Krasimir Georgiev91834222017-01-25 13:58:58 +0000609 // Here no reflow with the previous line will happen.
610 // Fix the decoration of the line at LineIndex.
Manuel Klimek9043c742013-05-27 15:23:34 +0000611 StringRef Prefix = Decoration;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000612 if (Content[LineIndex].empty()) {
Manuel Klimek281dcbe2013-05-28 08:55:01 +0000613 if (LineIndex + 1 == Lines.size()) {
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000614 if (!LastLineNeedsDecoration) {
615 // If the last line was empty, we don't need a prefix, as the */ will
616 // line up with the decoration (if it exists).
617 Prefix = "";
618 }
Manuel Klimek281dcbe2013-05-28 08:55:01 +0000619 } else if (!Decoration.empty()) {
620 // For other empty lines, if we do have a decoration, adapt it to not
621 // contain a trailing whitespace.
622 Prefix = Prefix.substr(0, 1);
623 }
Daniel Jasper51fb2b22013-05-30 06:40:07 +0000624 } else {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000625 if (ContentColumn[LineIndex] == 1) {
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000626 // This line starts immediately after the decorating *.
Daniel Jasper51fb2b22013-05-30 06:40:07 +0000627 Prefix = Prefix.substr(0, 1);
628 }
Manuel Klimek281dcbe2013-05-28 08:55:01 +0000629 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000630 // This is the offset of the end of the last line relative to the start of the
631 // token text in the token.
632 unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
633 Content[LineIndex - 1].size() -
634 tokenAt(LineIndex).TokenText.data();
635 unsigned WhitespaceLength = Content[LineIndex].data() -
636 tokenAt(LineIndex).TokenText.data() -
637 WhitespaceOffsetInToken;
Alexander Kornienko555efc32013-06-11 16:01:49 +0000638 Whitespaces.replaceWhitespaceInToken(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000639 tokenAt(LineIndex), WhitespaceOffsetInToken, WhitespaceLength, "", Prefix,
640 InPPDirective, /*Newlines=*/1, ContentColumn[LineIndex] - Prefix.size());
Manuel Klimek9043c742013-05-27 15:23:34 +0000641}
642
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000643bool BreakableBlockComment::mayReflow(unsigned LineIndex,
644 llvm::Regex &CommentPragmasRegex) const {
645 // Content[LineIndex] may exclude the indent after the '*' decoration. In that
646 // case, we compute the start of the comment pragma manually.
647 StringRef IndentContent = Content[LineIndex];
648 if (Lines[LineIndex].ltrim(Blanks).startswith("*")) {
649 IndentContent = Lines[LineIndex].ltrim(Blanks).substr(1);
650 }
651 return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
652 mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
653 !switchesFormatting(tokenAt(LineIndex));
654}
655
Manuel Klimek9043c742013-05-27 15:23:34 +0000656unsigned
657BreakableBlockComment::getContentStartColumn(unsigned LineIndex,
658 unsigned TailOffset) const {
659 // If we break, we always break at the predefined indent.
660 if (TailOffset != 0)
661 return IndentAtLineBreak;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000662 return std::max(0, ContentColumn[LineIndex]);
663}
664
665BreakableLineCommentSection::BreakableLineCommentSection(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000666 const FormatToken &Token, unsigned StartColumn,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000667 unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective,
668 encoding::Encoding Encoding, const FormatStyle &Style)
Krasimir Georgiev4b159222017-02-21 10:54:50 +0000669 : BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000670 assert(Tok.is(TT_LineComment) &&
671 "line comment section must start with a line comment");
672 FormatToken *LineTok = nullptr;
673 for (const FormatToken *CurrentTok = &Tok;
674 CurrentTok && CurrentTok->is(TT_LineComment);
675 CurrentTok = CurrentTok->Next) {
676 LastLineTok = LineTok;
677 StringRef TokenText(CurrentTok->TokenText);
678 assert(TokenText.startswith("//"));
679 size_t FirstLineIndex = Lines.size();
680 TokenText.split(Lines, "\n");
681 Content.resize(Lines.size());
682 ContentColumn.resize(Lines.size());
683 OriginalContentColumn.resize(Lines.size());
684 Tokens.resize(Lines.size());
685 Prefix.resize(Lines.size());
686 OriginalPrefix.resize(Lines.size());
687 for (size_t i = FirstLineIndex, e = Lines.size(); i < e; ++i) {
Krasimir Georgieve518e0b2017-01-30 21:00:01 +0000688 // We need to trim the blanks in case this is not the first line in a
689 // multiline comment. Then the indent is included in Lines[i].
690 StringRef IndentPrefix =
691 getLineCommentIndentPrefix(Lines[i].ltrim(Blanks));
692 assert(IndentPrefix.startswith("//"));
Krasimir Georgiev91834222017-01-25 13:58:58 +0000693 OriginalPrefix[i] = Prefix[i] = IndentPrefix;
694 if (Lines[i].size() > Prefix[i].size() &&
695 isAlphanumeric(Lines[i][Prefix[i].size()])) {
696 if (Prefix[i] == "//")
697 Prefix[i] = "// ";
698 else if (Prefix[i] == "///")
699 Prefix[i] = "/// ";
700 else if (Prefix[i] == "//!")
701 Prefix[i] = "//! ";
702 }
703
704 Tokens[i] = LineTok;
705 Content[i] = Lines[i].substr(IndentPrefix.size());
706 OriginalContentColumn[i] =
707 StartColumn +
708 encoding::columnWidthWithTabs(OriginalPrefix[i],
709 StartColumn,
710 Style.TabWidth,
711 Encoding);
712 ContentColumn[i] =
713 StartColumn +
714 encoding::columnWidthWithTabs(Prefix[i],
715 StartColumn,
716 Style.TabWidth,
717 Encoding);
718
719 // Calculate the end of the non-whitespace text in this line.
720 size_t EndOfLine = Content[i].find_last_not_of(Blanks);
721 if (EndOfLine == StringRef::npos)
722 EndOfLine = Content[i].size();
723 else
724 ++EndOfLine;
725 Content[i] = Content[i].substr(0, EndOfLine);
726 }
727 LineTok = CurrentTok->Next;
Krasimir Georgievb6ccd382017-02-02 14:36:50 +0000728 if (CurrentTok->Next && !CurrentTok->Next->ContinuesLineCommentSection) {
Krasimir Georgiev753625b2017-01-31 13:32:38 +0000729 // A line comment section needs to broken by a line comment that is
730 // preceded by at least two newlines. Note that we put this break here
731 // instead of breaking at a previous stage during parsing, since that
732 // would split the contents of the enum into two unwrapped lines in this
733 // example, which is undesirable:
734 // enum A {
735 // a, // comment about a
736 //
737 // // comment about b
738 // b
739 // };
740 //
741 // FIXME: Consider putting separate line comment sections as children to
742 // the unwrapped line instead.
743 break;
744 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000745 }
746}
747
748unsigned BreakableLineCommentSection::getLineLengthAfterSplit(
749 unsigned LineIndex, unsigned TailOffset,
750 StringRef::size_type Length) const {
751 unsigned ContentStartColumn =
752 (TailOffset == 0 ? ContentColumn[LineIndex]
753 : OriginalContentColumn[LineIndex]);
754 return ContentStartColumn + encoding::columnWidthWithTabs(
755 Content[LineIndex].substr(TailOffset, Length),
756 ContentStartColumn, Style.TabWidth, Encoding);
757}
758
759void BreakableLineCommentSection::insertBreak(unsigned LineIndex,
760 unsigned TailOffset, Split Split,
761 WhitespaceManager &Whitespaces) {
762 StringRef Text = Content[LineIndex].substr(TailOffset);
763 // Compute the offset of the split relative to the beginning of the token
764 // text.
765 unsigned BreakOffsetInToken =
766 Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
767 unsigned CharsToRemove = Split.second;
768 // Compute the size of the new indent, including the size of the new prefix of
769 // the newly broken line.
770 unsigned IndentAtLineBreak = OriginalContentColumn[LineIndex] +
771 Prefix[LineIndex].size() -
772 OriginalPrefix[LineIndex].size();
773 assert(IndentAtLineBreak >= Prefix[LineIndex].size());
774 Whitespaces.replaceWhitespaceInToken(
775 tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "",
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000776 Prefix[LineIndex], InPPDirective, /*Newlines=*/1,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000777 /*Spaces=*/IndentAtLineBreak - Prefix[LineIndex].size());
778}
779
780BreakableComment::Split BreakableLineCommentSection::getSplitBefore(
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000781 unsigned LineIndex, unsigned PreviousEndColumn, unsigned ColumnLimit,
782 llvm::Regex &CommentPragmasRegex) const {
783 if (!mayReflow(LineIndex, CommentPragmasRegex))
784 return Split(StringRef::npos, 0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000785 return getReflowSplit(Content[LineIndex], ReflowPrefix, PreviousEndColumn,
786 ColumnLimit);
787}
788
789unsigned BreakableLineCommentSection::getLineLengthAfterSplitBefore(
790 unsigned LineIndex, unsigned TailOffset,
791 unsigned PreviousEndColumn,
792 unsigned ColumnLimit,
793 Split SplitBefore) const {
794 if (SplitBefore.first == StringRef::npos ||
795 SplitBefore.first + SplitBefore.second < Content[LineIndex].size()) {
796 // A piece of line, not the whole line, gets reflown.
797 return getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
798 } else {
799 // The whole line gets reflown.
800 unsigned StartColumn = PreviousEndColumn + ReflowPrefix.size();
801 return StartColumn + encoding::columnWidthWithTabs(Content[LineIndex],
802 StartColumn,
803 Style.TabWidth,
804 Encoding);
805 }
806}
807
808void BreakableLineCommentSection::replaceWhitespaceBefore(
809 unsigned LineIndex, unsigned PreviousEndColumn, unsigned ColumnLimit,
810 Split SplitBefore, WhitespaceManager &Whitespaces) {
811 // If this is the first line of a token, we need to inform Whitespace Manager
812 // about it: either adapt the whitespace range preceding it, or mark it as an
813 // untouchable token.
814 // This happens for instance here:
815 // // line 1 \
816 // // line 2
817 if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) {
818 if (SplitBefore.first != StringRef::npos) {
819 // Reflow happens between tokens. Replace the whitespace between the
820 // tokens by the empty string.
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000821 Whitespaces.replaceWhitespace(
822 *Tokens[LineIndex], /*Newlines=*/0, /*Spaces=*/0,
823 /*StartOfTokenColumn=*/StartColumn, /*InPPDirective=*/false);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000824 // Replace the indent and prefix of the token with the reflow prefix.
825 unsigned WhitespaceLength =
826 Content[LineIndex].data() - tokenAt(LineIndex).TokenText.data();
827 Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex],
828 /*Offset=*/0,
829 /*ReplaceChars=*/WhitespaceLength,
830 /*PreviousPostfix=*/"",
831 /*CurrentPrefix=*/ReflowPrefix,
832 /*InPPDirective=*/false,
833 /*Newlines=*/0,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000834 /*Spaces=*/0);
835 } else {
836 // This is the first line for the current token, but no reflow with the
837 // previous token is necessary. However, we still may need to adjust the
Krasimir Georgievb796ceb2017-01-31 15:40:15 +0000838 // start column. Note that ContentColumn[LineIndex] is the expected
839 // content column after a possible update to the prefix, hence the prefix
840 // length change is included.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000841 unsigned LineColumn =
842 ContentColumn[LineIndex] -
Krasimir Georgievb796ceb2017-01-31 15:40:15 +0000843 (Content[LineIndex].data() - Lines[LineIndex].data()) +
844 (OriginalPrefix[LineIndex].size() - Prefix[LineIndex].size());
Krasimir Georgiev13dbaa02017-02-01 10:10:04 +0000845
846 // We always want to create a replacement instead of adding an untouchable
847 // token, even if LineColumn is the same as the original column of the
848 // token. This is because WhitespaceManager doesn't align trailing
849 // comments if they are untouchable.
850 Whitespaces.replaceWhitespace(*Tokens[LineIndex],
851 /*Newlines=*/1,
852 /*Spaces=*/LineColumn,
853 /*StartOfTokenColumn=*/LineColumn,
854 /*InPPDirective=*/false);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000855 }
Krasimir Georgievb796ceb2017-01-31 15:40:15 +0000856 }
857 if (OriginalPrefix[LineIndex] != Prefix[LineIndex]) {
858 // Adjust the prefix if necessary.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000859
860 // Take care of the space possibly introduced after a decoration.
861 assert(Prefix[LineIndex] == (OriginalPrefix[LineIndex] + " ").str() &&
Krasimir Georgievb796ceb2017-01-31 15:40:15 +0000862 "Expecting a line comment prefix to differ from original by at most "
863 "a space");
Krasimir Georgiev91834222017-01-25 13:58:58 +0000864 Whitespaces.replaceWhitespaceInToken(
865 tokenAt(LineIndex), OriginalPrefix[LineIndex].size(), 0, "", "",
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000866 /*InPPDirective=*/false, /*Newlines=*/0, /*Spaces=*/1);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000867 }
868 // Add a break after a reflow split has been introduced, if necessary.
869 // Note that this break doesn't need to be penalized, since it doesn't change
870 // the number of lines.
871 if (SplitBefore.first != StringRef::npos &&
872 SplitBefore.first + SplitBefore.second < Content[LineIndex].size()) {
873 insertBreak(LineIndex, 0, SplitBefore, Whitespaces);
874 }
875}
876
877void BreakableLineCommentSection::updateNextToken(LineState& State) const {
878 if (LastLineTok) {
879 State.NextToken = LastLineTok->Next;
880 }
881}
882
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000883bool BreakableLineCommentSection::mayReflow(
884 unsigned LineIndex, llvm::Regex &CommentPragmasRegex) const {
885 // Line comments have the indent as part of the prefix, so we need to
886 // recompute the start of the line.
887 StringRef IndentContent = Content[LineIndex];
888 if (Lines[LineIndex].startswith("//")) {
889 IndentContent = Lines[LineIndex].substr(2);
890 }
891 return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
892 mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
893 !switchesFormatting(tokenAt(LineIndex)) &&
894 OriginalPrefix[LineIndex] == OriginalPrefix[LineIndex - 1];
895}
896
Krasimir Georgiev91834222017-01-25 13:58:58 +0000897unsigned
898BreakableLineCommentSection::getContentStartColumn(unsigned LineIndex,
899 unsigned TailOffset) const {
900 if (TailOffset != 0) {
901 return OriginalContentColumn[LineIndex];
902 }
903 return ContentColumn[LineIndex];
Manuel Klimek9043c742013-05-27 15:23:34 +0000904}
905
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000906} // namespace format
907} // namespace clang