blob: 20e3e5b1dfd665abb79af9e7ba3276ec0f1b971d [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) {
Krasimir Georgievba6b3152017-05-18 07:36:21 +000044 static const char *const KnownPrefixes[] = {
45 "///<", "//!<", "///", "//", "//!"};
Krasimir Georgiev91834222017-01-25 13:58:58 +000046 StringRef LongestPrefix;
47 for (StringRef KnownPrefix : KnownPrefixes) {
48 if (Comment.startswith(KnownPrefix)) {
49 size_t PrefixLength = KnownPrefix.size();
50 while (PrefixLength < Comment.size() && Comment[PrefixLength] == ' ')
51 ++PrefixLength;
52 if (PrefixLength > LongestPrefix.size())
53 LongestPrefix = Comment.substr(0, PrefixLength);
54 }
55 }
56 return LongestPrefix;
57}
58
Craig Topperbfb5c402013-07-01 03:38:29 +000059static BreakableToken::Split getCommentSplit(StringRef Text,
60 unsigned ContentStartColumn,
61 unsigned ColumnLimit,
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +000062 unsigned TabWidth,
Craig Topperbfb5c402013-07-01 03:38:29 +000063 encoding::Encoding Encoding) {
Alexander Kornienko9e90b622013-04-17 17:34:05 +000064 if (ColumnLimit <= ContentStartColumn + 1)
Manuel Klimek9043c742013-05-27 15:23:34 +000065 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienko9e90b622013-04-17 17:34:05 +000066
67 unsigned MaxSplit = ColumnLimit - ContentStartColumn + 1;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +000068 unsigned MaxSplitBytes = 0;
69
70 for (unsigned NumChars = 0;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +000071 NumChars < MaxSplit && MaxSplitBytes < Text.size();) {
72 unsigned BytesInChar =
Alexander Kornienkoffcc0102013-06-05 14:09:10 +000073 encoding::getCodePointNumBytes(Text[MaxSplitBytes], Encoding);
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +000074 NumChars +=
75 encoding::columnWidthWithTabs(Text.substr(MaxSplitBytes, BytesInChar),
76 ContentStartColumn, TabWidth, Encoding);
77 MaxSplitBytes += BytesInChar;
78 }
Alexander Kornienkoffcc0102013-06-05 14:09:10 +000079
Alexander Kornienkob93062e2013-06-20 13:58:37 +000080 StringRef::size_type SpaceOffset = Text.find_last_of(Blanks, MaxSplitBytes);
Francois Ferranda881be82017-05-22 14:47:17 +000081
82 // Do not split before a number followed by a dot: this would be interpreted
83 // as a numbered list, which would prevent re-flowing in subsequent passes.
84 static llvm::Regex kNumberedListRegexp = llvm::Regex("^[1-9][0-9]?\\.");
85 if (SpaceOffset != StringRef::npos &&
86 kNumberedListRegexp.match(Text.substr(SpaceOffset).ltrim(Blanks)))
87 SpaceOffset = Text.find_last_of(Blanks, SpaceOffset);
88
Alexander Kornienko9e90b622013-04-17 17:34:05 +000089 if (SpaceOffset == StringRef::npos ||
Manuel Klimek9043c742013-05-27 15:23:34 +000090 // Don't break at leading whitespace.
Alexander Kornienkob93062e2013-06-20 13:58:37 +000091 Text.find_last_not_of(Blanks, SpaceOffset) == StringRef::npos) {
Manuel Klimekae1fbfb2013-05-29 22:06:18 +000092 // Make sure that we don't break at leading whitespace that
93 // reaches past MaxSplit.
Alexander Kornienkob93062e2013-06-20 13:58:37 +000094 StringRef::size_type FirstNonWhitespace = Text.find_first_not_of(Blanks);
Manuel Klimekae1fbfb2013-05-29 22:06:18 +000095 if (FirstNonWhitespace == StringRef::npos)
96 // If the comment is only whitespace, we cannot split.
97 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienkob93062e2013-06-20 13:58:37 +000098 SpaceOffset = Text.find_first_of(
99 Blanks, std::max<unsigned>(MaxSplitBytes, FirstNonWhitespace));
Manuel Klimekae1fbfb2013-05-29 22:06:18 +0000100 }
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000101 if (SpaceOffset != StringRef::npos && SpaceOffset != 0) {
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000102 StringRef BeforeCut = Text.substr(0, SpaceOffset).rtrim(Blanks);
103 StringRef AfterCut = Text.substr(SpaceOffset).ltrim(Blanks);
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000104 return BreakableToken::Split(BeforeCut.size(),
105 AfterCut.begin() - BeforeCut.end());
106 }
107 return BreakableToken::Split(StringRef::npos, 0);
108}
109
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000110static BreakableToken::Split
111getStringSplit(StringRef Text, unsigned UsedColumns, unsigned ColumnLimit,
112 unsigned TabWidth, encoding::Encoding Encoding) {
Manuel Klimek9043c742013-05-27 15:23:34 +0000113 // FIXME: Reduce unit test case.
114 if (Text.empty())
115 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienko81e32942013-09-16 20:20:49 +0000116 if (ColumnLimit <= UsedColumns)
Manuel Klimek9043c742013-05-27 15:23:34 +0000117 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienko71d95d62013-11-26 10:38:53 +0000118 unsigned MaxSplit = ColumnLimit - UsedColumns;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000119 StringRef::size_type SpaceOffset = 0;
120 StringRef::size_type SlashOffset = 0;
Alexander Kornienko72852072013-06-19 14:22:47 +0000121 StringRef::size_type WordStartOffset = 0;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000122 StringRef::size_type SplitPoint = 0;
123 for (unsigned Chars = 0;;) {
124 unsigned Advance;
125 if (Text[0] == '\\') {
126 Advance = encoding::getEscapeSequenceLength(Text);
127 Chars += Advance;
128 } else {
129 Advance = encoding::getCodePointNumBytes(Text[0], Encoding);
Alexander Kornienko81e32942013-09-16 20:20:49 +0000130 Chars += encoding::columnWidthWithTabs(
131 Text.substr(0, Advance), UsedColumns + Chars, TabWidth, Encoding);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000132 }
133
Daniel Jaspere4b48c62015-01-21 19:50:35 +0000134 if (Chars > MaxSplit || Text.size() <= Advance)
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000135 break;
136
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000137 if (IsBlank(Text[0]))
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000138 SpaceOffset = SplitPoint;
139 if (Text[0] == '/')
140 SlashOffset = SplitPoint;
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000141 if (Advance == 1 && !isAlphanumeric(Text[0]))
Alexander Kornienko72852072013-06-19 14:22:47 +0000142 WordStartOffset = SplitPoint;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000143
144 SplitPoint += Advance;
145 Text = Text.substr(Advance);
146 }
147
148 if (SpaceOffset != 0)
149 return BreakableToken::Split(SpaceOffset + 1, 0);
150 if (SlashOffset != 0)
151 return BreakableToken::Split(SlashOffset + 1, 0);
Alexander Kornienko72852072013-06-19 14:22:47 +0000152 if (WordStartOffset != 0)
153 return BreakableToken::Split(WordStartOffset + 1, 0);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000154 if (SplitPoint != 0)
155 return BreakableToken::Split(SplitPoint, 0);
156 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000157}
158
Krasimir Georgiev91834222017-01-25 13:58:58 +0000159bool switchesFormatting(const FormatToken &Token) {
160 assert((Token.is(TT_BlockComment) || Token.is(TT_LineComment)) &&
161 "formatting regions are switched by comment tokens");
162 StringRef Content = Token.TokenText.substr(2).ltrim();
163 return Content.startswith("clang-format on") ||
164 Content.startswith("clang-format off");
165}
166
167unsigned
168BreakableToken::getLineLengthAfterCompression(unsigned RemainingTokenColumns,
169 Split Split) const {
170 // Example: consider the content
171 // lala lala
172 // - RemainingTokenColumns is the original number of columns, 10;
173 // - Split is (4, 2), denoting the two spaces between the two words;
174 //
175 // We compute the number of columns when the split is compressed into a single
176 // space, like:
177 // lala lala
178 return RemainingTokenColumns + 1 - Split.second;
179}
180
Manuel Klimek9043c742013-05-27 15:23:34 +0000181unsigned BreakableSingleLineToken::getLineCount() const { return 1; }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000182
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000183unsigned BreakableSingleLineToken::getLineLengthAfterSplit(
Krasimir Georgiev91834222017-01-25 13:58:58 +0000184 unsigned LineIndex, unsigned TailOffset,
185 StringRef::size_type Length) const {
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000186 return StartColumn + Prefix.size() + Postfix.size() +
Krasimir Georgiev91834222017-01-25 13:58:58 +0000187 encoding::columnWidthWithTabs(Line.substr(TailOffset, Length),
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000188 StartColumn + Prefix.size(),
189 Style.TabWidth, Encoding);
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000190}
191
Alexander Kornienkobe633902013-06-14 11:46:10 +0000192BreakableSingleLineToken::BreakableSingleLineToken(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000193 const FormatToken &Tok, unsigned StartColumn, StringRef Prefix,
194 StringRef Postfix, bool InPPDirective, encoding::Encoding Encoding,
195 const FormatStyle &Style)
196 : BreakableToken(Tok, InPPDirective, Encoding, Style),
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000197 StartColumn(StartColumn), Prefix(Prefix), Postfix(Postfix) {
Alexander Kornienkod4fa2e62017-04-11 09:55:00 +0000198 assert(Tok.TokenText.startswith(Prefix) && Tok.TokenText.endswith(Postfix));
Manuel Klimek9043c742013-05-27 15:23:34 +0000199 Line = Tok.TokenText.substr(
200 Prefix.size(), Tok.TokenText.size() - Prefix.size() - Postfix.size());
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000201}
202
Alexander Kornienko81e32942013-09-16 20:20:49 +0000203BreakableStringLiteral::BreakableStringLiteral(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000204 const FormatToken &Tok, unsigned StartColumn, StringRef Prefix,
205 StringRef Postfix, bool InPPDirective, encoding::Encoding Encoding,
206 const FormatStyle &Style)
207 : BreakableSingleLineToken(Tok, StartColumn, Prefix, Postfix, InPPDirective,
208 Encoding, Style) {}
Manuel Klimek9043c742013-05-27 15:23:34 +0000209
210BreakableToken::Split
211BreakableStringLiteral::getSplit(unsigned LineIndex, unsigned TailOffset,
Krasimir Georgiev17725d82017-03-08 08:55:12 +0000212 unsigned ColumnLimit,
213 llvm::Regex &CommentPragmasRegex) const {
Alexander Kornienko81e32942013-09-16 20:20:49 +0000214 return getStringSplit(Line.substr(TailOffset),
215 StartColumn + Prefix.size() + Postfix.size(),
216 ColumnLimit, Style.TabWidth, Encoding);
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000217}
218
Alexander Kornienko555efc32013-06-11 16:01:49 +0000219void BreakableStringLiteral::insertBreak(unsigned LineIndex,
220 unsigned TailOffset, Split Split,
Alexander Kornienko555efc32013-06-11 16:01:49 +0000221 WhitespaceManager &Whitespaces) {
222 Whitespaces.replaceWhitespaceInToken(
223 Tok, Prefix.size() + TailOffset + Split.first, Split.second, Postfix,
Alexander Kornienkod4fa2e62017-04-11 09:55:00 +0000224 Prefix, InPPDirective, 1, StartColumn);
Alexander Kornienko555efc32013-06-11 16:01:49 +0000225}
226
Krasimir Georgiev91834222017-01-25 13:58:58 +0000227BreakableComment::BreakableComment(const FormatToken &Token,
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000228 unsigned StartColumn,
Krasimir Georgiev4b159222017-02-21 10:54:50 +0000229 bool InPPDirective,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000230 encoding::Encoding Encoding,
231 const FormatStyle &Style)
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000232 : BreakableToken(Token, InPPDirective, Encoding, Style),
Krasimir Georgiev4b159222017-02-21 10:54:50 +0000233 StartColumn(StartColumn) {}
Manuel Klimek9043c742013-05-27 15:23:34 +0000234
Krasimir Georgiev91834222017-01-25 13:58:58 +0000235unsigned BreakableComment::getLineCount() const { return Lines.size(); }
236
Krasimir Georgiev17725d82017-03-08 08:55:12 +0000237BreakableToken::Split
238BreakableComment::getSplit(unsigned LineIndex, unsigned TailOffset,
239 unsigned ColumnLimit,
240 llvm::Regex &CommentPragmasRegex) const {
241 // Don't break lines matching the comment pragmas regex.
242 if (CommentPragmasRegex.match(Content[LineIndex]))
243 return Split(StringRef::npos, 0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000244 return getCommentSplit(Content[LineIndex].substr(TailOffset),
245 getContentStartColumn(LineIndex, TailOffset),
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000246 ColumnLimit, Style.TabWidth, Encoding);
Manuel Klimek9043c742013-05-27 15:23:34 +0000247}
248
Krasimir Georgiev91834222017-01-25 13:58:58 +0000249void BreakableComment::compressWhitespace(unsigned LineIndex,
250 unsigned TailOffset, Split Split,
251 WhitespaceManager &Whitespaces) {
252 StringRef Text = Content[LineIndex].substr(TailOffset);
253 // Text is relative to the content line, but Whitespaces operates relative to
254 // the start of the corresponding token, so compute the start of the Split
255 // that needs to be compressed into a single space relative to the start of
256 // its token.
257 unsigned BreakOffsetInToken =
258 Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
259 unsigned CharsToRemove = Split.second;
Alexander Kornienko555efc32013-06-11 16:01:49 +0000260 Whitespaces.replaceWhitespaceInToken(
Krasimir Georgiev91834222017-01-25 13:58:58 +0000261 tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", "",
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000262 /*InPPDirective=*/false, /*Newlines=*/0, /*Spaces=*/1);
Alexander Kornienko875395f2013-11-12 17:50:13 +0000263}
264
Krasimir Georgiev91834222017-01-25 13:58:58 +0000265BreakableToken::Split
266BreakableComment::getReflowSplit(StringRef Text, StringRef ReflowPrefix,
267 unsigned PreviousEndColumn,
268 unsigned ColumnLimit) const {
269 unsigned ReflowStartColumn = PreviousEndColumn + ReflowPrefix.size();
270 StringRef TrimmedText = Text.rtrim(Blanks);
271 // This is the width of the resulting line in case the full line of Text gets
272 // reflown up starting at ReflowStartColumn.
273 unsigned FullWidth = ReflowStartColumn + encoding::columnWidthWithTabs(
274 TrimmedText, ReflowStartColumn,
275 Style.TabWidth, Encoding);
276 // If the full line fits up, we return a reflow split after it,
277 // otherwise we compute the largest piece of text that fits after
278 // ReflowStartColumn.
279 Split ReflowSplit =
280 FullWidth <= ColumnLimit
281 ? Split(TrimmedText.size(), Text.size() - TrimmedText.size())
282 : getCommentSplit(Text, ReflowStartColumn, ColumnLimit,
283 Style.TabWidth, Encoding);
Alexander Kornienko555efc32013-06-11 16:01:49 +0000284
Krasimir Georgiev91834222017-01-25 13:58:58 +0000285 // We need to be extra careful here, because while it's OK to keep a long line
286 // if it can't be broken into smaller pieces (like when the first word of a
287 // long line is longer than the column limit), it's not OK to reflow that long
288 // word up. So we recompute the size of the previous line after reflowing and
289 // only return the reflow split if that's under the line limit.
290 if (ReflowSplit.first != StringRef::npos &&
291 // Check if the width of the newly reflown line is under the limit.
292 PreviousEndColumn + ReflowPrefix.size() +
293 encoding::columnWidthWithTabs(Text.substr(0, ReflowSplit.first),
294 PreviousEndColumn +
295 ReflowPrefix.size(),
296 Style.TabWidth, Encoding) <=
297 ColumnLimit) {
298 return ReflowSplit;
Alexander Kornienko555efc32013-06-11 16:01:49 +0000299 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000300 return Split(StringRef::npos, 0);
301}
302
303const FormatToken &BreakableComment::tokenAt(unsigned LineIndex) const {
304 return Tokens[LineIndex] ? *Tokens[LineIndex] : Tok;
305}
306
307static bool mayReflowContent(StringRef Content) {
308 Content = Content.trim(Blanks);
Krasimir Georgiev28912c02017-02-02 10:52:08 +0000309 // Lines starting with '@' commonly have special meaning.
Francois Ferranda881be82017-05-22 14:47:17 +0000310 // Lines starting with '-', '-#', '+' or '*' are bulleted/numbered lists.
311 static const SmallVector<StringRef, 8> kSpecialMeaningPrefixes = {
312 "@", "TODO", "FIXME", "XXX", "-# ", "- ", "+ ", "* " };
Krasimir Georgiev28912c02017-02-02 10:52:08 +0000313 bool hasSpecialMeaningPrefix = false;
314 for (StringRef Prefix : kSpecialMeaningPrefixes) {
315 if (Content.startswith(Prefix)) {
316 hasSpecialMeaningPrefix = true;
317 break;
318 }
319 }
Francois Ferranda881be82017-05-22 14:47:17 +0000320
321 // Numbered lists may also start with a number followed by '.'
322 // To avoid issues if a line starts with a number which is actually the end
323 // of a previous line, we only consider numbers with up to 2 digits.
324 static llvm::Regex kNumberedListRegexp = llvm::Regex("^[1-9][0-9]?\\. ");
325 hasSpecialMeaningPrefix = hasSpecialMeaningPrefix ||
326 kNumberedListRegexp.match(Content);
327
Krasimir Georgiev91834222017-01-25 13:58:58 +0000328 // Simple heuristic for what to reflow: content should contain at least two
329 // characters and either the first or second character must be
330 // non-punctuation.
Krasimir Georgiev28912c02017-02-02 10:52:08 +0000331 return Content.size() >= 2 && !hasSpecialMeaningPrefix &&
332 !Content.endswith("\\") &&
Krasimir Georgiev91834222017-01-25 13:58:58 +0000333 // Note that this is UTF-8 safe, since if isPunctuation(Content[0]) is
334 // true, then the first code point must be 1 byte long.
335 (!isPunctuation(Content[0]) || !isPunctuation(Content[1]));
336}
337
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000338BreakableBlockComment::BreakableBlockComment(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000339 const FormatToken &Token, unsigned StartColumn,
Alexander Kornienkobe633902013-06-14 11:46:10 +0000340 unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective,
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000341 encoding::Encoding Encoding, const FormatStyle &Style)
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000342 : BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style),
343 DelimitersOnNewline(false) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000344 assert(Tok.is(TT_BlockComment) &&
345 "block comment section must start with a block comment");
346
347 StringRef TokenText(Tok.TokenText);
Manuel Klimek9043c742013-05-27 15:23:34 +0000348 assert(TokenText.startswith("/*") && TokenText.endswith("*/"));
349 TokenText.substr(2, TokenText.size() - 4).split(Lines, "\n");
350
351 int IndentDelta = StartColumn - OriginalStartColumn;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000352 Content.resize(Lines.size());
353 Content[0] = Lines[0];
354 ContentColumn.resize(Lines.size());
355 // Account for the initial '/*'.
356 ContentColumn[0] = StartColumn + 2;
357 Tokens.resize(Lines.size());
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000358 for (size_t i = 1; i < Lines.size(); ++i)
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000359 adjustWhitespace(i, IndentDelta);
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000360
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000361 // Align decorations with the column of the star on the first line,
362 // that is one column after the start "/*".
363 DecorationColumn = StartColumn + 1;
364
365 // Account for comment decoration patterns like this:
366 //
367 // /*
368 // ** blah blah blah
369 // */
370 if (Lines.size() >= 2 && Content[1].startswith("**") &&
371 static_cast<unsigned>(ContentColumn[1]) == StartColumn) {
372 DecorationColumn = StartColumn;
373 }
374
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000375 Decoration = "* ";
Manuel Klimek9043c742013-05-27 15:23:34 +0000376 if (Lines.size() == 1 && !FirstInLine) {
377 // Comments for which FirstInLine is false can start on arbitrary column,
378 // and available horizontal space can be too small to align consecutive
379 // lines with the first one.
380 // FIXME: We could, probably, align them to current indentation level, but
381 // now we just wrap them without stars.
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000382 Decoration = "";
Manuel Klimek9043c742013-05-27 15:23:34 +0000383 }
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000384 for (size_t i = 1, e = Lines.size(); i < e && !Decoration.empty(); ++i) {
385 // If the last line is empty, the closing "*/" will have a star.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000386 if (i + 1 == e && Content[i].empty())
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000387 break;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000388 if (!Content[i].empty() && i + 1 != e &&
389 Decoration.startswith(Content[i]))
Daniel Jasper6d9b88d2015-05-06 07:17:22 +0000390 continue;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000391 while (!Content[i].startswith(Decoration))
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000392 Decoration = Decoration.substr(0, Decoration.size() - 1);
Manuel Klimek9043c742013-05-27 15:23:34 +0000393 }
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000394
395 LastLineNeedsDecoration = true;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000396 IndentAtLineBreak = ContentColumn[0] + 1;
397 for (size_t i = 1, e = Lines.size(); i < e; ++i) {
398 if (Content[i].empty()) {
399 if (i + 1 == e) {
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000400 // Empty last line means that we already have a star as a part of the
401 // trailing */. We also need to preserve whitespace, so that */ is
402 // correctly indented.
403 LastLineNeedsDecoration = false;
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000404 // Align the star in the last '*/' with the stars on the previous lines.
405 if (e >= 2 && !Decoration.empty()) {
406 ContentColumn[i] = DecorationColumn;
407 }
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000408 } else if (Decoration.empty()) {
409 // For all other lines, set the start column to 0 if they're empty, so
410 // we do not insert trailing whitespace anywhere.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000411 ContentColumn[i] = 0;
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000412 }
Manuel Klimek9043c742013-05-27 15:23:34 +0000413 continue;
414 }
Daniel Jasper6d9b88d2015-05-06 07:17:22 +0000415
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000416 // The first line already excludes the star.
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000417 // The last line excludes the star if LastLineNeedsDecoration is false.
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000418 // For all other lines, adjust the line to exclude the star and
419 // (optionally) the first whitespace.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000420 unsigned DecorationSize = Decoration.startswith(Content[i])
421 ? Content[i].size()
422 : Decoration.size();
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000423 if (DecorationSize) {
424 ContentColumn[i] = DecorationColumn + DecorationSize;
425 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000426 Content[i] = Content[i].substr(DecorationSize);
427 if (!Decoration.startswith(Content[i]))
Daniel Jasper6d9b88d2015-05-06 07:17:22 +0000428 IndentAtLineBreak =
Krasimir Georgiev91834222017-01-25 13:58:58 +0000429 std::min<int>(IndentAtLineBreak, std::max(0, ContentColumn[i]));
Manuel Klimek9043c742013-05-27 15:23:34 +0000430 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000431 IndentAtLineBreak =
432 std::max<unsigned>(IndentAtLineBreak, Decoration.size());
433
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000434 // Detect a multiline jsdoc comment and set DelimitersOnNewline in that case.
435 if (Style.Language == FormatStyle::LK_JavaScript ||
436 Style.Language == FormatStyle::LK_Java) {
437 if ((Lines[0] == "*" || Lines[0].startswith("* ")) && Lines.size() > 1) {
438 // This is a multiline jsdoc comment.
439 DelimitersOnNewline = true;
440 } else if (Lines[0].startswith("* ") && Lines.size() == 1) {
441 // Detect a long single-line comment, like:
442 // /** long long long */
443 // Below, '2' is the width of '*/'.
444 unsigned EndColumn = ContentColumn[0] + encoding::columnWidthWithTabs(
445 Lines[0], ContentColumn[0], Style.TabWidth, Encoding) + 2;
446 DelimitersOnNewline = EndColumn > Style.ColumnLimit;
447 }
448 }
449
Manuel Klimek9043c742013-05-27 15:23:34 +0000450 DEBUG({
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000451 llvm::dbgs() << "IndentAtLineBreak " << IndentAtLineBreak << "\n";
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000452 llvm::dbgs() << "DelimitersOnNewline " << DelimitersOnNewline << "\n";
Manuel Klimek9043c742013-05-27 15:23:34 +0000453 for (size_t i = 0; i < Lines.size(); ++i) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000454 llvm::dbgs() << i << " |" << Content[i] << "| "
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000455 << "CC=" << ContentColumn[i] << "| "
456 << "IN=" << (Content[i].data() - Lines[i].data()) << "\n";
Manuel Klimek9043c742013-05-27 15:23:34 +0000457 }
458 });
459}
460
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000461void BreakableBlockComment::adjustWhitespace(unsigned LineIndex,
Manuel Klimek9043c742013-05-27 15:23:34 +0000462 int IndentDelta) {
Alexander Kornienkobe633902013-06-14 11:46:10 +0000463 // When in a preprocessor directive, the trailing backslash in a block comment
464 // is not needed, but can serve a purpose of uniformity with necessary escaped
465 // newlines outside the comment. In this case we remove it here before
466 // trimming the trailing whitespace. The backslash will be re-added later when
467 // inserting a line break.
468 size_t EndOfPreviousLine = Lines[LineIndex - 1].size();
469 if (InPPDirective && Lines[LineIndex - 1].endswith("\\"))
470 --EndOfPreviousLine;
471
Manuel Klimek9043c742013-05-27 15:23:34 +0000472 // Calculate the end of the non-whitespace text in the previous line.
Alexander Kornienkobe633902013-06-14 11:46:10 +0000473 EndOfPreviousLine =
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000474 Lines[LineIndex - 1].find_last_not_of(Blanks, EndOfPreviousLine);
Manuel Klimek9043c742013-05-27 15:23:34 +0000475 if (EndOfPreviousLine == StringRef::npos)
476 EndOfPreviousLine = 0;
477 else
478 ++EndOfPreviousLine;
479 // Calculate the start of the non-whitespace text in the current line.
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000480 size_t StartOfLine = Lines[LineIndex].find_first_not_of(Blanks);
Manuel Klimek9043c742013-05-27 15:23:34 +0000481 if (StartOfLine == StringRef::npos)
Daniel Jasperd6e61882015-06-17 12:23:15 +0000482 StartOfLine = Lines[LineIndex].rtrim("\r\n").size();
Manuel Klimek9043c742013-05-27 15:23:34 +0000483
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000484 StringRef Whitespace = Lines[LineIndex].substr(0, StartOfLine);
Manuel Klimek9043c742013-05-27 15:23:34 +0000485 // Adjust Lines to only contain relevant text.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000486 size_t PreviousContentOffset =
487 Content[LineIndex - 1].data() - Lines[LineIndex - 1].data();
488 Content[LineIndex - 1] = Lines[LineIndex - 1].substr(
489 PreviousContentOffset, EndOfPreviousLine - PreviousContentOffset);
490 Content[LineIndex] = Lines[LineIndex].substr(StartOfLine);
Manuel Klimek34d15152013-05-28 10:01:59 +0000491
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000492 // Adjust the start column uniformly across all lines.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000493 ContentColumn[LineIndex] =
Alexander Kornienko39856b72013-09-10 09:38:25 +0000494 encoding::columnWidthWithTabs(Whitespace, 0, Style.TabWidth, Encoding) +
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000495 IndentDelta;
Manuel Klimek9043c742013-05-27 15:23:34 +0000496}
497
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000498unsigned BreakableBlockComment::getLineLengthAfterSplit(
Krasimir Georgiev91834222017-01-25 13:58:58 +0000499 unsigned LineIndex, unsigned TailOffset,
500 StringRef::size_type Length) const {
501 unsigned ContentStartColumn = getContentStartColumn(LineIndex, TailOffset);
502 unsigned LineLength =
503 ContentStartColumn + encoding::columnWidthWithTabs(
504 Content[LineIndex].substr(TailOffset, Length),
505 ContentStartColumn, Style.TabWidth, Encoding);
506 // The last line gets a "*/" postfix.
507 if (LineIndex + 1 == Lines.size()) {
508 LineLength += 2;
509 // We never need a decoration when breaking just the trailing "*/" postfix.
510 // Note that checking that Length == 0 is not enough, since Length could
511 // also be StringRef::npos.
512 if (Content[LineIndex].substr(TailOffset, Length).empty()) {
513 LineLength -= Decoration.size();
514 }
515 }
516 return LineLength;
Manuel Klimek9043c742013-05-27 15:23:34 +0000517}
518
519void BreakableBlockComment::insertBreak(unsigned LineIndex, unsigned TailOffset,
Alexander Kornienkobe633902013-06-14 11:46:10 +0000520 Split Split,
Manuel Klimek9043c742013-05-27 15:23:34 +0000521 WhitespaceManager &Whitespaces) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000522 StringRef Text = Content[LineIndex].substr(TailOffset);
Manuel Klimek9043c742013-05-27 15:23:34 +0000523 StringRef Prefix = Decoration;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000524 // We need this to account for the case when we have a decoration "* " for all
525 // the lines except for the last one, where the star in "*/" acts as a
526 // decoration.
527 unsigned LocalIndentAtLineBreak = IndentAtLineBreak;
Manuel Klimek9043c742013-05-27 15:23:34 +0000528 if (LineIndex + 1 == Lines.size() &&
529 Text.size() == Split.first + Split.second) {
530 // For the last line we need to break before "*/", but not to add "* ".
531 Prefix = "";
Krasimir Georgiev91834222017-01-25 13:58:58 +0000532 if (LocalIndentAtLineBreak >= 2)
533 LocalIndentAtLineBreak -= 2;
534 }
535 // The split offset is from the beginning of the line. Convert it to an offset
536 // from the beginning of the token text.
537 unsigned BreakOffsetInToken =
538 Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
539 unsigned CharsToRemove = Split.second;
540 assert(LocalIndentAtLineBreak >= Prefix.size());
541 Whitespaces.replaceWhitespaceInToken(
542 tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", Prefix,
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000543 InPPDirective, /*Newlines=*/1,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000544 /*Spaces=*/LocalIndentAtLineBreak - Prefix.size());
545}
546
547BreakableToken::Split BreakableBlockComment::getSplitBefore(
548 unsigned LineIndex,
549 unsigned PreviousEndColumn,
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000550 unsigned ColumnLimit,
551 llvm::Regex &CommentPragmasRegex) const {
552 if (!mayReflow(LineIndex, CommentPragmasRegex))
Krasimir Georgiev91834222017-01-25 13:58:58 +0000553 return Split(StringRef::npos, 0);
554 StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
555 return getReflowSplit(TrimmedContent, ReflowPrefix, PreviousEndColumn,
556 ColumnLimit);
557}
558
559unsigned BreakableBlockComment::getReflownColumn(
560 StringRef Content,
561 unsigned LineIndex,
562 unsigned PreviousEndColumn) const {
563 unsigned StartColumn = PreviousEndColumn + ReflowPrefix.size();
564 // If this is the last line, it will carry around its '*/' postfix.
565 unsigned PostfixLength = (LineIndex + 1 == Lines.size() ? 2 : 0);
566 // The line is composed of previous text, reflow prefix, reflown text and
567 // postfix.
568 unsigned ReflownColumn =
569 StartColumn + encoding::columnWidthWithTabs(Content, StartColumn,
570 Style.TabWidth, Encoding) +
571 PostfixLength;
572 return ReflownColumn;
573}
574
575unsigned BreakableBlockComment::getLineLengthAfterSplitBefore(
576 unsigned LineIndex, unsigned TailOffset,
577 unsigned PreviousEndColumn,
578 unsigned ColumnLimit,
579 Split SplitBefore) const {
Krasimir Georgievaf1b9622017-01-31 14:31:44 +0000580 if (SplitBefore.first == StringRef::npos ||
581 // Block comment line contents contain the trailing whitespace after the
582 // decoration, so the need of left trim. Note that this behavior is
583 // consistent with the breaking of block comments where the indentation of
584 // a broken line is uniform across all the lines of the block comment.
585 SplitBefore.first + SplitBefore.second <
586 Content[LineIndex].ltrim().size()) {
587 // A piece of line, not the whole, gets reflown.
588 return getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000589 } else {
590 // The whole line gets reflown, need to check if we need to insert a break
591 // for the postfix or not.
592 StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
593 unsigned ReflownColumn =
594 getReflownColumn(TrimmedContent, LineIndex, PreviousEndColumn);
595 if (ReflownColumn <= ColumnLimit) {
596 return ReflownColumn;
597 }
598 return getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
599 }
600}
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000601
Krasimir Georgiev91834222017-01-25 13:58:58 +0000602void BreakableBlockComment::replaceWhitespaceBefore(
603 unsigned LineIndex, unsigned PreviousEndColumn, unsigned ColumnLimit,
604 Split SplitBefore, WhitespaceManager &Whitespaces) {
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000605 if (LineIndex == 0) {
606 if (DelimitersOnNewline) {
607 // Since we're breaking af index 1 below, the break position and the
608 // break length are the same.
609 size_t BreakLength = Lines[0].substr(1).find_first_not_of(Blanks);
610 if (BreakLength != StringRef::npos) {
611 insertBreak(LineIndex, 0, Split(1, BreakLength), Whitespaces);
612 DelimitersOnNewline = true;
613 }
614 }
615 return;
616 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000617 StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
618 if (SplitBefore.first != StringRef::npos) {
619 // Here we need to reflow.
620 assert(Tokens[LineIndex - 1] == Tokens[LineIndex] &&
621 "Reflowing whitespace within a token");
622 // This is the offset of the end of the last line relative to the start of
623 // the token text in the token.
624 unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
625 Content[LineIndex - 1].size() -
626 tokenAt(LineIndex).TokenText.data();
627 unsigned WhitespaceLength = TrimmedContent.data() -
628 tokenAt(LineIndex).TokenText.data() -
629 WhitespaceOffsetInToken;
630 Whitespaces.replaceWhitespaceInToken(
631 tokenAt(LineIndex), WhitespaceOffsetInToken,
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000632 /*ReplaceChars=*/WhitespaceLength, /*PreviousPostfix=*/"",
633 /*CurrentPrefix=*/ReflowPrefix, InPPDirective, /*Newlines=*/0,
634 /*Spaces=*/0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000635 // Check if we need to also insert a break at the whitespace range.
636 // For this we first adapt the reflow split relative to the beginning of the
637 // content.
638 // Note that we don't need a penalty for this break, since it doesn't change
639 // the total number of lines.
640 Split BreakSplit = SplitBefore;
641 BreakSplit.first += TrimmedContent.data() - Content[LineIndex].data();
642 unsigned ReflownColumn =
643 getReflownColumn(TrimmedContent, LineIndex, PreviousEndColumn);
644 if (ReflownColumn > ColumnLimit) {
645 insertBreak(LineIndex, 0, BreakSplit, Whitespaces);
646 }
647 return;
Manuel Klimek9043c742013-05-27 15:23:34 +0000648 }
649
Krasimir Georgiev91834222017-01-25 13:58:58 +0000650 // Here no reflow with the previous line will happen.
651 // Fix the decoration of the line at LineIndex.
Manuel Klimek9043c742013-05-27 15:23:34 +0000652 StringRef Prefix = Decoration;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000653 if (Content[LineIndex].empty()) {
Manuel Klimek281dcbe2013-05-28 08:55:01 +0000654 if (LineIndex + 1 == Lines.size()) {
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000655 if (!LastLineNeedsDecoration) {
656 // If the last line was empty, we don't need a prefix, as the */ will
657 // line up with the decoration (if it exists).
658 Prefix = "";
659 }
Manuel Klimek281dcbe2013-05-28 08:55:01 +0000660 } else if (!Decoration.empty()) {
661 // For other empty lines, if we do have a decoration, adapt it to not
662 // contain a trailing whitespace.
663 Prefix = Prefix.substr(0, 1);
664 }
Daniel Jasper51fb2b22013-05-30 06:40:07 +0000665 } else {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000666 if (ContentColumn[LineIndex] == 1) {
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000667 // This line starts immediately after the decorating *.
Daniel Jasper51fb2b22013-05-30 06:40:07 +0000668 Prefix = Prefix.substr(0, 1);
669 }
Manuel Klimek281dcbe2013-05-28 08:55:01 +0000670 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000671 // This is the offset of the end of the last line relative to the start of the
672 // token text in the token.
673 unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
674 Content[LineIndex - 1].size() -
675 tokenAt(LineIndex).TokenText.data();
676 unsigned WhitespaceLength = Content[LineIndex].data() -
677 tokenAt(LineIndex).TokenText.data() -
678 WhitespaceOffsetInToken;
Alexander Kornienko555efc32013-06-11 16:01:49 +0000679 Whitespaces.replaceWhitespaceInToken(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000680 tokenAt(LineIndex), WhitespaceOffsetInToken, WhitespaceLength, "", Prefix,
681 InPPDirective, /*Newlines=*/1, ContentColumn[LineIndex] - Prefix.size());
Manuel Klimek9043c742013-05-27 15:23:34 +0000682}
683
Krasimir Georgiev3b865342017-08-09 09:42:32 +0000684BreakableToken::Split
685BreakableBlockComment::getSplitAfterLastLine(unsigned TailOffset,
686 unsigned ColumnLimit) const {
687 if (DelimitersOnNewline) {
688 // Replace the trailing whitespace of the last line with a newline.
689 // In case the last line is empty, the ending '*/' is already on its own
690 // line.
691 StringRef Line = Content.back().substr(TailOffset);
692 StringRef TrimmedLine = Line.rtrim(Blanks);
693 if (!TrimmedLine.empty())
694 return Split(TrimmedLine.size(), Line.size() - TrimmedLine.size());
695 }
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000696 return Split(StringRef::npos, 0);
697}
698
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000699bool BreakableBlockComment::mayReflow(unsigned LineIndex,
700 llvm::Regex &CommentPragmasRegex) const {
701 // Content[LineIndex] may exclude the indent after the '*' decoration. In that
702 // case, we compute the start of the comment pragma manually.
703 StringRef IndentContent = Content[LineIndex];
704 if (Lines[LineIndex].ltrim(Blanks).startswith("*")) {
705 IndentContent = Lines[LineIndex].ltrim(Blanks).substr(1);
706 }
707 return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
708 mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
709 !switchesFormatting(tokenAt(LineIndex));
710}
711
Manuel Klimek9043c742013-05-27 15:23:34 +0000712unsigned
713BreakableBlockComment::getContentStartColumn(unsigned LineIndex,
714 unsigned TailOffset) const {
715 // If we break, we always break at the predefined indent.
716 if (TailOffset != 0)
717 return IndentAtLineBreak;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000718 return std::max(0, ContentColumn[LineIndex]);
719}
720
721BreakableLineCommentSection::BreakableLineCommentSection(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000722 const FormatToken &Token, unsigned StartColumn,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000723 unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective,
724 encoding::Encoding Encoding, const FormatStyle &Style)
Krasimir Georgiev4b159222017-02-21 10:54:50 +0000725 : BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000726 assert(Tok.is(TT_LineComment) &&
727 "line comment section must start with a line comment");
728 FormatToken *LineTok = nullptr;
729 for (const FormatToken *CurrentTok = &Tok;
730 CurrentTok && CurrentTok->is(TT_LineComment);
731 CurrentTok = CurrentTok->Next) {
732 LastLineTok = LineTok;
733 StringRef TokenText(CurrentTok->TokenText);
734 assert(TokenText.startswith("//"));
735 size_t FirstLineIndex = Lines.size();
736 TokenText.split(Lines, "\n");
737 Content.resize(Lines.size());
738 ContentColumn.resize(Lines.size());
739 OriginalContentColumn.resize(Lines.size());
740 Tokens.resize(Lines.size());
741 Prefix.resize(Lines.size());
742 OriginalPrefix.resize(Lines.size());
743 for (size_t i = FirstLineIndex, e = Lines.size(); i < e; ++i) {
Krasimir Georgieve518e0b2017-01-30 21:00:01 +0000744 // We need to trim the blanks in case this is not the first line in a
745 // multiline comment. Then the indent is included in Lines[i].
746 StringRef IndentPrefix =
747 getLineCommentIndentPrefix(Lines[i].ltrim(Blanks));
748 assert(IndentPrefix.startswith("//"));
Krasimir Georgiev91834222017-01-25 13:58:58 +0000749 OriginalPrefix[i] = Prefix[i] = IndentPrefix;
750 if (Lines[i].size() > Prefix[i].size() &&
751 isAlphanumeric(Lines[i][Prefix[i].size()])) {
752 if (Prefix[i] == "//")
753 Prefix[i] = "// ";
754 else if (Prefix[i] == "///")
755 Prefix[i] = "/// ";
756 else if (Prefix[i] == "//!")
757 Prefix[i] = "//! ";
Krasimir Georgievba6b3152017-05-18 07:36:21 +0000758 else if (Prefix[i] == "///<")
759 Prefix[i] = "///< ";
760 else if (Prefix[i] == "//!<")
761 Prefix[i] = "//!< ";
Krasimir Georgiev91834222017-01-25 13:58:58 +0000762 }
763
764 Tokens[i] = LineTok;
765 Content[i] = Lines[i].substr(IndentPrefix.size());
766 OriginalContentColumn[i] =
767 StartColumn +
768 encoding::columnWidthWithTabs(OriginalPrefix[i],
769 StartColumn,
770 Style.TabWidth,
771 Encoding);
772 ContentColumn[i] =
773 StartColumn +
774 encoding::columnWidthWithTabs(Prefix[i],
775 StartColumn,
776 Style.TabWidth,
777 Encoding);
778
779 // Calculate the end of the non-whitespace text in this line.
780 size_t EndOfLine = Content[i].find_last_not_of(Blanks);
781 if (EndOfLine == StringRef::npos)
782 EndOfLine = Content[i].size();
783 else
784 ++EndOfLine;
785 Content[i] = Content[i].substr(0, EndOfLine);
786 }
787 LineTok = CurrentTok->Next;
Krasimir Georgievb6ccd382017-02-02 14:36:50 +0000788 if (CurrentTok->Next && !CurrentTok->Next->ContinuesLineCommentSection) {
Krasimir Georgiev753625b2017-01-31 13:32:38 +0000789 // A line comment section needs to broken by a line comment that is
790 // preceded by at least two newlines. Note that we put this break here
791 // instead of breaking at a previous stage during parsing, since that
792 // would split the contents of the enum into two unwrapped lines in this
793 // example, which is undesirable:
794 // enum A {
795 // a, // comment about a
796 //
797 // // comment about b
798 // b
799 // };
800 //
801 // FIXME: Consider putting separate line comment sections as children to
802 // the unwrapped line instead.
803 break;
804 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000805 }
806}
807
808unsigned BreakableLineCommentSection::getLineLengthAfterSplit(
809 unsigned LineIndex, unsigned TailOffset,
810 StringRef::size_type Length) const {
811 unsigned ContentStartColumn =
812 (TailOffset == 0 ? ContentColumn[LineIndex]
813 : OriginalContentColumn[LineIndex]);
814 return ContentStartColumn + encoding::columnWidthWithTabs(
815 Content[LineIndex].substr(TailOffset, Length),
816 ContentStartColumn, Style.TabWidth, Encoding);
817}
818
819void BreakableLineCommentSection::insertBreak(unsigned LineIndex,
820 unsigned TailOffset, Split Split,
821 WhitespaceManager &Whitespaces) {
822 StringRef Text = Content[LineIndex].substr(TailOffset);
823 // Compute the offset of the split relative to the beginning of the token
824 // text.
825 unsigned BreakOffsetInToken =
826 Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
827 unsigned CharsToRemove = Split.second;
828 // Compute the size of the new indent, including the size of the new prefix of
829 // the newly broken line.
830 unsigned IndentAtLineBreak = OriginalContentColumn[LineIndex] +
831 Prefix[LineIndex].size() -
832 OriginalPrefix[LineIndex].size();
833 assert(IndentAtLineBreak >= Prefix[LineIndex].size());
834 Whitespaces.replaceWhitespaceInToken(
835 tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "",
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000836 Prefix[LineIndex], InPPDirective, /*Newlines=*/1,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000837 /*Spaces=*/IndentAtLineBreak - Prefix[LineIndex].size());
838}
839
840BreakableComment::Split BreakableLineCommentSection::getSplitBefore(
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000841 unsigned LineIndex, unsigned PreviousEndColumn, unsigned ColumnLimit,
842 llvm::Regex &CommentPragmasRegex) const {
843 if (!mayReflow(LineIndex, CommentPragmasRegex))
844 return Split(StringRef::npos, 0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000845 return getReflowSplit(Content[LineIndex], ReflowPrefix, PreviousEndColumn,
846 ColumnLimit);
847}
848
849unsigned BreakableLineCommentSection::getLineLengthAfterSplitBefore(
850 unsigned LineIndex, unsigned TailOffset,
851 unsigned PreviousEndColumn,
852 unsigned ColumnLimit,
853 Split SplitBefore) const {
854 if (SplitBefore.first == StringRef::npos ||
855 SplitBefore.first + SplitBefore.second < Content[LineIndex].size()) {
856 // A piece of line, not the whole line, gets reflown.
857 return getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
858 } else {
859 // The whole line gets reflown.
860 unsigned StartColumn = PreviousEndColumn + ReflowPrefix.size();
861 return StartColumn + encoding::columnWidthWithTabs(Content[LineIndex],
862 StartColumn,
863 Style.TabWidth,
864 Encoding);
865 }
866}
867
868void BreakableLineCommentSection::replaceWhitespaceBefore(
869 unsigned LineIndex, unsigned PreviousEndColumn, unsigned ColumnLimit,
870 Split SplitBefore, WhitespaceManager &Whitespaces) {
871 // If this is the first line of a token, we need to inform Whitespace Manager
872 // about it: either adapt the whitespace range preceding it, or mark it as an
873 // untouchable token.
874 // This happens for instance here:
875 // // line 1 \
876 // // line 2
877 if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) {
878 if (SplitBefore.first != StringRef::npos) {
879 // Reflow happens between tokens. Replace the whitespace between the
880 // tokens by the empty string.
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000881 Whitespaces.replaceWhitespace(
882 *Tokens[LineIndex], /*Newlines=*/0, /*Spaces=*/0,
883 /*StartOfTokenColumn=*/StartColumn, /*InPPDirective=*/false);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000884 // Replace the indent and prefix of the token with the reflow prefix.
885 unsigned WhitespaceLength =
886 Content[LineIndex].data() - tokenAt(LineIndex).TokenText.data();
887 Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex],
888 /*Offset=*/0,
889 /*ReplaceChars=*/WhitespaceLength,
890 /*PreviousPostfix=*/"",
891 /*CurrentPrefix=*/ReflowPrefix,
892 /*InPPDirective=*/false,
893 /*Newlines=*/0,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000894 /*Spaces=*/0);
895 } else {
896 // This is the first line for the current token, but no reflow with the
897 // previous token is necessary. However, we still may need to adjust the
Krasimir Georgievb796ceb2017-01-31 15:40:15 +0000898 // start column. Note that ContentColumn[LineIndex] is the expected
899 // content column after a possible update to the prefix, hence the prefix
900 // length change is included.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000901 unsigned LineColumn =
902 ContentColumn[LineIndex] -
Krasimir Georgievb796ceb2017-01-31 15:40:15 +0000903 (Content[LineIndex].data() - Lines[LineIndex].data()) +
904 (OriginalPrefix[LineIndex].size() - Prefix[LineIndex].size());
Krasimir Georgiev13dbaa02017-02-01 10:10:04 +0000905
906 // We always want to create a replacement instead of adding an untouchable
907 // token, even if LineColumn is the same as the original column of the
908 // token. This is because WhitespaceManager doesn't align trailing
909 // comments if they are untouchable.
910 Whitespaces.replaceWhitespace(*Tokens[LineIndex],
911 /*Newlines=*/1,
912 /*Spaces=*/LineColumn,
913 /*StartOfTokenColumn=*/LineColumn,
914 /*InPPDirective=*/false);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000915 }
Krasimir Georgievb796ceb2017-01-31 15:40:15 +0000916 }
917 if (OriginalPrefix[LineIndex] != Prefix[LineIndex]) {
918 // Adjust the prefix if necessary.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000919
920 // Take care of the space possibly introduced after a decoration.
921 assert(Prefix[LineIndex] == (OriginalPrefix[LineIndex] + " ").str() &&
Krasimir Georgievb796ceb2017-01-31 15:40:15 +0000922 "Expecting a line comment prefix to differ from original by at most "
923 "a space");
Krasimir Georgiev91834222017-01-25 13:58:58 +0000924 Whitespaces.replaceWhitespaceInToken(
925 tokenAt(LineIndex), OriginalPrefix[LineIndex].size(), 0, "", "",
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000926 /*InPPDirective=*/false, /*Newlines=*/0, /*Spaces=*/1);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000927 }
928 // Add a break after a reflow split has been introduced, if necessary.
929 // Note that this break doesn't need to be penalized, since it doesn't change
930 // the number of lines.
931 if (SplitBefore.first != StringRef::npos &&
932 SplitBefore.first + SplitBefore.second < Content[LineIndex].size()) {
933 insertBreak(LineIndex, 0, SplitBefore, Whitespaces);
934 }
935}
936
937void BreakableLineCommentSection::updateNextToken(LineState& State) const {
938 if (LastLineTok) {
939 State.NextToken = LastLineTok->Next;
940 }
941}
942
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000943bool BreakableLineCommentSection::mayReflow(
944 unsigned LineIndex, llvm::Regex &CommentPragmasRegex) const {
945 // Line comments have the indent as part of the prefix, so we need to
946 // recompute the start of the line.
947 StringRef IndentContent = Content[LineIndex];
948 if (Lines[LineIndex].startswith("//")) {
949 IndentContent = Lines[LineIndex].substr(2);
950 }
951 return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
952 mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
953 !switchesFormatting(tokenAt(LineIndex)) &&
954 OriginalPrefix[LineIndex] == OriginalPrefix[LineIndex - 1];
955}
956
Krasimir Georgiev91834222017-01-25 13:58:58 +0000957unsigned
958BreakableLineCommentSection::getContentStartColumn(unsigned LineIndex,
959 unsigned TailOffset) const {
960 if (TailOffset != 0) {
961 return OriginalContentColumn[LineIndex];
962 }
963 return ContentColumn[LineIndex];
Manuel Klimek9043c742013-05-27 15:23:34 +0000964}
965
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000966} // namespace format
967} // namespace clang