blob: 300e3f802cb4ece688bd3e7179e0ebd622d8e957 [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
93 // Do not split before a number followed by a dot: this would be interpreted
94 // as a numbered list, which would prevent re-flowing in subsequent passes.
Benjamin Kramerf76861c2018-03-20 21:52:19 +000095 static auto *const kNumberedListRegexp = new llvm::Regex("^[1-9][0-9]?\\.");
Francois Ferranda881be82017-05-22 14:47:17 +000096 if (SpaceOffset != StringRef::npos &&
Benjamin Kramerf76861c2018-03-20 21:52:19 +000097 kNumberedListRegexp->match(Text.substr(SpaceOffset).ltrim(Blanks)))
Francois Ferranda881be82017-05-22 14:47:17 +000098 SpaceOffset = Text.find_last_of(Blanks, SpaceOffset);
Martin Probst9d717812018-08-02 11:52:08 +000099 // 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 if (Style.Language == FormatStyle::LK_JavaScript &&
103 SpaceOffset != StringRef::npos && SpaceOffset + 1 < Text.size() &&
104 Text[SpaceOffset + 1] == '{')
105 SpaceOffset = Text.find_last_of(Blanks, SpaceOffset);
Francois Ferranda881be82017-05-22 14:47:17 +0000106
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000107 if (SpaceOffset == StringRef::npos ||
Manuel Klimek9043c742013-05-27 15:23:34 +0000108 // Don't break at leading whitespace.
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000109 Text.find_last_not_of(Blanks, SpaceOffset) == StringRef::npos) {
Manuel Klimekae1fbfb2013-05-29 22:06:18 +0000110 // Make sure that we don't break at leading whitespace that
111 // reaches past MaxSplit.
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000112 StringRef::size_type FirstNonWhitespace = Text.find_first_not_of(Blanks);
Manuel Klimekae1fbfb2013-05-29 22:06:18 +0000113 if (FirstNonWhitespace == StringRef::npos)
114 // If the comment is only whitespace, we cannot split.
115 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000116 SpaceOffset = Text.find_first_of(
117 Blanks, std::max<unsigned>(MaxSplitBytes, FirstNonWhitespace));
Manuel Klimekae1fbfb2013-05-29 22:06:18 +0000118 }
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000119 if (SpaceOffset != StringRef::npos && SpaceOffset != 0) {
Martin Probst9d717812018-08-02 11:52:08 +0000120 // adaptStartOfLine will break after lines starting with /** if the comment
121 // is broken anywhere. Avoid emitting this break twice here.
122 // Example: in /** longtextcomesherethatbreaks */ (with ColumnLimit 20) will
123 // insert a break after /**, so this code must not insert the same break.
124 if (SpaceOffset == 1 && Text[SpaceOffset - 1] == '*')
125 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000126 StringRef BeforeCut = Text.substr(0, SpaceOffset).rtrim(Blanks);
127 StringRef AfterCut = Text.substr(SpaceOffset).ltrim(Blanks);
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000128 return BreakableToken::Split(BeforeCut.size(),
129 AfterCut.begin() - BeforeCut.end());
130 }
131 return BreakableToken::Split(StringRef::npos, 0);
132}
133
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000134static BreakableToken::Split
135getStringSplit(StringRef Text, unsigned UsedColumns, unsigned ColumnLimit,
136 unsigned TabWidth, encoding::Encoding Encoding) {
Manuel Klimek9043c742013-05-27 15:23:34 +0000137 // FIXME: Reduce unit test case.
138 if (Text.empty())
139 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienko81e32942013-09-16 20:20:49 +0000140 if (ColumnLimit <= UsedColumns)
Manuel Klimek9043c742013-05-27 15:23:34 +0000141 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienko71d95d62013-11-26 10:38:53 +0000142 unsigned MaxSplit = ColumnLimit - UsedColumns;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000143 StringRef::size_type SpaceOffset = 0;
144 StringRef::size_type SlashOffset = 0;
Alexander Kornienko72852072013-06-19 14:22:47 +0000145 StringRef::size_type WordStartOffset = 0;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000146 StringRef::size_type SplitPoint = 0;
147 for (unsigned Chars = 0;;) {
148 unsigned Advance;
149 if (Text[0] == '\\') {
150 Advance = encoding::getEscapeSequenceLength(Text);
151 Chars += Advance;
152 } else {
153 Advance = encoding::getCodePointNumBytes(Text[0], Encoding);
Alexander Kornienko81e32942013-09-16 20:20:49 +0000154 Chars += encoding::columnWidthWithTabs(
155 Text.substr(0, Advance), UsedColumns + Chars, TabWidth, Encoding);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000156 }
157
Daniel Jaspere4b48c62015-01-21 19:50:35 +0000158 if (Chars > MaxSplit || Text.size() <= Advance)
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000159 break;
160
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000161 if (IsBlank(Text[0]))
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000162 SpaceOffset = SplitPoint;
163 if (Text[0] == '/')
164 SlashOffset = SplitPoint;
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000165 if (Advance == 1 && !isAlphanumeric(Text[0]))
Alexander Kornienko72852072013-06-19 14:22:47 +0000166 WordStartOffset = SplitPoint;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000167
168 SplitPoint += Advance;
169 Text = Text.substr(Advance);
170 }
171
172 if (SpaceOffset != 0)
173 return BreakableToken::Split(SpaceOffset + 1, 0);
174 if (SlashOffset != 0)
175 return BreakableToken::Split(SlashOffset + 1, 0);
Alexander Kornienko72852072013-06-19 14:22:47 +0000176 if (WordStartOffset != 0)
177 return BreakableToken::Split(WordStartOffset + 1, 0);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000178 if (SplitPoint != 0)
179 return BreakableToken::Split(SplitPoint, 0);
180 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000181}
182
Krasimir Georgiev91834222017-01-25 13:58:58 +0000183bool switchesFormatting(const FormatToken &Token) {
184 assert((Token.is(TT_BlockComment) || Token.is(TT_LineComment)) &&
185 "formatting regions are switched by comment tokens");
186 StringRef Content = Token.TokenText.substr(2).ltrim();
187 return Content.startswith("clang-format on") ||
188 Content.startswith("clang-format off");
189}
190
191unsigned
Manuel Klimek93699f42017-11-29 14:29:43 +0000192BreakableToken::getLengthAfterCompression(unsigned RemainingTokenColumns,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000193 Split Split) const {
194 // Example: consider the content
195 // lala lala
196 // - RemainingTokenColumns is the original number of columns, 10;
197 // - Split is (4, 2), denoting the two spaces between the two words;
198 //
199 // We compute the number of columns when the split is compressed into a single
200 // space, like:
201 // lala lala
Manuel Klimek93699f42017-11-29 14:29:43 +0000202 //
203 // FIXME: Correctly measure the length of whitespace in Split.second so it
204 // works with tabs.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000205 return RemainingTokenColumns + 1 - Split.second;
206}
207
Manuel Klimek93699f42017-11-29 14:29:43 +0000208unsigned BreakableStringLiteral::getLineCount() const { return 1; }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000209
Manuel Klimek93699f42017-11-29 14:29:43 +0000210unsigned BreakableStringLiteral::getRangeLength(unsigned LineIndex,
211 unsigned Offset,
212 StringRef::size_type Length,
213 unsigned StartColumn) const {
Manuel Klimek477f3692017-11-29 15:09:12 +0000214 llvm_unreachable("Getting the length of a part of the string literal "
215 "indicates that the code tries to reflow it.");
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000216}
217
Manuel Klimek93699f42017-11-29 14:29:43 +0000218unsigned
219BreakableStringLiteral::getRemainingLength(unsigned LineIndex, unsigned Offset,
220 unsigned StartColumn) const {
221 return UnbreakableTailLength + Postfix.size() +
222 encoding::columnWidthWithTabs(Line.substr(Offset, StringRef::npos),
223 StartColumn, Style.TabWidth, Encoding);
224}
225
226unsigned BreakableStringLiteral::getContentStartColumn(unsigned LineIndex,
227 bool Break) const {
228 return StartColumn + Prefix.size();
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000229}
230
Alexander Kornienko81e32942013-09-16 20:20:49 +0000231BreakableStringLiteral::BreakableStringLiteral(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000232 const FormatToken &Tok, unsigned StartColumn, StringRef Prefix,
Krasimir Georgiev55c23a12018-01-23 11:26:19 +0000233 StringRef Postfix, unsigned UnbreakableTailLength, bool InPPDirective,
234 encoding::Encoding Encoding, const FormatStyle &Style)
Manuel Klimek93699f42017-11-29 14:29:43 +0000235 : BreakableToken(Tok, InPPDirective, Encoding, Style),
236 StartColumn(StartColumn), Prefix(Prefix), Postfix(Postfix),
Krasimir Georgiev55c23a12018-01-23 11:26:19 +0000237 UnbreakableTailLength(UnbreakableTailLength) {
Manuel Klimek93699f42017-11-29 14:29:43 +0000238 assert(Tok.TokenText.startswith(Prefix) && Tok.TokenText.endswith(Postfix));
239 Line = Tok.TokenText.substr(
240 Prefix.size(), Tok.TokenText.size() - Prefix.size() - Postfix.size());
241}
Manuel Klimek9043c742013-05-27 15:23:34 +0000242
Manuel Klimek93699f42017-11-29 14:29:43 +0000243BreakableToken::Split BreakableStringLiteral::getSplit(
244 unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit,
245 unsigned ContentStartColumn, llvm::Regex &CommentPragmasRegex) const {
246 return getStringSplit(Line.substr(TailOffset), ContentStartColumn,
247 ColumnLimit - Postfix.size(), Style.TabWidth, Encoding);
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000248}
249
Alexander Kornienko555efc32013-06-11 16:01:49 +0000250void BreakableStringLiteral::insertBreak(unsigned LineIndex,
251 unsigned TailOffset, Split Split,
Krasimir Georgiev6a5c95b2018-07-30 08:45:45 +0000252 unsigned ContentIndent,
Manuel Klimek93699f42017-11-29 14:29:43 +0000253 WhitespaceManager &Whitespaces) const {
Alexander Kornienko555efc32013-06-11 16:01:49 +0000254 Whitespaces.replaceWhitespaceInToken(
255 Tok, Prefix.size() + TailOffset + Split.first, Split.second, Postfix,
Alexander Kornienkod4fa2e62017-04-11 09:55:00 +0000256 Prefix, InPPDirective, 1, StartColumn);
Alexander Kornienko555efc32013-06-11 16:01:49 +0000257}
258
Krasimir Georgiev91834222017-01-25 13:58:58 +0000259BreakableComment::BreakableComment(const FormatToken &Token,
Manuel Klimek89628f62017-09-20 09:51:03 +0000260 unsigned StartColumn, bool InPPDirective,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000261 encoding::Encoding Encoding,
262 const FormatStyle &Style)
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000263 : BreakableToken(Token, InPPDirective, Encoding, Style),
Krasimir Georgiev4b159222017-02-21 10:54:50 +0000264 StartColumn(StartColumn) {}
Manuel Klimek9043c742013-05-27 15:23:34 +0000265
Krasimir Georgiev91834222017-01-25 13:58:58 +0000266unsigned BreakableComment::getLineCount() const { return Lines.size(); }
267
Krasimir Georgiev17725d82017-03-08 08:55:12 +0000268BreakableToken::Split
269BreakableComment::getSplit(unsigned LineIndex, unsigned TailOffset,
Manuel Klimek93699f42017-11-29 14:29:43 +0000270 unsigned ColumnLimit, unsigned ContentStartColumn,
Krasimir Georgiev17725d82017-03-08 08:55:12 +0000271 llvm::Regex &CommentPragmasRegex) const {
272 // Don't break lines matching the comment pragmas regex.
273 if (CommentPragmasRegex.match(Content[LineIndex]))
274 return Split(StringRef::npos, 0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000275 return getCommentSplit(Content[LineIndex].substr(TailOffset),
Manuel Klimek93699f42017-11-29 14:29:43 +0000276 ContentStartColumn, ColumnLimit, Style.TabWidth,
Martin Probst9d717812018-08-02 11:52:08 +0000277 Encoding, Style);
Manuel Klimek9043c742013-05-27 15:23:34 +0000278}
279
Manuel Klimek93699f42017-11-29 14:29:43 +0000280void BreakableComment::compressWhitespace(
281 unsigned LineIndex, unsigned TailOffset, Split Split,
282 WhitespaceManager &Whitespaces) const {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000283 StringRef Text = Content[LineIndex].substr(TailOffset);
284 // Text is relative to the content line, but Whitespaces operates relative to
285 // the start of the corresponding token, so compute the start of the Split
286 // that needs to be compressed into a single space relative to the start of
287 // its token.
288 unsigned BreakOffsetInToken =
289 Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
290 unsigned CharsToRemove = Split.second;
Alexander Kornienko555efc32013-06-11 16:01:49 +0000291 Whitespaces.replaceWhitespaceInToken(
Krasimir Georgiev91834222017-01-25 13:58:58 +0000292 tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", "",
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000293 /*InPPDirective=*/false, /*Newlines=*/0, /*Spaces=*/1);
Alexander Kornienko875395f2013-11-12 17:50:13 +0000294}
295
Krasimir Georgiev91834222017-01-25 13:58:58 +0000296const FormatToken &BreakableComment::tokenAt(unsigned LineIndex) const {
297 return Tokens[LineIndex] ? *Tokens[LineIndex] : Tok;
298}
299
300static bool mayReflowContent(StringRef Content) {
301 Content = Content.trim(Blanks);
Krasimir Georgiev28912c02017-02-02 10:52:08 +0000302 // Lines starting with '@' commonly have special meaning.
Francois Ferranda881be82017-05-22 14:47:17 +0000303 // Lines starting with '-', '-#', '+' or '*' are bulleted/numbered lists.
Krasimir Georgiev28912c02017-02-02 10:52:08 +0000304 bool hasSpecialMeaningPrefix = false;
Benjamin Kramerf76861c2018-03-20 21:52:19 +0000305 for (StringRef Prefix :
306 {"@", "TODO", "FIXME", "XXX", "-# ", "- ", "+ ", "* "}) {
Krasimir Georgiev28912c02017-02-02 10:52:08 +0000307 if (Content.startswith(Prefix)) {
308 hasSpecialMeaningPrefix = true;
309 break;
310 }
311 }
Francois Ferranda881be82017-05-22 14:47:17 +0000312
313 // Numbered lists may also start with a number followed by '.'
314 // To avoid issues if a line starts with a number which is actually the end
315 // of a previous line, we only consider numbers with up to 2 digits.
Benjamin Kramerf76861c2018-03-20 21:52:19 +0000316 static auto *const kNumberedListRegexp = new llvm::Regex("^[1-9][0-9]?\\. ");
Manuel Klimek89628f62017-09-20 09:51:03 +0000317 hasSpecialMeaningPrefix =
Benjamin Kramerf76861c2018-03-20 21:52:19 +0000318 hasSpecialMeaningPrefix || kNumberedListRegexp->match(Content);
Francois Ferranda881be82017-05-22 14:47:17 +0000319
Krasimir Georgiev91834222017-01-25 13:58:58 +0000320 // Simple heuristic for what to reflow: content should contain at least two
321 // characters and either the first or second character must be
322 // non-punctuation.
Krasimir Georgiev28912c02017-02-02 10:52:08 +0000323 return Content.size() >= 2 && !hasSpecialMeaningPrefix &&
324 !Content.endswith("\\") &&
Krasimir Georgiev91834222017-01-25 13:58:58 +0000325 // Note that this is UTF-8 safe, since if isPunctuation(Content[0]) is
326 // true, then the first code point must be 1 byte long.
327 (!isPunctuation(Content[0]) || !isPunctuation(Content[1]));
328}
329
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000330BreakableBlockComment::BreakableBlockComment(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000331 const FormatToken &Token, unsigned StartColumn,
Alexander Kornienkobe633902013-06-14 11:46:10 +0000332 unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective,
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000333 encoding::Encoding Encoding, const FormatStyle &Style)
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000334 : BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style),
Manuel Klimek48c930c2017-12-04 08:53:16 +0000335 DelimitersOnNewline(false),
336 UnbreakableTailLength(Token.UnbreakableTailLength) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000337 assert(Tok.is(TT_BlockComment) &&
338 "block comment section must start with a block comment");
339
340 StringRef TokenText(Tok.TokenText);
Manuel Klimek9043c742013-05-27 15:23:34 +0000341 assert(TokenText.startswith("/*") && TokenText.endswith("*/"));
342 TokenText.substr(2, TokenText.size() - 4).split(Lines, "\n");
343
344 int IndentDelta = StartColumn - OriginalStartColumn;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000345 Content.resize(Lines.size());
346 Content[0] = Lines[0];
347 ContentColumn.resize(Lines.size());
348 // Account for the initial '/*'.
349 ContentColumn[0] = StartColumn + 2;
350 Tokens.resize(Lines.size());
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000351 for (size_t i = 1; i < Lines.size(); ++i)
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000352 adjustWhitespace(i, IndentDelta);
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000353
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000354 // Align decorations with the column of the star on the first line,
355 // that is one column after the start "/*".
356 DecorationColumn = StartColumn + 1;
357
358 // Account for comment decoration patterns like this:
359 //
360 // /*
361 // ** blah blah blah
362 // */
363 if (Lines.size() >= 2 && Content[1].startswith("**") &&
364 static_cast<unsigned>(ContentColumn[1]) == StartColumn) {
365 DecorationColumn = StartColumn;
366 }
367
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000368 Decoration = "* ";
Manuel Klimek9043c742013-05-27 15:23:34 +0000369 if (Lines.size() == 1 && !FirstInLine) {
370 // Comments for which FirstInLine is false can start on arbitrary column,
371 // and available horizontal space can be too small to align consecutive
372 // lines with the first one.
373 // FIXME: We could, probably, align them to current indentation level, but
374 // now we just wrap them without stars.
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000375 Decoration = "";
Manuel Klimek9043c742013-05-27 15:23:34 +0000376 }
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000377 for (size_t i = 1, e = Lines.size(); i < e && !Decoration.empty(); ++i) {
378 // If the last line is empty, the closing "*/" will have a star.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000379 if (i + 1 == e && Content[i].empty())
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000380 break;
Manuel Klimek89628f62017-09-20 09:51:03 +0000381 if (!Content[i].empty() && i + 1 != e && Decoration.startswith(Content[i]))
Daniel Jasper6d9b88d2015-05-06 07:17:22 +0000382 continue;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000383 while (!Content[i].startswith(Decoration))
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000384 Decoration = Decoration.substr(0, Decoration.size() - 1);
Manuel Klimek9043c742013-05-27 15:23:34 +0000385 }
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000386
387 LastLineNeedsDecoration = true;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000388 IndentAtLineBreak = ContentColumn[0] + 1;
389 for (size_t i = 1, e = Lines.size(); i < e; ++i) {
390 if (Content[i].empty()) {
391 if (i + 1 == e) {
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000392 // Empty last line means that we already have a star as a part of the
393 // trailing */. We also need to preserve whitespace, so that */ is
394 // correctly indented.
395 LastLineNeedsDecoration = false;
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000396 // Align the star in the last '*/' with the stars on the previous lines.
397 if (e >= 2 && !Decoration.empty()) {
398 ContentColumn[i] = DecorationColumn;
399 }
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000400 } else if (Decoration.empty()) {
401 // For all other lines, set the start column to 0 if they're empty, so
402 // we do not insert trailing whitespace anywhere.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000403 ContentColumn[i] = 0;
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000404 }
Manuel Klimek9043c742013-05-27 15:23:34 +0000405 continue;
406 }
Daniel Jasper6d9b88d2015-05-06 07:17:22 +0000407
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000408 // The first line already excludes the star.
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000409 // The last line excludes the star if LastLineNeedsDecoration is false.
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000410 // For all other lines, adjust the line to exclude the star and
411 // (optionally) the first whitespace.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000412 unsigned DecorationSize = Decoration.startswith(Content[i])
413 ? Content[i].size()
414 : Decoration.size();
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000415 if (DecorationSize) {
416 ContentColumn[i] = DecorationColumn + DecorationSize;
417 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000418 Content[i] = Content[i].substr(DecorationSize);
419 if (!Decoration.startswith(Content[i]))
Daniel Jasper6d9b88d2015-05-06 07:17:22 +0000420 IndentAtLineBreak =
Krasimir Georgiev91834222017-01-25 13:58:58 +0000421 std::min<int>(IndentAtLineBreak, std::max(0, ContentColumn[i]));
Manuel Klimek9043c742013-05-27 15:23:34 +0000422 }
Manuel Klimek89628f62017-09-20 09:51:03 +0000423 IndentAtLineBreak = std::max<unsigned>(IndentAtLineBreak, Decoration.size());
Krasimir Georgiev91834222017-01-25 13:58:58 +0000424
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000425 // Detect a multiline jsdoc comment and set DelimitersOnNewline in that case.
426 if (Style.Language == FormatStyle::LK_JavaScript ||
427 Style.Language == FormatStyle::LK_Java) {
428 if ((Lines[0] == "*" || Lines[0].startswith("* ")) && Lines.size() > 1) {
429 // This is a multiline jsdoc comment.
430 DelimitersOnNewline = true;
431 } else if (Lines[0].startswith("* ") && Lines.size() == 1) {
432 // Detect a long single-line comment, like:
433 // /** long long long */
434 // Below, '2' is the width of '*/'.
Manuel Klimek89628f62017-09-20 09:51:03 +0000435 unsigned EndColumn =
436 ContentColumn[0] +
437 encoding::columnWidthWithTabs(Lines[0], ContentColumn[0],
438 Style.TabWidth, Encoding) +
439 2;
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000440 DelimitersOnNewline = EndColumn > Style.ColumnLimit;
441 }
442 }
443
Nicola Zaghen3538b392018-05-15 13:30:56 +0000444 LLVM_DEBUG({
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000445 llvm::dbgs() << "IndentAtLineBreak " << IndentAtLineBreak << "\n";
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000446 llvm::dbgs() << "DelimitersOnNewline " << DelimitersOnNewline << "\n";
Manuel Klimek9043c742013-05-27 15:23:34 +0000447 for (size_t i = 0; i < Lines.size(); ++i) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000448 llvm::dbgs() << i << " |" << Content[i] << "| "
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000449 << "CC=" << ContentColumn[i] << "| "
450 << "IN=" << (Content[i].data() - Lines[i].data()) << "\n";
Manuel Klimek9043c742013-05-27 15:23:34 +0000451 }
452 });
453}
454
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000455void BreakableBlockComment::adjustWhitespace(unsigned LineIndex,
Manuel Klimek9043c742013-05-27 15:23:34 +0000456 int IndentDelta) {
Alexander Kornienkobe633902013-06-14 11:46:10 +0000457 // When in a preprocessor directive, the trailing backslash in a block comment
458 // is not needed, but can serve a purpose of uniformity with necessary escaped
459 // newlines outside the comment. In this case we remove it here before
460 // trimming the trailing whitespace. The backslash will be re-added later when
461 // inserting a line break.
462 size_t EndOfPreviousLine = Lines[LineIndex - 1].size();
463 if (InPPDirective && Lines[LineIndex - 1].endswith("\\"))
464 --EndOfPreviousLine;
465
Manuel Klimek9043c742013-05-27 15:23:34 +0000466 // Calculate the end of the non-whitespace text in the previous line.
Alexander Kornienkobe633902013-06-14 11:46:10 +0000467 EndOfPreviousLine =
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000468 Lines[LineIndex - 1].find_last_not_of(Blanks, EndOfPreviousLine);
Manuel Klimek9043c742013-05-27 15:23:34 +0000469 if (EndOfPreviousLine == StringRef::npos)
470 EndOfPreviousLine = 0;
471 else
472 ++EndOfPreviousLine;
473 // Calculate the start of the non-whitespace text in the current line.
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000474 size_t StartOfLine = Lines[LineIndex].find_first_not_of(Blanks);
Manuel Klimek9043c742013-05-27 15:23:34 +0000475 if (StartOfLine == StringRef::npos)
Daniel Jasperd6e61882015-06-17 12:23:15 +0000476 StartOfLine = Lines[LineIndex].rtrim("\r\n").size();
Manuel Klimek9043c742013-05-27 15:23:34 +0000477
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000478 StringRef Whitespace = Lines[LineIndex].substr(0, StartOfLine);
Manuel Klimek9043c742013-05-27 15:23:34 +0000479 // Adjust Lines to only contain relevant text.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000480 size_t PreviousContentOffset =
481 Content[LineIndex - 1].data() - Lines[LineIndex - 1].data();
482 Content[LineIndex - 1] = Lines[LineIndex - 1].substr(
483 PreviousContentOffset, EndOfPreviousLine - PreviousContentOffset);
484 Content[LineIndex] = Lines[LineIndex].substr(StartOfLine);
Manuel Klimek34d15152013-05-28 10:01:59 +0000485
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000486 // Adjust the start column uniformly across all lines.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000487 ContentColumn[LineIndex] =
Alexander Kornienko39856b72013-09-10 09:38:25 +0000488 encoding::columnWidthWithTabs(Whitespace, 0, Style.TabWidth, Encoding) +
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000489 IndentDelta;
Manuel Klimek9043c742013-05-27 15:23:34 +0000490}
491
Manuel Klimek93699f42017-11-29 14:29:43 +0000492unsigned BreakableBlockComment::getRangeLength(unsigned LineIndex,
493 unsigned Offset,
494 StringRef::size_type Length,
495 unsigned StartColumn) const {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000496 unsigned LineLength =
Manuel Klimek93699f42017-11-29 14:29:43 +0000497 encoding::columnWidthWithTabs(Content[LineIndex].substr(Offset, Length),
498 StartColumn, Style.TabWidth, Encoding);
499 // FIXME: This should go into getRemainingLength instead, but we currently
500 // break tests when putting it there. Investigate how to fix those tests.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000501 // The last line gets a "*/" postfix.
502 if (LineIndex + 1 == Lines.size()) {
503 LineLength += 2;
504 // We never need a decoration when breaking just the trailing "*/" postfix.
505 // Note that checking that Length == 0 is not enough, since Length could
506 // also be StringRef::npos.
Manuel Klimek93699f42017-11-29 14:29:43 +0000507 if (Content[LineIndex].substr(Offset, StringRef::npos).empty()) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000508 LineLength -= Decoration.size();
509 }
510 }
511 return LineLength;
Manuel Klimek9043c742013-05-27 15:23:34 +0000512}
513
Manuel Klimek93699f42017-11-29 14:29:43 +0000514unsigned BreakableBlockComment::getRemainingLength(unsigned LineIndex,
515 unsigned Offset,
516 unsigned StartColumn) const {
Manuel Klimek48c930c2017-12-04 08:53:16 +0000517 return UnbreakableTailLength +
518 getRangeLength(LineIndex, Offset, StringRef::npos, StartColumn);
Manuel Klimek93699f42017-11-29 14:29:43 +0000519}
520
521unsigned BreakableBlockComment::getContentStartColumn(unsigned LineIndex,
522 bool Break) const {
523 if (Break)
524 return IndentAtLineBreak;
525 return std::max(0, ContentColumn[LineIndex]);
526}
527
Krasimir Georgiev6a5c95b2018-07-30 08:45:45 +0000528const llvm::StringSet<>
529 BreakableBlockComment::ContentIndentingJavadocAnnotations = {
530 "@param", "@return", "@returns", "@throws", "@type", "@template",
Krasimir Georgiev186478d2018-08-01 11:48:04 +0000531 "@see", "@deprecated", "@define", "@exports", "@mods", "@private",
Krasimir Georgiev6a5c95b2018-07-30 08:45:45 +0000532};
533
534unsigned BreakableBlockComment::getContentIndent(unsigned LineIndex) const {
535 if (Style.Language != FormatStyle::LK_Java &&
536 Style.Language != FormatStyle::LK_JavaScript)
537 return 0;
538 // The content at LineIndex 0 of a comment like:
539 // /** line 0 */
540 // is "* line 0", so we need to skip over the decoration in that case.
541 StringRef ContentWithNoDecoration = Content[LineIndex];
542 if (LineIndex == 0 && ContentWithNoDecoration.startswith("*")) {
543 ContentWithNoDecoration = ContentWithNoDecoration.substr(1).ltrim(Blanks);
544 }
545 StringRef FirstWord = ContentWithNoDecoration.substr(
546 0, ContentWithNoDecoration.find_first_of(Blanks));
547 if (ContentIndentingJavadocAnnotations.find(FirstWord) !=
548 ContentIndentingJavadocAnnotations.end())
549 return Style.ContinuationIndentWidth;
550 return 0;
551}
552
Manuel Klimek9043c742013-05-27 15:23:34 +0000553void BreakableBlockComment::insertBreak(unsigned LineIndex, unsigned TailOffset,
Krasimir Georgiev6a5c95b2018-07-30 08:45:45 +0000554 Split Split, unsigned ContentIndent,
Manuel Klimek93699f42017-11-29 14:29:43 +0000555 WhitespaceManager &Whitespaces) const {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000556 StringRef Text = Content[LineIndex].substr(TailOffset);
Manuel Klimek9043c742013-05-27 15:23:34 +0000557 StringRef Prefix = Decoration;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000558 // We need this to account for the case when we have a decoration "* " for all
559 // the lines except for the last one, where the star in "*/" acts as a
560 // decoration.
561 unsigned LocalIndentAtLineBreak = IndentAtLineBreak;
Manuel Klimek9043c742013-05-27 15:23:34 +0000562 if (LineIndex + 1 == Lines.size() &&
563 Text.size() == Split.first + Split.second) {
564 // For the last line we need to break before "*/", but not to add "* ".
565 Prefix = "";
Krasimir Georgiev91834222017-01-25 13:58:58 +0000566 if (LocalIndentAtLineBreak >= 2)
567 LocalIndentAtLineBreak -= 2;
568 }
569 // The split offset is from the beginning of the line. Convert it to an offset
570 // from the beginning of the token text.
571 unsigned BreakOffsetInToken =
572 Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
573 unsigned CharsToRemove = Split.second;
574 assert(LocalIndentAtLineBreak >= Prefix.size());
Krasimir Georgiev6a5c95b2018-07-30 08:45:45 +0000575 std::string PrefixWithTrailingIndent = Prefix;
576 for (unsigned I = 0; I < ContentIndent; ++I)
577 PrefixWithTrailingIndent += " ";
Krasimir Georgiev91834222017-01-25 13:58:58 +0000578 Whitespaces.replaceWhitespaceInToken(
Krasimir Georgiev6a5c95b2018-07-30 08:45:45 +0000579 tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "",
580 PrefixWithTrailingIndent, InPPDirective, /*Newlines=*/1,
581 /*Spaces=*/LocalIndentAtLineBreak + ContentIndent -
582 PrefixWithTrailingIndent.size());
Krasimir Georgiev91834222017-01-25 13:58:58 +0000583}
584
Manuel Klimek93699f42017-11-29 14:29:43 +0000585BreakableToken::Split
586BreakableBlockComment::getReflowSplit(unsigned LineIndex,
587 llvm::Regex &CommentPragmasRegex) const {
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000588 if (!mayReflow(LineIndex, CommentPragmasRegex))
Krasimir Georgiev91834222017-01-25 13:58:58 +0000589 return Split(StringRef::npos, 0);
Fangrui Song6907ce22018-07-30 19:24:48 +0000590
Krasimir Georgiev6a5c95b2018-07-30 08:45:45 +0000591 // If we're reflowing into a line with content indent, only reflow the next
592 // line if its starting whitespace matches the content indent.
Manuel Klimek93699f42017-11-29 14:29:43 +0000593 size_t Trimmed = Content[LineIndex].find_first_not_of(Blanks);
Krasimir Georgiev6a5c95b2018-07-30 08:45:45 +0000594 if (LineIndex) {
595 unsigned PreviousContentIndent = getContentIndent(LineIndex - 1);
596 if (PreviousContentIndent && Trimmed != StringRef::npos &&
597 Trimmed != PreviousContentIndent)
598 return Split(StringRef::npos, 0);
599 }
600
Manuel Klimek93699f42017-11-29 14:29:43 +0000601 return Split(0, Trimmed != StringRef::npos ? Trimmed : 0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000602}
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000603
Manuel Klimek77866142017-11-17 11:17:15 +0000604bool BreakableBlockComment::introducesBreakBeforeToken() const {
Krasimir Georgiev35599fd2017-10-16 09:08:53 +0000605 // A break is introduced when we want delimiters on newline.
Manuel Klimek77866142017-11-17 11:17:15 +0000606 return DelimitersOnNewline &&
Krasimir Georgiev35599fd2017-10-16 09:08:53 +0000607 Lines[0].substr(1).find_first_not_of(Blanks) != StringRef::npos;
608}
609
Manuel Klimek93699f42017-11-29 14:29:43 +0000610void BreakableBlockComment::reflow(unsigned LineIndex,
611 WhitespaceManager &Whitespaces) const {
612 StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
613 // Here we need to reflow.
614 assert(Tokens[LineIndex - 1] == Tokens[LineIndex] &&
615 "Reflowing whitespace within a token");
616 // This is the offset of the end of the last line relative to the start of
617 // the token text in the token.
618 unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
619 Content[LineIndex - 1].size() -
620 tokenAt(LineIndex).TokenText.data();
621 unsigned WhitespaceLength = TrimmedContent.data() -
622 tokenAt(LineIndex).TokenText.data() -
623 WhitespaceOffsetInToken;
624 Whitespaces.replaceWhitespaceInToken(
625 tokenAt(LineIndex), WhitespaceOffsetInToken,
626 /*ReplaceChars=*/WhitespaceLength, /*PreviousPostfix=*/"",
627 /*CurrentPrefix=*/ReflowPrefix, InPPDirective, /*Newlines=*/0,
628 /*Spaces=*/0);
629}
630
631void BreakableBlockComment::adaptStartOfLine(
632 unsigned LineIndex, WhitespaceManager &Whitespaces) const {
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000633 if (LineIndex == 0) {
634 if (DelimitersOnNewline) {
Manuel Klimek93699f42017-11-29 14:29:43 +0000635 // Since we're breaking at index 1 below, the break position and the
Manuel Klimek89628f62017-09-20 09:51:03 +0000636 // break length are the same.
Martin Probst9d717812018-08-02 11:52:08 +0000637 // Note: this works because getCommentSplit is careful never to split at
638 // the beginning of a line.
Manuel Klimek89628f62017-09-20 09:51:03 +0000639 size_t BreakLength = Lines[0].substr(1).find_first_not_of(Blanks);
Manuel Klimek93699f42017-11-29 14:29:43 +0000640 if (BreakLength != StringRef::npos)
Krasimir Georgiev6a5c95b2018-07-30 08:45:45 +0000641 insertBreak(LineIndex, 0, Split(1, BreakLength), /*ContentIndent=*/0,
642 Whitespaces);
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000643 }
644 return;
645 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000646 // Here no reflow with the previous line will happen.
647 // Fix the decoration of the line at LineIndex.
Manuel Klimek9043c742013-05-27 15:23:34 +0000648 StringRef Prefix = Decoration;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000649 if (Content[LineIndex].empty()) {
Manuel Klimek281dcbe2013-05-28 08:55:01 +0000650 if (LineIndex + 1 == Lines.size()) {
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000651 if (!LastLineNeedsDecoration) {
652 // If the last line was empty, we don't need a prefix, as the */ will
653 // line up with the decoration (if it exists).
654 Prefix = "";
655 }
Manuel Klimek281dcbe2013-05-28 08:55:01 +0000656 } else if (!Decoration.empty()) {
657 // For other empty lines, if we do have a decoration, adapt it to not
658 // contain a trailing whitespace.
659 Prefix = Prefix.substr(0, 1);
660 }
Daniel Jasper51fb2b22013-05-30 06:40:07 +0000661 } else {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000662 if (ContentColumn[LineIndex] == 1) {
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000663 // This line starts immediately after the decorating *.
Daniel Jasper51fb2b22013-05-30 06:40:07 +0000664 Prefix = Prefix.substr(0, 1);
665 }
Manuel Klimek281dcbe2013-05-28 08:55:01 +0000666 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000667 // This is the offset of the end of the last line relative to the start of the
668 // token text in the token.
669 unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
670 Content[LineIndex - 1].size() -
671 tokenAt(LineIndex).TokenText.data();
672 unsigned WhitespaceLength = Content[LineIndex].data() -
673 tokenAt(LineIndex).TokenText.data() -
674 WhitespaceOffsetInToken;
Alexander Kornienko555efc32013-06-11 16:01:49 +0000675 Whitespaces.replaceWhitespaceInToken(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000676 tokenAt(LineIndex), WhitespaceOffsetInToken, WhitespaceLength, "", Prefix,
677 InPPDirective, /*Newlines=*/1, ContentColumn[LineIndex] - Prefix.size());
Manuel Klimek9043c742013-05-27 15:23:34 +0000678}
679
Krasimir Georgiev3b865342017-08-09 09:42:32 +0000680BreakableToken::Split
Manuel Klimek93699f42017-11-29 14:29:43 +0000681BreakableBlockComment::getSplitAfterLastLine(unsigned TailOffset) const {
Krasimir Georgiev3b865342017-08-09 09:42:32 +0000682 if (DelimitersOnNewline) {
683 // Replace the trailing whitespace of the last line with a newline.
684 // In case the last line is empty, the ending '*/' is already on its own
685 // line.
686 StringRef Line = Content.back().substr(TailOffset);
687 StringRef TrimmedLine = Line.rtrim(Blanks);
688 if (!TrimmedLine.empty())
689 return Split(TrimmedLine.size(), Line.size() - TrimmedLine.size());
690 }
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000691 return Split(StringRef::npos, 0);
692}
693
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000694bool BreakableBlockComment::mayReflow(unsigned LineIndex,
695 llvm::Regex &CommentPragmasRegex) const {
696 // Content[LineIndex] may exclude the indent after the '*' decoration. In that
697 // case, we compute the start of the comment pragma manually.
698 StringRef IndentContent = Content[LineIndex];
699 if (Lines[LineIndex].ltrim(Blanks).startswith("*")) {
700 IndentContent = Lines[LineIndex].ltrim(Blanks).substr(1);
701 }
702 return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
703 mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
704 !switchesFormatting(tokenAt(LineIndex));
705}
706
Krasimir Georgiev91834222017-01-25 13:58:58 +0000707BreakableLineCommentSection::BreakableLineCommentSection(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000708 const FormatToken &Token, unsigned StartColumn,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000709 unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective,
710 encoding::Encoding Encoding, const FormatStyle &Style)
Krasimir Georgiev4b159222017-02-21 10:54:50 +0000711 : BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000712 assert(Tok.is(TT_LineComment) &&
713 "line comment section must start with a line comment");
714 FormatToken *LineTok = nullptr;
715 for (const FormatToken *CurrentTok = &Tok;
716 CurrentTok && CurrentTok->is(TT_LineComment);
717 CurrentTok = CurrentTok->Next) {
718 LastLineTok = LineTok;
719 StringRef TokenText(CurrentTok->TokenText);
Krasimir Georgiev410ed242017-11-10 12:50:09 +0000720 assert((TokenText.startswith("//") || TokenText.startswith("#")) &&
721 "unsupported line comment prefix, '//' and '#' are supported");
Krasimir Georgiev91834222017-01-25 13:58:58 +0000722 size_t FirstLineIndex = Lines.size();
723 TokenText.split(Lines, "\n");
724 Content.resize(Lines.size());
725 ContentColumn.resize(Lines.size());
726 OriginalContentColumn.resize(Lines.size());
727 Tokens.resize(Lines.size());
728 Prefix.resize(Lines.size());
729 OriginalPrefix.resize(Lines.size());
730 for (size_t i = FirstLineIndex, e = Lines.size(); i < e; ++i) {
Manuel Klimek45ab5592017-11-14 09:19:53 +0000731 Lines[i] = Lines[i].ltrim(Blanks);
Krasimir Georgieve518e0b2017-01-30 21:00:01 +0000732 // We need to trim the blanks in case this is not the first line in a
733 // multiline comment. Then the indent is included in Lines[i].
734 StringRef IndentPrefix =
Krasimir Georgiev410ed242017-11-10 12:50:09 +0000735 getLineCommentIndentPrefix(Lines[i].ltrim(Blanks), Style);
736 assert((TokenText.startswith("//") || TokenText.startswith("#")) &&
737 "unsupported line comment prefix, '//' and '#' are supported");
Krasimir Georgiev91834222017-01-25 13:58:58 +0000738 OriginalPrefix[i] = Prefix[i] = IndentPrefix;
739 if (Lines[i].size() > Prefix[i].size() &&
740 isAlphanumeric(Lines[i][Prefix[i].size()])) {
741 if (Prefix[i] == "//")
742 Prefix[i] = "// ";
743 else if (Prefix[i] == "///")
744 Prefix[i] = "/// ";
745 else if (Prefix[i] == "//!")
746 Prefix[i] = "//! ";
Krasimir Georgievba6b3152017-05-18 07:36:21 +0000747 else if (Prefix[i] == "///<")
748 Prefix[i] = "///< ";
749 else if (Prefix[i] == "//!<")
750 Prefix[i] = "//!< ";
Krasimir Georgiev410ed242017-11-10 12:50:09 +0000751 else if (Prefix[i] == "#" &&
752 Style.Language == FormatStyle::LK_TextProto)
753 Prefix[i] = "# ";
Krasimir Georgiev91834222017-01-25 13:58:58 +0000754 }
755
756 Tokens[i] = LineTok;
757 Content[i] = Lines[i].substr(IndentPrefix.size());
758 OriginalContentColumn[i] =
Manuel Klimek89628f62017-09-20 09:51:03 +0000759 StartColumn + encoding::columnWidthWithTabs(OriginalPrefix[i],
760 StartColumn,
761 Style.TabWidth, Encoding);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000762 ContentColumn[i] =
Manuel Klimek89628f62017-09-20 09:51:03 +0000763 StartColumn + encoding::columnWidthWithTabs(Prefix[i], StartColumn,
764 Style.TabWidth, Encoding);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000765
766 // Calculate the end of the non-whitespace text in this line.
767 size_t EndOfLine = Content[i].find_last_not_of(Blanks);
768 if (EndOfLine == StringRef::npos)
769 EndOfLine = Content[i].size();
770 else
771 ++EndOfLine;
772 Content[i] = Content[i].substr(0, EndOfLine);
773 }
774 LineTok = CurrentTok->Next;
Krasimir Georgievb6ccd382017-02-02 14:36:50 +0000775 if (CurrentTok->Next && !CurrentTok->Next->ContinuesLineCommentSection) {
Krasimir Georgiev753625b2017-01-31 13:32:38 +0000776 // A line comment section needs to broken by a line comment that is
777 // preceded by at least two newlines. Note that we put this break here
778 // instead of breaking at a previous stage during parsing, since that
779 // would split the contents of the enum into two unwrapped lines in this
780 // example, which is undesirable:
781 // enum A {
782 // a, // comment about a
783 //
784 // // comment about b
785 // b
786 // };
787 //
788 // FIXME: Consider putting separate line comment sections as children to
789 // the unwrapped line instead.
790 break;
791 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000792 }
793}
794
Manuel Klimek93699f42017-11-29 14:29:43 +0000795unsigned
796BreakableLineCommentSection::getRangeLength(unsigned LineIndex, unsigned Offset,
797 StringRef::size_type Length,
798 unsigned StartColumn) const {
799 return encoding::columnWidthWithTabs(
800 Content[LineIndex].substr(Offset, Length), StartColumn, Style.TabWidth,
801 Encoding);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000802}
803
Manuel Klimek93699f42017-11-29 14:29:43 +0000804unsigned BreakableLineCommentSection::getContentStartColumn(unsigned LineIndex,
805 bool Break) const {
806 if (Break)
807 return OriginalContentColumn[LineIndex];
808 return ContentColumn[LineIndex];
809}
810
811void BreakableLineCommentSection::insertBreak(
812 unsigned LineIndex, unsigned TailOffset, Split Split,
Krasimir Georgiev6a5c95b2018-07-30 08:45:45 +0000813 unsigned ContentIndent, WhitespaceManager &Whitespaces) const {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000814 StringRef Text = Content[LineIndex].substr(TailOffset);
815 // Compute the offset of the split relative to the beginning of the token
816 // text.
817 unsigned BreakOffsetInToken =
818 Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
819 unsigned CharsToRemove = Split.second;
820 // Compute the size of the new indent, including the size of the new prefix of
821 // the newly broken line.
822 unsigned IndentAtLineBreak = OriginalContentColumn[LineIndex] +
823 Prefix[LineIndex].size() -
824 OriginalPrefix[LineIndex].size();
825 assert(IndentAtLineBreak >= Prefix[LineIndex].size());
826 Whitespaces.replaceWhitespaceInToken(
827 tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "",
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000828 Prefix[LineIndex], InPPDirective, /*Newlines=*/1,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000829 /*Spaces=*/IndentAtLineBreak - Prefix[LineIndex].size());
830}
831
Manuel Klimek93699f42017-11-29 14:29:43 +0000832BreakableComment::Split BreakableLineCommentSection::getReflowSplit(
833 unsigned LineIndex, llvm::Regex &CommentPragmasRegex) const {
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000834 if (!mayReflow(LineIndex, CommentPragmasRegex))
835 return Split(StringRef::npos, 0);
Manuel Klimek93699f42017-11-29 14:29:43 +0000836
837 size_t Trimmed = Content[LineIndex].find_first_not_of(Blanks);
838
839 // In a line comment section each line is a separate token; thus, after a
840 // split we replace all whitespace before the current line comment token
841 // (which does not need to be included in the split), plus the start of the
842 // line up to where the content starts.
843 return Split(0, Trimmed != StringRef::npos ? Trimmed : 0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000844}
845
Manuel Klimek93699f42017-11-29 14:29:43 +0000846void BreakableLineCommentSection::reflow(unsigned LineIndex,
847 WhitespaceManager &Whitespaces) const {
Krasimir Georgiev4fc55a72018-06-12 19:33:15 +0000848 if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) {
849 // Reflow happens between tokens. Replace the whitespace between the
850 // tokens by the empty string.
851 Whitespaces.replaceWhitespace(
852 *Tokens[LineIndex], /*Newlines=*/0, /*Spaces=*/0,
853 /*StartOfTokenColumn=*/StartColumn, /*InPPDirective=*/false);
854 } else if (LineIndex > 0) {
855 // In case we're reflowing after the '\' in:
856 //
857 // // line comment \
858 // // line 2
859 //
860 // the reflow happens inside the single comment token (it is a single line
861 // comment with an unescaped newline).
862 // Replace the whitespace between the '\' and '//' with the empty string.
863 //
864 // Offset points to after the '\' relative to start of the token.
865 unsigned Offset = Lines[LineIndex - 1].data() +
866 Lines[LineIndex - 1].size() -
867 tokenAt(LineIndex - 1).TokenText.data();
868 // WhitespaceLength is the number of chars between the '\' and the '//' on
869 // the next line.
870 unsigned WhitespaceLength =
871 Lines[LineIndex].data() - tokenAt(LineIndex).TokenText.data() - Offset;
872 Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex],
873 Offset,
874 /*ReplaceChars=*/WhitespaceLength,
875 /*PreviousPostfix=*/"",
876 /*CurrentPrefix=*/"",
877 /*InPPDirective=*/false,
878 /*Newlines=*/0,
879 /*Spaces=*/0);
880
881 }
Manuel Klimek93699f42017-11-29 14:29:43 +0000882 // Replace the indent and prefix of the token with the reflow prefix.
Krasimir Georgiev4fc55a72018-06-12 19:33:15 +0000883 unsigned Offset =
884 Lines[LineIndex].data() - tokenAt(LineIndex).TokenText.data();
Manuel Klimek93699f42017-11-29 14:29:43 +0000885 unsigned WhitespaceLength =
Krasimir Georgiev4fc55a72018-06-12 19:33:15 +0000886 Content[LineIndex].data() - Lines[LineIndex].data();
Manuel Klimek93699f42017-11-29 14:29:43 +0000887 Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex],
Krasimir Georgiev4fc55a72018-06-12 19:33:15 +0000888 Offset,
Manuel Klimek93699f42017-11-29 14:29:43 +0000889 /*ReplaceChars=*/WhitespaceLength,
890 /*PreviousPostfix=*/"",
891 /*CurrentPrefix=*/ReflowPrefix,
892 /*InPPDirective=*/false,
893 /*Newlines=*/0,
894 /*Spaces=*/0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000895}
896
Manuel Klimek93699f42017-11-29 14:29:43 +0000897void BreakableLineCommentSection::adaptStartOfLine(
898 unsigned LineIndex, WhitespaceManager &Whitespaces) const {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000899 // If this is the first line of a token, we need to inform Whitespace Manager
900 // about it: either adapt the whitespace range preceding it, or mark it as an
901 // untouchable token.
902 // This happens for instance here:
903 // // line 1 \
904 // // line 2
905 if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) {
Manuel Klimek93699f42017-11-29 14:29:43 +0000906 // This is the first line for the current token, but no reflow with the
907 // previous token is necessary. However, we still may need to adjust the
908 // start column. Note that ContentColumn[LineIndex] is the expected
909 // content column after a possible update to the prefix, hence the prefix
910 // length change is included.
911 unsigned LineColumn =
912 ContentColumn[LineIndex] -
913 (Content[LineIndex].data() - Lines[LineIndex].data()) +
914 (OriginalPrefix[LineIndex].size() - Prefix[LineIndex].size());
Krasimir Georgiev13dbaa02017-02-01 10:10:04 +0000915
Manuel Klimek93699f42017-11-29 14:29:43 +0000916 // We always want to create a replacement instead of adding an untouchable
917 // token, even if LineColumn is the same as the original column of the
918 // token. This is because WhitespaceManager doesn't align trailing
919 // comments if they are untouchable.
920 Whitespaces.replaceWhitespace(*Tokens[LineIndex],
921 /*Newlines=*/1,
922 /*Spaces=*/LineColumn,
923 /*StartOfTokenColumn=*/LineColumn,
924 /*InPPDirective=*/false);
Krasimir Georgievb796ceb2017-01-31 15:40:15 +0000925 }
926 if (OriginalPrefix[LineIndex] != Prefix[LineIndex]) {
927 // Adjust the prefix if necessary.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000928
929 // Take care of the space possibly introduced after a decoration.
930 assert(Prefix[LineIndex] == (OriginalPrefix[LineIndex] + " ").str() &&
Krasimir Georgievb796ceb2017-01-31 15:40:15 +0000931 "Expecting a line comment prefix to differ from original by at most "
932 "a space");
Krasimir Georgiev91834222017-01-25 13:58:58 +0000933 Whitespaces.replaceWhitespaceInToken(
934 tokenAt(LineIndex), OriginalPrefix[LineIndex].size(), 0, "", "",
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000935 /*InPPDirective=*/false, /*Newlines=*/0, /*Spaces=*/1);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000936 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000937}
938
Manuel Klimek89628f62017-09-20 09:51:03 +0000939void BreakableLineCommentSection::updateNextToken(LineState &State) const {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000940 if (LastLineTok) {
941 State.NextToken = LastLineTok->Next;
942 }
943}
944
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000945bool BreakableLineCommentSection::mayReflow(
946 unsigned LineIndex, llvm::Regex &CommentPragmasRegex) const {
947 // Line comments have the indent as part of the prefix, so we need to
948 // recompute the start of the line.
949 StringRef IndentContent = Content[LineIndex];
950 if (Lines[LineIndex].startswith("//")) {
951 IndentContent = Lines[LineIndex].substr(2);
952 }
Manuel Klimek93699f42017-11-29 14:29:43 +0000953 // FIXME: Decide whether we want to reflow non-regular indents:
954 // Currently, we only reflow when the OriginalPrefix[LineIndex] matches the
955 // OriginalPrefix[LineIndex-1]. That means we don't reflow
956 // // text that protrudes
957 // // into text with different indent
958 // We do reflow in that case in block comments.
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000959 return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
960 mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
961 !switchesFormatting(tokenAt(LineIndex)) &&
962 OriginalPrefix[LineIndex] == OriginalPrefix[LineIndex - 1];
963}
964
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000965} // namespace format
966} // namespace clang