blob: ad1ec9f8ad2994764f9559ca3a99fff12df6d614 [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 Georgiev410ed242017-11-10 12:50:09 +000043static StringRef getLineCommentIndentPrefix(StringRef Comment,
44 const FormatStyle &Style) {
45 static const char *const KnownCStylePrefixes[] = {"///<", "//!<", "///", "//",
46 "//!"};
47 static const char *const KnownTextProtoPrefixes[] = {"//", "#"};
48 ArrayRef<const char *> KnownPrefixes(KnownCStylePrefixes);
49 if (Style.Language == FormatStyle::LK_TextProto)
50 KnownPrefixes = KnownTextProtoPrefixes;
51
Krasimir Georgiev91834222017-01-25 13:58:58 +000052 StringRef LongestPrefix;
53 for (StringRef KnownPrefix : KnownPrefixes) {
54 if (Comment.startswith(KnownPrefix)) {
55 size_t PrefixLength = KnownPrefix.size();
56 while (PrefixLength < Comment.size() && Comment[PrefixLength] == ' ')
57 ++PrefixLength;
58 if (PrefixLength > LongestPrefix.size())
59 LongestPrefix = Comment.substr(0, PrefixLength);
60 }
61 }
62 return LongestPrefix;
63}
64
Craig Topperbfb5c402013-07-01 03:38:29 +000065static BreakableToken::Split getCommentSplit(StringRef Text,
66 unsigned ContentStartColumn,
67 unsigned ColumnLimit,
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +000068 unsigned TabWidth,
Craig Topperbfb5c402013-07-01 03:38:29 +000069 encoding::Encoding Encoding) {
Alexander Kornienko9e90b622013-04-17 17:34:05 +000070 if (ColumnLimit <= ContentStartColumn + 1)
Manuel Klimek9043c742013-05-27 15:23:34 +000071 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienko9e90b622013-04-17 17:34:05 +000072
73 unsigned MaxSplit = ColumnLimit - ContentStartColumn + 1;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +000074 unsigned MaxSplitBytes = 0;
75
76 for (unsigned NumChars = 0;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +000077 NumChars < MaxSplit && MaxSplitBytes < Text.size();) {
78 unsigned BytesInChar =
Alexander Kornienkoffcc0102013-06-05 14:09:10 +000079 encoding::getCodePointNumBytes(Text[MaxSplitBytes], Encoding);
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +000080 NumChars +=
81 encoding::columnWidthWithTabs(Text.substr(MaxSplitBytes, BytesInChar),
82 ContentStartColumn, TabWidth, Encoding);
83 MaxSplitBytes += BytesInChar;
84 }
Alexander Kornienkoffcc0102013-06-05 14:09:10 +000085
Alexander Kornienkob93062e2013-06-20 13:58:37 +000086 StringRef::size_type SpaceOffset = Text.find_last_of(Blanks, MaxSplitBytes);
Francois Ferranda881be82017-05-22 14:47:17 +000087
88 // Do not split before a number followed by a dot: this would be interpreted
89 // as a numbered list, which would prevent re-flowing in subsequent passes.
90 static llvm::Regex kNumberedListRegexp = llvm::Regex("^[1-9][0-9]?\\.");
91 if (SpaceOffset != StringRef::npos &&
92 kNumberedListRegexp.match(Text.substr(SpaceOffset).ltrim(Blanks)))
93 SpaceOffset = Text.find_last_of(Blanks, SpaceOffset);
94
Alexander Kornienko9e90b622013-04-17 17:34:05 +000095 if (SpaceOffset == StringRef::npos ||
Manuel Klimek9043c742013-05-27 15:23:34 +000096 // Don't break at leading whitespace.
Alexander Kornienkob93062e2013-06-20 13:58:37 +000097 Text.find_last_not_of(Blanks, SpaceOffset) == StringRef::npos) {
Manuel Klimekae1fbfb2013-05-29 22:06:18 +000098 // Make sure that we don't break at leading whitespace that
99 // reaches past MaxSplit.
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000100 StringRef::size_type FirstNonWhitespace = Text.find_first_not_of(Blanks);
Manuel Klimekae1fbfb2013-05-29 22:06:18 +0000101 if (FirstNonWhitespace == StringRef::npos)
102 // If the comment is only whitespace, we cannot split.
103 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000104 SpaceOffset = Text.find_first_of(
105 Blanks, std::max<unsigned>(MaxSplitBytes, FirstNonWhitespace));
Manuel Klimekae1fbfb2013-05-29 22:06:18 +0000106 }
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000107 if (SpaceOffset != StringRef::npos && SpaceOffset != 0) {
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000108 StringRef BeforeCut = Text.substr(0, SpaceOffset).rtrim(Blanks);
109 StringRef AfterCut = Text.substr(SpaceOffset).ltrim(Blanks);
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000110 return BreakableToken::Split(BeforeCut.size(),
111 AfterCut.begin() - BeforeCut.end());
112 }
113 return BreakableToken::Split(StringRef::npos, 0);
114}
115
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000116static BreakableToken::Split
117getStringSplit(StringRef Text, unsigned UsedColumns, unsigned ColumnLimit,
118 unsigned TabWidth, encoding::Encoding Encoding) {
Manuel Klimek9043c742013-05-27 15:23:34 +0000119 // FIXME: Reduce unit test case.
120 if (Text.empty())
121 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienko81e32942013-09-16 20:20:49 +0000122 if (ColumnLimit <= UsedColumns)
Manuel Klimek9043c742013-05-27 15:23:34 +0000123 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienko71d95d62013-11-26 10:38:53 +0000124 unsigned MaxSplit = ColumnLimit - UsedColumns;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000125 StringRef::size_type SpaceOffset = 0;
126 StringRef::size_type SlashOffset = 0;
Alexander Kornienko72852072013-06-19 14:22:47 +0000127 StringRef::size_type WordStartOffset = 0;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000128 StringRef::size_type SplitPoint = 0;
129 for (unsigned Chars = 0;;) {
130 unsigned Advance;
131 if (Text[0] == '\\') {
132 Advance = encoding::getEscapeSequenceLength(Text);
133 Chars += Advance;
134 } else {
135 Advance = encoding::getCodePointNumBytes(Text[0], Encoding);
Alexander Kornienko81e32942013-09-16 20:20:49 +0000136 Chars += encoding::columnWidthWithTabs(
137 Text.substr(0, Advance), UsedColumns + Chars, TabWidth, Encoding);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000138 }
139
Daniel Jaspere4b48c62015-01-21 19:50:35 +0000140 if (Chars > MaxSplit || Text.size() <= Advance)
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000141 break;
142
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000143 if (IsBlank(Text[0]))
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000144 SpaceOffset = SplitPoint;
145 if (Text[0] == '/')
146 SlashOffset = SplitPoint;
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000147 if (Advance == 1 && !isAlphanumeric(Text[0]))
Alexander Kornienko72852072013-06-19 14:22:47 +0000148 WordStartOffset = SplitPoint;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000149
150 SplitPoint += Advance;
151 Text = Text.substr(Advance);
152 }
153
154 if (SpaceOffset != 0)
155 return BreakableToken::Split(SpaceOffset + 1, 0);
156 if (SlashOffset != 0)
157 return BreakableToken::Split(SlashOffset + 1, 0);
Alexander Kornienko72852072013-06-19 14:22:47 +0000158 if (WordStartOffset != 0)
159 return BreakableToken::Split(WordStartOffset + 1, 0);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000160 if (SplitPoint != 0)
161 return BreakableToken::Split(SplitPoint, 0);
162 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000163}
164
Krasimir Georgiev91834222017-01-25 13:58:58 +0000165bool switchesFormatting(const FormatToken &Token) {
166 assert((Token.is(TT_BlockComment) || Token.is(TT_LineComment)) &&
167 "formatting regions are switched by comment tokens");
168 StringRef Content = Token.TokenText.substr(2).ltrim();
169 return Content.startswith("clang-format on") ||
170 Content.startswith("clang-format off");
171}
172
173unsigned
174BreakableToken::getLineLengthAfterCompression(unsigned RemainingTokenColumns,
175 Split Split) const {
176 // Example: consider the content
177 // lala lala
178 // - RemainingTokenColumns is the original number of columns, 10;
179 // - Split is (4, 2), denoting the two spaces between the two words;
180 //
181 // We compute the number of columns when the split is compressed into a single
182 // space, like:
183 // lala lala
184 return RemainingTokenColumns + 1 - Split.second;
185}
186
Manuel Klimek9043c742013-05-27 15:23:34 +0000187unsigned BreakableSingleLineToken::getLineCount() const { return 1; }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000188
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000189unsigned BreakableSingleLineToken::getLineLengthAfterSplit(
Krasimir Georgiev91834222017-01-25 13:58:58 +0000190 unsigned LineIndex, unsigned TailOffset,
191 StringRef::size_type Length) const {
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000192 return StartColumn + Prefix.size() + Postfix.size() +
Krasimir Georgiev91834222017-01-25 13:58:58 +0000193 encoding::columnWidthWithTabs(Line.substr(TailOffset, Length),
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000194 StartColumn + Prefix.size(),
195 Style.TabWidth, Encoding);
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000196}
197
Alexander Kornienkobe633902013-06-14 11:46:10 +0000198BreakableSingleLineToken::BreakableSingleLineToken(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000199 const FormatToken &Tok, unsigned StartColumn, StringRef Prefix,
200 StringRef Postfix, bool InPPDirective, encoding::Encoding Encoding,
201 const FormatStyle &Style)
202 : BreakableToken(Tok, InPPDirective, Encoding, Style),
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000203 StartColumn(StartColumn), Prefix(Prefix), Postfix(Postfix) {
Alexander Kornienkod4fa2e62017-04-11 09:55:00 +0000204 assert(Tok.TokenText.startswith(Prefix) && Tok.TokenText.endswith(Postfix));
Manuel Klimek9043c742013-05-27 15:23:34 +0000205 Line = Tok.TokenText.substr(
206 Prefix.size(), Tok.TokenText.size() - Prefix.size() - Postfix.size());
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000207}
208
Alexander Kornienko81e32942013-09-16 20:20:49 +0000209BreakableStringLiteral::BreakableStringLiteral(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000210 const FormatToken &Tok, unsigned StartColumn, StringRef Prefix,
211 StringRef Postfix, bool InPPDirective, encoding::Encoding Encoding,
212 const FormatStyle &Style)
213 : BreakableSingleLineToken(Tok, StartColumn, Prefix, Postfix, InPPDirective,
214 Encoding, Style) {}
Manuel Klimek9043c742013-05-27 15:23:34 +0000215
216BreakableToken::Split
217BreakableStringLiteral::getSplit(unsigned LineIndex, unsigned TailOffset,
Krasimir Georgiev17725d82017-03-08 08:55:12 +0000218 unsigned ColumnLimit,
219 llvm::Regex &CommentPragmasRegex) const {
Alexander Kornienko81e32942013-09-16 20:20:49 +0000220 return getStringSplit(Line.substr(TailOffset),
221 StartColumn + Prefix.size() + Postfix.size(),
222 ColumnLimit, Style.TabWidth, Encoding);
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000223}
224
Alexander Kornienko555efc32013-06-11 16:01:49 +0000225void BreakableStringLiteral::insertBreak(unsigned LineIndex,
226 unsigned TailOffset, Split Split,
Alexander Kornienko555efc32013-06-11 16:01:49 +0000227 WhitespaceManager &Whitespaces) {
228 Whitespaces.replaceWhitespaceInToken(
229 Tok, Prefix.size() + TailOffset + Split.first, Split.second, Postfix,
Alexander Kornienkod4fa2e62017-04-11 09:55:00 +0000230 Prefix, InPPDirective, 1, StartColumn);
Alexander Kornienko555efc32013-06-11 16:01:49 +0000231}
232
Krasimir Georgiev91834222017-01-25 13:58:58 +0000233BreakableComment::BreakableComment(const FormatToken &Token,
Manuel Klimek89628f62017-09-20 09:51:03 +0000234 unsigned StartColumn, bool InPPDirective,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000235 encoding::Encoding Encoding,
236 const FormatStyle &Style)
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000237 : BreakableToken(Token, InPPDirective, Encoding, Style),
Krasimir Georgiev4b159222017-02-21 10:54:50 +0000238 StartColumn(StartColumn) {}
Manuel Klimek9043c742013-05-27 15:23:34 +0000239
Krasimir Georgiev91834222017-01-25 13:58:58 +0000240unsigned BreakableComment::getLineCount() const { return Lines.size(); }
241
Krasimir Georgiev17725d82017-03-08 08:55:12 +0000242BreakableToken::Split
243BreakableComment::getSplit(unsigned LineIndex, unsigned TailOffset,
244 unsigned ColumnLimit,
245 llvm::Regex &CommentPragmasRegex) const {
246 // Don't break lines matching the comment pragmas regex.
247 if (CommentPragmasRegex.match(Content[LineIndex]))
248 return Split(StringRef::npos, 0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000249 return getCommentSplit(Content[LineIndex].substr(TailOffset),
250 getContentStartColumn(LineIndex, TailOffset),
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000251 ColumnLimit, Style.TabWidth, Encoding);
Manuel Klimek9043c742013-05-27 15:23:34 +0000252}
253
Krasimir Georgiev91834222017-01-25 13:58:58 +0000254void BreakableComment::compressWhitespace(unsigned LineIndex,
255 unsigned TailOffset, Split Split,
256 WhitespaceManager &Whitespaces) {
257 StringRef Text = Content[LineIndex].substr(TailOffset);
258 // Text is relative to the content line, but Whitespaces operates relative to
259 // the start of the corresponding token, so compute the start of the Split
260 // that needs to be compressed into a single space relative to the start of
261 // its token.
262 unsigned BreakOffsetInToken =
263 Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
264 unsigned CharsToRemove = Split.second;
Alexander Kornienko555efc32013-06-11 16:01:49 +0000265 Whitespaces.replaceWhitespaceInToken(
Krasimir Georgiev91834222017-01-25 13:58:58 +0000266 tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", "",
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000267 /*InPPDirective=*/false, /*Newlines=*/0, /*Spaces=*/1);
Alexander Kornienko875395f2013-11-12 17:50:13 +0000268}
269
Krasimir Georgiev91834222017-01-25 13:58:58 +0000270BreakableToken::Split
271BreakableComment::getReflowSplit(StringRef Text, StringRef ReflowPrefix,
272 unsigned PreviousEndColumn,
273 unsigned ColumnLimit) const {
274 unsigned ReflowStartColumn = PreviousEndColumn + ReflowPrefix.size();
275 StringRef TrimmedText = Text.rtrim(Blanks);
276 // This is the width of the resulting line in case the full line of Text gets
277 // reflown up starting at ReflowStartColumn.
278 unsigned FullWidth = ReflowStartColumn + encoding::columnWidthWithTabs(
279 TrimmedText, ReflowStartColumn,
280 Style.TabWidth, Encoding);
281 // If the full line fits up, we return a reflow split after it,
282 // otherwise we compute the largest piece of text that fits after
283 // ReflowStartColumn.
284 Split ReflowSplit =
285 FullWidth <= ColumnLimit
286 ? Split(TrimmedText.size(), Text.size() - TrimmedText.size())
287 : getCommentSplit(Text, ReflowStartColumn, ColumnLimit,
288 Style.TabWidth, Encoding);
Alexander Kornienko555efc32013-06-11 16:01:49 +0000289
Krasimir Georgiev91834222017-01-25 13:58:58 +0000290 // We need to be extra careful here, because while it's OK to keep a long line
291 // if it can't be broken into smaller pieces (like when the first word of a
292 // long line is longer than the column limit), it's not OK to reflow that long
293 // word up. So we recompute the size of the previous line after reflowing and
294 // only return the reflow split if that's under the line limit.
295 if (ReflowSplit.first != StringRef::npos &&
296 // Check if the width of the newly reflown line is under the limit.
297 PreviousEndColumn + ReflowPrefix.size() +
298 encoding::columnWidthWithTabs(Text.substr(0, ReflowSplit.first),
299 PreviousEndColumn +
300 ReflowPrefix.size(),
301 Style.TabWidth, Encoding) <=
302 ColumnLimit) {
303 return ReflowSplit;
Alexander Kornienko555efc32013-06-11 16:01:49 +0000304 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000305 return Split(StringRef::npos, 0);
306}
307
308const FormatToken &BreakableComment::tokenAt(unsigned LineIndex) const {
309 return Tokens[LineIndex] ? *Tokens[LineIndex] : Tok;
310}
311
312static bool mayReflowContent(StringRef Content) {
313 Content = Content.trim(Blanks);
Krasimir Georgiev28912c02017-02-02 10:52:08 +0000314 // Lines starting with '@' commonly have special meaning.
Francois Ferranda881be82017-05-22 14:47:17 +0000315 // Lines starting with '-', '-#', '+' or '*' are bulleted/numbered lists.
316 static const SmallVector<StringRef, 8> kSpecialMeaningPrefixes = {
Manuel Klimek89628f62017-09-20 09:51:03 +0000317 "@", "TODO", "FIXME", "XXX", "-# ", "- ", "+ ", "* "};
Krasimir Georgiev28912c02017-02-02 10:52:08 +0000318 bool hasSpecialMeaningPrefix = false;
319 for (StringRef Prefix : kSpecialMeaningPrefixes) {
320 if (Content.startswith(Prefix)) {
321 hasSpecialMeaningPrefix = true;
322 break;
323 }
324 }
Francois Ferranda881be82017-05-22 14:47:17 +0000325
326 // Numbered lists may also start with a number followed by '.'
327 // To avoid issues if a line starts with a number which is actually the end
328 // of a previous line, we only consider numbers with up to 2 digits.
329 static llvm::Regex kNumberedListRegexp = llvm::Regex("^[1-9][0-9]?\\. ");
Manuel Klimek89628f62017-09-20 09:51:03 +0000330 hasSpecialMeaningPrefix =
331 hasSpecialMeaningPrefix || kNumberedListRegexp.match(Content);
Francois Ferranda881be82017-05-22 14:47:17 +0000332
Krasimir Georgiev91834222017-01-25 13:58:58 +0000333 // Simple heuristic for what to reflow: content should contain at least two
334 // characters and either the first or second character must be
335 // non-punctuation.
Krasimir Georgiev28912c02017-02-02 10:52:08 +0000336 return Content.size() >= 2 && !hasSpecialMeaningPrefix &&
337 !Content.endswith("\\") &&
Krasimir Georgiev91834222017-01-25 13:58:58 +0000338 // Note that this is UTF-8 safe, since if isPunctuation(Content[0]) is
339 // true, then the first code point must be 1 byte long.
340 (!isPunctuation(Content[0]) || !isPunctuation(Content[1]));
341}
342
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000343BreakableBlockComment::BreakableBlockComment(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000344 const FormatToken &Token, unsigned StartColumn,
Alexander Kornienkobe633902013-06-14 11:46:10 +0000345 unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective,
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000346 encoding::Encoding Encoding, const FormatStyle &Style)
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000347 : BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style),
348 DelimitersOnNewline(false) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000349 assert(Tok.is(TT_BlockComment) &&
350 "block comment section must start with a block comment");
351
352 StringRef TokenText(Tok.TokenText);
Manuel Klimek9043c742013-05-27 15:23:34 +0000353 assert(TokenText.startswith("/*") && TokenText.endswith("*/"));
354 TokenText.substr(2, TokenText.size() - 4).split(Lines, "\n");
355
356 int IndentDelta = StartColumn - OriginalStartColumn;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000357 Content.resize(Lines.size());
358 Content[0] = Lines[0];
359 ContentColumn.resize(Lines.size());
360 // Account for the initial '/*'.
361 ContentColumn[0] = StartColumn + 2;
362 Tokens.resize(Lines.size());
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000363 for (size_t i = 1; i < Lines.size(); ++i)
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000364 adjustWhitespace(i, IndentDelta);
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000365
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000366 // Align decorations with the column of the star on the first line,
367 // that is one column after the start "/*".
368 DecorationColumn = StartColumn + 1;
369
370 // Account for comment decoration patterns like this:
371 //
372 // /*
373 // ** blah blah blah
374 // */
375 if (Lines.size() >= 2 && Content[1].startswith("**") &&
376 static_cast<unsigned>(ContentColumn[1]) == StartColumn) {
377 DecorationColumn = StartColumn;
378 }
379
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000380 Decoration = "* ";
Manuel Klimek9043c742013-05-27 15:23:34 +0000381 if (Lines.size() == 1 && !FirstInLine) {
382 // Comments for which FirstInLine is false can start on arbitrary column,
383 // and available horizontal space can be too small to align consecutive
384 // lines with the first one.
385 // FIXME: We could, probably, align them to current indentation level, but
386 // now we just wrap them without stars.
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000387 Decoration = "";
Manuel Klimek9043c742013-05-27 15:23:34 +0000388 }
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000389 for (size_t i = 1, e = Lines.size(); i < e && !Decoration.empty(); ++i) {
390 // If the last line is empty, the closing "*/" will have a star.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000391 if (i + 1 == e && Content[i].empty())
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000392 break;
Manuel Klimek89628f62017-09-20 09:51:03 +0000393 if (!Content[i].empty() && i + 1 != e && Decoration.startswith(Content[i]))
Daniel Jasper6d9b88d2015-05-06 07:17:22 +0000394 continue;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000395 while (!Content[i].startswith(Decoration))
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000396 Decoration = Decoration.substr(0, Decoration.size() - 1);
Manuel Klimek9043c742013-05-27 15:23:34 +0000397 }
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000398
399 LastLineNeedsDecoration = true;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000400 IndentAtLineBreak = ContentColumn[0] + 1;
401 for (size_t i = 1, e = Lines.size(); i < e; ++i) {
402 if (Content[i].empty()) {
403 if (i + 1 == e) {
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000404 // Empty last line means that we already have a star as a part of the
405 // trailing */. We also need to preserve whitespace, so that */ is
406 // correctly indented.
407 LastLineNeedsDecoration = false;
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000408 // Align the star in the last '*/' with the stars on the previous lines.
409 if (e >= 2 && !Decoration.empty()) {
410 ContentColumn[i] = DecorationColumn;
411 }
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000412 } else if (Decoration.empty()) {
413 // For all other lines, set the start column to 0 if they're empty, so
414 // we do not insert trailing whitespace anywhere.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000415 ContentColumn[i] = 0;
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000416 }
Manuel Klimek9043c742013-05-27 15:23:34 +0000417 continue;
418 }
Daniel Jasper6d9b88d2015-05-06 07:17:22 +0000419
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000420 // The first line already excludes the star.
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000421 // The last line excludes the star if LastLineNeedsDecoration is false.
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000422 // For all other lines, adjust the line to exclude the star and
423 // (optionally) the first whitespace.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000424 unsigned DecorationSize = Decoration.startswith(Content[i])
425 ? Content[i].size()
426 : Decoration.size();
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000427 if (DecorationSize) {
428 ContentColumn[i] = DecorationColumn + DecorationSize;
429 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000430 Content[i] = Content[i].substr(DecorationSize);
431 if (!Decoration.startswith(Content[i]))
Daniel Jasper6d9b88d2015-05-06 07:17:22 +0000432 IndentAtLineBreak =
Krasimir Georgiev91834222017-01-25 13:58:58 +0000433 std::min<int>(IndentAtLineBreak, std::max(0, ContentColumn[i]));
Manuel Klimek9043c742013-05-27 15:23:34 +0000434 }
Manuel Klimek89628f62017-09-20 09:51:03 +0000435 IndentAtLineBreak = std::max<unsigned>(IndentAtLineBreak, Decoration.size());
Krasimir Georgiev91834222017-01-25 13:58:58 +0000436
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000437 // Detect a multiline jsdoc comment and set DelimitersOnNewline in that case.
438 if (Style.Language == FormatStyle::LK_JavaScript ||
439 Style.Language == FormatStyle::LK_Java) {
440 if ((Lines[0] == "*" || Lines[0].startswith("* ")) && Lines.size() > 1) {
441 // This is a multiline jsdoc comment.
442 DelimitersOnNewline = true;
443 } else if (Lines[0].startswith("* ") && Lines.size() == 1) {
444 // Detect a long single-line comment, like:
445 // /** long long long */
446 // Below, '2' is the width of '*/'.
Manuel Klimek89628f62017-09-20 09:51:03 +0000447 unsigned EndColumn =
448 ContentColumn[0] +
449 encoding::columnWidthWithTabs(Lines[0], ContentColumn[0],
450 Style.TabWidth, Encoding) +
451 2;
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000452 DelimitersOnNewline = EndColumn > Style.ColumnLimit;
453 }
454 }
455
Manuel Klimek9043c742013-05-27 15:23:34 +0000456 DEBUG({
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000457 llvm::dbgs() << "IndentAtLineBreak " << IndentAtLineBreak << "\n";
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000458 llvm::dbgs() << "DelimitersOnNewline " << DelimitersOnNewline << "\n";
Manuel Klimek9043c742013-05-27 15:23:34 +0000459 for (size_t i = 0; i < Lines.size(); ++i) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000460 llvm::dbgs() << i << " |" << Content[i] << "| "
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000461 << "CC=" << ContentColumn[i] << "| "
462 << "IN=" << (Content[i].data() - Lines[i].data()) << "\n";
Manuel Klimek9043c742013-05-27 15:23:34 +0000463 }
464 });
465}
466
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000467void BreakableBlockComment::adjustWhitespace(unsigned LineIndex,
Manuel Klimek9043c742013-05-27 15:23:34 +0000468 int IndentDelta) {
Alexander Kornienkobe633902013-06-14 11:46:10 +0000469 // When in a preprocessor directive, the trailing backslash in a block comment
470 // is not needed, but can serve a purpose of uniformity with necessary escaped
471 // newlines outside the comment. In this case we remove it here before
472 // trimming the trailing whitespace. The backslash will be re-added later when
473 // inserting a line break.
474 size_t EndOfPreviousLine = Lines[LineIndex - 1].size();
475 if (InPPDirective && Lines[LineIndex - 1].endswith("\\"))
476 --EndOfPreviousLine;
477
Manuel Klimek9043c742013-05-27 15:23:34 +0000478 // Calculate the end of the non-whitespace text in the previous line.
Alexander Kornienkobe633902013-06-14 11:46:10 +0000479 EndOfPreviousLine =
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000480 Lines[LineIndex - 1].find_last_not_of(Blanks, EndOfPreviousLine);
Manuel Klimek9043c742013-05-27 15:23:34 +0000481 if (EndOfPreviousLine == StringRef::npos)
482 EndOfPreviousLine = 0;
483 else
484 ++EndOfPreviousLine;
485 // Calculate the start of the non-whitespace text in the current line.
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000486 size_t StartOfLine = Lines[LineIndex].find_first_not_of(Blanks);
Manuel Klimek9043c742013-05-27 15:23:34 +0000487 if (StartOfLine == StringRef::npos)
Daniel Jasperd6e61882015-06-17 12:23:15 +0000488 StartOfLine = Lines[LineIndex].rtrim("\r\n").size();
Manuel Klimek9043c742013-05-27 15:23:34 +0000489
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000490 StringRef Whitespace = Lines[LineIndex].substr(0, StartOfLine);
Manuel Klimek9043c742013-05-27 15:23:34 +0000491 // Adjust Lines to only contain relevant text.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000492 size_t PreviousContentOffset =
493 Content[LineIndex - 1].data() - Lines[LineIndex - 1].data();
494 Content[LineIndex - 1] = Lines[LineIndex - 1].substr(
495 PreviousContentOffset, EndOfPreviousLine - PreviousContentOffset);
496 Content[LineIndex] = Lines[LineIndex].substr(StartOfLine);
Manuel Klimek34d15152013-05-28 10:01:59 +0000497
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000498 // Adjust the start column uniformly across all lines.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000499 ContentColumn[LineIndex] =
Alexander Kornienko39856b72013-09-10 09:38:25 +0000500 encoding::columnWidthWithTabs(Whitespace, 0, Style.TabWidth, Encoding) +
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000501 IndentDelta;
Manuel Klimek9043c742013-05-27 15:23:34 +0000502}
503
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000504unsigned BreakableBlockComment::getLineLengthAfterSplit(
Krasimir Georgiev91834222017-01-25 13:58:58 +0000505 unsigned LineIndex, unsigned TailOffset,
506 StringRef::size_type Length) const {
507 unsigned ContentStartColumn = getContentStartColumn(LineIndex, TailOffset);
508 unsigned LineLength =
509 ContentStartColumn + encoding::columnWidthWithTabs(
510 Content[LineIndex].substr(TailOffset, Length),
511 ContentStartColumn, Style.TabWidth, Encoding);
512 // The last line gets a "*/" postfix.
513 if (LineIndex + 1 == Lines.size()) {
514 LineLength += 2;
515 // We never need a decoration when breaking just the trailing "*/" postfix.
516 // Note that checking that Length == 0 is not enough, since Length could
517 // also be StringRef::npos.
518 if (Content[LineIndex].substr(TailOffset, Length).empty()) {
519 LineLength -= Decoration.size();
520 }
521 }
522 return LineLength;
Manuel Klimek9043c742013-05-27 15:23:34 +0000523}
524
525void BreakableBlockComment::insertBreak(unsigned LineIndex, unsigned TailOffset,
Alexander Kornienkobe633902013-06-14 11:46:10 +0000526 Split Split,
Manuel Klimek9043c742013-05-27 15:23:34 +0000527 WhitespaceManager &Whitespaces) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000528 StringRef Text = Content[LineIndex].substr(TailOffset);
Manuel Klimek9043c742013-05-27 15:23:34 +0000529 StringRef Prefix = Decoration;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000530 // We need this to account for the case when we have a decoration "* " for all
531 // the lines except for the last one, where the star in "*/" acts as a
532 // decoration.
533 unsigned LocalIndentAtLineBreak = IndentAtLineBreak;
Manuel Klimek9043c742013-05-27 15:23:34 +0000534 if (LineIndex + 1 == Lines.size() &&
535 Text.size() == Split.first + Split.second) {
536 // For the last line we need to break before "*/", but not to add "* ".
537 Prefix = "";
Krasimir Georgiev91834222017-01-25 13:58:58 +0000538 if (LocalIndentAtLineBreak >= 2)
539 LocalIndentAtLineBreak -= 2;
540 }
541 // The split offset is from the beginning of the line. Convert it to an offset
542 // from the beginning of the token text.
543 unsigned BreakOffsetInToken =
544 Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
545 unsigned CharsToRemove = Split.second;
546 assert(LocalIndentAtLineBreak >= Prefix.size());
547 Whitespaces.replaceWhitespaceInToken(
548 tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", Prefix,
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000549 InPPDirective, /*Newlines=*/1,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000550 /*Spaces=*/LocalIndentAtLineBreak - Prefix.size());
551}
552
553BreakableToken::Split BreakableBlockComment::getSplitBefore(
Krasimir Georgiev33bd8522017-08-24 16:41:10 +0000554 unsigned LineIndex, unsigned PreviousEndColumn, unsigned ColumnLimit,
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000555 llvm::Regex &CommentPragmasRegex) const {
556 if (!mayReflow(LineIndex, CommentPragmasRegex))
Krasimir Georgiev91834222017-01-25 13:58:58 +0000557 return Split(StringRef::npos, 0);
558 StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
Krasimir Georgiev33bd8522017-08-24 16:41:10 +0000559 Split Result = getReflowSplit(TrimmedContent, ReflowPrefix, PreviousEndColumn,
560 ColumnLimit);
561 // Result is relative to TrimmedContent. Adapt it relative to
562 // Content[LineIndex].
563 if (Result.first != StringRef::npos)
564 Result.first += Content[LineIndex].size() - TrimmedContent.size();
565 return Result;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000566}
567
Manuel Klimek89628f62017-09-20 09:51:03 +0000568unsigned
569BreakableBlockComment::getReflownColumn(StringRef Content, unsigned LineIndex,
570 unsigned PreviousEndColumn) const {
571 unsigned StartColumn = PreviousEndColumn + ReflowPrefix.size();
572 // If this is the last line, it will carry around its '*/' postfix.
573 unsigned PostfixLength = (LineIndex + 1 == Lines.size() ? 2 : 0);
574 // The line is composed of previous text, reflow prefix, reflown text and
575 // postfix.
576 unsigned ReflownColumn = StartColumn +
577 encoding::columnWidthWithTabs(
578 Content, StartColumn, Style.TabWidth, Encoding) +
579 PostfixLength;
580 return ReflownColumn;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000581}
582
583unsigned BreakableBlockComment::getLineLengthAfterSplitBefore(
Manuel Klimek89628f62017-09-20 09:51:03 +0000584 unsigned LineIndex, unsigned TailOffset, unsigned PreviousEndColumn,
585 unsigned ColumnLimit, Split SplitBefore) const {
Krasimir Georgievaf1b9622017-01-31 14:31:44 +0000586 if (SplitBefore.first == StringRef::npos ||
587 // Block comment line contents contain the trailing whitespace after the
588 // decoration, so the need of left trim. Note that this behavior is
589 // consistent with the breaking of block comments where the indentation of
590 // a broken line is uniform across all the lines of the block comment.
591 SplitBefore.first + SplitBefore.second <
592 Content[LineIndex].ltrim().size()) {
593 // A piece of line, not the whole, gets reflown.
594 return getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000595 } else {
596 // The whole line gets reflown, need to check if we need to insert a break
597 // for the postfix or not.
598 StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
599 unsigned ReflownColumn =
600 getReflownColumn(TrimmedContent, LineIndex, PreviousEndColumn);
601 if (ReflownColumn <= ColumnLimit) {
602 return ReflownColumn;
603 }
604 return getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
605 }
606}
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000607
Krasimir Georgiev35599fd2017-10-16 09:08:53 +0000608bool BreakableBlockComment::introducesBreakBefore(unsigned LineIndex) const {
609 // A break is introduced when we want delimiters on newline.
610 return LineIndex == 0 && DelimitersOnNewline &&
611 Lines[0].substr(1).find_first_not_of(Blanks) != StringRef::npos;
612}
613
Krasimir Georgiev91834222017-01-25 13:58:58 +0000614void BreakableBlockComment::replaceWhitespaceBefore(
615 unsigned LineIndex, unsigned PreviousEndColumn, unsigned ColumnLimit,
616 Split SplitBefore, WhitespaceManager &Whitespaces) {
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000617 if (LineIndex == 0) {
618 if (DelimitersOnNewline) {
Manuel Klimek89628f62017-09-20 09:51:03 +0000619 // Since we're breaking af index 1 below, the break position and the
620 // break length are the same.
621 size_t BreakLength = Lines[0].substr(1).find_first_not_of(Blanks);
622 if (BreakLength != StringRef::npos) {
623 insertBreak(LineIndex, 0, Split(1, BreakLength), Whitespaces);
624 DelimitersOnNewline = true;
625 }
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000626 }
627 return;
628 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000629 StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
630 if (SplitBefore.first != StringRef::npos) {
631 // Here we need to reflow.
632 assert(Tokens[LineIndex - 1] == Tokens[LineIndex] &&
633 "Reflowing whitespace within a token");
634 // This is the offset of the end of the last line relative to the start of
635 // the token text in the token.
636 unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
Manuel Klimek89628f62017-09-20 09:51:03 +0000637 Content[LineIndex - 1].size() -
638 tokenAt(LineIndex).TokenText.data();
Krasimir Georgiev91834222017-01-25 13:58:58 +0000639 unsigned WhitespaceLength = TrimmedContent.data() -
Manuel Klimek89628f62017-09-20 09:51:03 +0000640 tokenAt(LineIndex).TokenText.data() -
641 WhitespaceOffsetInToken;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000642 Whitespaces.replaceWhitespaceInToken(
643 tokenAt(LineIndex), WhitespaceOffsetInToken,
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000644 /*ReplaceChars=*/WhitespaceLength, /*PreviousPostfix=*/"",
645 /*CurrentPrefix=*/ReflowPrefix, InPPDirective, /*Newlines=*/0,
646 /*Spaces=*/0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000647 // Check if we need to also insert a break at the whitespace range.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000648 // Note that we don't need a penalty for this break, since it doesn't change
649 // the total number of lines.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000650 unsigned ReflownColumn =
651 getReflownColumn(TrimmedContent, LineIndex, PreviousEndColumn);
Krasimir Georgiev33bd8522017-08-24 16:41:10 +0000652 if (ReflownColumn > ColumnLimit)
653 insertBreak(LineIndex, 0, SplitBefore, Whitespaces);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000654 return;
Manuel Klimek9043c742013-05-27 15:23:34 +0000655 }
656
Krasimir Georgiev91834222017-01-25 13:58:58 +0000657 // Here no reflow with the previous line will happen.
658 // Fix the decoration of the line at LineIndex.
Manuel Klimek9043c742013-05-27 15:23:34 +0000659 StringRef Prefix = Decoration;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000660 if (Content[LineIndex].empty()) {
Manuel Klimek281dcbe2013-05-28 08:55:01 +0000661 if (LineIndex + 1 == Lines.size()) {
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000662 if (!LastLineNeedsDecoration) {
663 // If the last line was empty, we don't need a prefix, as the */ will
664 // line up with the decoration (if it exists).
665 Prefix = "";
666 }
Manuel Klimek281dcbe2013-05-28 08:55:01 +0000667 } else if (!Decoration.empty()) {
668 // For other empty lines, if we do have a decoration, adapt it to not
669 // contain a trailing whitespace.
670 Prefix = Prefix.substr(0, 1);
671 }
Daniel Jasper51fb2b22013-05-30 06:40:07 +0000672 } else {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000673 if (ContentColumn[LineIndex] == 1) {
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000674 // This line starts immediately after the decorating *.
Daniel Jasper51fb2b22013-05-30 06:40:07 +0000675 Prefix = Prefix.substr(0, 1);
676 }
Manuel Klimek281dcbe2013-05-28 08:55:01 +0000677 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000678 // This is the offset of the end of the last line relative to the start of the
679 // token text in the token.
680 unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
681 Content[LineIndex - 1].size() -
682 tokenAt(LineIndex).TokenText.data();
683 unsigned WhitespaceLength = Content[LineIndex].data() -
684 tokenAt(LineIndex).TokenText.data() -
685 WhitespaceOffsetInToken;
Alexander Kornienko555efc32013-06-11 16:01:49 +0000686 Whitespaces.replaceWhitespaceInToken(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000687 tokenAt(LineIndex), WhitespaceOffsetInToken, WhitespaceLength, "", Prefix,
688 InPPDirective, /*Newlines=*/1, ContentColumn[LineIndex] - Prefix.size());
Manuel Klimek9043c742013-05-27 15:23:34 +0000689}
690
Krasimir Georgiev3b865342017-08-09 09:42:32 +0000691BreakableToken::Split
692BreakableBlockComment::getSplitAfterLastLine(unsigned TailOffset,
693 unsigned ColumnLimit) const {
694 if (DelimitersOnNewline) {
695 // Replace the trailing whitespace of the last line with a newline.
696 // In case the last line is empty, the ending '*/' is already on its own
697 // line.
698 StringRef Line = Content.back().substr(TailOffset);
699 StringRef TrimmedLine = Line.rtrim(Blanks);
700 if (!TrimmedLine.empty())
701 return Split(TrimmedLine.size(), Line.size() - TrimmedLine.size());
702 }
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000703 return Split(StringRef::npos, 0);
704}
705
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000706bool BreakableBlockComment::mayReflow(unsigned LineIndex,
707 llvm::Regex &CommentPragmasRegex) const {
708 // Content[LineIndex] may exclude the indent after the '*' decoration. In that
709 // case, we compute the start of the comment pragma manually.
710 StringRef IndentContent = Content[LineIndex];
711 if (Lines[LineIndex].ltrim(Blanks).startswith("*")) {
712 IndentContent = Lines[LineIndex].ltrim(Blanks).substr(1);
713 }
714 return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
715 mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
716 !switchesFormatting(tokenAt(LineIndex));
717}
718
Manuel Klimek9043c742013-05-27 15:23:34 +0000719unsigned
720BreakableBlockComment::getContentStartColumn(unsigned LineIndex,
721 unsigned TailOffset) const {
722 // If we break, we always break at the predefined indent.
723 if (TailOffset != 0)
724 return IndentAtLineBreak;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000725 return std::max(0, ContentColumn[LineIndex]);
726}
727
728BreakableLineCommentSection::BreakableLineCommentSection(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000729 const FormatToken &Token, unsigned StartColumn,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000730 unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective,
731 encoding::Encoding Encoding, const FormatStyle &Style)
Krasimir Georgiev4b159222017-02-21 10:54:50 +0000732 : BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000733 assert(Tok.is(TT_LineComment) &&
734 "line comment section must start with a line comment");
735 FormatToken *LineTok = nullptr;
736 for (const FormatToken *CurrentTok = &Tok;
737 CurrentTok && CurrentTok->is(TT_LineComment);
738 CurrentTok = CurrentTok->Next) {
739 LastLineTok = LineTok;
740 StringRef TokenText(CurrentTok->TokenText);
Krasimir Georgiev410ed242017-11-10 12:50:09 +0000741 assert((TokenText.startswith("//") || TokenText.startswith("#")) &&
742 "unsupported line comment prefix, '//' and '#' are supported");
Krasimir Georgiev91834222017-01-25 13:58:58 +0000743 size_t FirstLineIndex = Lines.size();
744 TokenText.split(Lines, "\n");
745 Content.resize(Lines.size());
746 ContentColumn.resize(Lines.size());
747 OriginalContentColumn.resize(Lines.size());
748 Tokens.resize(Lines.size());
749 Prefix.resize(Lines.size());
750 OriginalPrefix.resize(Lines.size());
751 for (size_t i = FirstLineIndex, e = Lines.size(); i < e; ++i) {
Krasimir Georgieve518e0b2017-01-30 21:00:01 +0000752 // We need to trim the blanks in case this is not the first line in a
753 // multiline comment. Then the indent is included in Lines[i].
754 StringRef IndentPrefix =
Krasimir Georgiev410ed242017-11-10 12:50:09 +0000755 getLineCommentIndentPrefix(Lines[i].ltrim(Blanks), Style);
756 assert((TokenText.startswith("//") || TokenText.startswith("#")) &&
757 "unsupported line comment prefix, '//' and '#' are supported");
Krasimir Georgiev91834222017-01-25 13:58:58 +0000758 OriginalPrefix[i] = Prefix[i] = IndentPrefix;
759 if (Lines[i].size() > Prefix[i].size() &&
760 isAlphanumeric(Lines[i][Prefix[i].size()])) {
761 if (Prefix[i] == "//")
762 Prefix[i] = "// ";
763 else if (Prefix[i] == "///")
764 Prefix[i] = "/// ";
765 else if (Prefix[i] == "//!")
766 Prefix[i] = "//! ";
Krasimir Georgievba6b3152017-05-18 07:36:21 +0000767 else if (Prefix[i] == "///<")
768 Prefix[i] = "///< ";
769 else if (Prefix[i] == "//!<")
770 Prefix[i] = "//!< ";
Krasimir Georgiev410ed242017-11-10 12:50:09 +0000771 else if (Prefix[i] == "#" &&
772 Style.Language == FormatStyle::LK_TextProto)
773 Prefix[i] = "# ";
Krasimir Georgiev91834222017-01-25 13:58:58 +0000774 }
775
776 Tokens[i] = LineTok;
777 Content[i] = Lines[i].substr(IndentPrefix.size());
778 OriginalContentColumn[i] =
Manuel Klimek89628f62017-09-20 09:51:03 +0000779 StartColumn + encoding::columnWidthWithTabs(OriginalPrefix[i],
780 StartColumn,
781 Style.TabWidth, Encoding);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000782 ContentColumn[i] =
Manuel Klimek89628f62017-09-20 09:51:03 +0000783 StartColumn + encoding::columnWidthWithTabs(Prefix[i], StartColumn,
784 Style.TabWidth, Encoding);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000785
786 // Calculate the end of the non-whitespace text in this line.
787 size_t EndOfLine = Content[i].find_last_not_of(Blanks);
788 if (EndOfLine == StringRef::npos)
789 EndOfLine = Content[i].size();
790 else
791 ++EndOfLine;
792 Content[i] = Content[i].substr(0, EndOfLine);
793 }
794 LineTok = CurrentTok->Next;
Krasimir Georgievb6ccd382017-02-02 14:36:50 +0000795 if (CurrentTok->Next && !CurrentTok->Next->ContinuesLineCommentSection) {
Krasimir Georgiev753625b2017-01-31 13:32:38 +0000796 // A line comment section needs to broken by a line comment that is
797 // preceded by at least two newlines. Note that we put this break here
798 // instead of breaking at a previous stage during parsing, since that
799 // would split the contents of the enum into two unwrapped lines in this
800 // example, which is undesirable:
801 // enum A {
802 // a, // comment about a
803 //
804 // // comment about b
805 // b
806 // };
807 //
808 // FIXME: Consider putting separate line comment sections as children to
809 // the unwrapped line instead.
810 break;
811 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000812 }
813}
814
815unsigned BreakableLineCommentSection::getLineLengthAfterSplit(
816 unsigned LineIndex, unsigned TailOffset,
817 StringRef::size_type Length) const {
818 unsigned ContentStartColumn =
819 (TailOffset == 0 ? ContentColumn[LineIndex]
820 : OriginalContentColumn[LineIndex]);
821 return ContentStartColumn + encoding::columnWidthWithTabs(
822 Content[LineIndex].substr(TailOffset, Length),
823 ContentStartColumn, Style.TabWidth, Encoding);
824}
825
826void BreakableLineCommentSection::insertBreak(unsigned LineIndex,
827 unsigned TailOffset, Split Split,
828 WhitespaceManager &Whitespaces) {
829 StringRef Text = Content[LineIndex].substr(TailOffset);
830 // Compute the offset of the split relative to the beginning of the token
831 // text.
832 unsigned BreakOffsetInToken =
833 Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
834 unsigned CharsToRemove = Split.second;
835 // Compute the size of the new indent, including the size of the new prefix of
836 // the newly broken line.
837 unsigned IndentAtLineBreak = OriginalContentColumn[LineIndex] +
838 Prefix[LineIndex].size() -
839 OriginalPrefix[LineIndex].size();
840 assert(IndentAtLineBreak >= Prefix[LineIndex].size());
841 Whitespaces.replaceWhitespaceInToken(
842 tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "",
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000843 Prefix[LineIndex], InPPDirective, /*Newlines=*/1,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000844 /*Spaces=*/IndentAtLineBreak - Prefix[LineIndex].size());
845}
846
847BreakableComment::Split BreakableLineCommentSection::getSplitBefore(
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000848 unsigned LineIndex, unsigned PreviousEndColumn, unsigned ColumnLimit,
849 llvm::Regex &CommentPragmasRegex) const {
850 if (!mayReflow(LineIndex, CommentPragmasRegex))
851 return Split(StringRef::npos, 0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000852 return getReflowSplit(Content[LineIndex], ReflowPrefix, PreviousEndColumn,
853 ColumnLimit);
854}
855
856unsigned BreakableLineCommentSection::getLineLengthAfterSplitBefore(
Manuel Klimek89628f62017-09-20 09:51:03 +0000857 unsigned LineIndex, unsigned TailOffset, unsigned PreviousEndColumn,
858 unsigned ColumnLimit, Split SplitBefore) const {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000859 if (SplitBefore.first == StringRef::npos ||
860 SplitBefore.first + SplitBefore.second < Content[LineIndex].size()) {
861 // A piece of line, not the whole line, gets reflown.
862 return getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
863 } else {
864 // The whole line gets reflown.
865 unsigned StartColumn = PreviousEndColumn + ReflowPrefix.size();
Manuel Klimek89628f62017-09-20 09:51:03 +0000866 return StartColumn +
867 encoding::columnWidthWithTabs(Content[LineIndex], StartColumn,
868 Style.TabWidth, Encoding);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000869 }
870}
871
872void BreakableLineCommentSection::replaceWhitespaceBefore(
873 unsigned LineIndex, unsigned PreviousEndColumn, unsigned ColumnLimit,
874 Split SplitBefore, WhitespaceManager &Whitespaces) {
875 // If this is the first line of a token, we need to inform Whitespace Manager
876 // about it: either adapt the whitespace range preceding it, or mark it as an
877 // untouchable token.
878 // This happens for instance here:
879 // // line 1 \
880 // // line 2
881 if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) {
882 if (SplitBefore.first != StringRef::npos) {
883 // Reflow happens between tokens. Replace the whitespace between the
884 // tokens by the empty string.
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000885 Whitespaces.replaceWhitespace(
886 *Tokens[LineIndex], /*Newlines=*/0, /*Spaces=*/0,
887 /*StartOfTokenColumn=*/StartColumn, /*InPPDirective=*/false);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000888 // Replace the indent and prefix of the token with the reflow prefix.
889 unsigned WhitespaceLength =
890 Content[LineIndex].data() - tokenAt(LineIndex).TokenText.data();
891 Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex],
892 /*Offset=*/0,
893 /*ReplaceChars=*/WhitespaceLength,
894 /*PreviousPostfix=*/"",
895 /*CurrentPrefix=*/ReflowPrefix,
896 /*InPPDirective=*/false,
897 /*Newlines=*/0,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000898 /*Spaces=*/0);
899 } else {
900 // This is the first line for the current token, but no reflow with the
901 // previous token is necessary. However, we still may need to adjust the
Krasimir Georgievb796ceb2017-01-31 15:40:15 +0000902 // start column. Note that ContentColumn[LineIndex] is the expected
903 // content column after a possible update to the prefix, hence the prefix
904 // length change is included.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000905 unsigned LineColumn =
906 ContentColumn[LineIndex] -
Krasimir Georgievb796ceb2017-01-31 15:40:15 +0000907 (Content[LineIndex].data() - Lines[LineIndex].data()) +
908 (OriginalPrefix[LineIndex].size() - Prefix[LineIndex].size());
Krasimir Georgiev13dbaa02017-02-01 10:10:04 +0000909
910 // We always want to create a replacement instead of adding an untouchable
911 // token, even if LineColumn is the same as the original column of the
912 // token. This is because WhitespaceManager doesn't align trailing
913 // comments if they are untouchable.
914 Whitespaces.replaceWhitespace(*Tokens[LineIndex],
915 /*Newlines=*/1,
916 /*Spaces=*/LineColumn,
917 /*StartOfTokenColumn=*/LineColumn,
918 /*InPPDirective=*/false);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000919 }
Krasimir Georgievb796ceb2017-01-31 15:40:15 +0000920 }
921 if (OriginalPrefix[LineIndex] != Prefix[LineIndex]) {
922 // Adjust the prefix if necessary.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000923
924 // Take care of the space possibly introduced after a decoration.
925 assert(Prefix[LineIndex] == (OriginalPrefix[LineIndex] + " ").str() &&
Krasimir Georgievb796ceb2017-01-31 15:40:15 +0000926 "Expecting a line comment prefix to differ from original by at most "
927 "a space");
Krasimir Georgiev91834222017-01-25 13:58:58 +0000928 Whitespaces.replaceWhitespaceInToken(
929 tokenAt(LineIndex), OriginalPrefix[LineIndex].size(), 0, "", "",
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000930 /*InPPDirective=*/false, /*Newlines=*/0, /*Spaces=*/1);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000931 }
932 // Add a break after a reflow split has been introduced, if necessary.
933 // Note that this break doesn't need to be penalized, since it doesn't change
934 // the number of lines.
935 if (SplitBefore.first != StringRef::npos &&
936 SplitBefore.first + SplitBefore.second < Content[LineIndex].size()) {
937 insertBreak(LineIndex, 0, SplitBefore, Whitespaces);
938 }
939}
940
Manuel Klimek89628f62017-09-20 09:51:03 +0000941void BreakableLineCommentSection::updateNextToken(LineState &State) const {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000942 if (LastLineTok) {
943 State.NextToken = LastLineTok->Next;
944 }
945}
946
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000947bool BreakableLineCommentSection::mayReflow(
948 unsigned LineIndex, llvm::Regex &CommentPragmasRegex) const {
949 // Line comments have the indent as part of the prefix, so we need to
950 // recompute the start of the line.
951 StringRef IndentContent = Content[LineIndex];
952 if (Lines[LineIndex].startswith("//")) {
953 IndentContent = Lines[LineIndex].substr(2);
954 }
955 return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
956 mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
957 !switchesFormatting(tokenAt(LineIndex)) &&
958 OriginalPrefix[LineIndex] == OriginalPrefix[LineIndex - 1];
959}
960
Krasimir Georgiev91834222017-01-25 13:58:58 +0000961unsigned
962BreakableLineCommentSection::getContentStartColumn(unsigned LineIndex,
963 unsigned TailOffset) const {
964 if (TailOffset != 0) {
965 return OriginalContentColumn[LineIndex];
966 }
967 return ContentColumn[LineIndex];
Manuel Klimek9043c742013-05-27 15:23:34 +0000968}
969
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000970} // namespace format
971} // namespace clang