blob: f727f8ddf8966de6f3051fc197d99454d35b7a96 [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,
Craig Topperbfb5c402013-07-01 03:38:29 +000070 encoding::Encoding Encoding) {
Nicola Zaghen3538b392018-05-15 13:30:56 +000071 LLVM_DEBUG(llvm::dbgs() << "Comment split: \"" << Text << ", " << ColumnLimit
72 << "\", Content start: " << ContentStartColumn
73 << "\n");
Alexander Kornienko9e90b622013-04-17 17:34:05 +000074 if (ColumnLimit <= ContentStartColumn + 1)
Manuel Klimek9043c742013-05-27 15:23:34 +000075 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienko9e90b622013-04-17 17:34:05 +000076
77 unsigned MaxSplit = ColumnLimit - ContentStartColumn + 1;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +000078 unsigned MaxSplitBytes = 0;
79
80 for (unsigned NumChars = 0;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +000081 NumChars < MaxSplit && MaxSplitBytes < Text.size();) {
82 unsigned BytesInChar =
Alexander Kornienkoffcc0102013-06-05 14:09:10 +000083 encoding::getCodePointNumBytes(Text[MaxSplitBytes], Encoding);
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +000084 NumChars +=
85 encoding::columnWidthWithTabs(Text.substr(MaxSplitBytes, BytesInChar),
86 ContentStartColumn, TabWidth, Encoding);
87 MaxSplitBytes += BytesInChar;
88 }
Alexander Kornienkoffcc0102013-06-05 14:09:10 +000089
Alexander Kornienkob93062e2013-06-20 13:58:37 +000090 StringRef::size_type SpaceOffset = Text.find_last_of(Blanks, MaxSplitBytes);
Francois Ferranda881be82017-05-22 14:47:17 +000091
92 // Do not split before a number followed by a dot: this would be interpreted
93 // as a numbered list, which would prevent re-flowing in subsequent passes.
Benjamin Kramerf76861c2018-03-20 21:52:19 +000094 static auto *const kNumberedListRegexp = new llvm::Regex("^[1-9][0-9]?\\.");
Francois Ferranda881be82017-05-22 14:47:17 +000095 if (SpaceOffset != StringRef::npos &&
Benjamin Kramerf76861c2018-03-20 21:52:19 +000096 kNumberedListRegexp->match(Text.substr(SpaceOffset).ltrim(Blanks)))
Francois Ferranda881be82017-05-22 14:47:17 +000097 SpaceOffset = Text.find_last_of(Blanks, SpaceOffset);
98
Alexander Kornienko9e90b622013-04-17 17:34:05 +000099 if (SpaceOffset == StringRef::npos ||
Manuel Klimek9043c742013-05-27 15:23:34 +0000100 // Don't break at leading whitespace.
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000101 Text.find_last_not_of(Blanks, SpaceOffset) == StringRef::npos) {
Manuel Klimekae1fbfb2013-05-29 22:06:18 +0000102 // Make sure that we don't break at leading whitespace that
103 // reaches past MaxSplit.
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000104 StringRef::size_type FirstNonWhitespace = Text.find_first_not_of(Blanks);
Manuel Klimekae1fbfb2013-05-29 22:06:18 +0000105 if (FirstNonWhitespace == StringRef::npos)
106 // If the comment is only whitespace, we cannot split.
107 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000108 SpaceOffset = Text.find_first_of(
109 Blanks, std::max<unsigned>(MaxSplitBytes, FirstNonWhitespace));
Manuel Klimekae1fbfb2013-05-29 22:06:18 +0000110 }
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000111 if (SpaceOffset != StringRef::npos && SpaceOffset != 0) {
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000112 StringRef BeforeCut = Text.substr(0, SpaceOffset).rtrim(Blanks);
113 StringRef AfterCut = Text.substr(SpaceOffset).ltrim(Blanks);
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000114 return BreakableToken::Split(BeforeCut.size(),
115 AfterCut.begin() - BeforeCut.end());
116 }
117 return BreakableToken::Split(StringRef::npos, 0);
118}
119
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000120static BreakableToken::Split
121getStringSplit(StringRef Text, unsigned UsedColumns, unsigned ColumnLimit,
122 unsigned TabWidth, encoding::Encoding Encoding) {
Manuel Klimek9043c742013-05-27 15:23:34 +0000123 // FIXME: Reduce unit test case.
124 if (Text.empty())
125 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienko81e32942013-09-16 20:20:49 +0000126 if (ColumnLimit <= UsedColumns)
Manuel Klimek9043c742013-05-27 15:23:34 +0000127 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienko71d95d62013-11-26 10:38:53 +0000128 unsigned MaxSplit = ColumnLimit - UsedColumns;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000129 StringRef::size_type SpaceOffset = 0;
130 StringRef::size_type SlashOffset = 0;
Alexander Kornienko72852072013-06-19 14:22:47 +0000131 StringRef::size_type WordStartOffset = 0;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000132 StringRef::size_type SplitPoint = 0;
133 for (unsigned Chars = 0;;) {
134 unsigned Advance;
135 if (Text[0] == '\\') {
136 Advance = encoding::getEscapeSequenceLength(Text);
137 Chars += Advance;
138 } else {
139 Advance = encoding::getCodePointNumBytes(Text[0], Encoding);
Alexander Kornienko81e32942013-09-16 20:20:49 +0000140 Chars += encoding::columnWidthWithTabs(
141 Text.substr(0, Advance), UsedColumns + Chars, TabWidth, Encoding);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000142 }
143
Daniel Jaspere4b48c62015-01-21 19:50:35 +0000144 if (Chars > MaxSplit || Text.size() <= Advance)
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000145 break;
146
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000147 if (IsBlank(Text[0]))
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000148 SpaceOffset = SplitPoint;
149 if (Text[0] == '/')
150 SlashOffset = SplitPoint;
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000151 if (Advance == 1 && !isAlphanumeric(Text[0]))
Alexander Kornienko72852072013-06-19 14:22:47 +0000152 WordStartOffset = SplitPoint;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000153
154 SplitPoint += Advance;
155 Text = Text.substr(Advance);
156 }
157
158 if (SpaceOffset != 0)
159 return BreakableToken::Split(SpaceOffset + 1, 0);
160 if (SlashOffset != 0)
161 return BreakableToken::Split(SlashOffset + 1, 0);
Alexander Kornienko72852072013-06-19 14:22:47 +0000162 if (WordStartOffset != 0)
163 return BreakableToken::Split(WordStartOffset + 1, 0);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000164 if (SplitPoint != 0)
165 return BreakableToken::Split(SplitPoint, 0);
166 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000167}
168
Krasimir Georgiev91834222017-01-25 13:58:58 +0000169bool switchesFormatting(const FormatToken &Token) {
170 assert((Token.is(TT_BlockComment) || Token.is(TT_LineComment)) &&
171 "formatting regions are switched by comment tokens");
172 StringRef Content = Token.TokenText.substr(2).ltrim();
173 return Content.startswith("clang-format on") ||
174 Content.startswith("clang-format off");
175}
176
177unsigned
Manuel Klimek93699f42017-11-29 14:29:43 +0000178BreakableToken::getLengthAfterCompression(unsigned RemainingTokenColumns,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000179 Split Split) const {
180 // Example: consider the content
181 // lala lala
182 // - RemainingTokenColumns is the original number of columns, 10;
183 // - Split is (4, 2), denoting the two spaces between the two words;
184 //
185 // We compute the number of columns when the split is compressed into a single
186 // space, like:
187 // lala lala
Manuel Klimek93699f42017-11-29 14:29:43 +0000188 //
189 // FIXME: Correctly measure the length of whitespace in Split.second so it
190 // works with tabs.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000191 return RemainingTokenColumns + 1 - Split.second;
192}
193
Manuel Klimek93699f42017-11-29 14:29:43 +0000194unsigned BreakableStringLiteral::getLineCount() const { return 1; }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000195
Manuel Klimek93699f42017-11-29 14:29:43 +0000196unsigned BreakableStringLiteral::getRangeLength(unsigned LineIndex,
197 unsigned Offset,
198 StringRef::size_type Length,
199 unsigned StartColumn) const {
Manuel Klimek477f3692017-11-29 15:09:12 +0000200 llvm_unreachable("Getting the length of a part of the string literal "
201 "indicates that the code tries to reflow it.");
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000202}
203
Manuel Klimek93699f42017-11-29 14:29:43 +0000204unsigned
205BreakableStringLiteral::getRemainingLength(unsigned LineIndex, unsigned Offset,
206 unsigned StartColumn) const {
207 return UnbreakableTailLength + Postfix.size() +
208 encoding::columnWidthWithTabs(Line.substr(Offset, StringRef::npos),
209 StartColumn, Style.TabWidth, Encoding);
210}
211
212unsigned BreakableStringLiteral::getContentStartColumn(unsigned LineIndex,
213 bool Break) const {
214 return StartColumn + Prefix.size();
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000215}
216
Alexander Kornienko81e32942013-09-16 20:20:49 +0000217BreakableStringLiteral::BreakableStringLiteral(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000218 const FormatToken &Tok, unsigned StartColumn, StringRef Prefix,
Krasimir Georgiev55c23a12018-01-23 11:26:19 +0000219 StringRef Postfix, unsigned UnbreakableTailLength, bool InPPDirective,
220 encoding::Encoding Encoding, const FormatStyle &Style)
Manuel Klimek93699f42017-11-29 14:29:43 +0000221 : BreakableToken(Tok, InPPDirective, Encoding, Style),
222 StartColumn(StartColumn), Prefix(Prefix), Postfix(Postfix),
Krasimir Georgiev55c23a12018-01-23 11:26:19 +0000223 UnbreakableTailLength(UnbreakableTailLength) {
Manuel Klimek93699f42017-11-29 14:29:43 +0000224 assert(Tok.TokenText.startswith(Prefix) && Tok.TokenText.endswith(Postfix));
225 Line = Tok.TokenText.substr(
226 Prefix.size(), Tok.TokenText.size() - Prefix.size() - Postfix.size());
227}
Manuel Klimek9043c742013-05-27 15:23:34 +0000228
Manuel Klimek93699f42017-11-29 14:29:43 +0000229BreakableToken::Split BreakableStringLiteral::getSplit(
230 unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit,
231 unsigned ContentStartColumn, llvm::Regex &CommentPragmasRegex) const {
232 return getStringSplit(Line.substr(TailOffset), ContentStartColumn,
233 ColumnLimit - Postfix.size(), Style.TabWidth, Encoding);
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000234}
235
Alexander Kornienko555efc32013-06-11 16:01:49 +0000236void BreakableStringLiteral::insertBreak(unsigned LineIndex,
237 unsigned TailOffset, Split Split,
Manuel Klimek93699f42017-11-29 14:29:43 +0000238 WhitespaceManager &Whitespaces) const {
Alexander Kornienko555efc32013-06-11 16:01:49 +0000239 Whitespaces.replaceWhitespaceInToken(
240 Tok, Prefix.size() + TailOffset + Split.first, Split.second, Postfix,
Alexander Kornienkod4fa2e62017-04-11 09:55:00 +0000241 Prefix, InPPDirective, 1, StartColumn);
Alexander Kornienko555efc32013-06-11 16:01:49 +0000242}
243
Krasimir Georgiev91834222017-01-25 13:58:58 +0000244BreakableComment::BreakableComment(const FormatToken &Token,
Manuel Klimek89628f62017-09-20 09:51:03 +0000245 unsigned StartColumn, bool InPPDirective,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000246 encoding::Encoding Encoding,
247 const FormatStyle &Style)
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000248 : BreakableToken(Token, InPPDirective, Encoding, Style),
Krasimir Georgiev4b159222017-02-21 10:54:50 +0000249 StartColumn(StartColumn) {}
Manuel Klimek9043c742013-05-27 15:23:34 +0000250
Krasimir Georgiev91834222017-01-25 13:58:58 +0000251unsigned BreakableComment::getLineCount() const { return Lines.size(); }
252
Krasimir Georgiev17725d82017-03-08 08:55:12 +0000253BreakableToken::Split
254BreakableComment::getSplit(unsigned LineIndex, unsigned TailOffset,
Manuel Klimek93699f42017-11-29 14:29:43 +0000255 unsigned ColumnLimit, unsigned ContentStartColumn,
Krasimir Georgiev17725d82017-03-08 08:55:12 +0000256 llvm::Regex &CommentPragmasRegex) const {
257 // Don't break lines matching the comment pragmas regex.
258 if (CommentPragmasRegex.match(Content[LineIndex]))
259 return Split(StringRef::npos, 0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000260 return getCommentSplit(Content[LineIndex].substr(TailOffset),
Manuel Klimek93699f42017-11-29 14:29:43 +0000261 ContentStartColumn, ColumnLimit, Style.TabWidth,
262 Encoding);
Manuel Klimek9043c742013-05-27 15:23:34 +0000263}
264
Manuel Klimek93699f42017-11-29 14:29:43 +0000265void BreakableComment::compressWhitespace(
266 unsigned LineIndex, unsigned TailOffset, Split Split,
267 WhitespaceManager &Whitespaces) const {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000268 StringRef Text = Content[LineIndex].substr(TailOffset);
269 // Text is relative to the content line, but Whitespaces operates relative to
270 // the start of the corresponding token, so compute the start of the Split
271 // that needs to be compressed into a single space relative to the start of
272 // its token.
273 unsigned BreakOffsetInToken =
274 Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
275 unsigned CharsToRemove = Split.second;
Alexander Kornienko555efc32013-06-11 16:01:49 +0000276 Whitespaces.replaceWhitespaceInToken(
Krasimir Georgiev91834222017-01-25 13:58:58 +0000277 tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", "",
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000278 /*InPPDirective=*/false, /*Newlines=*/0, /*Spaces=*/1);
Alexander Kornienko875395f2013-11-12 17:50:13 +0000279}
280
Krasimir Georgiev91834222017-01-25 13:58:58 +0000281const FormatToken &BreakableComment::tokenAt(unsigned LineIndex) const {
282 return Tokens[LineIndex] ? *Tokens[LineIndex] : Tok;
283}
284
285static bool mayReflowContent(StringRef Content) {
286 Content = Content.trim(Blanks);
Krasimir Georgiev28912c02017-02-02 10:52:08 +0000287 // Lines starting with '@' commonly have special meaning.
Francois Ferranda881be82017-05-22 14:47:17 +0000288 // Lines starting with '-', '-#', '+' or '*' are bulleted/numbered lists.
Krasimir Georgiev28912c02017-02-02 10:52:08 +0000289 bool hasSpecialMeaningPrefix = false;
Benjamin Kramerf76861c2018-03-20 21:52:19 +0000290 for (StringRef Prefix :
291 {"@", "TODO", "FIXME", "XXX", "-# ", "- ", "+ ", "* "}) {
Krasimir Georgiev28912c02017-02-02 10:52:08 +0000292 if (Content.startswith(Prefix)) {
293 hasSpecialMeaningPrefix = true;
294 break;
295 }
296 }
Francois Ferranda881be82017-05-22 14:47:17 +0000297
298 // Numbered lists may also start with a number followed by '.'
299 // To avoid issues if a line starts with a number which is actually the end
300 // of a previous line, we only consider numbers with up to 2 digits.
Benjamin Kramerf76861c2018-03-20 21:52:19 +0000301 static auto *const kNumberedListRegexp = new llvm::Regex("^[1-9][0-9]?\\. ");
Manuel Klimek89628f62017-09-20 09:51:03 +0000302 hasSpecialMeaningPrefix =
Benjamin Kramerf76861c2018-03-20 21:52:19 +0000303 hasSpecialMeaningPrefix || kNumberedListRegexp->match(Content);
Francois Ferranda881be82017-05-22 14:47:17 +0000304
Krasimir Georgiev91834222017-01-25 13:58:58 +0000305 // Simple heuristic for what to reflow: content should contain at least two
306 // characters and either the first or second character must be
307 // non-punctuation.
Krasimir Georgiev28912c02017-02-02 10:52:08 +0000308 return Content.size() >= 2 && !hasSpecialMeaningPrefix &&
309 !Content.endswith("\\") &&
Krasimir Georgiev91834222017-01-25 13:58:58 +0000310 // Note that this is UTF-8 safe, since if isPunctuation(Content[0]) is
311 // true, then the first code point must be 1 byte long.
312 (!isPunctuation(Content[0]) || !isPunctuation(Content[1]));
313}
314
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000315BreakableBlockComment::BreakableBlockComment(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000316 const FormatToken &Token, unsigned StartColumn,
Alexander Kornienkobe633902013-06-14 11:46:10 +0000317 unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective,
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000318 encoding::Encoding Encoding, const FormatStyle &Style)
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000319 : BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style),
Manuel Klimek48c930c2017-12-04 08:53:16 +0000320 DelimitersOnNewline(false),
321 UnbreakableTailLength(Token.UnbreakableTailLength) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000322 assert(Tok.is(TT_BlockComment) &&
323 "block comment section must start with a block comment");
324
325 StringRef TokenText(Tok.TokenText);
Manuel Klimek9043c742013-05-27 15:23:34 +0000326 assert(TokenText.startswith("/*") && TokenText.endswith("*/"));
327 TokenText.substr(2, TokenText.size() - 4).split(Lines, "\n");
328
329 int IndentDelta = StartColumn - OriginalStartColumn;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000330 Content.resize(Lines.size());
331 Content[0] = Lines[0];
332 ContentColumn.resize(Lines.size());
333 // Account for the initial '/*'.
334 ContentColumn[0] = StartColumn + 2;
335 Tokens.resize(Lines.size());
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000336 for (size_t i = 1; i < Lines.size(); ++i)
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000337 adjustWhitespace(i, IndentDelta);
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000338
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000339 // Align decorations with the column of the star on the first line,
340 // that is one column after the start "/*".
341 DecorationColumn = StartColumn + 1;
342
343 // Account for comment decoration patterns like this:
344 //
345 // /*
346 // ** blah blah blah
347 // */
348 if (Lines.size() >= 2 && Content[1].startswith("**") &&
349 static_cast<unsigned>(ContentColumn[1]) == StartColumn) {
350 DecorationColumn = StartColumn;
351 }
352
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000353 Decoration = "* ";
Manuel Klimek9043c742013-05-27 15:23:34 +0000354 if (Lines.size() == 1 && !FirstInLine) {
355 // Comments for which FirstInLine is false can start on arbitrary column,
356 // and available horizontal space can be too small to align consecutive
357 // lines with the first one.
358 // FIXME: We could, probably, align them to current indentation level, but
359 // now we just wrap them without stars.
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000360 Decoration = "";
Manuel Klimek9043c742013-05-27 15:23:34 +0000361 }
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000362 for (size_t i = 1, e = Lines.size(); i < e && !Decoration.empty(); ++i) {
363 // If the last line is empty, the closing "*/" will have a star.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000364 if (i + 1 == e && Content[i].empty())
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000365 break;
Manuel Klimek89628f62017-09-20 09:51:03 +0000366 if (!Content[i].empty() && i + 1 != e && Decoration.startswith(Content[i]))
Daniel Jasper6d9b88d2015-05-06 07:17:22 +0000367 continue;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000368 while (!Content[i].startswith(Decoration))
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000369 Decoration = Decoration.substr(0, Decoration.size() - 1);
Manuel Klimek9043c742013-05-27 15:23:34 +0000370 }
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000371
372 LastLineNeedsDecoration = true;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000373 IndentAtLineBreak = ContentColumn[0] + 1;
374 for (size_t i = 1, e = Lines.size(); i < e; ++i) {
375 if (Content[i].empty()) {
376 if (i + 1 == e) {
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000377 // Empty last line means that we already have a star as a part of the
378 // trailing */. We also need to preserve whitespace, so that */ is
379 // correctly indented.
380 LastLineNeedsDecoration = false;
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000381 // Align the star in the last '*/' with the stars on the previous lines.
382 if (e >= 2 && !Decoration.empty()) {
383 ContentColumn[i] = DecorationColumn;
384 }
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000385 } else if (Decoration.empty()) {
386 // For all other lines, set the start column to 0 if they're empty, so
387 // we do not insert trailing whitespace anywhere.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000388 ContentColumn[i] = 0;
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000389 }
Manuel Klimek9043c742013-05-27 15:23:34 +0000390 continue;
391 }
Daniel Jasper6d9b88d2015-05-06 07:17:22 +0000392
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000393 // The first line already excludes the star.
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000394 // The last line excludes the star if LastLineNeedsDecoration is false.
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000395 // For all other lines, adjust the line to exclude the star and
396 // (optionally) the first whitespace.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000397 unsigned DecorationSize = Decoration.startswith(Content[i])
398 ? Content[i].size()
399 : Decoration.size();
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000400 if (DecorationSize) {
401 ContentColumn[i] = DecorationColumn + DecorationSize;
402 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000403 Content[i] = Content[i].substr(DecorationSize);
404 if (!Decoration.startswith(Content[i]))
Daniel Jasper6d9b88d2015-05-06 07:17:22 +0000405 IndentAtLineBreak =
Krasimir Georgiev91834222017-01-25 13:58:58 +0000406 std::min<int>(IndentAtLineBreak, std::max(0, ContentColumn[i]));
Manuel Klimek9043c742013-05-27 15:23:34 +0000407 }
Manuel Klimek89628f62017-09-20 09:51:03 +0000408 IndentAtLineBreak = std::max<unsigned>(IndentAtLineBreak, Decoration.size());
Krasimir Georgiev91834222017-01-25 13:58:58 +0000409
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000410 // Detect a multiline jsdoc comment and set DelimitersOnNewline in that case.
411 if (Style.Language == FormatStyle::LK_JavaScript ||
412 Style.Language == FormatStyle::LK_Java) {
413 if ((Lines[0] == "*" || Lines[0].startswith("* ")) && Lines.size() > 1) {
414 // This is a multiline jsdoc comment.
415 DelimitersOnNewline = true;
416 } else if (Lines[0].startswith("* ") && Lines.size() == 1) {
417 // Detect a long single-line comment, like:
418 // /** long long long */
419 // Below, '2' is the width of '*/'.
Manuel Klimek89628f62017-09-20 09:51:03 +0000420 unsigned EndColumn =
421 ContentColumn[0] +
422 encoding::columnWidthWithTabs(Lines[0], ContentColumn[0],
423 Style.TabWidth, Encoding) +
424 2;
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000425 DelimitersOnNewline = EndColumn > Style.ColumnLimit;
426 }
427 }
428
Nicola Zaghen3538b392018-05-15 13:30:56 +0000429 LLVM_DEBUG({
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000430 llvm::dbgs() << "IndentAtLineBreak " << IndentAtLineBreak << "\n";
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000431 llvm::dbgs() << "DelimitersOnNewline " << DelimitersOnNewline << "\n";
Manuel Klimek9043c742013-05-27 15:23:34 +0000432 for (size_t i = 0; i < Lines.size(); ++i) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000433 llvm::dbgs() << i << " |" << Content[i] << "| "
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000434 << "CC=" << ContentColumn[i] << "| "
435 << "IN=" << (Content[i].data() - Lines[i].data()) << "\n";
Manuel Klimek9043c742013-05-27 15:23:34 +0000436 }
437 });
438}
439
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000440void BreakableBlockComment::adjustWhitespace(unsigned LineIndex,
Manuel Klimek9043c742013-05-27 15:23:34 +0000441 int IndentDelta) {
Alexander Kornienkobe633902013-06-14 11:46:10 +0000442 // When in a preprocessor directive, the trailing backslash in a block comment
443 // is not needed, but can serve a purpose of uniformity with necessary escaped
444 // newlines outside the comment. In this case we remove it here before
445 // trimming the trailing whitespace. The backslash will be re-added later when
446 // inserting a line break.
447 size_t EndOfPreviousLine = Lines[LineIndex - 1].size();
448 if (InPPDirective && Lines[LineIndex - 1].endswith("\\"))
449 --EndOfPreviousLine;
450
Manuel Klimek9043c742013-05-27 15:23:34 +0000451 // Calculate the end of the non-whitespace text in the previous line.
Alexander Kornienkobe633902013-06-14 11:46:10 +0000452 EndOfPreviousLine =
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000453 Lines[LineIndex - 1].find_last_not_of(Blanks, EndOfPreviousLine);
Manuel Klimek9043c742013-05-27 15:23:34 +0000454 if (EndOfPreviousLine == StringRef::npos)
455 EndOfPreviousLine = 0;
456 else
457 ++EndOfPreviousLine;
458 // Calculate the start of the non-whitespace text in the current line.
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000459 size_t StartOfLine = Lines[LineIndex].find_first_not_of(Blanks);
Manuel Klimek9043c742013-05-27 15:23:34 +0000460 if (StartOfLine == StringRef::npos)
Daniel Jasperd6e61882015-06-17 12:23:15 +0000461 StartOfLine = Lines[LineIndex].rtrim("\r\n").size();
Manuel Klimek9043c742013-05-27 15:23:34 +0000462
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000463 StringRef Whitespace = Lines[LineIndex].substr(0, StartOfLine);
Manuel Klimek9043c742013-05-27 15:23:34 +0000464 // Adjust Lines to only contain relevant text.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000465 size_t PreviousContentOffset =
466 Content[LineIndex - 1].data() - Lines[LineIndex - 1].data();
467 Content[LineIndex - 1] = Lines[LineIndex - 1].substr(
468 PreviousContentOffset, EndOfPreviousLine - PreviousContentOffset);
469 Content[LineIndex] = Lines[LineIndex].substr(StartOfLine);
Manuel Klimek34d15152013-05-28 10:01:59 +0000470
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000471 // Adjust the start column uniformly across all lines.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000472 ContentColumn[LineIndex] =
Alexander Kornienko39856b72013-09-10 09:38:25 +0000473 encoding::columnWidthWithTabs(Whitespace, 0, Style.TabWidth, Encoding) +
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000474 IndentDelta;
Manuel Klimek9043c742013-05-27 15:23:34 +0000475}
476
Manuel Klimek93699f42017-11-29 14:29:43 +0000477unsigned BreakableBlockComment::getRangeLength(unsigned LineIndex,
478 unsigned Offset,
479 StringRef::size_type Length,
480 unsigned StartColumn) const {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000481 unsigned LineLength =
Manuel Klimek93699f42017-11-29 14:29:43 +0000482 encoding::columnWidthWithTabs(Content[LineIndex].substr(Offset, Length),
483 StartColumn, Style.TabWidth, Encoding);
484 // FIXME: This should go into getRemainingLength instead, but we currently
485 // break tests when putting it there. Investigate how to fix those tests.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000486 // The last line gets a "*/" postfix.
487 if (LineIndex + 1 == Lines.size()) {
488 LineLength += 2;
489 // We never need a decoration when breaking just the trailing "*/" postfix.
490 // Note that checking that Length == 0 is not enough, since Length could
491 // also be StringRef::npos.
Manuel Klimek93699f42017-11-29 14:29:43 +0000492 if (Content[LineIndex].substr(Offset, StringRef::npos).empty()) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000493 LineLength -= Decoration.size();
494 }
495 }
496 return LineLength;
Manuel Klimek9043c742013-05-27 15:23:34 +0000497}
498
Manuel Klimek93699f42017-11-29 14:29:43 +0000499unsigned BreakableBlockComment::getRemainingLength(unsigned LineIndex,
500 unsigned Offset,
501 unsigned StartColumn) const {
Manuel Klimek48c930c2017-12-04 08:53:16 +0000502 return UnbreakableTailLength +
503 getRangeLength(LineIndex, Offset, StringRef::npos, StartColumn);
Manuel Klimek93699f42017-11-29 14:29:43 +0000504}
505
506unsigned BreakableBlockComment::getContentStartColumn(unsigned LineIndex,
507 bool Break) const {
508 if (Break)
509 return IndentAtLineBreak;
510 return std::max(0, ContentColumn[LineIndex]);
511}
512
Manuel Klimek9043c742013-05-27 15:23:34 +0000513void BreakableBlockComment::insertBreak(unsigned LineIndex, unsigned TailOffset,
Alexander Kornienkobe633902013-06-14 11:46:10 +0000514 Split Split,
Manuel Klimek93699f42017-11-29 14:29:43 +0000515 WhitespaceManager &Whitespaces) const {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000516 StringRef Text = Content[LineIndex].substr(TailOffset);
Manuel Klimek9043c742013-05-27 15:23:34 +0000517 StringRef Prefix = Decoration;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000518 // We need this to account for the case when we have a decoration "* " for all
519 // the lines except for the last one, where the star in "*/" acts as a
520 // decoration.
521 unsigned LocalIndentAtLineBreak = IndentAtLineBreak;
Manuel Klimek9043c742013-05-27 15:23:34 +0000522 if (LineIndex + 1 == Lines.size() &&
523 Text.size() == Split.first + Split.second) {
524 // For the last line we need to break before "*/", but not to add "* ".
525 Prefix = "";
Krasimir Georgiev91834222017-01-25 13:58:58 +0000526 if (LocalIndentAtLineBreak >= 2)
527 LocalIndentAtLineBreak -= 2;
528 }
529 // The split offset is from the beginning of the line. Convert it to an offset
530 // from the beginning of the token text.
531 unsigned BreakOffsetInToken =
532 Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
533 unsigned CharsToRemove = Split.second;
534 assert(LocalIndentAtLineBreak >= Prefix.size());
535 Whitespaces.replaceWhitespaceInToken(
536 tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", Prefix,
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000537 InPPDirective, /*Newlines=*/1,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000538 /*Spaces=*/LocalIndentAtLineBreak - Prefix.size());
539}
540
Manuel Klimek93699f42017-11-29 14:29:43 +0000541BreakableToken::Split
542BreakableBlockComment::getReflowSplit(unsigned LineIndex,
543 llvm::Regex &CommentPragmasRegex) const {
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000544 if (!mayReflow(LineIndex, CommentPragmasRegex))
Krasimir Georgiev91834222017-01-25 13:58:58 +0000545 return Split(StringRef::npos, 0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000546
Manuel Klimek93699f42017-11-29 14:29:43 +0000547 size_t Trimmed = Content[LineIndex].find_first_not_of(Blanks);
548 return Split(0, Trimmed != StringRef::npos ? Trimmed : 0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000549}
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000550
Manuel Klimek77866142017-11-17 11:17:15 +0000551bool BreakableBlockComment::introducesBreakBeforeToken() const {
Krasimir Georgiev35599fd2017-10-16 09:08:53 +0000552 // A break is introduced when we want delimiters on newline.
Manuel Klimek77866142017-11-17 11:17:15 +0000553 return DelimitersOnNewline &&
Krasimir Georgiev35599fd2017-10-16 09:08:53 +0000554 Lines[0].substr(1).find_first_not_of(Blanks) != StringRef::npos;
555}
556
Manuel Klimek93699f42017-11-29 14:29:43 +0000557void BreakableBlockComment::reflow(unsigned LineIndex,
558 WhitespaceManager &Whitespaces) const {
559 StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
560 // Here we need to reflow.
561 assert(Tokens[LineIndex - 1] == Tokens[LineIndex] &&
562 "Reflowing whitespace within a token");
563 // This is the offset of the end of the last line relative to the start of
564 // the token text in the token.
565 unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
566 Content[LineIndex - 1].size() -
567 tokenAt(LineIndex).TokenText.data();
568 unsigned WhitespaceLength = TrimmedContent.data() -
569 tokenAt(LineIndex).TokenText.data() -
570 WhitespaceOffsetInToken;
571 Whitespaces.replaceWhitespaceInToken(
572 tokenAt(LineIndex), WhitespaceOffsetInToken,
573 /*ReplaceChars=*/WhitespaceLength, /*PreviousPostfix=*/"",
574 /*CurrentPrefix=*/ReflowPrefix, InPPDirective, /*Newlines=*/0,
575 /*Spaces=*/0);
576}
577
578void BreakableBlockComment::adaptStartOfLine(
579 unsigned LineIndex, WhitespaceManager &Whitespaces) const {
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000580 if (LineIndex == 0) {
581 if (DelimitersOnNewline) {
Manuel Klimek93699f42017-11-29 14:29:43 +0000582 // Since we're breaking at index 1 below, the break position and the
Manuel Klimek89628f62017-09-20 09:51:03 +0000583 // break length are the same.
584 size_t BreakLength = Lines[0].substr(1).find_first_not_of(Blanks);
Manuel Klimek93699f42017-11-29 14:29:43 +0000585 if (BreakLength != StringRef::npos)
Manuel Klimek89628f62017-09-20 09:51:03 +0000586 insertBreak(LineIndex, 0, Split(1, BreakLength), Whitespaces);
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000587 }
588 return;
589 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000590 // Here no reflow with the previous line will happen.
591 // Fix the decoration of the line at LineIndex.
Manuel Klimek9043c742013-05-27 15:23:34 +0000592 StringRef Prefix = Decoration;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000593 if (Content[LineIndex].empty()) {
Manuel Klimek281dcbe2013-05-28 08:55:01 +0000594 if (LineIndex + 1 == Lines.size()) {
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000595 if (!LastLineNeedsDecoration) {
596 // If the last line was empty, we don't need a prefix, as the */ will
597 // line up with the decoration (if it exists).
598 Prefix = "";
599 }
Manuel Klimek281dcbe2013-05-28 08:55:01 +0000600 } else if (!Decoration.empty()) {
601 // For other empty lines, if we do have a decoration, adapt it to not
602 // contain a trailing whitespace.
603 Prefix = Prefix.substr(0, 1);
604 }
Daniel Jasper51fb2b22013-05-30 06:40:07 +0000605 } else {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000606 if (ContentColumn[LineIndex] == 1) {
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000607 // This line starts immediately after the decorating *.
Daniel Jasper51fb2b22013-05-30 06:40:07 +0000608 Prefix = Prefix.substr(0, 1);
609 }
Manuel Klimek281dcbe2013-05-28 08:55:01 +0000610 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000611 // This is the offset of the end of the last line relative to the start of the
612 // token text in the token.
613 unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
614 Content[LineIndex - 1].size() -
615 tokenAt(LineIndex).TokenText.data();
616 unsigned WhitespaceLength = Content[LineIndex].data() -
617 tokenAt(LineIndex).TokenText.data() -
618 WhitespaceOffsetInToken;
Alexander Kornienko555efc32013-06-11 16:01:49 +0000619 Whitespaces.replaceWhitespaceInToken(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000620 tokenAt(LineIndex), WhitespaceOffsetInToken, WhitespaceLength, "", Prefix,
621 InPPDirective, /*Newlines=*/1, ContentColumn[LineIndex] - Prefix.size());
Manuel Klimek9043c742013-05-27 15:23:34 +0000622}
623
Krasimir Georgiev3b865342017-08-09 09:42:32 +0000624BreakableToken::Split
Manuel Klimek93699f42017-11-29 14:29:43 +0000625BreakableBlockComment::getSplitAfterLastLine(unsigned TailOffset) const {
Krasimir Georgiev3b865342017-08-09 09:42:32 +0000626 if (DelimitersOnNewline) {
627 // Replace the trailing whitespace of the last line with a newline.
628 // In case the last line is empty, the ending '*/' is already on its own
629 // line.
630 StringRef Line = Content.back().substr(TailOffset);
631 StringRef TrimmedLine = Line.rtrim(Blanks);
632 if (!TrimmedLine.empty())
633 return Split(TrimmedLine.size(), Line.size() - TrimmedLine.size());
634 }
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000635 return Split(StringRef::npos, 0);
636}
637
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000638bool BreakableBlockComment::mayReflow(unsigned LineIndex,
639 llvm::Regex &CommentPragmasRegex) const {
640 // Content[LineIndex] may exclude the indent after the '*' decoration. In that
641 // case, we compute the start of the comment pragma manually.
642 StringRef IndentContent = Content[LineIndex];
643 if (Lines[LineIndex].ltrim(Blanks).startswith("*")) {
644 IndentContent = Lines[LineIndex].ltrim(Blanks).substr(1);
645 }
646 return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
647 mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
648 !switchesFormatting(tokenAt(LineIndex));
649}
650
Krasimir Georgiev91834222017-01-25 13:58:58 +0000651BreakableLineCommentSection::BreakableLineCommentSection(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000652 const FormatToken &Token, unsigned StartColumn,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000653 unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective,
654 encoding::Encoding Encoding, const FormatStyle &Style)
Krasimir Georgiev4b159222017-02-21 10:54:50 +0000655 : BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000656 assert(Tok.is(TT_LineComment) &&
657 "line comment section must start with a line comment");
658 FormatToken *LineTok = nullptr;
659 for (const FormatToken *CurrentTok = &Tok;
660 CurrentTok && CurrentTok->is(TT_LineComment);
661 CurrentTok = CurrentTok->Next) {
662 LastLineTok = LineTok;
663 StringRef TokenText(CurrentTok->TokenText);
Krasimir Georgiev410ed242017-11-10 12:50:09 +0000664 assert((TokenText.startswith("//") || TokenText.startswith("#")) &&
665 "unsupported line comment prefix, '//' and '#' are supported");
Krasimir Georgiev91834222017-01-25 13:58:58 +0000666 size_t FirstLineIndex = Lines.size();
667 TokenText.split(Lines, "\n");
668 Content.resize(Lines.size());
669 ContentColumn.resize(Lines.size());
670 OriginalContentColumn.resize(Lines.size());
671 Tokens.resize(Lines.size());
672 Prefix.resize(Lines.size());
673 OriginalPrefix.resize(Lines.size());
674 for (size_t i = FirstLineIndex, e = Lines.size(); i < e; ++i) {
Manuel Klimek45ab5592017-11-14 09:19:53 +0000675 Lines[i] = Lines[i].ltrim(Blanks);
Krasimir Georgieve518e0b2017-01-30 21:00:01 +0000676 // We need to trim the blanks in case this is not the first line in a
677 // multiline comment. Then the indent is included in Lines[i].
678 StringRef IndentPrefix =
Krasimir Georgiev410ed242017-11-10 12:50:09 +0000679 getLineCommentIndentPrefix(Lines[i].ltrim(Blanks), Style);
680 assert((TokenText.startswith("//") || TokenText.startswith("#")) &&
681 "unsupported line comment prefix, '//' and '#' are supported");
Krasimir Georgiev91834222017-01-25 13:58:58 +0000682 OriginalPrefix[i] = Prefix[i] = IndentPrefix;
683 if (Lines[i].size() > Prefix[i].size() &&
684 isAlphanumeric(Lines[i][Prefix[i].size()])) {
685 if (Prefix[i] == "//")
686 Prefix[i] = "// ";
687 else if (Prefix[i] == "///")
688 Prefix[i] = "/// ";
689 else if (Prefix[i] == "//!")
690 Prefix[i] = "//! ";
Krasimir Georgievba6b3152017-05-18 07:36:21 +0000691 else if (Prefix[i] == "///<")
692 Prefix[i] = "///< ";
693 else if (Prefix[i] == "//!<")
694 Prefix[i] = "//!< ";
Krasimir Georgiev410ed242017-11-10 12:50:09 +0000695 else if (Prefix[i] == "#" &&
696 Style.Language == FormatStyle::LK_TextProto)
697 Prefix[i] = "# ";
Krasimir Georgiev91834222017-01-25 13:58:58 +0000698 }
699
700 Tokens[i] = LineTok;
701 Content[i] = Lines[i].substr(IndentPrefix.size());
702 OriginalContentColumn[i] =
Manuel Klimek89628f62017-09-20 09:51:03 +0000703 StartColumn + encoding::columnWidthWithTabs(OriginalPrefix[i],
704 StartColumn,
705 Style.TabWidth, Encoding);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000706 ContentColumn[i] =
Manuel Klimek89628f62017-09-20 09:51:03 +0000707 StartColumn + encoding::columnWidthWithTabs(Prefix[i], StartColumn,
708 Style.TabWidth, Encoding);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000709
710 // Calculate the end of the non-whitespace text in this line.
711 size_t EndOfLine = Content[i].find_last_not_of(Blanks);
712 if (EndOfLine == StringRef::npos)
713 EndOfLine = Content[i].size();
714 else
715 ++EndOfLine;
716 Content[i] = Content[i].substr(0, EndOfLine);
717 }
718 LineTok = CurrentTok->Next;
Krasimir Georgievb6ccd382017-02-02 14:36:50 +0000719 if (CurrentTok->Next && !CurrentTok->Next->ContinuesLineCommentSection) {
Krasimir Georgiev753625b2017-01-31 13:32:38 +0000720 // A line comment section needs to broken by a line comment that is
721 // preceded by at least two newlines. Note that we put this break here
722 // instead of breaking at a previous stage during parsing, since that
723 // would split the contents of the enum into two unwrapped lines in this
724 // example, which is undesirable:
725 // enum A {
726 // a, // comment about a
727 //
728 // // comment about b
729 // b
730 // };
731 //
732 // FIXME: Consider putting separate line comment sections as children to
733 // the unwrapped line instead.
734 break;
735 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000736 }
737}
738
Manuel Klimek93699f42017-11-29 14:29:43 +0000739unsigned
740BreakableLineCommentSection::getRangeLength(unsigned LineIndex, unsigned Offset,
741 StringRef::size_type Length,
742 unsigned StartColumn) const {
743 return encoding::columnWidthWithTabs(
744 Content[LineIndex].substr(Offset, Length), StartColumn, Style.TabWidth,
745 Encoding);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000746}
747
Manuel Klimek93699f42017-11-29 14:29:43 +0000748unsigned BreakableLineCommentSection::getContentStartColumn(unsigned LineIndex,
749 bool Break) const {
750 if (Break)
751 return OriginalContentColumn[LineIndex];
752 return ContentColumn[LineIndex];
753}
754
755void BreakableLineCommentSection::insertBreak(
756 unsigned LineIndex, unsigned TailOffset, Split Split,
757 WhitespaceManager &Whitespaces) const {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000758 StringRef Text = Content[LineIndex].substr(TailOffset);
759 // Compute the offset of the split relative to the beginning of the token
760 // text.
761 unsigned BreakOffsetInToken =
762 Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
763 unsigned CharsToRemove = Split.second;
764 // Compute the size of the new indent, including the size of the new prefix of
765 // the newly broken line.
766 unsigned IndentAtLineBreak = OriginalContentColumn[LineIndex] +
767 Prefix[LineIndex].size() -
768 OriginalPrefix[LineIndex].size();
769 assert(IndentAtLineBreak >= Prefix[LineIndex].size());
770 Whitespaces.replaceWhitespaceInToken(
771 tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "",
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000772 Prefix[LineIndex], InPPDirective, /*Newlines=*/1,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000773 /*Spaces=*/IndentAtLineBreak - Prefix[LineIndex].size());
774}
775
Manuel Klimek93699f42017-11-29 14:29:43 +0000776BreakableComment::Split BreakableLineCommentSection::getReflowSplit(
777 unsigned LineIndex, llvm::Regex &CommentPragmasRegex) const {
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000778 if (!mayReflow(LineIndex, CommentPragmasRegex))
779 return Split(StringRef::npos, 0);
Manuel Klimek93699f42017-11-29 14:29:43 +0000780
781 size_t Trimmed = Content[LineIndex].find_first_not_of(Blanks);
782
783 // In a line comment section each line is a separate token; thus, after a
784 // split we replace all whitespace before the current line comment token
785 // (which does not need to be included in the split), plus the start of the
786 // line up to where the content starts.
787 return Split(0, Trimmed != StringRef::npos ? Trimmed : 0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000788}
789
Manuel Klimek93699f42017-11-29 14:29:43 +0000790void BreakableLineCommentSection::reflow(unsigned LineIndex,
791 WhitespaceManager &Whitespaces) const {
792 // Reflow happens between tokens. Replace the whitespace between the
793 // tokens by the empty string.
794 Whitespaces.replaceWhitespace(
795 *Tokens[LineIndex], /*Newlines=*/0, /*Spaces=*/0,
796 /*StartOfTokenColumn=*/StartColumn, /*InPPDirective=*/false);
797 // Replace the indent and prefix of the token with the reflow prefix.
798 unsigned WhitespaceLength =
799 Content[LineIndex].data() - tokenAt(LineIndex).TokenText.data();
800 Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex],
801 /*Offset=*/0,
802 /*ReplaceChars=*/WhitespaceLength,
803 /*PreviousPostfix=*/"",
804 /*CurrentPrefix=*/ReflowPrefix,
805 /*InPPDirective=*/false,
806 /*Newlines=*/0,
807 /*Spaces=*/0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000808}
809
Manuel Klimek93699f42017-11-29 14:29:43 +0000810void BreakableLineCommentSection::adaptStartOfLine(
811 unsigned LineIndex, WhitespaceManager &Whitespaces) const {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000812 // If this is the first line of a token, we need to inform Whitespace Manager
813 // about it: either adapt the whitespace range preceding it, or mark it as an
814 // untouchable token.
815 // This happens for instance here:
816 // // line 1 \
817 // // line 2
818 if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) {
Manuel Klimek93699f42017-11-29 14:29:43 +0000819 // This is the first line for the current token, but no reflow with the
820 // previous token is necessary. However, we still may need to adjust the
821 // start column. Note that ContentColumn[LineIndex] is the expected
822 // content column after a possible update to the prefix, hence the prefix
823 // length change is included.
824 unsigned LineColumn =
825 ContentColumn[LineIndex] -
826 (Content[LineIndex].data() - Lines[LineIndex].data()) +
827 (OriginalPrefix[LineIndex].size() - Prefix[LineIndex].size());
Krasimir Georgiev13dbaa02017-02-01 10:10:04 +0000828
Manuel Klimek93699f42017-11-29 14:29:43 +0000829 // We always want to create a replacement instead of adding an untouchable
830 // token, even if LineColumn is the same as the original column of the
831 // token. This is because WhitespaceManager doesn't align trailing
832 // comments if they are untouchable.
833 Whitespaces.replaceWhitespace(*Tokens[LineIndex],
834 /*Newlines=*/1,
835 /*Spaces=*/LineColumn,
836 /*StartOfTokenColumn=*/LineColumn,
837 /*InPPDirective=*/false);
Krasimir Georgievb796ceb2017-01-31 15:40:15 +0000838 }
839 if (OriginalPrefix[LineIndex] != Prefix[LineIndex]) {
840 // Adjust the prefix if necessary.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000841
842 // Take care of the space possibly introduced after a decoration.
843 assert(Prefix[LineIndex] == (OriginalPrefix[LineIndex] + " ").str() &&
Krasimir Georgievb796ceb2017-01-31 15:40:15 +0000844 "Expecting a line comment prefix to differ from original by at most "
845 "a space");
Krasimir Georgiev91834222017-01-25 13:58:58 +0000846 Whitespaces.replaceWhitespaceInToken(
847 tokenAt(LineIndex), OriginalPrefix[LineIndex].size(), 0, "", "",
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000848 /*InPPDirective=*/false, /*Newlines=*/0, /*Spaces=*/1);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000849 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000850}
851
Manuel Klimek89628f62017-09-20 09:51:03 +0000852void BreakableLineCommentSection::updateNextToken(LineState &State) const {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000853 if (LastLineTok) {
854 State.NextToken = LastLineTok->Next;
855 }
856}
857
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000858bool BreakableLineCommentSection::mayReflow(
859 unsigned LineIndex, llvm::Regex &CommentPragmasRegex) const {
860 // Line comments have the indent as part of the prefix, so we need to
861 // recompute the start of the line.
862 StringRef IndentContent = Content[LineIndex];
863 if (Lines[LineIndex].startswith("//")) {
864 IndentContent = Lines[LineIndex].substr(2);
865 }
Manuel Klimek93699f42017-11-29 14:29:43 +0000866 // FIXME: Decide whether we want to reflow non-regular indents:
867 // Currently, we only reflow when the OriginalPrefix[LineIndex] matches the
868 // OriginalPrefix[LineIndex-1]. That means we don't reflow
869 // // text that protrudes
870 // // into text with different indent
871 // We do reflow in that case in block comments.
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000872 return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
873 mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
874 !switchesFormatting(tokenAt(LineIndex)) &&
875 OriginalPrefix[LineIndex] == OriginalPrefix[LineIndex - 1];
876}
877
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000878} // namespace format
879} // namespace clang