blob: e6ce01b520b5ad83fc8453ae0bae88fbe0ce08cd [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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011/// Contains implementation of BreakableToken class and classes derived
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000012/// from it.
13///
14//===----------------------------------------------------------------------===//
15
16#include "BreakableToken.h"
Krasimir Georgiev91834222017-01-25 13:58:58 +000017#include "ContinuationIndenter.h"
Alexander Kornienko555efc32013-06-11 16:01:49 +000018#include "clang/Basic/CharInfo.h"
Manuel Klimek9043c742013-05-27 15:23:34 +000019#include "clang/Format/Format.h"
Alexander Kornienko9e90b622013-04-17 17:34:05 +000020#include "llvm/ADT/STLExtras.h"
Manuel Klimek9043c742013-05-27 15:23:34 +000021#include "llvm/Support/Debug.h"
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000022#include <algorithm>
23
Chandler Carruth10346662014-04-22 03:17:02 +000024#define DEBUG_TYPE "format-token-breaker"
25
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000026namespace clang {
27namespace format {
28
Daniel Jasper580da272013-10-30 07:36:40 +000029static const char *const Blanks = " \t\v\f\r";
Alexander Kornienkob93062e2013-06-20 13:58:37 +000030static bool IsBlank(char C) {
31 switch (C) {
Daniel Jasper3ac9b9e2013-07-08 14:34:09 +000032 case ' ':
33 case '\t':
34 case '\v':
35 case '\f':
Daniel Jasper580da272013-10-30 07:36:40 +000036 case '\r':
Daniel Jasper3ac9b9e2013-07-08 14:34:09 +000037 return true;
38 default:
39 return false;
Alexander Kornienkob93062e2013-06-20 13:58:37 +000040 }
41}
42
Krasimir Georgiev410ed242017-11-10 12:50:09 +000043static StringRef getLineCommentIndentPrefix(StringRef Comment,
44 const FormatStyle &Style) {
45 static const char *const KnownCStylePrefixes[] = {"///<", "//!<", "///", "//",
46 "//!"};
Krasimir Georgiev45dde412018-06-07 09:46:24 +000047 static const char *const KnownTextProtoPrefixes[] = {"//", "#", "##", "###",
48 "####"};
Krasimir Georgiev410ed242017-11-10 12:50:09 +000049 ArrayRef<const char *> KnownPrefixes(KnownCStylePrefixes);
50 if (Style.Language == FormatStyle::LK_TextProto)
51 KnownPrefixes = KnownTextProtoPrefixes;
52
Krasimir Georgiev91834222017-01-25 13:58:58 +000053 StringRef LongestPrefix;
54 for (StringRef KnownPrefix : KnownPrefixes) {
55 if (Comment.startswith(KnownPrefix)) {
56 size_t PrefixLength = KnownPrefix.size();
57 while (PrefixLength < Comment.size() && Comment[PrefixLength] == ' ')
58 ++PrefixLength;
59 if (PrefixLength > LongestPrefix.size())
60 LongestPrefix = Comment.substr(0, PrefixLength);
61 }
62 }
63 return LongestPrefix;
64}
65
Craig Topperbfb5c402013-07-01 03:38:29 +000066static BreakableToken::Split getCommentSplit(StringRef Text,
67 unsigned ContentStartColumn,
68 unsigned ColumnLimit,
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +000069 unsigned TabWidth,
Martin Probst9d717812018-08-02 11:52:08 +000070 encoding::Encoding Encoding,
71 const FormatStyle &Style) {
72 LLVM_DEBUG(llvm::dbgs() << "Comment split: \"" << Text
73 << "\", Column limit: " << ColumnLimit
74 << ", Content start: " << ContentStartColumn << "\n");
Alexander Kornienko9e90b622013-04-17 17:34:05 +000075 if (ColumnLimit <= ContentStartColumn + 1)
Manuel Klimek9043c742013-05-27 15:23:34 +000076 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienko9e90b622013-04-17 17:34:05 +000077
78 unsigned MaxSplit = ColumnLimit - ContentStartColumn + 1;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +000079 unsigned MaxSplitBytes = 0;
80
81 for (unsigned NumChars = 0;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +000082 NumChars < MaxSplit && MaxSplitBytes < Text.size();) {
83 unsigned BytesInChar =
Alexander Kornienkoffcc0102013-06-05 14:09:10 +000084 encoding::getCodePointNumBytes(Text[MaxSplitBytes], Encoding);
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +000085 NumChars +=
86 encoding::columnWidthWithTabs(Text.substr(MaxSplitBytes, BytesInChar),
87 ContentStartColumn, TabWidth, Encoding);
88 MaxSplitBytes += BytesInChar;
89 }
Alexander Kornienkoffcc0102013-06-05 14:09:10 +000090
Alexander Kornienkob93062e2013-06-20 13:58:37 +000091 StringRef::size_type SpaceOffset = Text.find_last_of(Blanks, MaxSplitBytes);
Francois Ferranda881be82017-05-22 14:47:17 +000092
Benjamin Kramerf76861c2018-03-20 21:52:19 +000093 static auto *const kNumberedListRegexp = new llvm::Regex("^[1-9][0-9]?\\.");
Martin Probstf326b6b2018-08-03 13:58:33 +000094 while (SpaceOffset != StringRef::npos) {
95 // Do not split before a number followed by a dot: this would be interpreted
96 // as a numbered list, which would prevent re-flowing in subsequent passes.
97 if (kNumberedListRegexp->match(Text.substr(SpaceOffset).ltrim(Blanks)))
98 SpaceOffset = Text.find_last_of(Blanks, SpaceOffset);
99 // In JavaScript, some @tags can be followed by {, and machinery that parses
100 // these comments will fail to understand the comment if followed by a line
101 // break. So avoid ever breaking before a {.
102 else if (Style.Language == FormatStyle::LK_JavaScript &&
103 SpaceOffset + 1 < Text.size() && Text[SpaceOffset + 1] == '{')
104 SpaceOffset = Text.find_last_of(Blanks, SpaceOffset);
105 else
106 break;
107 }
Francois Ferranda881be82017-05-22 14:47:17 +0000108
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000109 if (SpaceOffset == StringRef::npos ||
Manuel Klimek9043c742013-05-27 15:23:34 +0000110 // Don't break at leading whitespace.
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000111 Text.find_last_not_of(Blanks, SpaceOffset) == StringRef::npos) {
Manuel Klimekae1fbfb2013-05-29 22:06:18 +0000112 // Make sure that we don't break at leading whitespace that
113 // reaches past MaxSplit.
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000114 StringRef::size_type FirstNonWhitespace = Text.find_first_not_of(Blanks);
Manuel Klimekae1fbfb2013-05-29 22:06:18 +0000115 if (FirstNonWhitespace == StringRef::npos)
116 // If the comment is only whitespace, we cannot split.
117 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000118 SpaceOffset = Text.find_first_of(
119 Blanks, std::max<unsigned>(MaxSplitBytes, FirstNonWhitespace));
Manuel Klimekae1fbfb2013-05-29 22:06:18 +0000120 }
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000121 if (SpaceOffset != StringRef::npos && SpaceOffset != 0) {
Martin Probst9d717812018-08-02 11:52:08 +0000122 // adaptStartOfLine will break after lines starting with /** if the comment
123 // is broken anywhere. Avoid emitting this break twice here.
124 // Example: in /** longtextcomesherethatbreaks */ (with ColumnLimit 20) will
125 // insert a break after /**, so this code must not insert the same break.
126 if (SpaceOffset == 1 && Text[SpaceOffset - 1] == '*')
127 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000128 StringRef BeforeCut = Text.substr(0, SpaceOffset).rtrim(Blanks);
129 StringRef AfterCut = Text.substr(SpaceOffset).ltrim(Blanks);
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000130 return BreakableToken::Split(BeforeCut.size(),
131 AfterCut.begin() - BeforeCut.end());
132 }
133 return BreakableToken::Split(StringRef::npos, 0);
134}
135
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000136static BreakableToken::Split
137getStringSplit(StringRef Text, unsigned UsedColumns, unsigned ColumnLimit,
138 unsigned TabWidth, encoding::Encoding Encoding) {
Manuel Klimek9043c742013-05-27 15:23:34 +0000139 // FIXME: Reduce unit test case.
140 if (Text.empty())
141 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienko81e32942013-09-16 20:20:49 +0000142 if (ColumnLimit <= UsedColumns)
Manuel Klimek9043c742013-05-27 15:23:34 +0000143 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienko71d95d62013-11-26 10:38:53 +0000144 unsigned MaxSplit = ColumnLimit - UsedColumns;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000145 StringRef::size_type SpaceOffset = 0;
146 StringRef::size_type SlashOffset = 0;
Alexander Kornienko72852072013-06-19 14:22:47 +0000147 StringRef::size_type WordStartOffset = 0;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000148 StringRef::size_type SplitPoint = 0;
149 for (unsigned Chars = 0;;) {
150 unsigned Advance;
151 if (Text[0] == '\\') {
152 Advance = encoding::getEscapeSequenceLength(Text);
153 Chars += Advance;
154 } else {
155 Advance = encoding::getCodePointNumBytes(Text[0], Encoding);
Alexander Kornienko81e32942013-09-16 20:20:49 +0000156 Chars += encoding::columnWidthWithTabs(
157 Text.substr(0, Advance), UsedColumns + Chars, TabWidth, Encoding);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000158 }
159
Daniel Jaspere4b48c62015-01-21 19:50:35 +0000160 if (Chars > MaxSplit || Text.size() <= Advance)
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000161 break;
162
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000163 if (IsBlank(Text[0]))
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000164 SpaceOffset = SplitPoint;
165 if (Text[0] == '/')
166 SlashOffset = SplitPoint;
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000167 if (Advance == 1 && !isAlphanumeric(Text[0]))
Alexander Kornienko72852072013-06-19 14:22:47 +0000168 WordStartOffset = SplitPoint;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000169
170 SplitPoint += Advance;
171 Text = Text.substr(Advance);
172 }
173
174 if (SpaceOffset != 0)
175 return BreakableToken::Split(SpaceOffset + 1, 0);
176 if (SlashOffset != 0)
177 return BreakableToken::Split(SlashOffset + 1, 0);
Alexander Kornienko72852072013-06-19 14:22:47 +0000178 if (WordStartOffset != 0)
179 return BreakableToken::Split(WordStartOffset + 1, 0);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000180 if (SplitPoint != 0)
181 return BreakableToken::Split(SplitPoint, 0);
182 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000183}
184
Krasimir Georgiev91834222017-01-25 13:58:58 +0000185bool switchesFormatting(const FormatToken &Token) {
186 assert((Token.is(TT_BlockComment) || Token.is(TT_LineComment)) &&
187 "formatting regions are switched by comment tokens");
188 StringRef Content = Token.TokenText.substr(2).ltrim();
189 return Content.startswith("clang-format on") ||
190 Content.startswith("clang-format off");
191}
192
193unsigned
Manuel Klimek93699f42017-11-29 14:29:43 +0000194BreakableToken::getLengthAfterCompression(unsigned RemainingTokenColumns,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000195 Split Split) const {
196 // Example: consider the content
197 // lala lala
198 // - RemainingTokenColumns is the original number of columns, 10;
199 // - Split is (4, 2), denoting the two spaces between the two words;
200 //
201 // We compute the number of columns when the split is compressed into a single
202 // space, like:
203 // lala lala
Manuel Klimek93699f42017-11-29 14:29:43 +0000204 //
205 // FIXME: Correctly measure the length of whitespace in Split.second so it
206 // works with tabs.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000207 return RemainingTokenColumns + 1 - Split.second;
208}
209
Manuel Klimek93699f42017-11-29 14:29:43 +0000210unsigned BreakableStringLiteral::getLineCount() const { return 1; }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000211
Manuel Klimek93699f42017-11-29 14:29:43 +0000212unsigned BreakableStringLiteral::getRangeLength(unsigned LineIndex,
213 unsigned Offset,
214 StringRef::size_type Length,
215 unsigned StartColumn) const {
Manuel Klimek477f3692017-11-29 15:09:12 +0000216 llvm_unreachable("Getting the length of a part of the string literal "
217 "indicates that the code tries to reflow it.");
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000218}
219
Manuel Klimek93699f42017-11-29 14:29:43 +0000220unsigned
221BreakableStringLiteral::getRemainingLength(unsigned LineIndex, unsigned Offset,
222 unsigned StartColumn) const {
223 return UnbreakableTailLength + Postfix.size() +
224 encoding::columnWidthWithTabs(Line.substr(Offset, StringRef::npos),
225 StartColumn, Style.TabWidth, Encoding);
226}
227
228unsigned BreakableStringLiteral::getContentStartColumn(unsigned LineIndex,
229 bool Break) const {
230 return StartColumn + Prefix.size();
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000231}
232
Alexander Kornienko81e32942013-09-16 20:20:49 +0000233BreakableStringLiteral::BreakableStringLiteral(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000234 const FormatToken &Tok, unsigned StartColumn, StringRef Prefix,
Krasimir Georgiev55c23a12018-01-23 11:26:19 +0000235 StringRef Postfix, unsigned UnbreakableTailLength, bool InPPDirective,
236 encoding::Encoding Encoding, const FormatStyle &Style)
Manuel Klimek93699f42017-11-29 14:29:43 +0000237 : BreakableToken(Tok, InPPDirective, Encoding, Style),
238 StartColumn(StartColumn), Prefix(Prefix), Postfix(Postfix),
Krasimir Georgiev55c23a12018-01-23 11:26:19 +0000239 UnbreakableTailLength(UnbreakableTailLength) {
Manuel Klimek93699f42017-11-29 14:29:43 +0000240 assert(Tok.TokenText.startswith(Prefix) && Tok.TokenText.endswith(Postfix));
241 Line = Tok.TokenText.substr(
242 Prefix.size(), Tok.TokenText.size() - Prefix.size() - Postfix.size());
243}
Manuel Klimek9043c742013-05-27 15:23:34 +0000244
Manuel Klimek93699f42017-11-29 14:29:43 +0000245BreakableToken::Split BreakableStringLiteral::getSplit(
246 unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit,
247 unsigned ContentStartColumn, llvm::Regex &CommentPragmasRegex) const {
248 return getStringSplit(Line.substr(TailOffset), ContentStartColumn,
249 ColumnLimit - Postfix.size(), Style.TabWidth, Encoding);
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000250}
251
Alexander Kornienko555efc32013-06-11 16:01:49 +0000252void BreakableStringLiteral::insertBreak(unsigned LineIndex,
253 unsigned TailOffset, Split Split,
Krasimir Georgiev6a5c95b2018-07-30 08:45:45 +0000254 unsigned ContentIndent,
Manuel Klimek93699f42017-11-29 14:29:43 +0000255 WhitespaceManager &Whitespaces) const {
Alexander Kornienko555efc32013-06-11 16:01:49 +0000256 Whitespaces.replaceWhitespaceInToken(
257 Tok, Prefix.size() + TailOffset + Split.first, Split.second, Postfix,
Alexander Kornienkod4fa2e62017-04-11 09:55:00 +0000258 Prefix, InPPDirective, 1, StartColumn);
Alexander Kornienko555efc32013-06-11 16:01:49 +0000259}
260
Krasimir Georgiev91834222017-01-25 13:58:58 +0000261BreakableComment::BreakableComment(const FormatToken &Token,
Manuel Klimek89628f62017-09-20 09:51:03 +0000262 unsigned StartColumn, bool InPPDirective,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000263 encoding::Encoding Encoding,
264 const FormatStyle &Style)
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000265 : BreakableToken(Token, InPPDirective, Encoding, Style),
Krasimir Georgiev4b159222017-02-21 10:54:50 +0000266 StartColumn(StartColumn) {}
Manuel Klimek9043c742013-05-27 15:23:34 +0000267
Krasimir Georgiev91834222017-01-25 13:58:58 +0000268unsigned BreakableComment::getLineCount() const { return Lines.size(); }
269
Krasimir Georgiev17725d82017-03-08 08:55:12 +0000270BreakableToken::Split
271BreakableComment::getSplit(unsigned LineIndex, unsigned TailOffset,
Manuel Klimek93699f42017-11-29 14:29:43 +0000272 unsigned ColumnLimit, unsigned ContentStartColumn,
Krasimir Georgiev17725d82017-03-08 08:55:12 +0000273 llvm::Regex &CommentPragmasRegex) const {
274 // Don't break lines matching the comment pragmas regex.
275 if (CommentPragmasRegex.match(Content[LineIndex]))
276 return Split(StringRef::npos, 0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000277 return getCommentSplit(Content[LineIndex].substr(TailOffset),
Manuel Klimek93699f42017-11-29 14:29:43 +0000278 ContentStartColumn, ColumnLimit, Style.TabWidth,
Martin Probst9d717812018-08-02 11:52:08 +0000279 Encoding, Style);
Manuel Klimek9043c742013-05-27 15:23:34 +0000280}
281
Manuel Klimek93699f42017-11-29 14:29:43 +0000282void BreakableComment::compressWhitespace(
283 unsigned LineIndex, unsigned TailOffset, Split Split,
284 WhitespaceManager &Whitespaces) const {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000285 StringRef Text = Content[LineIndex].substr(TailOffset);
286 // Text is relative to the content line, but Whitespaces operates relative to
287 // the start of the corresponding token, so compute the start of the Split
288 // that needs to be compressed into a single space relative to the start of
289 // its token.
290 unsigned BreakOffsetInToken =
291 Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
292 unsigned CharsToRemove = Split.second;
Alexander Kornienko555efc32013-06-11 16:01:49 +0000293 Whitespaces.replaceWhitespaceInToken(
Krasimir Georgiev91834222017-01-25 13:58:58 +0000294 tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", "",
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000295 /*InPPDirective=*/false, /*Newlines=*/0, /*Spaces=*/1);
Alexander Kornienko875395f2013-11-12 17:50:13 +0000296}
297
Krasimir Georgiev91834222017-01-25 13:58:58 +0000298const FormatToken &BreakableComment::tokenAt(unsigned LineIndex) const {
299 return Tokens[LineIndex] ? *Tokens[LineIndex] : Tok;
300}
301
302static bool mayReflowContent(StringRef Content) {
303 Content = Content.trim(Blanks);
Krasimir Georgiev28912c02017-02-02 10:52:08 +0000304 // Lines starting with '@' commonly have special meaning.
Francois Ferranda881be82017-05-22 14:47:17 +0000305 // Lines starting with '-', '-#', '+' or '*' are bulleted/numbered lists.
Krasimir Georgiev28912c02017-02-02 10:52:08 +0000306 bool hasSpecialMeaningPrefix = false;
Benjamin Kramerf76861c2018-03-20 21:52:19 +0000307 for (StringRef Prefix :
308 {"@", "TODO", "FIXME", "XXX", "-# ", "- ", "+ ", "* "}) {
Krasimir Georgiev28912c02017-02-02 10:52:08 +0000309 if (Content.startswith(Prefix)) {
310 hasSpecialMeaningPrefix = true;
311 break;
312 }
313 }
Francois Ferranda881be82017-05-22 14:47:17 +0000314
315 // Numbered lists may also start with a number followed by '.'
316 // To avoid issues if a line starts with a number which is actually the end
317 // of a previous line, we only consider numbers with up to 2 digits.
Benjamin Kramerf76861c2018-03-20 21:52:19 +0000318 static auto *const kNumberedListRegexp = new llvm::Regex("^[1-9][0-9]?\\. ");
Manuel Klimek89628f62017-09-20 09:51:03 +0000319 hasSpecialMeaningPrefix =
Benjamin Kramerf76861c2018-03-20 21:52:19 +0000320 hasSpecialMeaningPrefix || kNumberedListRegexp->match(Content);
Francois Ferranda881be82017-05-22 14:47:17 +0000321
Krasimir Georgiev91834222017-01-25 13:58:58 +0000322 // Simple heuristic for what to reflow: content should contain at least two
323 // characters and either the first or second character must be
324 // non-punctuation.
Krasimir Georgiev28912c02017-02-02 10:52:08 +0000325 return Content.size() >= 2 && !hasSpecialMeaningPrefix &&
326 !Content.endswith("\\") &&
Krasimir Georgiev91834222017-01-25 13:58:58 +0000327 // Note that this is UTF-8 safe, since if isPunctuation(Content[0]) is
328 // true, then the first code point must be 1 byte long.
329 (!isPunctuation(Content[0]) || !isPunctuation(Content[1]));
330}
331
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000332BreakableBlockComment::BreakableBlockComment(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000333 const FormatToken &Token, unsigned StartColumn,
Alexander Kornienkobe633902013-06-14 11:46:10 +0000334 unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective,
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000335 encoding::Encoding Encoding, const FormatStyle &Style)
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000336 : BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style),
Manuel Klimek48c930c2017-12-04 08:53:16 +0000337 DelimitersOnNewline(false),
338 UnbreakableTailLength(Token.UnbreakableTailLength) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000339 assert(Tok.is(TT_BlockComment) &&
340 "block comment section must start with a block comment");
341
342 StringRef TokenText(Tok.TokenText);
Manuel Klimek9043c742013-05-27 15:23:34 +0000343 assert(TokenText.startswith("/*") && TokenText.endswith("*/"));
344 TokenText.substr(2, TokenText.size() - 4).split(Lines, "\n");
345
346 int IndentDelta = StartColumn - OriginalStartColumn;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000347 Content.resize(Lines.size());
348 Content[0] = Lines[0];
349 ContentColumn.resize(Lines.size());
350 // Account for the initial '/*'.
351 ContentColumn[0] = StartColumn + 2;
352 Tokens.resize(Lines.size());
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000353 for (size_t i = 1; i < Lines.size(); ++i)
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000354 adjustWhitespace(i, IndentDelta);
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000355
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000356 // Align decorations with the column of the star on the first line,
357 // that is one column after the start "/*".
358 DecorationColumn = StartColumn + 1;
359
360 // Account for comment decoration patterns like this:
361 //
362 // /*
363 // ** blah blah blah
364 // */
365 if (Lines.size() >= 2 && Content[1].startswith("**") &&
366 static_cast<unsigned>(ContentColumn[1]) == StartColumn) {
367 DecorationColumn = StartColumn;
368 }
369
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000370 Decoration = "* ";
Manuel Klimek9043c742013-05-27 15:23:34 +0000371 if (Lines.size() == 1 && !FirstInLine) {
372 // Comments for which FirstInLine is false can start on arbitrary column,
373 // and available horizontal space can be too small to align consecutive
374 // lines with the first one.
375 // FIXME: We could, probably, align them to current indentation level, but
376 // now we just wrap them without stars.
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000377 Decoration = "";
Manuel Klimek9043c742013-05-27 15:23:34 +0000378 }
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000379 for (size_t i = 1, e = Lines.size(); i < e && !Decoration.empty(); ++i) {
380 // If the last line is empty, the closing "*/" will have a star.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000381 if (i + 1 == e && Content[i].empty())
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000382 break;
Manuel Klimek89628f62017-09-20 09:51:03 +0000383 if (!Content[i].empty() && i + 1 != e && Decoration.startswith(Content[i]))
Daniel Jasper6d9b88d2015-05-06 07:17:22 +0000384 continue;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000385 while (!Content[i].startswith(Decoration))
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000386 Decoration = Decoration.substr(0, Decoration.size() - 1);
Manuel Klimek9043c742013-05-27 15:23:34 +0000387 }
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000388
389 LastLineNeedsDecoration = true;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000390 IndentAtLineBreak = ContentColumn[0] + 1;
391 for (size_t i = 1, e = Lines.size(); i < e; ++i) {
392 if (Content[i].empty()) {
393 if (i + 1 == e) {
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000394 // Empty last line means that we already have a star as a part of the
395 // trailing */. We also need to preserve whitespace, so that */ is
396 // correctly indented.
397 LastLineNeedsDecoration = false;
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000398 // Align the star in the last '*/' with the stars on the previous lines.
399 if (e >= 2 && !Decoration.empty()) {
400 ContentColumn[i] = DecorationColumn;
401 }
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000402 } else if (Decoration.empty()) {
403 // For all other lines, set the start column to 0 if they're empty, so
404 // we do not insert trailing whitespace anywhere.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000405 ContentColumn[i] = 0;
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000406 }
Manuel Klimek9043c742013-05-27 15:23:34 +0000407 continue;
408 }
Daniel Jasper6d9b88d2015-05-06 07:17:22 +0000409
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000410 // The first line already excludes the star.
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000411 // The last line excludes the star if LastLineNeedsDecoration is false.
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000412 // For all other lines, adjust the line to exclude the star and
413 // (optionally) the first whitespace.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000414 unsigned DecorationSize = Decoration.startswith(Content[i])
415 ? Content[i].size()
416 : Decoration.size();
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000417 if (DecorationSize) {
418 ContentColumn[i] = DecorationColumn + DecorationSize;
419 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000420 Content[i] = Content[i].substr(DecorationSize);
421 if (!Decoration.startswith(Content[i]))
Daniel Jasper6d9b88d2015-05-06 07:17:22 +0000422 IndentAtLineBreak =
Krasimir Georgiev91834222017-01-25 13:58:58 +0000423 std::min<int>(IndentAtLineBreak, std::max(0, ContentColumn[i]));
Manuel Klimek9043c742013-05-27 15:23:34 +0000424 }
Manuel Klimek89628f62017-09-20 09:51:03 +0000425 IndentAtLineBreak = std::max<unsigned>(IndentAtLineBreak, Decoration.size());
Krasimir Georgiev91834222017-01-25 13:58:58 +0000426
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000427 // Detect a multiline jsdoc comment and set DelimitersOnNewline in that case.
428 if (Style.Language == FormatStyle::LK_JavaScript ||
429 Style.Language == FormatStyle::LK_Java) {
430 if ((Lines[0] == "*" || Lines[0].startswith("* ")) && Lines.size() > 1) {
431 // This is a multiline jsdoc comment.
432 DelimitersOnNewline = true;
433 } else if (Lines[0].startswith("* ") && Lines.size() == 1) {
434 // Detect a long single-line comment, like:
435 // /** long long long */
436 // Below, '2' is the width of '*/'.
Manuel Klimek89628f62017-09-20 09:51:03 +0000437 unsigned EndColumn =
438 ContentColumn[0] +
439 encoding::columnWidthWithTabs(Lines[0], ContentColumn[0],
440 Style.TabWidth, Encoding) +
441 2;
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000442 DelimitersOnNewline = EndColumn > Style.ColumnLimit;
443 }
444 }
445
Nicola Zaghen3538b392018-05-15 13:30:56 +0000446 LLVM_DEBUG({
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000447 llvm::dbgs() << "IndentAtLineBreak " << IndentAtLineBreak << "\n";
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000448 llvm::dbgs() << "DelimitersOnNewline " << DelimitersOnNewline << "\n";
Manuel Klimek9043c742013-05-27 15:23:34 +0000449 for (size_t i = 0; i < Lines.size(); ++i) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000450 llvm::dbgs() << i << " |" << Content[i] << "| "
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000451 << "CC=" << ContentColumn[i] << "| "
452 << "IN=" << (Content[i].data() - Lines[i].data()) << "\n";
Manuel Klimek9043c742013-05-27 15:23:34 +0000453 }
454 });
455}
456
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000457void BreakableBlockComment::adjustWhitespace(unsigned LineIndex,
Manuel Klimek9043c742013-05-27 15:23:34 +0000458 int IndentDelta) {
Alexander Kornienkobe633902013-06-14 11:46:10 +0000459 // When in a preprocessor directive, the trailing backslash in a block comment
460 // is not needed, but can serve a purpose of uniformity with necessary escaped
461 // newlines outside the comment. In this case we remove it here before
462 // trimming the trailing whitespace. The backslash will be re-added later when
463 // inserting a line break.
464 size_t EndOfPreviousLine = Lines[LineIndex - 1].size();
465 if (InPPDirective && Lines[LineIndex - 1].endswith("\\"))
466 --EndOfPreviousLine;
467
Manuel Klimek9043c742013-05-27 15:23:34 +0000468 // Calculate the end of the non-whitespace text in the previous line.
Alexander Kornienkobe633902013-06-14 11:46:10 +0000469 EndOfPreviousLine =
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000470 Lines[LineIndex - 1].find_last_not_of(Blanks, EndOfPreviousLine);
Manuel Klimek9043c742013-05-27 15:23:34 +0000471 if (EndOfPreviousLine == StringRef::npos)
472 EndOfPreviousLine = 0;
473 else
474 ++EndOfPreviousLine;
475 // Calculate the start of the non-whitespace text in the current line.
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000476 size_t StartOfLine = Lines[LineIndex].find_first_not_of(Blanks);
Manuel Klimek9043c742013-05-27 15:23:34 +0000477 if (StartOfLine == StringRef::npos)
Daniel Jasperd6e61882015-06-17 12:23:15 +0000478 StartOfLine = Lines[LineIndex].rtrim("\r\n").size();
Manuel Klimek9043c742013-05-27 15:23:34 +0000479
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000480 StringRef Whitespace = Lines[LineIndex].substr(0, StartOfLine);
Manuel Klimek9043c742013-05-27 15:23:34 +0000481 // Adjust Lines to only contain relevant text.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000482 size_t PreviousContentOffset =
483 Content[LineIndex - 1].data() - Lines[LineIndex - 1].data();
484 Content[LineIndex - 1] = Lines[LineIndex - 1].substr(
485 PreviousContentOffset, EndOfPreviousLine - PreviousContentOffset);
486 Content[LineIndex] = Lines[LineIndex].substr(StartOfLine);
Manuel Klimek34d15152013-05-28 10:01:59 +0000487
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000488 // Adjust the start column uniformly across all lines.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000489 ContentColumn[LineIndex] =
Alexander Kornienko39856b72013-09-10 09:38:25 +0000490 encoding::columnWidthWithTabs(Whitespace, 0, Style.TabWidth, Encoding) +
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000491 IndentDelta;
Manuel Klimek9043c742013-05-27 15:23:34 +0000492}
493
Manuel Klimek93699f42017-11-29 14:29:43 +0000494unsigned BreakableBlockComment::getRangeLength(unsigned LineIndex,
495 unsigned Offset,
496 StringRef::size_type Length,
497 unsigned StartColumn) const {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000498 unsigned LineLength =
Manuel Klimek93699f42017-11-29 14:29:43 +0000499 encoding::columnWidthWithTabs(Content[LineIndex].substr(Offset, Length),
500 StartColumn, Style.TabWidth, Encoding);
501 // FIXME: This should go into getRemainingLength instead, but we currently
502 // break tests when putting it there. Investigate how to fix those tests.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000503 // The last line gets a "*/" postfix.
504 if (LineIndex + 1 == Lines.size()) {
505 LineLength += 2;
506 // We never need a decoration when breaking just the trailing "*/" postfix.
507 // Note that checking that Length == 0 is not enough, since Length could
508 // also be StringRef::npos.
Manuel Klimek93699f42017-11-29 14:29:43 +0000509 if (Content[LineIndex].substr(Offset, StringRef::npos).empty()) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000510 LineLength -= Decoration.size();
511 }
512 }
513 return LineLength;
Manuel Klimek9043c742013-05-27 15:23:34 +0000514}
515
Manuel Klimek93699f42017-11-29 14:29:43 +0000516unsigned BreakableBlockComment::getRemainingLength(unsigned LineIndex,
517 unsigned Offset,
518 unsigned StartColumn) const {
Manuel Klimek48c930c2017-12-04 08:53:16 +0000519 return UnbreakableTailLength +
520 getRangeLength(LineIndex, Offset, StringRef::npos, StartColumn);
Manuel Klimek93699f42017-11-29 14:29:43 +0000521}
522
523unsigned BreakableBlockComment::getContentStartColumn(unsigned LineIndex,
524 bool Break) const {
525 if (Break)
526 return IndentAtLineBreak;
527 return std::max(0, ContentColumn[LineIndex]);
528}
529
Krasimir Georgiev6a5c95b2018-07-30 08:45:45 +0000530const llvm::StringSet<>
531 BreakableBlockComment::ContentIndentingJavadocAnnotations = {
532 "@param", "@return", "@returns", "@throws", "@type", "@template",
Krasimir Georgiev186478d2018-08-01 11:48:04 +0000533 "@see", "@deprecated", "@define", "@exports", "@mods", "@private",
Krasimir Georgiev6a5c95b2018-07-30 08:45:45 +0000534};
535
536unsigned BreakableBlockComment::getContentIndent(unsigned LineIndex) const {
537 if (Style.Language != FormatStyle::LK_Java &&
538 Style.Language != FormatStyle::LK_JavaScript)
539 return 0;
540 // The content at LineIndex 0 of a comment like:
541 // /** line 0 */
542 // is "* line 0", so we need to skip over the decoration in that case.
543 StringRef ContentWithNoDecoration = Content[LineIndex];
544 if (LineIndex == 0 && ContentWithNoDecoration.startswith("*")) {
545 ContentWithNoDecoration = ContentWithNoDecoration.substr(1).ltrim(Blanks);
546 }
547 StringRef FirstWord = ContentWithNoDecoration.substr(
548 0, ContentWithNoDecoration.find_first_of(Blanks));
549 if (ContentIndentingJavadocAnnotations.find(FirstWord) !=
550 ContentIndentingJavadocAnnotations.end())
551 return Style.ContinuationIndentWidth;
552 return 0;
553}
554
Manuel Klimek9043c742013-05-27 15:23:34 +0000555void BreakableBlockComment::insertBreak(unsigned LineIndex, unsigned TailOffset,
Krasimir Georgiev6a5c95b2018-07-30 08:45:45 +0000556 Split Split, unsigned ContentIndent,
Manuel Klimek93699f42017-11-29 14:29:43 +0000557 WhitespaceManager &Whitespaces) const {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000558 StringRef Text = Content[LineIndex].substr(TailOffset);
Manuel Klimek9043c742013-05-27 15:23:34 +0000559 StringRef Prefix = Decoration;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000560 // We need this to account for the case when we have a decoration "* " for all
561 // the lines except for the last one, where the star in "*/" acts as a
562 // decoration.
563 unsigned LocalIndentAtLineBreak = IndentAtLineBreak;
Manuel Klimek9043c742013-05-27 15:23:34 +0000564 if (LineIndex + 1 == Lines.size() &&
565 Text.size() == Split.first + Split.second) {
566 // For the last line we need to break before "*/", but not to add "* ".
567 Prefix = "";
Krasimir Georgiev91834222017-01-25 13:58:58 +0000568 if (LocalIndentAtLineBreak >= 2)
569 LocalIndentAtLineBreak -= 2;
570 }
571 // The split offset is from the beginning of the line. Convert it to an offset
572 // from the beginning of the token text.
573 unsigned BreakOffsetInToken =
574 Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
575 unsigned CharsToRemove = Split.second;
576 assert(LocalIndentAtLineBreak >= Prefix.size());
Krasimir Georgiev6a5c95b2018-07-30 08:45:45 +0000577 std::string PrefixWithTrailingIndent = Prefix;
578 for (unsigned I = 0; I < ContentIndent; ++I)
579 PrefixWithTrailingIndent += " ";
Krasimir Georgiev91834222017-01-25 13:58:58 +0000580 Whitespaces.replaceWhitespaceInToken(
Krasimir Georgiev6a5c95b2018-07-30 08:45:45 +0000581 tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "",
582 PrefixWithTrailingIndent, InPPDirective, /*Newlines=*/1,
583 /*Spaces=*/LocalIndentAtLineBreak + ContentIndent -
584 PrefixWithTrailingIndent.size());
Krasimir Georgiev91834222017-01-25 13:58:58 +0000585}
586
Manuel Klimek93699f42017-11-29 14:29:43 +0000587BreakableToken::Split
588BreakableBlockComment::getReflowSplit(unsigned LineIndex,
589 llvm::Regex &CommentPragmasRegex) const {
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000590 if (!mayReflow(LineIndex, CommentPragmasRegex))
Krasimir Georgiev91834222017-01-25 13:58:58 +0000591 return Split(StringRef::npos, 0);
Fangrui Song6907ce22018-07-30 19:24:48 +0000592
Krasimir Georgiev6a5c95b2018-07-30 08:45:45 +0000593 // If we're reflowing into a line with content indent, only reflow the next
594 // line if its starting whitespace matches the content indent.
Manuel Klimek93699f42017-11-29 14:29:43 +0000595 size_t Trimmed = Content[LineIndex].find_first_not_of(Blanks);
Krasimir Georgiev6a5c95b2018-07-30 08:45:45 +0000596 if (LineIndex) {
597 unsigned PreviousContentIndent = getContentIndent(LineIndex - 1);
598 if (PreviousContentIndent && Trimmed != StringRef::npos &&
599 Trimmed != PreviousContentIndent)
600 return Split(StringRef::npos, 0);
601 }
602
Manuel Klimek93699f42017-11-29 14:29:43 +0000603 return Split(0, Trimmed != StringRef::npos ? Trimmed : 0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000604}
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000605
Manuel Klimek77866142017-11-17 11:17:15 +0000606bool BreakableBlockComment::introducesBreakBeforeToken() const {
Krasimir Georgiev35599fd2017-10-16 09:08:53 +0000607 // A break is introduced when we want delimiters on newline.
Manuel Klimek77866142017-11-17 11:17:15 +0000608 return DelimitersOnNewline &&
Krasimir Georgiev35599fd2017-10-16 09:08:53 +0000609 Lines[0].substr(1).find_first_not_of(Blanks) != StringRef::npos;
610}
611
Manuel Klimek93699f42017-11-29 14:29:43 +0000612void BreakableBlockComment::reflow(unsigned LineIndex,
613 WhitespaceManager &Whitespaces) const {
614 StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
615 // Here we need to reflow.
616 assert(Tokens[LineIndex - 1] == Tokens[LineIndex] &&
617 "Reflowing whitespace within a token");
618 // This is the offset of the end of the last line relative to the start of
619 // the token text in the token.
620 unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
621 Content[LineIndex - 1].size() -
622 tokenAt(LineIndex).TokenText.data();
623 unsigned WhitespaceLength = TrimmedContent.data() -
624 tokenAt(LineIndex).TokenText.data() -
625 WhitespaceOffsetInToken;
626 Whitespaces.replaceWhitespaceInToken(
627 tokenAt(LineIndex), WhitespaceOffsetInToken,
628 /*ReplaceChars=*/WhitespaceLength, /*PreviousPostfix=*/"",
629 /*CurrentPrefix=*/ReflowPrefix, InPPDirective, /*Newlines=*/0,
630 /*Spaces=*/0);
631}
632
633void BreakableBlockComment::adaptStartOfLine(
634 unsigned LineIndex, WhitespaceManager &Whitespaces) const {
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000635 if (LineIndex == 0) {
636 if (DelimitersOnNewline) {
Manuel Klimek93699f42017-11-29 14:29:43 +0000637 // Since we're breaking at index 1 below, the break position and the
Manuel Klimek89628f62017-09-20 09:51:03 +0000638 // break length are the same.
Martin Probst9d717812018-08-02 11:52:08 +0000639 // Note: this works because getCommentSplit is careful never to split at
640 // the beginning of a line.
Manuel Klimek89628f62017-09-20 09:51:03 +0000641 size_t BreakLength = Lines[0].substr(1).find_first_not_of(Blanks);
Manuel Klimek93699f42017-11-29 14:29:43 +0000642 if (BreakLength != StringRef::npos)
Krasimir Georgiev6a5c95b2018-07-30 08:45:45 +0000643 insertBreak(LineIndex, 0, Split(1, BreakLength), /*ContentIndent=*/0,
644 Whitespaces);
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000645 }
646 return;
647 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000648 // Here no reflow with the previous line will happen.
649 // Fix the decoration of the line at LineIndex.
Manuel Klimek9043c742013-05-27 15:23:34 +0000650 StringRef Prefix = Decoration;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000651 if (Content[LineIndex].empty()) {
Manuel Klimek281dcbe2013-05-28 08:55:01 +0000652 if (LineIndex + 1 == Lines.size()) {
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000653 if (!LastLineNeedsDecoration) {
654 // If the last line was empty, we don't need a prefix, as the */ will
655 // line up with the decoration (if it exists).
656 Prefix = "";
657 }
Manuel Klimek281dcbe2013-05-28 08:55:01 +0000658 } else if (!Decoration.empty()) {
659 // For other empty lines, if we do have a decoration, adapt it to not
660 // contain a trailing whitespace.
661 Prefix = Prefix.substr(0, 1);
662 }
Daniel Jasper51fb2b22013-05-30 06:40:07 +0000663 } else {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000664 if (ContentColumn[LineIndex] == 1) {
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000665 // This line starts immediately after the decorating *.
Daniel Jasper51fb2b22013-05-30 06:40:07 +0000666 Prefix = Prefix.substr(0, 1);
667 }
Manuel Klimek281dcbe2013-05-28 08:55:01 +0000668 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000669 // This is the offset of the end of the last line relative to the start of the
670 // token text in the token.
671 unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
672 Content[LineIndex - 1].size() -
673 tokenAt(LineIndex).TokenText.data();
674 unsigned WhitespaceLength = Content[LineIndex].data() -
675 tokenAt(LineIndex).TokenText.data() -
676 WhitespaceOffsetInToken;
Alexander Kornienko555efc32013-06-11 16:01:49 +0000677 Whitespaces.replaceWhitespaceInToken(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000678 tokenAt(LineIndex), WhitespaceOffsetInToken, WhitespaceLength, "", Prefix,
679 InPPDirective, /*Newlines=*/1, ContentColumn[LineIndex] - Prefix.size());
Manuel Klimek9043c742013-05-27 15:23:34 +0000680}
681
Krasimir Georgiev3b865342017-08-09 09:42:32 +0000682BreakableToken::Split
Manuel Klimek93699f42017-11-29 14:29:43 +0000683BreakableBlockComment::getSplitAfterLastLine(unsigned TailOffset) const {
Krasimir Georgiev3b865342017-08-09 09:42:32 +0000684 if (DelimitersOnNewline) {
685 // Replace the trailing whitespace of the last line with a newline.
686 // In case the last line is empty, the ending '*/' is already on its own
687 // line.
688 StringRef Line = Content.back().substr(TailOffset);
689 StringRef TrimmedLine = Line.rtrim(Blanks);
690 if (!TrimmedLine.empty())
691 return Split(TrimmedLine.size(), Line.size() - TrimmedLine.size());
692 }
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000693 return Split(StringRef::npos, 0);
694}
695
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000696bool BreakableBlockComment::mayReflow(unsigned LineIndex,
697 llvm::Regex &CommentPragmasRegex) const {
698 // Content[LineIndex] may exclude the indent after the '*' decoration. In that
699 // case, we compute the start of the comment pragma manually.
700 StringRef IndentContent = Content[LineIndex];
701 if (Lines[LineIndex].ltrim(Blanks).startswith("*")) {
702 IndentContent = Lines[LineIndex].ltrim(Blanks).substr(1);
703 }
704 return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
705 mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
706 !switchesFormatting(tokenAt(LineIndex));
707}
708
Krasimir Georgiev91834222017-01-25 13:58:58 +0000709BreakableLineCommentSection::BreakableLineCommentSection(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000710 const FormatToken &Token, unsigned StartColumn,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000711 unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective,
712 encoding::Encoding Encoding, const FormatStyle &Style)
Krasimir Georgiev4b159222017-02-21 10:54:50 +0000713 : BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000714 assert(Tok.is(TT_LineComment) &&
715 "line comment section must start with a line comment");
716 FormatToken *LineTok = nullptr;
717 for (const FormatToken *CurrentTok = &Tok;
718 CurrentTok && CurrentTok->is(TT_LineComment);
719 CurrentTok = CurrentTok->Next) {
720 LastLineTok = LineTok;
721 StringRef TokenText(CurrentTok->TokenText);
Krasimir Georgiev410ed242017-11-10 12:50:09 +0000722 assert((TokenText.startswith("//") || TokenText.startswith("#")) &&
723 "unsupported line comment prefix, '//' and '#' are supported");
Krasimir Georgiev91834222017-01-25 13:58:58 +0000724 size_t FirstLineIndex = Lines.size();
725 TokenText.split(Lines, "\n");
726 Content.resize(Lines.size());
727 ContentColumn.resize(Lines.size());
728 OriginalContentColumn.resize(Lines.size());
729 Tokens.resize(Lines.size());
730 Prefix.resize(Lines.size());
731 OriginalPrefix.resize(Lines.size());
732 for (size_t i = FirstLineIndex, e = Lines.size(); i < e; ++i) {
Manuel Klimek45ab5592017-11-14 09:19:53 +0000733 Lines[i] = Lines[i].ltrim(Blanks);
Krasimir Georgieve518e0b2017-01-30 21:00:01 +0000734 // We need to trim the blanks in case this is not the first line in a
735 // multiline comment. Then the indent is included in Lines[i].
736 StringRef IndentPrefix =
Krasimir Georgiev410ed242017-11-10 12:50:09 +0000737 getLineCommentIndentPrefix(Lines[i].ltrim(Blanks), Style);
738 assert((TokenText.startswith("//") || TokenText.startswith("#")) &&
739 "unsupported line comment prefix, '//' and '#' are supported");
Krasimir Georgiev91834222017-01-25 13:58:58 +0000740 OriginalPrefix[i] = Prefix[i] = IndentPrefix;
741 if (Lines[i].size() > Prefix[i].size() &&
742 isAlphanumeric(Lines[i][Prefix[i].size()])) {
743 if (Prefix[i] == "//")
744 Prefix[i] = "// ";
745 else if (Prefix[i] == "///")
746 Prefix[i] = "/// ";
747 else if (Prefix[i] == "//!")
748 Prefix[i] = "//! ";
Krasimir Georgievba6b3152017-05-18 07:36:21 +0000749 else if (Prefix[i] == "///<")
750 Prefix[i] = "///< ";
751 else if (Prefix[i] == "//!<")
752 Prefix[i] = "//!< ";
Krasimir Georgiev410ed242017-11-10 12:50:09 +0000753 else if (Prefix[i] == "#" &&
754 Style.Language == FormatStyle::LK_TextProto)
755 Prefix[i] = "# ";
Krasimir Georgiev91834222017-01-25 13:58:58 +0000756 }
757
758 Tokens[i] = LineTok;
759 Content[i] = Lines[i].substr(IndentPrefix.size());
760 OriginalContentColumn[i] =
Manuel Klimek89628f62017-09-20 09:51:03 +0000761 StartColumn + encoding::columnWidthWithTabs(OriginalPrefix[i],
762 StartColumn,
763 Style.TabWidth, Encoding);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000764 ContentColumn[i] =
Manuel Klimek89628f62017-09-20 09:51:03 +0000765 StartColumn + encoding::columnWidthWithTabs(Prefix[i], StartColumn,
766 Style.TabWidth, Encoding);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000767
768 // Calculate the end of the non-whitespace text in this line.
769 size_t EndOfLine = Content[i].find_last_not_of(Blanks);
770 if (EndOfLine == StringRef::npos)
771 EndOfLine = Content[i].size();
772 else
773 ++EndOfLine;
774 Content[i] = Content[i].substr(0, EndOfLine);
775 }
776 LineTok = CurrentTok->Next;
Krasimir Georgievb6ccd382017-02-02 14:36:50 +0000777 if (CurrentTok->Next && !CurrentTok->Next->ContinuesLineCommentSection) {
Krasimir Georgiev753625b2017-01-31 13:32:38 +0000778 // A line comment section needs to broken by a line comment that is
779 // preceded by at least two newlines. Note that we put this break here
780 // instead of breaking at a previous stage during parsing, since that
781 // would split the contents of the enum into two unwrapped lines in this
782 // example, which is undesirable:
783 // enum A {
784 // a, // comment about a
785 //
786 // // comment about b
787 // b
788 // };
789 //
790 // FIXME: Consider putting separate line comment sections as children to
791 // the unwrapped line instead.
792 break;
793 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000794 }
795}
796
Manuel Klimek93699f42017-11-29 14:29:43 +0000797unsigned
798BreakableLineCommentSection::getRangeLength(unsigned LineIndex, unsigned Offset,
799 StringRef::size_type Length,
800 unsigned StartColumn) const {
801 return encoding::columnWidthWithTabs(
802 Content[LineIndex].substr(Offset, Length), StartColumn, Style.TabWidth,
803 Encoding);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000804}
805
Manuel Klimek93699f42017-11-29 14:29:43 +0000806unsigned BreakableLineCommentSection::getContentStartColumn(unsigned LineIndex,
807 bool Break) const {
808 if (Break)
809 return OriginalContentColumn[LineIndex];
810 return ContentColumn[LineIndex];
811}
812
813void BreakableLineCommentSection::insertBreak(
814 unsigned LineIndex, unsigned TailOffset, Split Split,
Krasimir Georgiev6a5c95b2018-07-30 08:45:45 +0000815 unsigned ContentIndent, WhitespaceManager &Whitespaces) const {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000816 StringRef Text = Content[LineIndex].substr(TailOffset);
817 // Compute the offset of the split relative to the beginning of the token
818 // text.
819 unsigned BreakOffsetInToken =
820 Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
821 unsigned CharsToRemove = Split.second;
822 // Compute the size of the new indent, including the size of the new prefix of
823 // the newly broken line.
824 unsigned IndentAtLineBreak = OriginalContentColumn[LineIndex] +
825 Prefix[LineIndex].size() -
826 OriginalPrefix[LineIndex].size();
827 assert(IndentAtLineBreak >= Prefix[LineIndex].size());
828 Whitespaces.replaceWhitespaceInToken(
829 tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "",
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000830 Prefix[LineIndex], InPPDirective, /*Newlines=*/1,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000831 /*Spaces=*/IndentAtLineBreak - Prefix[LineIndex].size());
832}
833
Manuel Klimek93699f42017-11-29 14:29:43 +0000834BreakableComment::Split BreakableLineCommentSection::getReflowSplit(
835 unsigned LineIndex, llvm::Regex &CommentPragmasRegex) const {
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000836 if (!mayReflow(LineIndex, CommentPragmasRegex))
837 return Split(StringRef::npos, 0);
Manuel Klimek93699f42017-11-29 14:29:43 +0000838
839 size_t Trimmed = Content[LineIndex].find_first_not_of(Blanks);
840
841 // In a line comment section each line is a separate token; thus, after a
842 // split we replace all whitespace before the current line comment token
843 // (which does not need to be included in the split), plus the start of the
844 // line up to where the content starts.
845 return Split(0, Trimmed != StringRef::npos ? Trimmed : 0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000846}
847
Manuel Klimek93699f42017-11-29 14:29:43 +0000848void BreakableLineCommentSection::reflow(unsigned LineIndex,
849 WhitespaceManager &Whitespaces) const {
Krasimir Georgiev4fc55a72018-06-12 19:33:15 +0000850 if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) {
851 // Reflow happens between tokens. Replace the whitespace between the
852 // tokens by the empty string.
853 Whitespaces.replaceWhitespace(
854 *Tokens[LineIndex], /*Newlines=*/0, /*Spaces=*/0,
855 /*StartOfTokenColumn=*/StartColumn, /*InPPDirective=*/false);
856 } else if (LineIndex > 0) {
857 // In case we're reflowing after the '\' in:
858 //
859 // // line comment \
860 // // line 2
861 //
862 // the reflow happens inside the single comment token (it is a single line
863 // comment with an unescaped newline).
864 // Replace the whitespace between the '\' and '//' with the empty string.
865 //
866 // Offset points to after the '\' relative to start of the token.
867 unsigned Offset = Lines[LineIndex - 1].data() +
868 Lines[LineIndex - 1].size() -
869 tokenAt(LineIndex - 1).TokenText.data();
870 // WhitespaceLength is the number of chars between the '\' and the '//' on
871 // the next line.
872 unsigned WhitespaceLength =
873 Lines[LineIndex].data() - tokenAt(LineIndex).TokenText.data() - Offset;
874 Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex],
875 Offset,
876 /*ReplaceChars=*/WhitespaceLength,
877 /*PreviousPostfix=*/"",
878 /*CurrentPrefix=*/"",
879 /*InPPDirective=*/false,
880 /*Newlines=*/0,
881 /*Spaces=*/0);
882
883 }
Manuel Klimek93699f42017-11-29 14:29:43 +0000884 // Replace the indent and prefix of the token with the reflow prefix.
Krasimir Georgiev4fc55a72018-06-12 19:33:15 +0000885 unsigned Offset =
886 Lines[LineIndex].data() - tokenAt(LineIndex).TokenText.data();
Manuel Klimek93699f42017-11-29 14:29:43 +0000887 unsigned WhitespaceLength =
Krasimir Georgiev4fc55a72018-06-12 19:33:15 +0000888 Content[LineIndex].data() - Lines[LineIndex].data();
Manuel Klimek93699f42017-11-29 14:29:43 +0000889 Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex],
Krasimir Georgiev4fc55a72018-06-12 19:33:15 +0000890 Offset,
Manuel Klimek93699f42017-11-29 14:29:43 +0000891 /*ReplaceChars=*/WhitespaceLength,
892 /*PreviousPostfix=*/"",
893 /*CurrentPrefix=*/ReflowPrefix,
894 /*InPPDirective=*/false,
895 /*Newlines=*/0,
896 /*Spaces=*/0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000897}
898
Manuel Klimek93699f42017-11-29 14:29:43 +0000899void BreakableLineCommentSection::adaptStartOfLine(
900 unsigned LineIndex, WhitespaceManager &Whitespaces) const {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000901 // If this is the first line of a token, we need to inform Whitespace Manager
902 // about it: either adapt the whitespace range preceding it, or mark it as an
903 // untouchable token.
904 // This happens for instance here:
905 // // line 1 \
906 // // line 2
907 if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) {
Manuel Klimek93699f42017-11-29 14:29:43 +0000908 // This is the first line for the current token, but no reflow with the
909 // previous token is necessary. However, we still may need to adjust the
910 // start column. Note that ContentColumn[LineIndex] is the expected
911 // content column after a possible update to the prefix, hence the prefix
912 // length change is included.
913 unsigned LineColumn =
914 ContentColumn[LineIndex] -
915 (Content[LineIndex].data() - Lines[LineIndex].data()) +
916 (OriginalPrefix[LineIndex].size() - Prefix[LineIndex].size());
Krasimir Georgiev13dbaa02017-02-01 10:10:04 +0000917
Manuel Klimek93699f42017-11-29 14:29:43 +0000918 // We always want to create a replacement instead of adding an untouchable
919 // token, even if LineColumn is the same as the original column of the
920 // token. This is because WhitespaceManager doesn't align trailing
921 // comments if they are untouchable.
922 Whitespaces.replaceWhitespace(*Tokens[LineIndex],
923 /*Newlines=*/1,
924 /*Spaces=*/LineColumn,
925 /*StartOfTokenColumn=*/LineColumn,
926 /*InPPDirective=*/false);
Krasimir Georgievb796ceb2017-01-31 15:40:15 +0000927 }
928 if (OriginalPrefix[LineIndex] != Prefix[LineIndex]) {
929 // Adjust the prefix if necessary.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000930
931 // Take care of the space possibly introduced after a decoration.
932 assert(Prefix[LineIndex] == (OriginalPrefix[LineIndex] + " ").str() &&
Krasimir Georgievb796ceb2017-01-31 15:40:15 +0000933 "Expecting a line comment prefix to differ from original by at most "
934 "a space");
Krasimir Georgiev91834222017-01-25 13:58:58 +0000935 Whitespaces.replaceWhitespaceInToken(
936 tokenAt(LineIndex), OriginalPrefix[LineIndex].size(), 0, "", "",
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000937 /*InPPDirective=*/false, /*Newlines=*/0, /*Spaces=*/1);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000938 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000939}
940
Manuel Klimek89628f62017-09-20 09:51:03 +0000941void BreakableLineCommentSection::updateNextToken(LineState &State) const {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000942 if (LastLineTok) {
943 State.NextToken = LastLineTok->Next;
944 }
945}
946
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000947bool BreakableLineCommentSection::mayReflow(
948 unsigned LineIndex, llvm::Regex &CommentPragmasRegex) const {
949 // Line comments have the indent as part of the prefix, so we need to
950 // recompute the start of the line.
951 StringRef IndentContent = Content[LineIndex];
952 if (Lines[LineIndex].startswith("//")) {
953 IndentContent = Lines[LineIndex].substr(2);
954 }
Manuel Klimek93699f42017-11-29 14:29:43 +0000955 // FIXME: Decide whether we want to reflow non-regular indents:
956 // Currently, we only reflow when the OriginalPrefix[LineIndex] matches the
957 // OriginalPrefix[LineIndex-1]. That means we don't reflow
958 // // text that protrudes
959 // // into text with different indent
960 // We do reflow in that case in block comments.
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000961 return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
962 mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
963 !switchesFormatting(tokenAt(LineIndex)) &&
964 OriginalPrefix[LineIndex] == OriginalPrefix[LineIndex - 1];
965}
966
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000967} // namespace format
968} // namespace clang