blob: bbf3d88eec45556b34025d735afc4f9913b52599 [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) {
Manuel Klimek89628f62017-09-20 09:51:03 +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,
Manuel Klimek89628f62017-09-20 09:51:03 +0000228 unsigned StartColumn, bool InPPDirective,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000229 encoding::Encoding Encoding,
230 const FormatStyle &Style)
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000231 : BreakableToken(Token, InPPDirective, Encoding, Style),
Krasimir Georgiev4b159222017-02-21 10:54:50 +0000232 StartColumn(StartColumn) {}
Manuel Klimek9043c742013-05-27 15:23:34 +0000233
Krasimir Georgiev91834222017-01-25 13:58:58 +0000234unsigned BreakableComment::getLineCount() const { return Lines.size(); }
235
Krasimir Georgiev17725d82017-03-08 08:55:12 +0000236BreakableToken::Split
237BreakableComment::getSplit(unsigned LineIndex, unsigned TailOffset,
238 unsigned ColumnLimit,
239 llvm::Regex &CommentPragmasRegex) const {
240 // Don't break lines matching the comment pragmas regex.
241 if (CommentPragmasRegex.match(Content[LineIndex]))
242 return Split(StringRef::npos, 0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000243 return getCommentSplit(Content[LineIndex].substr(TailOffset),
244 getContentStartColumn(LineIndex, TailOffset),
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000245 ColumnLimit, Style.TabWidth, Encoding);
Manuel Klimek9043c742013-05-27 15:23:34 +0000246}
247
Krasimir Georgiev91834222017-01-25 13:58:58 +0000248void BreakableComment::compressWhitespace(unsigned LineIndex,
249 unsigned TailOffset, Split Split,
250 WhitespaceManager &Whitespaces) {
251 StringRef Text = Content[LineIndex].substr(TailOffset);
252 // Text is relative to the content line, but Whitespaces operates relative to
253 // the start of the corresponding token, so compute the start of the Split
254 // that needs to be compressed into a single space relative to the start of
255 // its token.
256 unsigned BreakOffsetInToken =
257 Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
258 unsigned CharsToRemove = Split.second;
Alexander Kornienko555efc32013-06-11 16:01:49 +0000259 Whitespaces.replaceWhitespaceInToken(
Krasimir Georgiev91834222017-01-25 13:58:58 +0000260 tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", "",
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000261 /*InPPDirective=*/false, /*Newlines=*/0, /*Spaces=*/1);
Alexander Kornienko875395f2013-11-12 17:50:13 +0000262}
263
Krasimir Georgiev91834222017-01-25 13:58:58 +0000264BreakableToken::Split
265BreakableComment::getReflowSplit(StringRef Text, StringRef ReflowPrefix,
266 unsigned PreviousEndColumn,
267 unsigned ColumnLimit) const {
268 unsigned ReflowStartColumn = PreviousEndColumn + ReflowPrefix.size();
269 StringRef TrimmedText = Text.rtrim(Blanks);
270 // This is the width of the resulting line in case the full line of Text gets
271 // reflown up starting at ReflowStartColumn.
272 unsigned FullWidth = ReflowStartColumn + encoding::columnWidthWithTabs(
273 TrimmedText, ReflowStartColumn,
274 Style.TabWidth, Encoding);
275 // If the full line fits up, we return a reflow split after it,
276 // otherwise we compute the largest piece of text that fits after
277 // ReflowStartColumn.
278 Split ReflowSplit =
279 FullWidth <= ColumnLimit
280 ? Split(TrimmedText.size(), Text.size() - TrimmedText.size())
281 : getCommentSplit(Text, ReflowStartColumn, ColumnLimit,
282 Style.TabWidth, Encoding);
Alexander Kornienko555efc32013-06-11 16:01:49 +0000283
Krasimir Georgiev91834222017-01-25 13:58:58 +0000284 // We need to be extra careful here, because while it's OK to keep a long line
285 // if it can't be broken into smaller pieces (like when the first word of a
286 // long line is longer than the column limit), it's not OK to reflow that long
287 // word up. So we recompute the size of the previous line after reflowing and
288 // only return the reflow split if that's under the line limit.
289 if (ReflowSplit.first != StringRef::npos &&
290 // Check if the width of the newly reflown line is under the limit.
291 PreviousEndColumn + ReflowPrefix.size() +
292 encoding::columnWidthWithTabs(Text.substr(0, ReflowSplit.first),
293 PreviousEndColumn +
294 ReflowPrefix.size(),
295 Style.TabWidth, Encoding) <=
296 ColumnLimit) {
297 return ReflowSplit;
Alexander Kornienko555efc32013-06-11 16:01:49 +0000298 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000299 return Split(StringRef::npos, 0);
300}
301
302const FormatToken &BreakableComment::tokenAt(unsigned LineIndex) const {
303 return Tokens[LineIndex] ? *Tokens[LineIndex] : Tok;
304}
305
306static bool mayReflowContent(StringRef Content) {
307 Content = Content.trim(Blanks);
Krasimir Georgiev28912c02017-02-02 10:52:08 +0000308 // Lines starting with '@' commonly have special meaning.
Francois Ferranda881be82017-05-22 14:47:17 +0000309 // Lines starting with '-', '-#', '+' or '*' are bulleted/numbered lists.
310 static const SmallVector<StringRef, 8> kSpecialMeaningPrefixes = {
Manuel Klimek89628f62017-09-20 09:51:03 +0000311 "@", "TODO", "FIXME", "XXX", "-# ", "- ", "+ ", "* "};
Krasimir Georgiev28912c02017-02-02 10:52:08 +0000312 bool hasSpecialMeaningPrefix = false;
313 for (StringRef Prefix : kSpecialMeaningPrefixes) {
314 if (Content.startswith(Prefix)) {
315 hasSpecialMeaningPrefix = true;
316 break;
317 }
318 }
Francois Ferranda881be82017-05-22 14:47:17 +0000319
320 // Numbered lists may also start with a number followed by '.'
321 // To avoid issues if a line starts with a number which is actually the end
322 // of a previous line, we only consider numbers with up to 2 digits.
323 static llvm::Regex kNumberedListRegexp = llvm::Regex("^[1-9][0-9]?\\. ");
Manuel Klimek89628f62017-09-20 09:51:03 +0000324 hasSpecialMeaningPrefix =
325 hasSpecialMeaningPrefix || kNumberedListRegexp.match(Content);
Francois Ferranda881be82017-05-22 14:47:17 +0000326
Krasimir Georgiev91834222017-01-25 13:58:58 +0000327 // Simple heuristic for what to reflow: content should contain at least two
328 // characters and either the first or second character must be
329 // non-punctuation.
Krasimir Georgiev28912c02017-02-02 10:52:08 +0000330 return Content.size() >= 2 && !hasSpecialMeaningPrefix &&
331 !Content.endswith("\\") &&
Krasimir Georgiev91834222017-01-25 13:58:58 +0000332 // Note that this is UTF-8 safe, since if isPunctuation(Content[0]) is
333 // true, then the first code point must be 1 byte long.
334 (!isPunctuation(Content[0]) || !isPunctuation(Content[1]));
335}
336
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000337BreakableBlockComment::BreakableBlockComment(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000338 const FormatToken &Token, unsigned StartColumn,
Alexander Kornienkobe633902013-06-14 11:46:10 +0000339 unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective,
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000340 encoding::Encoding Encoding, const FormatStyle &Style)
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000341 : BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style),
342 DelimitersOnNewline(false) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000343 assert(Tok.is(TT_BlockComment) &&
344 "block comment section must start with a block comment");
345
346 StringRef TokenText(Tok.TokenText);
Manuel Klimek9043c742013-05-27 15:23:34 +0000347 assert(TokenText.startswith("/*") && TokenText.endswith("*/"));
348 TokenText.substr(2, TokenText.size() - 4).split(Lines, "\n");
349
350 int IndentDelta = StartColumn - OriginalStartColumn;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000351 Content.resize(Lines.size());
352 Content[0] = Lines[0];
353 ContentColumn.resize(Lines.size());
354 // Account for the initial '/*'.
355 ContentColumn[0] = StartColumn + 2;
356 Tokens.resize(Lines.size());
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000357 for (size_t i = 1; i < Lines.size(); ++i)
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000358 adjustWhitespace(i, IndentDelta);
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000359
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000360 // Align decorations with the column of the star on the first line,
361 // that is one column after the start "/*".
362 DecorationColumn = StartColumn + 1;
363
364 // Account for comment decoration patterns like this:
365 //
366 // /*
367 // ** blah blah blah
368 // */
369 if (Lines.size() >= 2 && Content[1].startswith("**") &&
370 static_cast<unsigned>(ContentColumn[1]) == StartColumn) {
371 DecorationColumn = StartColumn;
372 }
373
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000374 Decoration = "* ";
Manuel Klimek9043c742013-05-27 15:23:34 +0000375 if (Lines.size() == 1 && !FirstInLine) {
376 // Comments for which FirstInLine is false can start on arbitrary column,
377 // and available horizontal space can be too small to align consecutive
378 // lines with the first one.
379 // FIXME: We could, probably, align them to current indentation level, but
380 // now we just wrap them without stars.
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000381 Decoration = "";
Manuel Klimek9043c742013-05-27 15:23:34 +0000382 }
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000383 for (size_t i = 1, e = Lines.size(); i < e && !Decoration.empty(); ++i) {
384 // If the last line is empty, the closing "*/" will have a star.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000385 if (i + 1 == e && Content[i].empty())
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000386 break;
Manuel Klimek89628f62017-09-20 09:51:03 +0000387 if (!Content[i].empty() && i + 1 != e && Decoration.startswith(Content[i]))
Daniel Jasper6d9b88d2015-05-06 07:17:22 +0000388 continue;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000389 while (!Content[i].startswith(Decoration))
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000390 Decoration = Decoration.substr(0, Decoration.size() - 1);
Manuel Klimek9043c742013-05-27 15:23:34 +0000391 }
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000392
393 LastLineNeedsDecoration = true;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000394 IndentAtLineBreak = ContentColumn[0] + 1;
395 for (size_t i = 1, e = Lines.size(); i < e; ++i) {
396 if (Content[i].empty()) {
397 if (i + 1 == e) {
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000398 // Empty last line means that we already have a star as a part of the
399 // trailing */. We also need to preserve whitespace, so that */ is
400 // correctly indented.
401 LastLineNeedsDecoration = false;
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000402 // Align the star in the last '*/' with the stars on the previous lines.
403 if (e >= 2 && !Decoration.empty()) {
404 ContentColumn[i] = DecorationColumn;
405 }
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000406 } else if (Decoration.empty()) {
407 // For all other lines, set the start column to 0 if they're empty, so
408 // we do not insert trailing whitespace anywhere.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000409 ContentColumn[i] = 0;
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000410 }
Manuel Klimek9043c742013-05-27 15:23:34 +0000411 continue;
412 }
Daniel Jasper6d9b88d2015-05-06 07:17:22 +0000413
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000414 // The first line already excludes the star.
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000415 // The last line excludes the star if LastLineNeedsDecoration is false.
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000416 // For all other lines, adjust the line to exclude the star and
417 // (optionally) the first whitespace.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000418 unsigned DecorationSize = Decoration.startswith(Content[i])
419 ? Content[i].size()
420 : Decoration.size();
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000421 if (DecorationSize) {
422 ContentColumn[i] = DecorationColumn + DecorationSize;
423 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000424 Content[i] = Content[i].substr(DecorationSize);
425 if (!Decoration.startswith(Content[i]))
Daniel Jasper6d9b88d2015-05-06 07:17:22 +0000426 IndentAtLineBreak =
Krasimir Georgiev91834222017-01-25 13:58:58 +0000427 std::min<int>(IndentAtLineBreak, std::max(0, ContentColumn[i]));
Manuel Klimek9043c742013-05-27 15:23:34 +0000428 }
Manuel Klimek89628f62017-09-20 09:51:03 +0000429 IndentAtLineBreak = std::max<unsigned>(IndentAtLineBreak, Decoration.size());
Krasimir Georgiev91834222017-01-25 13:58:58 +0000430
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000431 // Detect a multiline jsdoc comment and set DelimitersOnNewline in that case.
432 if (Style.Language == FormatStyle::LK_JavaScript ||
433 Style.Language == FormatStyle::LK_Java) {
434 if ((Lines[0] == "*" || Lines[0].startswith("* ")) && Lines.size() > 1) {
435 // This is a multiline jsdoc comment.
436 DelimitersOnNewline = true;
437 } else if (Lines[0].startswith("* ") && Lines.size() == 1) {
438 // Detect a long single-line comment, like:
439 // /** long long long */
440 // Below, '2' is the width of '*/'.
Manuel Klimek89628f62017-09-20 09:51:03 +0000441 unsigned EndColumn =
442 ContentColumn[0] +
443 encoding::columnWidthWithTabs(Lines[0], ContentColumn[0],
444 Style.TabWidth, Encoding) +
445 2;
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000446 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(
Krasimir Georgiev33bd8522017-08-24 16:41:10 +0000548 unsigned LineIndex, unsigned PreviousEndColumn, unsigned ColumnLimit,
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000549 llvm::Regex &CommentPragmasRegex) const {
550 if (!mayReflow(LineIndex, CommentPragmasRegex))
Krasimir Georgiev91834222017-01-25 13:58:58 +0000551 return Split(StringRef::npos, 0);
552 StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
Krasimir Georgiev33bd8522017-08-24 16:41:10 +0000553 Split Result = getReflowSplit(TrimmedContent, ReflowPrefix, PreviousEndColumn,
554 ColumnLimit);
555 // Result is relative to TrimmedContent. Adapt it relative to
556 // Content[LineIndex].
557 if (Result.first != StringRef::npos)
558 Result.first += Content[LineIndex].size() - TrimmedContent.size();
559 return Result;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000560}
561
Manuel Klimek89628f62017-09-20 09:51:03 +0000562unsigned
563BreakableBlockComment::getReflownColumn(StringRef Content, unsigned LineIndex,
564 unsigned PreviousEndColumn) const {
565 unsigned StartColumn = PreviousEndColumn + ReflowPrefix.size();
566 // If this is the last line, it will carry around its '*/' postfix.
567 unsigned PostfixLength = (LineIndex + 1 == Lines.size() ? 2 : 0);
568 // The line is composed of previous text, reflow prefix, reflown text and
569 // postfix.
570 unsigned ReflownColumn = StartColumn +
571 encoding::columnWidthWithTabs(
572 Content, StartColumn, Style.TabWidth, Encoding) +
573 PostfixLength;
574 return ReflownColumn;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000575}
576
577unsigned BreakableBlockComment::getLineLengthAfterSplitBefore(
Manuel Klimek89628f62017-09-20 09:51:03 +0000578 unsigned LineIndex, unsigned TailOffset, unsigned PreviousEndColumn,
579 unsigned ColumnLimit, 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 Georgiev35599fd2017-10-16 09:08:53 +0000602bool BreakableBlockComment::introducesBreakBefore(unsigned LineIndex) const {
603 // A break is introduced when we want delimiters on newline.
604 return LineIndex == 0 && DelimitersOnNewline &&
605 Lines[0].substr(1).find_first_not_of(Blanks) != StringRef::npos;
606}
607
Krasimir Georgiev91834222017-01-25 13:58:58 +0000608void BreakableBlockComment::replaceWhitespaceBefore(
609 unsigned LineIndex, unsigned PreviousEndColumn, unsigned ColumnLimit,
610 Split SplitBefore, WhitespaceManager &Whitespaces) {
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000611 if (LineIndex == 0) {
612 if (DelimitersOnNewline) {
Manuel Klimek89628f62017-09-20 09:51:03 +0000613 // Since we're breaking af index 1 below, the break position and the
614 // break length are the same.
615 size_t BreakLength = Lines[0].substr(1).find_first_not_of(Blanks);
616 if (BreakLength != StringRef::npos) {
617 insertBreak(LineIndex, 0, Split(1, BreakLength), Whitespaces);
618 DelimitersOnNewline = true;
619 }
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000620 }
621 return;
622 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000623 StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
624 if (SplitBefore.first != StringRef::npos) {
625 // Here we need to reflow.
626 assert(Tokens[LineIndex - 1] == Tokens[LineIndex] &&
627 "Reflowing whitespace within a token");
628 // This is the offset of the end of the last line relative to the start of
629 // the token text in the token.
630 unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
Manuel Klimek89628f62017-09-20 09:51:03 +0000631 Content[LineIndex - 1].size() -
632 tokenAt(LineIndex).TokenText.data();
Krasimir Georgiev91834222017-01-25 13:58:58 +0000633 unsigned WhitespaceLength = TrimmedContent.data() -
Manuel Klimek89628f62017-09-20 09:51:03 +0000634 tokenAt(LineIndex).TokenText.data() -
635 WhitespaceOffsetInToken;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000636 Whitespaces.replaceWhitespaceInToken(
637 tokenAt(LineIndex), WhitespaceOffsetInToken,
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000638 /*ReplaceChars=*/WhitespaceLength, /*PreviousPostfix=*/"",
639 /*CurrentPrefix=*/ReflowPrefix, InPPDirective, /*Newlines=*/0,
640 /*Spaces=*/0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000641 // Check if we need to also insert a break at the whitespace range.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000642 // Note that we don't need a penalty for this break, since it doesn't change
643 // the total number of lines.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000644 unsigned ReflownColumn =
645 getReflownColumn(TrimmedContent, LineIndex, PreviousEndColumn);
Krasimir Georgiev33bd8522017-08-24 16:41:10 +0000646 if (ReflownColumn > ColumnLimit)
647 insertBreak(LineIndex, 0, SplitBefore, Whitespaces);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000648 return;
Manuel Klimek9043c742013-05-27 15:23:34 +0000649 }
650
Krasimir Georgiev91834222017-01-25 13:58:58 +0000651 // Here no reflow with the previous line will happen.
652 // Fix the decoration of the line at LineIndex.
Manuel Klimek9043c742013-05-27 15:23:34 +0000653 StringRef Prefix = Decoration;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000654 if (Content[LineIndex].empty()) {
Manuel Klimek281dcbe2013-05-28 08:55:01 +0000655 if (LineIndex + 1 == Lines.size()) {
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000656 if (!LastLineNeedsDecoration) {
657 // If the last line was empty, we don't need a prefix, as the */ will
658 // line up with the decoration (if it exists).
659 Prefix = "";
660 }
Manuel Klimek281dcbe2013-05-28 08:55:01 +0000661 } else if (!Decoration.empty()) {
662 // For other empty lines, if we do have a decoration, adapt it to not
663 // contain a trailing whitespace.
664 Prefix = Prefix.substr(0, 1);
665 }
Daniel Jasper51fb2b22013-05-30 06:40:07 +0000666 } else {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000667 if (ContentColumn[LineIndex] == 1) {
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000668 // This line starts immediately after the decorating *.
Daniel Jasper51fb2b22013-05-30 06:40:07 +0000669 Prefix = Prefix.substr(0, 1);
670 }
Manuel Klimek281dcbe2013-05-28 08:55:01 +0000671 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000672 // This is the offset of the end of the last line relative to the start of the
673 // token text in the token.
674 unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
675 Content[LineIndex - 1].size() -
676 tokenAt(LineIndex).TokenText.data();
677 unsigned WhitespaceLength = Content[LineIndex].data() -
678 tokenAt(LineIndex).TokenText.data() -
679 WhitespaceOffsetInToken;
Alexander Kornienko555efc32013-06-11 16:01:49 +0000680 Whitespaces.replaceWhitespaceInToken(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000681 tokenAt(LineIndex), WhitespaceOffsetInToken, WhitespaceLength, "", Prefix,
682 InPPDirective, /*Newlines=*/1, ContentColumn[LineIndex] - Prefix.size());
Manuel Klimek9043c742013-05-27 15:23:34 +0000683}
684
Krasimir Georgiev3b865342017-08-09 09:42:32 +0000685BreakableToken::Split
686BreakableBlockComment::getSplitAfterLastLine(unsigned TailOffset,
687 unsigned ColumnLimit) const {
688 if (DelimitersOnNewline) {
689 // Replace the trailing whitespace of the last line with a newline.
690 // In case the last line is empty, the ending '*/' is already on its own
691 // line.
692 StringRef Line = Content.back().substr(TailOffset);
693 StringRef TrimmedLine = Line.rtrim(Blanks);
694 if (!TrimmedLine.empty())
695 return Split(TrimmedLine.size(), Line.size() - TrimmedLine.size());
696 }
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000697 return Split(StringRef::npos, 0);
698}
699
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000700bool BreakableBlockComment::mayReflow(unsigned LineIndex,
701 llvm::Regex &CommentPragmasRegex) const {
702 // Content[LineIndex] may exclude the indent after the '*' decoration. In that
703 // case, we compute the start of the comment pragma manually.
704 StringRef IndentContent = Content[LineIndex];
705 if (Lines[LineIndex].ltrim(Blanks).startswith("*")) {
706 IndentContent = Lines[LineIndex].ltrim(Blanks).substr(1);
707 }
708 return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
709 mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
710 !switchesFormatting(tokenAt(LineIndex));
711}
712
Manuel Klimek9043c742013-05-27 15:23:34 +0000713unsigned
714BreakableBlockComment::getContentStartColumn(unsigned LineIndex,
715 unsigned TailOffset) const {
716 // If we break, we always break at the predefined indent.
717 if (TailOffset != 0)
718 return IndentAtLineBreak;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000719 return std::max(0, ContentColumn[LineIndex]);
720}
721
722BreakableLineCommentSection::BreakableLineCommentSection(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000723 const FormatToken &Token, unsigned StartColumn,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000724 unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective,
725 encoding::Encoding Encoding, const FormatStyle &Style)
Krasimir Georgiev4b159222017-02-21 10:54:50 +0000726 : BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000727 assert(Tok.is(TT_LineComment) &&
728 "line comment section must start with a line comment");
729 FormatToken *LineTok = nullptr;
730 for (const FormatToken *CurrentTok = &Tok;
731 CurrentTok && CurrentTok->is(TT_LineComment);
732 CurrentTok = CurrentTok->Next) {
733 LastLineTok = LineTok;
734 StringRef TokenText(CurrentTok->TokenText);
735 assert(TokenText.startswith("//"));
736 size_t FirstLineIndex = Lines.size();
737 TokenText.split(Lines, "\n");
738 Content.resize(Lines.size());
739 ContentColumn.resize(Lines.size());
740 OriginalContentColumn.resize(Lines.size());
741 Tokens.resize(Lines.size());
742 Prefix.resize(Lines.size());
743 OriginalPrefix.resize(Lines.size());
744 for (size_t i = FirstLineIndex, e = Lines.size(); i < e; ++i) {
Krasimir Georgieve518e0b2017-01-30 21:00:01 +0000745 // We need to trim the blanks in case this is not the first line in a
746 // multiline comment. Then the indent is included in Lines[i].
747 StringRef IndentPrefix =
748 getLineCommentIndentPrefix(Lines[i].ltrim(Blanks));
749 assert(IndentPrefix.startswith("//"));
Krasimir Georgiev91834222017-01-25 13:58:58 +0000750 OriginalPrefix[i] = Prefix[i] = IndentPrefix;
751 if (Lines[i].size() > Prefix[i].size() &&
752 isAlphanumeric(Lines[i][Prefix[i].size()])) {
753 if (Prefix[i] == "//")
754 Prefix[i] = "// ";
755 else if (Prefix[i] == "///")
756 Prefix[i] = "/// ";
757 else if (Prefix[i] == "//!")
758 Prefix[i] = "//! ";
Krasimir Georgievba6b3152017-05-18 07:36:21 +0000759 else if (Prefix[i] == "///<")
760 Prefix[i] = "///< ";
761 else if (Prefix[i] == "//!<")
762 Prefix[i] = "//!< ";
Krasimir Georgiev91834222017-01-25 13:58:58 +0000763 }
764
765 Tokens[i] = LineTok;
766 Content[i] = Lines[i].substr(IndentPrefix.size());
767 OriginalContentColumn[i] =
Manuel Klimek89628f62017-09-20 09:51:03 +0000768 StartColumn + encoding::columnWidthWithTabs(OriginalPrefix[i],
769 StartColumn,
770 Style.TabWidth, Encoding);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000771 ContentColumn[i] =
Manuel Klimek89628f62017-09-20 09:51:03 +0000772 StartColumn + encoding::columnWidthWithTabs(Prefix[i], StartColumn,
773 Style.TabWidth, Encoding);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000774
775 // Calculate the end of the non-whitespace text in this line.
776 size_t EndOfLine = Content[i].find_last_not_of(Blanks);
777 if (EndOfLine == StringRef::npos)
778 EndOfLine = Content[i].size();
779 else
780 ++EndOfLine;
781 Content[i] = Content[i].substr(0, EndOfLine);
782 }
783 LineTok = CurrentTok->Next;
Krasimir Georgievb6ccd382017-02-02 14:36:50 +0000784 if (CurrentTok->Next && !CurrentTok->Next->ContinuesLineCommentSection) {
Krasimir Georgiev753625b2017-01-31 13:32:38 +0000785 // A line comment section needs to broken by a line comment that is
786 // preceded by at least two newlines. Note that we put this break here
787 // instead of breaking at a previous stage during parsing, since that
788 // would split the contents of the enum into two unwrapped lines in this
789 // example, which is undesirable:
790 // enum A {
791 // a, // comment about a
792 //
793 // // comment about b
794 // b
795 // };
796 //
797 // FIXME: Consider putting separate line comment sections as children to
798 // the unwrapped line instead.
799 break;
800 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000801 }
802}
803
804unsigned BreakableLineCommentSection::getLineLengthAfterSplit(
805 unsigned LineIndex, unsigned TailOffset,
806 StringRef::size_type Length) const {
807 unsigned ContentStartColumn =
808 (TailOffset == 0 ? ContentColumn[LineIndex]
809 : OriginalContentColumn[LineIndex]);
810 return ContentStartColumn + encoding::columnWidthWithTabs(
811 Content[LineIndex].substr(TailOffset, Length),
812 ContentStartColumn, Style.TabWidth, Encoding);
813}
814
815void BreakableLineCommentSection::insertBreak(unsigned LineIndex,
816 unsigned TailOffset, Split Split,
817 WhitespaceManager &Whitespaces) {
818 StringRef Text = Content[LineIndex].substr(TailOffset);
819 // Compute the offset of the split relative to the beginning of the token
820 // text.
821 unsigned BreakOffsetInToken =
822 Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
823 unsigned CharsToRemove = Split.second;
824 // Compute the size of the new indent, including the size of the new prefix of
825 // the newly broken line.
826 unsigned IndentAtLineBreak = OriginalContentColumn[LineIndex] +
827 Prefix[LineIndex].size() -
828 OriginalPrefix[LineIndex].size();
829 assert(IndentAtLineBreak >= Prefix[LineIndex].size());
830 Whitespaces.replaceWhitespaceInToken(
831 tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "",
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000832 Prefix[LineIndex], InPPDirective, /*Newlines=*/1,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000833 /*Spaces=*/IndentAtLineBreak - Prefix[LineIndex].size());
834}
835
836BreakableComment::Split BreakableLineCommentSection::getSplitBefore(
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000837 unsigned LineIndex, unsigned PreviousEndColumn, unsigned ColumnLimit,
838 llvm::Regex &CommentPragmasRegex) const {
839 if (!mayReflow(LineIndex, CommentPragmasRegex))
840 return Split(StringRef::npos, 0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000841 return getReflowSplit(Content[LineIndex], ReflowPrefix, PreviousEndColumn,
842 ColumnLimit);
843}
844
845unsigned BreakableLineCommentSection::getLineLengthAfterSplitBefore(
Manuel Klimek89628f62017-09-20 09:51:03 +0000846 unsigned LineIndex, unsigned TailOffset, unsigned PreviousEndColumn,
847 unsigned ColumnLimit, Split SplitBefore) const {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000848 if (SplitBefore.first == StringRef::npos ||
849 SplitBefore.first + SplitBefore.second < Content[LineIndex].size()) {
850 // A piece of line, not the whole line, gets reflown.
851 return getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
852 } else {
853 // The whole line gets reflown.
854 unsigned StartColumn = PreviousEndColumn + ReflowPrefix.size();
Manuel Klimek89628f62017-09-20 09:51:03 +0000855 return StartColumn +
856 encoding::columnWidthWithTabs(Content[LineIndex], StartColumn,
857 Style.TabWidth, Encoding);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000858 }
859}
860
861void BreakableLineCommentSection::replaceWhitespaceBefore(
862 unsigned LineIndex, unsigned PreviousEndColumn, unsigned ColumnLimit,
863 Split SplitBefore, WhitespaceManager &Whitespaces) {
864 // If this is the first line of a token, we need to inform Whitespace Manager
865 // about it: either adapt the whitespace range preceding it, or mark it as an
866 // untouchable token.
867 // This happens for instance here:
868 // // line 1 \
869 // // line 2
870 if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) {
871 if (SplitBefore.first != StringRef::npos) {
872 // Reflow happens between tokens. Replace the whitespace between the
873 // tokens by the empty string.
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000874 Whitespaces.replaceWhitespace(
875 *Tokens[LineIndex], /*Newlines=*/0, /*Spaces=*/0,
876 /*StartOfTokenColumn=*/StartColumn, /*InPPDirective=*/false);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000877 // Replace the indent and prefix of the token with the reflow prefix.
878 unsigned WhitespaceLength =
879 Content[LineIndex].data() - tokenAt(LineIndex).TokenText.data();
880 Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex],
881 /*Offset=*/0,
882 /*ReplaceChars=*/WhitespaceLength,
883 /*PreviousPostfix=*/"",
884 /*CurrentPrefix=*/ReflowPrefix,
885 /*InPPDirective=*/false,
886 /*Newlines=*/0,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000887 /*Spaces=*/0);
888 } else {
889 // This is the first line for the current token, but no reflow with the
890 // previous token is necessary. However, we still may need to adjust the
Krasimir Georgievb796ceb2017-01-31 15:40:15 +0000891 // start column. Note that ContentColumn[LineIndex] is the expected
892 // content column after a possible update to the prefix, hence the prefix
893 // length change is included.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000894 unsigned LineColumn =
895 ContentColumn[LineIndex] -
Krasimir Georgievb796ceb2017-01-31 15:40:15 +0000896 (Content[LineIndex].data() - Lines[LineIndex].data()) +
897 (OriginalPrefix[LineIndex].size() - Prefix[LineIndex].size());
Krasimir Georgiev13dbaa02017-02-01 10:10:04 +0000898
899 // We always want to create a replacement instead of adding an untouchable
900 // token, even if LineColumn is the same as the original column of the
901 // token. This is because WhitespaceManager doesn't align trailing
902 // comments if they are untouchable.
903 Whitespaces.replaceWhitespace(*Tokens[LineIndex],
904 /*Newlines=*/1,
905 /*Spaces=*/LineColumn,
906 /*StartOfTokenColumn=*/LineColumn,
907 /*InPPDirective=*/false);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000908 }
Krasimir Georgievb796ceb2017-01-31 15:40:15 +0000909 }
910 if (OriginalPrefix[LineIndex] != Prefix[LineIndex]) {
911 // Adjust the prefix if necessary.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000912
913 // Take care of the space possibly introduced after a decoration.
914 assert(Prefix[LineIndex] == (OriginalPrefix[LineIndex] + " ").str() &&
Krasimir Georgievb796ceb2017-01-31 15:40:15 +0000915 "Expecting a line comment prefix to differ from original by at most "
916 "a space");
Krasimir Georgiev91834222017-01-25 13:58:58 +0000917 Whitespaces.replaceWhitespaceInToken(
918 tokenAt(LineIndex), OriginalPrefix[LineIndex].size(), 0, "", "",
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000919 /*InPPDirective=*/false, /*Newlines=*/0, /*Spaces=*/1);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000920 }
921 // Add a break after a reflow split has been introduced, if necessary.
922 // Note that this break doesn't need to be penalized, since it doesn't change
923 // the number of lines.
924 if (SplitBefore.first != StringRef::npos &&
925 SplitBefore.first + SplitBefore.second < Content[LineIndex].size()) {
926 insertBreak(LineIndex, 0, SplitBefore, Whitespaces);
927 }
928}
929
Manuel Klimek89628f62017-09-20 09:51:03 +0000930void BreakableLineCommentSection::updateNextToken(LineState &State) const {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000931 if (LastLineTok) {
932 State.NextToken = LastLineTok->Next;
933 }
934}
935
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000936bool BreakableLineCommentSection::mayReflow(
937 unsigned LineIndex, llvm::Regex &CommentPragmasRegex) const {
938 // Line comments have the indent as part of the prefix, so we need to
939 // recompute the start of the line.
940 StringRef IndentContent = Content[LineIndex];
941 if (Lines[LineIndex].startswith("//")) {
942 IndentContent = Lines[LineIndex].substr(2);
943 }
944 return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
945 mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
946 !switchesFormatting(tokenAt(LineIndex)) &&
947 OriginalPrefix[LineIndex] == OriginalPrefix[LineIndex - 1];
948}
949
Krasimir Georgiev91834222017-01-25 13:58:58 +0000950unsigned
951BreakableLineCommentSection::getContentStartColumn(unsigned LineIndex,
952 unsigned TailOffset) const {
953 if (TailOffset != 0) {
954 return OriginalContentColumn[LineIndex];
955 }
956 return ContentColumn[LineIndex];
Manuel Klimek9043c742013-05-27 15:23:34 +0000957}
958
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000959} // namespace format
960} // namespace clang